feat(fullstack): complete account and session integration

Enforce live session grants for runtime routes and support profile and
credential updates in both the backend and demo modes.

Add the account settings workspace and document fullstack setup and PC
acceptance.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-06 21:39:36 +08:00
parent 59c1090ea4
commit 0e688a34bf
No known key found for this signature in database
96 changed files with 6152 additions and 733 deletions

View File

@ -138,7 +138,9 @@ pnpm fullstack:setup
pnpm dev:full
```
`setup` creates the private `apps/server/.env.local`, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. The generated administrator password is stored in that file; Mock passwords do not authenticate against the server. Repeating setup preserves existing configuration and accounts. For existing PostgreSQL and Redis services, provide `DATABASE_URL` and `REDIS_URL` and run `pnpm fullstack:setup --external`. `pnpm fullstack:stop` stops Compose services while retaining their data volumes.
To build and start the entire stack in Docker without installing host dependencies, run `node scripts/fullstack.mjs up` from the complete source. Open `http://127.0.0.1:8080/ray-template/`.
`setup` creates the private `apps/server/.env.local`, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. The generated administrator password is stored in that file; Mock passwords do not authenticate against the server. For existing PostgreSQL and Redis services, provide `DATABASE_URL` and `REDIS_URL` and run `pnpm fullstack:setup --external`. `pnpm fullstack:stop` retains data volumes.
The [Source distributions workflow](.github/workflows/distributions.yaml) verifies both archives before it can update the generated `frontend` branch or attach assets to an existing GitHub Release. Those actions are explicitly selected when running the workflow from `main`. See the [Compose and release instructions](apps/docs/guide/distributions.md#容器启动).

View File

@ -138,7 +138,9 @@ pnpm fullstack:setup
pnpm dev:full
```
`setup` 创建私有的 `apps/server/.env.local`、启动数据库与 Redis、迁移并初始化管理员。管理员密码随机生成并保存在该文件中;真实后端不接受 Mock 演示密码。重复执行保留已有配置和账号。已经有 PostgreSQL、Redis 时,可提供 `DATABASE_URL`、`REDIS_URL` 并执行 `pnpm fullstack:setup --external`。`pnpm fullstack:stop` 停止 Compose 服务并保留数据卷。
如需直接用 Docker 构建并启动整套服务,从完整源码根目录运行 `node scripts/fullstack.mjs up`。宿主机无需先安装前端依赖,默认打开 `http://127.0.0.1:8080/ray-template/`。
`setup` 创建私有的 `apps/server/.env.local`、启动数据库与 Redis、迁移并初始化管理员。管理员密码随机生成并保存在该文件中;真实后端不接受 Mock 演示密码。已有 PostgreSQL 和 Redis 时,提供 `DATABASE_URL`、`REDIS_URL` 后执行 `pnpm fullstack:setup --external`。`pnpm fullstack:stop` 停止 Compose 服务并保留数据卷。
[源码发行工作流](.github/workflows/distributions.yaml) 验证两个归档后,可以生成或更新 `frontend` 分支,也可以给已有 GitHub Release 附加源码归档。需要从 `main` 手动运行并选择对应操作。容器启动见[发行版本与快速启动](apps/docs/guide/distributions.md#容器启动)。

View File

@ -0,0 +1,52 @@
import { AdminApiError } from '@/api/admin/client'
import AccountPasswordForm from '@/app-components/app/AccountPasswordForm'
import { flushPromises, mount } from '@vue/test-utils'
import setupMiniApp from '../utils/setupMiniApp'
it('checks password confirmation, renders the API error and permits a retry', async () => {
const { app } = await setupMiniApp()
const save = vi
.fn<(next: string, current: string) => Promise<void>>()
.mockRejectedValueOnce(
new AdminApiError(
400,
'invalidCurrentPassword',
'invalidCurrentPassword',
),
)
.mockResolvedValueOnce(void 0)
const wrapper = mount(AccountPasswordForm, {
props: { username: 'fixture-user', requireCurrent: true, save },
})
try {
const current = wrapper.get('input[name="currentPassword"]')
const next = wrapper.get('input[name="newPassword"]')
const confirmation = wrapper.get('input[name="confirmPassword"]')
await current.setValue('fixture-old-password')
await next.setValue('fixture-new-password')
await confirmation.setValue('fixture-mismatch')
await wrapper.get('form').trigger('submit')
expect(save).not.toHaveBeenCalled()
expect(wrapper.get('[role="alert"]').text()).toContain('不一致')
await confirmation.setValue('fixture-new-password')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(save).toHaveBeenCalledWith(
'fixture-new-password',
'fixture-old-password',
)
expect(wrapper.get('[role="alert"]').text()).toContain('当前密码不正确')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(save).toHaveBeenCalledTimes(2)
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
expect((next.element as HTMLInputElement).value).toBe('')
} finally {
wrapper.unmount()
app.unmount()
}
})

View File

@ -2,9 +2,17 @@ import Signing from '@/views/login/components/Signing'
import { flushPromises, mount } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
const signing = vi.fn()
const { signing, loadRoutes, announceSession } = vi.hoisted(() => ({
signing: vi.fn(),
loadRoutes: vi.fn(),
announceSession: vi.fn(),
}))
vi.mock('@/api/admin/client', () => ({ apiMockEnabled: false }))
vi.mock('@/router', () => ({ loadAccountRoutes: loadRoutes }))
vi.mock('@/store/modules/signing', () => ({
announceAdminSessionChange: announceSession,
}))
vi.mock('@/hooks', () => ({
useI18n: () => ({ t: (key: string) => key }),
}))
@ -13,10 +21,8 @@ vi.mock('@/store', () => ({
}))
it('submits the real login form with native credential fields and no demo shortcuts', async () => {
signing.mockResolvedValue({
code: 0,
data: { id: 'test-account', username: 'qa-account' },
})
signing.mockResolvedValue(void 0)
loadRoutes.mockResolvedValue(void 0)
const router = createRouter({
history: createMemoryHistory(),
routes: ['/', '/welcome'].map((path) => ({
@ -44,6 +50,13 @@ it('submits the real login form with native credential fields and no demo shortc
name: 'qa-account',
pwd: 'qa-fixture-password',
})
expect(loadRoutes).toHaveBeenCalledExactlyOnceWith()
expect(signing.mock.invocationCallOrder[0]).toBeLessThan(
loadRoutes.mock.invocationCallOrder[0]!,
)
expect(loadRoutes.mock.invocationCallOrder[0]).toBeLessThan(
announceSession.mock.invocationCallOrder[0]!,
)
expect(router.currentRoute.value.path).toBe('/welcome')
} finally {
wrapper.unmount()

View File

@ -5,7 +5,7 @@ import type { AppMenuOption } from '../../apps/admin/src/types'
import setupMiniApp from '../utils/setupMiniApp'
describe('useBadge', async () => {
await setupMiniApp()
await setupMiniApp(true)
const { show, hidden, update } = useBadge()
const { getMenuOptions } = useMenuGetters()

View File

@ -1,6 +1,8 @@
import {
changeAccountPassword,
createUser,
deleteUsers,
getAccountProfile,
getAdminRoutes,
getAdminSession,
getUser,
@ -9,6 +11,8 @@ import {
loginAdmin,
logoutAdmin,
resetDemoUsers,
setUserCredential,
updateAccountProfile,
updateAdminRoutes,
updateUser,
updateUserStatus,
@ -32,6 +36,9 @@ const input: UserInput = {
const signIn = async (username = 'admin') => {
const result = await loginAdmin(username, '123456')
if (!('accessToken' in result))
throw new Error('Mock login must return a token.')
setStorage(APP_CATCH_KEY.token, result.accessToken, 'localStorage')
return result
@ -173,10 +180,10 @@ it('invalidates the server-side Mock session on logout', async () => {
await expect(getUsers({})).rejects.toMatchObject({ code: 401 })
})
it('restores Mock writes and active sessions after recreating the database', () => {
it('restores Mock writes and active sessions after recreating the database', async () => {
localStorage.clear()
const first = createAdminDatabase(localStorage)
const session = first.login({ username: 'admin', password: '123456' })
const session = await first.login({ username: 'admin', password: '123456' })
const user = first.saveUser(input, session.accessToken)
const second = createAdminDatabase(localStorage)
@ -184,7 +191,7 @@ it('restores Mock writes and active sessions after recreating the database', ()
expect(second.authorize(session.accessToken).user.id).toBe(session.user.id)
})
it('keeps writes atomic when persistence fails', () => {
it('keeps writes atomic when persistence fails', async () => {
const storage: Storage = {
length: 0,
key: () => null,
@ -194,7 +201,10 @@ it('keeps writes atomic when persistence fails', () => {
setItem: vi.fn(),
}
const database = createAdminDatabase(storage)
const session = database.login({ username: 'admin', password: '123456' })
const session = await database.login({
username: 'admin',
password: '123456',
})
vi.mocked(storage.setItem).mockImplementation(() => {
throw new Error('Quota exceeded')
@ -202,3 +212,41 @@ it('keeps writes atomic when persistence fails', () => {
expect(() => database.saveUser(input, session.accessToken)).toThrow('storage')
expect(database.listUsers({}, session.accessToken).total).toBe(24)
})
it('provisions a Mock login and updates only the signed-in profile', async () => {
const user = await createUser(input)
const original = 'mock-initial-password'
const changed = 'mock-changed-password'
await expect(loginAdmin(user.username, '123456')).rejects.toMatchObject({
code: 401,
})
await setUserCredential(user.id, original)
const session = await loginAdmin(user.username, original)
if (!('accessToken' in session))
throw new Error('Mock login must return a token.')
setStorage(APP_CATCH_KEY.token, session.accessToken, 'localStorage')
await expect(getAccountProfile()).resolves.toMatchObject({
id: user.id,
username: user.username,
})
await expect(
updateAccountProfile({ name: 'Updated profile', phone: '' }),
).resolves.toMatchObject({ name: 'Updated profile' })
await expect(setUserCredential(user.id, changed)).rejects.toMatchObject({
code: 403,
})
await changeAccountPassword({
currentPassword: original,
newPassword: changed,
})
await expect(getAccountProfile()).rejects.toMatchObject({ code: 401 })
await expect(loginAdmin(user.username, original)).rejects.toMatchObject({
code: 401,
})
await expect(loginAdmin(user.username, changed)).resolves.toMatchObject({
user: { name: 'Updated profile' },
})
})

View File

@ -19,7 +19,7 @@ const parse = (routes: unknown[]) =>
parseRouteConfig(JSON.stringify({ version: 1, routes }))
describe('route configuration', () => {
it('keeps both management pages under the same admin-only menu', () => {
it('requires the editor grant for the management menu and both direct links', () => {
const root = getAppRawRoutes().find(
({ path }) => path === '/route-management',
)
@ -28,15 +28,14 @@ describe('route configuration', () => {
)
expect(root?.children?.map(({ path }) => path)).toEqual(['visual', 'json'])
expect(root?.meta.requiredPermission).toBe('routes:write')
expect(leaves.map(({ path }) => path)).toEqual([
'/route-management/visual',
'/route-management/json',
])
for (const { meta } of leaves) {
expect(validRole(meta, 'admin')).toBe(true)
expect(validRole(meta, 'viewer')).toBe(false)
}
for (const { meta } of leaves)
expect(meta.requiredPermission).toBe('routes:write')
})
it('round-trips all bundled routes with their view IDs and metadata', () => {

View File

@ -1,5 +1,10 @@
import type { App } from 'vue'
import { router, setupRouter } from '../../apps/admin/src/router'
import {
clearAccountRoutes,
loadAccountRoutes,
router,
setupRouter,
} from '../../apps/admin/src/router'
const { load, register } = vi.hoisted(() => ({
load: vi.fn(),
@ -8,20 +13,29 @@ const { load, register } = vi.hoisted(() => ({
vi.mock('../../apps/admin/src/router/config/source', () => ({
loadRouteConfig: load,
resetRouteSource: vi.fn(),
}))
vi.mock('../../apps/admin/src/router/routes', () => ({
constantRoutes: [{ path: '/', component: { render: () => null } }],
constantRoutes: [
{ path: '/', name: 'RLayout', component: { render: () => null } },
],
getLayoutRoutes: () => [],
getSystemRoutes: () => [],
getAccountProfileRoute: () => ({
path: '/account/profile',
component: { render: () => null },
}),
}))
vi.mock('../../apps/admin/src/router/app-route-modules', () => ({
setAppRouteModules: vi.fn(),
getStaticAppRoutes: () => [],
}))
vi.mock('../../apps/admin/src/router/utils', () => ({
scrollViewToTop: vi.fn(),
vueRouterRegister: register,
}))
it('retries failed initialization on remount and shares the successful retry', async () => {
it('loads no business routes before login, then shares a retry and registers guards once', async () => {
const app = { use: vi.fn() } as unknown as App<Element>
load
@ -29,15 +43,16 @@ it('retries failed initialization on remount and shares the successful retry', a
.mockResolvedValue(void 0)
try {
await expect(setupRouter(app)).rejects.toThrow('route endpoint unavailable')
expect(register).not.toHaveBeenCalled()
await Promise.all([setupRouter(app), setupRouter(app)])
expect(load).toHaveBeenCalledTimes(2)
expect(register).toHaveBeenCalledOnce()
await setupRouter(app)
await setupRouter(app, false)
expect(load).not.toHaveBeenCalled()
await expect(loadAccountRoutes()).rejects.toThrow(
'route endpoint unavailable',
)
await Promise.all([loadAccountRoutes(), loadAccountRoutes()])
expect(load).toHaveBeenCalledTimes(2)
expect(register).toHaveBeenCalledOnce()
} finally {
clearAccountRoutes()
router.options.history.destroy()
}
})

View File

@ -2,13 +2,20 @@ import { createMemoryHistory, createRouter } from 'vue-router'
import { APP_CATCH_KEY } from '../../apps/admin/src/app-config'
import { permissionRouter } from '../../apps/admin/src/router/utils/permission'
import { resolveLandingPath } from '../../apps/admin/src/router/utils/resolve-landing-path'
import { setStorage } from '../../apps/admin/src/utils/cache'
vi.mock('../../apps/admin/src/router/utils/valid-role', () => ({
validRole: (meta: { role?: string[] }) =>
!meta.role?.length || meta.role.includes('admin'),
}))
const session: {
signingCallback: { id?: string }
revalidateSession: () => Promise<'active'>
} = {
signingCallback: {},
revalidateSession: async () => 'active',
}
function setupRouter(rootRole?: string[]) {
const component = { render: () => null }
const router = createRouter({
@ -50,13 +57,14 @@ function setupRouter(rootRole?: string[]) {
],
})
permissionRouter(router)
permissionRouter(router, () => session)
return router
}
describe('Router 5 permission guard', () => {
beforeEach(() => {
session.signingCallback = {}
localStorage.clear()
sessionStorage.clear()
})
@ -64,13 +72,15 @@ describe('Router 5 permission guard', () => {
it('redirects unauthenticated protected navigation to login', async () => {
const router = setupRouter()
localStorage.setItem(APP_CATCH_KEY.token, 'unverified-token')
await router.push('/allowed')
expect(router.currentRoute.value.path).toBe('/')
})
it('opens the neutral workspace after login without choosing a business home', async () => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
await router.push('/')
@ -79,7 +89,7 @@ describe('Router 5 permission guard', () => {
})
it('allows permitted roles and authenticated whitelist routes', async () => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
await router.push('/allowed')
@ -92,7 +102,7 @@ describe('Router 5 permission guard', () => {
})
it('shows forbidden state for a denied direct link', async () => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
await router.push('/denied')
@ -107,7 +117,7 @@ describe('Router 5 permission guard', () => {
'/via-private',
'/restricted-group/page',
])('blocks %s and keeps the attempted URL', async (path) => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
const attempted = `${path}?filter=open#row`
@ -123,7 +133,7 @@ describe('Router 5 permission guard', () => {
await router.push(attempted)
expect(router.currentRoute.value.query.redirect).toBe(attempted)
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
expect(
resolveLandingPath(router, router.currentRoute.value.query.redirect),
).toBe('/welcome')
@ -133,7 +143,7 @@ describe('Router 5 permission guard', () => {
const router = setupRouter(['editor'])
await router.push('/')
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
await router.push('/denied')
expect(router.currentRoute.value.path).toBe('/403')
@ -146,7 +156,7 @@ describe('Router 5 permission guard', () => {
expect(router.currentRoute.value.query.redirect).toBe(
'/allowed?filter=open#row-2',
)
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
await router.replace(
resolveLandingPath(router, router.currentRoute.value.query.redirect),
)
@ -156,7 +166,7 @@ describe('Router 5 permission guard', () => {
})
it('preserves query and hash when an authenticated login URL supplies a valid redirect', async () => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
await router.push({
@ -178,7 +188,7 @@ describe('Router 5 permission guard', () => {
])(
'does not restore unsafe, inaccessible or status target %s',
async (redirect) => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
await router.push({ path: '/', query: { redirect } })
@ -193,7 +203,7 @@ describe('Router 5 permission guard', () => {
})
it('shows not found for an unknown authenticated route', async () => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
session.signingCallback = { id: 'verified-test-user' }
const router = setupRouter()
await router.push('/missing?from=test')

View File

@ -34,7 +34,7 @@ it('retains the Mock recovery path after a failed route request', async () => {
expect(routeSourceStatus.active).toBe('static')
})
it('allows explicit offline static routes with a real backend configured', async () => {
it('ignores previously saved static routes when the backend owns runtime routes', async () => {
vi.stubEnv('VITE_API_MOCK', 'false')
localStorage.setItem(
'rayRouteConfig.v1',
@ -42,6 +42,6 @@ it('allows explicit offline static routes with a real backend configured', async
)
const { loadRouteConfig } = await import('@/router/config/source')
await expect(loadRouteConfig()).resolves.toBeUndefined()
expect(getRoutes).not.toHaveBeenCalled()
await expect(loadRouteConfig()).rejects.toThrow('Route backend unavailable')
expect(getRoutes).toHaveBeenCalled()
})

View File

@ -1,6 +1,7 @@
import { setupI18n } from '../../apps/admin/src/locales'
import { setupRouter } from '../../apps/admin/src/router'
import { setupStore } from '../../apps/admin/src/store'
import { piniaSigningStore } from '../../apps/admin/src/store/modules/signing'
import renderHook from '../utils/renderHook'
/**
@ -12,12 +13,18 @@ import renderHook from '../utils/renderHook'
* @example
* const { app } = await setupMiniApp()
*/
const setupMiniApp = async () => {
const setupMiniApp = async (authenticated = false) => {
const [_, app] = renderHook(() => {})
setupStore(app)
await setupI18n(app)
await setupRouter(app)
if (authenticated)
await app.runWithContext(() =>
piniaSigningStore().signing({ name: 'admin', pwd: '123456' }),
)
await setupRouter(app, authenticated)
return {
app,

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,4 @@
import { apiMockEnabled } from '@/api/admin/client'
import AppGlobalSpin from '@/app-components/app/AppGlobalSpin'
import AppLockScreen from '@/app-components/app/AppLockScreen'
import AppNaiveGlobalProvider from '@/app-components/provider/AppNaiveGlobalProvider'
@ -38,7 +39,7 @@ export default defineComponent({
return (
<AppNaiveGlobalProvider>
<AppVersionProvider />
<AppLockScreen />
{apiMockEnabled && <AppLockScreen />}
<AppStyleProvider />
<AppWatermarkProvider />
<AppGlobalSpin>

View File

@ -11,6 +11,9 @@ export const apiMockEnabled =
(import.meta.env.VITE_API_MOCK !== 'false' &&
!import.meta.env.VITE_API_BASE_URL?.trim())
export const browserSessionEnabled =
!apiMockEnabled && import.meta.env.VITE_API_AUTH_TRANSPORT === 'cookie'
export const apiUrl = (path: string) => {
const base =
import.meta.env.VITE_API_BASE_URL?.trim() ||
@ -33,21 +36,54 @@ export class AdminApiError extends Error {
}
}
let sessionVersion = 0
let onUnauthorized: (() => void) | undefined
export const advanceAdminSession = () => ++sessionVersion
export function bindAdminUnauthorized(handler: () => void) {
onUnauthorized = handler
return () => {
if (onUnauthorized === handler) onUnauthorized = void 0
}
}
export async function adminRequest<Schema extends v.GenericSchema>(
path: string,
schema: Schema,
options: AppRawRequestConfig<unknown> = {},
): Promise<v.InferOutput<Schema>> {
let body: unknown
const version = sessionVersion
const url = apiUrl(`admin/${path}`)
if (browserSessionEnabled && new URL(url).origin !== location.origin)
throw new Error('Cookie sessions require a same-origin API base.')
const reportError = (error: AdminApiError): never => {
if (
error.code === 401 &&
path !== 'auth/login' &&
path !== 'auth/session' &&
sessionVersion === version
)
onUnauthorized?.()
throw error
}
try {
const token = getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
const token = browserSessionEnabled
? null
: getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
body = await request<unknown>({
...options,
url: apiUrl(`admin/${path}`),
url,
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(browserSessionEnabled ? { 'X-Ray-Session': 'cookie' } : {}),
...options.headers,
},
cancelConfig: { cancel: false },
@ -58,24 +94,31 @@ export async function adminRequest<Schema extends v.GenericSchema>(
const result = v.safeParse(envelopeSchema, error.response.data)
if (result.success)
throw new AdminApiError(
result.output.code,
result.output.error?.key ?? 'requestFailed',
result.output.msg,
result.output.error?.fields,
return reportError(
new AdminApiError(
result.output.code,
result.output.error?.key ?? 'requestFailed',
result.output.msg,
result.output.error?.fields,
),
)
if (error.response.status === 401)
return reportError(new AdminApiError(401, 'unauthorized', error.message))
throw error
}
const envelope = v.parse(envelopeSchema, body)
if (envelope.code !== 200)
throw new AdminApiError(
envelope.code,
envelope.error?.key ?? 'requestFailed',
envelope.msg,
envelope.error?.fields,
return reportError(
new AdminApiError(
envelope.code,
envelope.error?.key ?? 'requestFailed',
envelope.msg,
envelope.error?.fields,
),
)
return v.parse(schema, envelope.data)

View File

@ -1,8 +1,10 @@
import type { RouteConfig } from '@/router/config/schema'
import { routeConfigSchema } from '@ray-template/routing/schema'
import * as v from 'valibot'
import { adminRequest } from './client'
import { adminRequest, browserSessionEnabled } from './client'
import {
accountProfileSchema,
browserLoginResultSchema,
changedSchema,
loginResultSchema,
sessionSchema,
@ -10,21 +12,44 @@ import {
userOptionsSchema,
userSchema,
} from './contracts'
import type { UserInput, UserListParams, UserStatus } from './contracts'
import type {
ChangePasswordInput,
ProfileInput,
UserInput,
UserListParams,
UserStatus,
} from './contracts'
export const loginAdmin = (username: string, password: string) =>
adminRequest('auth/login', loginResultSchema, {
export const loginAdmin = (username: string, password: string) => {
const options = {
method: 'post',
data: { username, password },
})
}
return browserSessionEnabled
? adminRequest('auth/login', browserLoginResultSchema, options)
: adminRequest('auth/login', loginResultSchema, options)
}
export const getAdminSession = () =>
adminRequest('auth/session', sessionSchema, { method: 'get' })
export const logoutAdmin = () =>
adminRequest('auth/logout', v.null(), { method: 'post' })
export const getAdminRoutes = (view?: 'editor') =>
export const getAccountProfile = (signal?: AbortSignal) =>
adminRequest('auth/profile', accountProfileSchema, { method: 'get', signal })
export const updateAccountProfile = (data: ProfileInput) =>
adminRequest('auth/profile', accountProfileSchema, { method: 'patch', data })
export const changeAccountPassword = (data: ChangePasswordInput) =>
adminRequest('auth/password', v.null(), { method: 'patch', data })
export const setUserCredential = (id: string, newPassword: string) =>
adminRequest(`users/${encodeURIComponent(id)}/credential`, v.null(), {
method: 'put',
data: { newPassword },
})
export const getAdminRoutes = (view?: 'editor', signal?: AbortSignal) =>
adminRequest('route-config', routeConfigSchema, {
method: 'get',
params: view ? { view } : void 0,
signal,
})
export const updateAdminRoutes = (config: RouteConfig) =>
adminRequest('route-config', routeConfigSchema, {

View File

@ -0,0 +1,171 @@
import { AdminApiError } from '@/api/admin/client'
import { credentialInputSchema } from '@/api/admin/contracts'
import { useI18n } from '@/hooks'
import { NAlert, NButton, NForm, NFormItem, NInput } from 'naive-ui'
import * as v from 'valibot'
import type { PropType } from 'vue'
const passwordErrors = new Set([
'invalidCurrentPassword',
'passwordUnchanged',
'credentialChanged',
'forbidden',
'selfProtected',
'notFound',
'tooManyRequests',
])
export default defineComponent({
name: 'AccountPasswordForm',
props: {
username: { type: String, required: true },
requireCurrent: Boolean,
compact: Boolean,
save: {
type: Function as PropType<
(newPassword: string, currentPassword: string) => Promise<void>
>,
required: true,
},
},
setup(props) {
const { t } = useI18n('account')
const current = ref('')
const next = ref('')
const confirmation = ref('')
const error = ref('')
const saving = ref(false)
const currentId = useId()
const newId = useId()
const confirmId = useId()
const hintId = useId()
const newLabelId = useId()
const submit = async (event: Event) => {
event.preventDefault()
if (saving.value) return
if (!v.is(credentialInputSchema, { newPassword: next.value })) {
error.value = t('passwordHint')
return
}
if (next.value !== confirmation.value) {
error.value = t('passwordMismatch')
return
}
error.value = ''
saving.value = true
try {
await props.save(next.value, current.value)
current.value = ''
next.value = ''
confirmation.value = ''
} catch (reason) {
error.value = t(
reason instanceof AdminApiError && passwordErrors.has(reason.key)
? reason.key
: 'saveFailed',
)
} finally {
saving.value = false
}
}
const field = (
label: string,
id: string,
value: Ref<string>,
autocomplete: 'current-password' | 'new-password',
) => (
<NFormItem
class={id === currentId ? 'r-account-password-form__current' : void 0}
label={t(label)}
labelProps={{ for: id }}
required
showRequireMark={props.compact && id === newId ? false : void 0}
>
{{
default: () => (
<NInput
value={value.value}
onUpdateValue={(input) => (value.value = input)}
type="password"
showPasswordOn="click"
disabled={saving.value}
inputProps={{
id,
name: label,
autocomplete,
required: true,
maxlength: 128,
'aria-describedby': id === newId ? hintId : void 0,
'aria-labelledby':
props.compact && id === newId ? newLabelId : void 0,
}}
/>
),
label:
props.compact && id === newId
? () => (
<>
<span id={newLabelId}>{t(label)}</span>
<span
class="r-account-password-form__required"
aria-hidden="true"
>
*
</span>
<span id={hintId} class="r-account-password-form__hint">
{t('passwordHint')}
</span>
</>
)
: void 0,
feedback: () =>
!props.compact &&
id === newId && <span id={hintId}>{t('passwordHint')}</span>,
}}
</NFormItem>
)
return () => (
<NForm
{...{
method: 'post',
autocomplete: props.requireCurrent ? 'on' : 'off',
}}
showFeedback={!props.compact}
onSubmit={submit}
>
{props.requireCurrent && (
<input
type="hidden"
name="username"
value={props.username}
autocomplete="username"
/>
)}
{props.requireCurrent &&
field('currentPassword', currentId, current, 'current-password')}
{field('newPassword', newId, next, 'new-password')}
{field('confirmPassword', confirmId, confirmation, 'new-password')}
{error.value && (
<NAlert type="error" {...{ role: 'alert' }}>
{error.value}
</NAlert>
)}
<div class="r-account-password-form__actions">
<NButton type="primary" attrType="submit" loading={saving.value}>
{t(props.requireCurrent ? 'changePassword' : 'setPassword')}
</NButton>
</div>
</NForm>
)
},
})

View File

@ -0,0 +1,107 @@
import './index.scss'
import { avatarProps, NAvatar } from 'naive-ui'
const center = 20
const fontSize = 26
export const accountAvatarFont = {
fontWeight: 600,
fontFamily: 'system-ui, sans-serif',
}
const segmenter =
typeof Intl.Segmenter === 'function'
? new Intl.Segmenter(void 0, { granularity: 'grapheme' })
: null
export function accountInitial(name: string) {
return segmenter?.segment(name).containing(0)?.segment ?? Array.from(name)[0]
}
let context: CanvasRenderingContext2D | null | undefined
export function measureAccountText(text: string, size: number) {
if (typeof document === 'undefined') return null
if (context === void 0)
context = document.createElement('canvas').getContext('2d')
if (!context) return null
const { fontWeight, fontFamily } = accountAvatarFont
context.font = `${fontWeight} ${size}px ${fontFamily}`
context.textAlign = 'left'
context.textBaseline = 'alphabetic'
context.direction = 'ltr'
return context.measureText(text)
}
export default defineComponent({
name: 'AccountAvatar',
props: {
...avatarProps,
name: { type: String, default: '' },
},
setup(props) {
const initial = computed(() => accountInitial(props.name.trim()) || '?')
const ink = computed(() => measureAccountText(initial.value, fontSize))
const renderInitial = () => {
const bounds = ink.value
// 字形与行框的中心不同,尤其是带下伸笔画的字母。
const x = bounds
? center +
(bounds.actualBoundingBoxLeft - bounds.actualBoundingBoxRight) / 2
: center
const y = bounds
? center +
(bounds.actualBoundingBoxAscent - bounds.actualBoundingBoxDescent) / 2
: center
return (
<svg
class="r-account-avatar__initial"
viewBox="0 0 40 40"
aria-hidden="true"
>
<text
x={x}
y={y}
fill="currentColor"
font-family={accountAvatarFont.fontFamily}
font-size={fontSize}
font-weight={accountAvatarFont.fontWeight}
text-anchor={bounds ? 'start' : 'middle'}
dominant-baseline={bounds ? 'alphabetic' : 'central'}
>
{initial.value}
</text>
</svg>
)
}
return () => {
const { name: _name, ...avatar } = props
return (
<NAvatar
{...avatar}
class="r-account-avatar"
style={avatar.color ? { backgroundColor: avatar.color } : void 0}
renderFallback={
avatar.renderFallback ??
(avatar.fallbackSrc ? void 0 : renderInitial)
}
aria-hidden="true"
>
{{
default: () =>
avatar.src || avatar.imgProps?.src ? null : renderInitial(),
}}
</NAvatar>
)
}
},
})

View File

@ -1,7 +1,33 @@
.app-avatar {
cursor: var(--app-avatar-cursor);
.r-account-avatar {
flex: none;
align-items: center;
justify-content: center;
& .app-avatar__name {
font-weight: 500;
&.n-avatar {
background-color: color-mix(
in srgb,
var(--r-surface) 90%,
var(--r-theme-primary-color)
);
}
&__initial {
display: block;
inline-size: calc(var(--n-merged-size, 32px) * 0.86);
block-size: calc(var(--n-merged-size, 32px) * 0.86);
color: var(--r-text);
}
}
.r-app-avatar__name {
overflow: hidden;
max-inline-size: 12rem;
color: var(--r-text);
line-height: 1.5;
text-overflow: ellipsis;
white-space: nowrap;
&:not(&--measured) {
text-box: trim-both cap alphabetic;
}
}

View File

@ -1,7 +1,14 @@
import { useSigningGetters } from '@/store'
import { avatarProps, NAvatar, NButton, NFlex } from 'naive-ui'
import { avatarProps, NButton, NFlex } from 'naive-ui'
import type { AvatarProps, FlexProps } from 'naive-ui'
import type { PropType } from 'vue'
import AccountAvatar, {
accountAvatarFont,
accountInitial,
measureAccountText,
} from './AccountAvatar'
const captionSize = 14
const AppAvatar = defineComponent({
name: 'AppAvatar',
@ -29,32 +36,84 @@ const AppAvatar = defineComponent({
default: false,
},
},
setup() {
setup(props) {
const { getSigningCallback } = useSigningGetters()
const name = computed(() => getSigningCallback.value.name?.trim() ?? '')
const showName = computed(
() =>
props.vertical ||
!!getSigningCallback.value.avatar ||
!!props.imgProps?.src ||
name.value !== accountInitial(name.value),
)
const captionOffset = computed(() => {
if (!showName.value || !name.value) return null
const metrics = measureAccountText(name.value, captionSize)
if (!metrics) return null
const offset =
(metrics.actualBoundingBoxAscent -
metrics.actualBoundingBoxDescent -
metrics.fontBoundingBoxAscent +
metrics.fontBoundingBoxDescent) /
2
return Number.isFinite(offset) ? offset : null
})
return {
getSigningCallback,
name,
showName,
captionOffset,
}
},
render() {
const { getSigningCallback, avatarSize, spaceSize, $props, vertical } = this
const {
getSigningCallback,
avatarSize,
spaceSize,
$props,
vertical,
name,
showName,
captionOffset,
} = this
return (
<NButton quaternary strong style={{ cursor: this.cursor }}>
<NButton
quaternary
strong
style={{ cursor: this.cursor }}
{...{ 'aria-label': showName ? void 0 : name }}
>
<NFlex align="center" size={spaceSize} vertical={vertical}>
<NAvatar
<AccountAvatar
{...($props as AvatarProps)}
name={name}
src={getSigningCallback?.avatar}
size={avatarSize ?? this.size}
>
{{
default: () =>
getSigningCallback.avatar
? null
: getSigningCallback?.name?.[0],
}}
</NAvatar>
{getSigningCallback?.name}
/>
{showName && (
<span
class={[
'r-app-avatar__name',
{ 'r-app-avatar__name--measured': captionOffset !== null },
]}
style={{
...accountAvatarFont,
fontSize: `${captionSize}px`,
transform:
captionOffset === null
? void 0
: `translateY(${captionOffset}px)`,
}}
>
{name}
</span>
)}
</NFlex>
</NButton>
)

View File

@ -4,6 +4,12 @@ import { appendRequestHeaders } from '@/axios/utils/append-request-headers'
import { getStorage } from '@/utils/cache'
const injectRequestHeaders: AxiosRequestInterceptor = (config) => {
if (
import.meta.env.VITE_API_MOCK !== 'true' &&
import.meta.env.VITE_API_AUTH_TRANSPORT === 'cookie'
)
return
const token = getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
if (

View File

@ -202,8 +202,8 @@ export default defineComponent({
</NButton>
</NDropdown>
<NDropdown
options={createAvatarOptions()}
onSelect={avatarDropdownClick.bind(this)}
options={createAvatarOptions(this.t)}
onSelect={(key) => void avatarDropdownClick(key)}
trigger="click"
>
<AppAvatar

View File

@ -1,18 +1,18 @@
import { apiMockEnabled } from '@/api/admin/client'
import { useI18n } from '@/hooks'
import { router } from '@/router'
import { ACCOUNT_PROFILE_PATH } from '@/router/constant'
import { useSettingActions, useSigningActions } from '@/store'
import type { IconOptions, IconOptionsFC } from './type'
/**
*
* 创建头像点击下拉菜单
*/
export const createAvatarOptions = () => [
export const createAvatarOptions = (t: ReturnType<typeof useI18n>['t']) => [
{
key: 'person',
label: '个人信息',
label: t('account.profile'),
},
{
key: 'lockScreen',
label: '锁定屏幕',
label: t(apiMockEnabled ? 'account.lockScreen' : 'account.lockSession'),
},
{
type: 'divider',
@ -20,50 +20,46 @@ export const createAvatarOptions = () => [
},
{
key: 'logout',
label: '退出登陆',
label: t('account.signOut'),
},
]
/**
*
* 头像 Dropdown 下拉点击事件 map
*/
const avatarDropdownActionMap = {
/**
*
* 退出登陆
* 清除所有 session 缓存并且重定向至登录页
*/
logout: () => {
const { logout } = useSigningActions()
export const avatarDropdownClick = async (key: string | number) => {
const { t } = useI18n('account')
const { logout } = useSigningActions()
const signOut = async (redirect?: string) => {
try {
await logout(redirect)
return true
} catch {
window.$message.error(t('signOutFailed'))
return false
}
}
if (key === 'person') {
await router.push(ACCOUNT_PROFILE_PATH)
return
}
if (key === 'logout') {
window.$dialog.warning({
title: '提示',
content: '您确定要退出登录吗',
positiveText: '确定',
negativeText: '不确定',
onPositiveClick: () => {
logout()
},
title: t('signOut'),
content: t('signOutPrompt'),
positiveText: t('signOut'),
negativeText: t('cancel'),
onPositiveClick: () => signOut(),
})
},
/**
*
* 锁定屏幕
*/
lockScreen: () => {
const { updateSettingState } = useSettingActions()
}
updateSettingState('lockScreenSwitch', true)
},
}
export const avatarDropdownClick = (
key: keyof typeof avatarDropdownActionMap,
) => {
const action = avatarDropdownActionMap[key]
action ? action() : window.$message.info('这个人很懒, 没做这个功能~')
if (key === 'lockScreen') {
if (apiMockEnabled)
useSettingActions().updateSettingState('lockScreenSwitch', true)
else await signOut(router.currentRoute.value.fullPath)
}
}
/**

View File

@ -1,3 +1,4 @@
import { apiMockEnabled } from '@/api/admin/client'
import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar'
import UnlockScreen from '@/app-components/app/AppLockScreen/components/UnlockScreen'
import { LAYOUT_CONTENT_REF } from '@/app-config'
@ -43,7 +44,7 @@ export default defineComponent({
)
return () => {
if (getLockAppScreen()) return <UnlockScreen />
if (apiMockEnabled && getLockAppScreen()) return <UnlockScreen />
const grouped = mode.value === 'mixed' || mode.value === 'split'

View File

@ -0,0 +1,50 @@
{
"eyebrow": "Account settings",
"profile": "My profile",
"description": "Manage your profile and sign-in security.",
"details": "Account overview",
"editProfile": "Personal details",
"profileNavHint": "Name and contact",
"profileHint": "Edit your display name and phone. Your admin manages your username and email.",
"securitySection": "Sign-in security",
"securityNavHint": "Change your password",
"username": "Username",
"email": "Email",
"department": "Department",
"role": "Role",
"name": "Display name",
"phone": "Phone",
"saveProfile": "Save profile",
"profileSaved": "Profile saved.",
"invalidProfile": "Enter a display name and a valid phone number, or leave the phone number blank.",
"loadFailed": "Could not load your profile.",
"saveFailed": "Could not save your changes. Try again.",
"retry": "Retry",
"changePassword": "Change password",
"currentPassword": "Current password",
"newPassword": "New password",
"confirmPassword": "Confirm new password",
"passwordHint": "Use 12 to 128 characters.",
"passwordMismatch": "The new passwords do not match.",
"invalidCurrentPassword": "The current password is incorrect.",
"passwordUnchanged": "Choose a password different from your current password.",
"credentialChanged": "Your credentials changed in another session. Sign in again before retrying.",
"tooManyRequests": "Too many attempts. Wait before trying again.",
"revokeNotice": "Changing your password signs you out on all devices.",
"passwordChanged": "Password changed. Sign in with your new password.",
"setPassword": "Set password",
"setPasswordFor": "Set password for {name}",
"credentialNotice": "Setting a password signs this account out on all devices.",
"credentialSaved": "Password set.",
"demoPasswordNotice": "This is a local demo. Use a password you do not use elsewhere.",
"userCreated": "User created. Set a password to enable sign-in.",
"forbidden": "You do not have permission to change this credential.",
"selfProtected": "Use My profile to change your own password.",
"notFound": "This account no longer exists.",
"lockScreen": "Lock screen",
"lockSession": "Lock and require sign-in",
"signOut": "Sign out",
"signOutPrompt": "End your session on this device?",
"signOutFailed": "Could not end the session. Try again when the server is available.",
"cancel": "Cancel"
}

View File

@ -1,7 +1,7 @@
{
"eyebrow": "WORKSPACE / ROUTING",
"title": "Route JSON configuration",
"description": "Switch route sources, preview the menu and validate page configuration as JSON.",
"description": "Preview, validate and edit menu and page configuration as JSON.",
"active": "Active · {source}",
"fallback": "API loading failed; using initial routes",
"source": "Route source",
@ -10,7 +10,7 @@
"remote": "Server API",
"staticHint": "Use initial JSON routes for offline recovery. Select the server API for the online experience.",
"localHint": "Validate and save the JSON in this browser. Applying changes reloads the page.",
"remoteHint": "Routes are fetched through the API at startup. Saving submits the current JSON and reloads. If loading fails, the initial configuration is used with an error notice.",
"remoteHint": "Signing in loads the pages your account can access. Saving submits the complete configuration and reloads the workspace.",
"apply": "Save and apply",
"manifest": "Route configuration",
"loadStatic": "Load initial configuration",
@ -38,11 +38,11 @@
"visualTitle": "Visual route editor",
"visualDescription": "Select a menu item to edit its path, view and access rules.",
"visualDraft": "Route configuration draft",
"visualHint": "The draft starts from active routes. Saving submits it through the API and reloads the app. The online demo persists it in this browser’s Mock database.",
"visualHint": "The draft includes saved routes that are hidden from your current menu. Saving reloads the workspace.",
"validateDraft": "Validate",
"draftValid": "Configuration is valid",
"resetDraft": "Reload active configuration",
"resetConfirm": "Discard your draft changes and reload the active configuration?",
"resetDraft": "Reload configuration",
"resetConfirm": "Discard your draft changes and reload the saved configuration?",
"addRoot": "Add top-level item",
"addChild": "Add child item",
"editNode": "Edit menu item",

View File

@ -1,5 +1,6 @@
{
"Register": "Register",
"PageTitle": "Sign in - Ray Admin",
"Signing": "Sign in",
"QRCodeSigning": "QR code",
"NamePlaceholder": "please enter user name",
@ -18,7 +19,10 @@
"AccessDescription": "Explore the workspace and component demos using the demo account.",
"AccountDescription": "Sign in with your administrator or provisioned account.",
"UseDemo": "Continue with demo account",
"SignInError": "Sign-in failed. Please try again.",
"SignInError": "The username or password is incorrect.",
"SignInUnavailable": "Could not sign in. Check the connection and try again.",
"RateLimit": "Too many sign-in attempts. Wait before trying again.",
"RouteLoadError": "Could not load your workspace. Try signing in again.",
"RegisterHint": "This registration example is ready to connect to your account service.",
"Provider": "Sign in with {provider}",
"ProviderHint": "The {provider} sign-in option is a demo.",

View File

@ -0,0 +1,50 @@
{
"eyebrow": "账号设置",
"profile": "个人信息",
"description": "管理你的个人资料和登录安全。",
"details": "账号概览",
"editProfile": "个人资料",
"profileNavHint": "名称与联系方式",
"profileHint": "可修改显示名称和手机号码。用户名和邮箱由管理员维护。",
"securitySection": "安全与密码",
"securityNavHint": "修改登录密码",
"username": "用户名",
"email": "邮箱",
"department": "部门",
"role": "角色",
"name": "显示名称",
"phone": "手机号码",
"saveProfile": "保存资料",
"profileSaved": "资料已保存。",
"invalidProfile": "请输入显示名称。手机号码可以留空,填写时请使用有效格式。",
"loadFailed": "无法加载个人信息。",
"saveFailed": "保存失败,请重试。",
"retry": "重试",
"changePassword": "修改密码",
"currentPassword": "当前密码",
"newPassword": "新密码",
"confirmPassword": "确认新密码",
"passwordHint": "密码长度为 12 至 128 个字符。",
"passwordMismatch": "两次输入的新密码不一致。",
"invalidCurrentPassword": "当前密码不正确。",
"passwordUnchanged": "新密码不能与当前密码相同。",
"credentialChanged": "凭据已在其他会话中更新,请重新登录后重试。",
"tooManyRequests": "尝试次数过多,请稍后再试。",
"revokeNotice": "修改密码后,所有设备都需要重新登录。",
"passwordChanged": "密码已修改,请使用新密码登录。",
"setPassword": "设置密码",
"setPasswordFor": "为 {name} 设置密码",
"credentialNotice": "设置密码后,此账号在所有设备上都需要重新登录。",
"credentialSaved": "密码已设置。",
"demoPasswordNotice": "这是本地演示,请使用未在其他站点使用过的密码。",
"userCreated": "用户已创建,设置密码后即可登录。",
"forbidden": "你没有权限修改该账号的凭据。",
"selfProtected": "请在个人信息页修改自己的密码。",
"notFound": "该账号已不存在。",
"lockScreen": "锁定屏幕",
"lockSession": "锁定并要求重新登录",
"signOut": "退出登录",
"signOutPrompt": "确定结束当前设备上的会话吗?",
"signOutFailed": "无法结束会话,请在服务恢复后重试。",
"cancel": "取消"
}

View File

@ -1,7 +1,7 @@
{
"eyebrow": "WORKSPACE / ROUTING",
"title": "路由 JSON 配置",
"description": "切换路由来源,预览并校验菜单和页面的 JSON 配置。",
"description": "预览、校验并维护菜单和页面的 JSON 配置。",
"active": "当前生效 · {source}",
"fallback": "接口加载失败,已使用内置初始配置",
"source": "路由来源",
@ -10,7 +10,7 @@
"remote": "服务端接口",
"staticHint": "使用内置 JSON 初始配置,适合离线恢复。正常在线体验请选择服务端接口。",
"localHint": "校验并保存编辑器中的 JSON,仅在此浏览器生效。应用设置时会重新加载页面。",
"remoteHint": "启动时通过接口读取路由;保存会提交当前 JSON 并重新加载。请求失败时使用内置初始配置并显示原因。",
"remoteHint": "登录后加载当前账号可访问的页面。保存会提交完整配置并刷新工作区。",
"apply": "保存并应用",
"manifest": "路由配置",
"loadStatic": "载入初始配置",
@ -38,11 +38,11 @@
"visualTitle": "路由可视化配置",
"visualDescription": "从菜单树选择一项,直接编辑它的路径、页面与访问规则。",
"visualDraft": "路由配置草稿",
"visualHint": "草稿从当前生效配置开始。保存时通过接口提交并重新加载;在线演示会持久化到当前浏览器的 Mock 数据库。",
"visualHint": "草稿包含已保存的配置,包括当前菜单里不可见的页面。保存后刷新工作区。",
"validateDraft": "校验配置",
"draftValid": "校验通过",
"resetDraft": "重载生效配置",
"resetConfirm": "放弃草稿改动,重新读取当前生效的配置?",
"resetDraft": "重新读取配置",
"resetConfirm": "放弃草稿改动,重新读取已保存的配置?",
"addRoot": "添加一级菜单",
"addChild": "添加子菜单",
"editNode": "编辑菜单项",

View File

@ -1,5 +1,6 @@
{
"Register": "注册",
"PageTitle": "登录 - Ray Admin",
"Signing": "登录",
"QRCodeSigning": "二维码",
"NamePlaceholder": "请输入用户名",
@ -18,7 +19,10 @@
"AccessDescription": "使用演示账号探索工作台与组件示例。",
"AccountDescription": "使用管理员或已开通的账号登录工作台。",
"UseDemo": "使用演示账号进入",
"SignInError": "登录失败,请重试。",
"SignInError": "用户名或密码不正确。",
"SignInUnavailable": "暂时无法登录,请检查连接后重试。",
"RateLimit": "登录尝试次数过多,请稍后再试。",
"RouteLoadError": "无法加载你的工作区,请重试登录。",
"RegisterHint": "此页面是注册流程的接入示例,可连接项目的账号服务。",
"Provider": "通过 {provider} 登录",
"ProviderHint": "{provider} 登录是演示入口。",

View File

@ -1,7 +1,7 @@
import App from './App'
import './styles/entry'
import type { App as AppType } from 'vue'
import { apiMockEnabled } from './api/admin/client'
import { apiMockEnabled, bindAdminUnauthorized } from './api/admin/client'
import { installAutocompleteDefaults } from './app-components/provider/AppAutocompleteDefaults'
import { GLOBAL_CLASS_NAMES } from './app-config'
import { setupDayjs } from './dayjs'
@ -10,7 +10,10 @@ import { runAppDoctor } from './doctor'
import { setupI18n } from './locales'
import { setupRouter } from './router'
import { setupStore } from './store'
import { piniaSigningStore } from './store/modules/signing'
import {
adminSessionChangeKey,
piniaSigningStore,
} from './store/modules/signing'
const bootSplash = () =>
document.getElementById(GLOBAL_CLASS_NAMES.preLoadingAnimation)
@ -38,8 +41,20 @@ const setupPlugins = async (inst: AppType<Element>) => {
setupStore(inst)
await setupI18n(inst)
await inst.runWithContext(() => piniaSigningStore().restoreSession())
await setupRouter(inst)
const signing = inst.runWithContext(() => piniaSigningStore())
await signing.restoreSession()
await setupRouter(inst, !!signing.signingCallback.id)
const unbindUnauthorized = bindAdminUnauthorized(signing.expireSession)
const syncSession = (event: StorageEvent) => {
if (event.key === adminSessionChangeKey) location.reload()
}
window.addEventListener('storage', syncSession)
inst.onUnmount(() => {
unbindUnauthorized()
window.removeEventListener('storage', syncSession)
})
setupDayjs()
setupDirectives(inst)
inst.onUnmount(installAutocompleteDefaults(document.body))

View File

@ -1,8 +1,11 @@
import {
changePasswordSchema,
credentialInputSchema,
idsSchema,
loginInputSchema,
loginResultSchema,
permissionCodes,
profileInputSchema,
statusInputSchema,
userInputSchema,
userListQuerySchema,
@ -16,6 +19,7 @@ import type {
} from '@/api/admin/contracts'
import { parseRouteConfig } from '@/router/config/contract'
import type { RouteConfig } from '@/router/config/schema'
import { filterRuntimeRoutes } from '@ray-template/api-contracts/routes'
import { initialRoutes } from '@ray-template/demo-data'
import * as v from 'valibot'
import { createInitialUsers, initialUserOptions } from './data/users'
@ -46,13 +50,33 @@ const snapshotSchema = v.object({
users: v.array(userSchema),
routes: v.unknown(),
sessions: v.array(loginResultSchema),
credentials: v.optional(
v.array(
v.object({
userId: v.string(),
salt: v.string(),
digest: v.string(),
}),
),
[],
),
})
async function demoDigest(password: string, salt: string) {
const bytes = new TextEncoder().encode(`${salt}:${password}`)
const digest = await crypto.subtle.digest('SHA-256', bytes)
return Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('')
}
export function createAdminDatabase(storage?: Storage) {
const key = 'rayMockAdmin.v1'
let users = createInitialUsers()
let routes = parseRouteConfig(JSON.stringify(initialRoutes))
let sessions: v.InferOutput<typeof loginResultSchema>[] = []
let credentials: v.InferOutput<typeof snapshotSchema>['credentials'] = []
try {
const raw = storage?.getItem(key)
@ -66,6 +90,7 @@ export function createAdminDatabase(storage?: Storage) {
users = value.users
routes = parsedRoutes
credentials = value.credentials
sessions = value.sessions.filter(
(session) => Date.parse(session.expiresAt) > Date.now(),
)
@ -78,11 +103,19 @@ export function createAdminDatabase(storage?: Storage) {
users?: AdminUser[]
routes?: RouteConfig
sessions?: typeof sessions
credentials?: typeof credentials
}) => {
try {
storage?.setItem(
key,
JSON.stringify({ version: 1, users, routes, sessions, ...next }),
JSON.stringify({
version: 1,
users,
routes,
sessions,
credentials,
...next,
}),
)
} catch {
throw new MockApiError(503, 'storage')
@ -91,6 +124,7 @@ export function createAdminDatabase(storage?: Storage) {
users = next.users ?? users
routes = next.routes ?? routes
sessions = next.sessions ?? sessions
credentials = next.credentials ?? credentials
}
const profile = (user: AdminUser): SessionInfo => ({
user: {
@ -115,14 +149,14 @@ export function createAdminDatabase(storage?: Storage) {
(item) => item.id === session.user.id && item.status === 'enabled',
)
if (!user) throw new MockApiError(401, 'unauthorized')
if (!user || !session) throw new MockApiError(401, 'unauthorized')
const result = profile(user)
if (permission && !result.permissions.includes(permission))
throw new MockApiError(403, 'forbidden')
return result
return { ...result, expiresAt: session.expiresAt }
}
const parseInput = <S extends v.GenericSchema>(
schema: S,
@ -141,6 +175,38 @@ export function createAdminDatabase(storage?: Storage) {
return user
}
const accountProfile = (user: AdminUser) => ({
...profile(user).user,
email: user.email,
phone: user.phone,
department: initialUserOptions.departments.find(
({ id }) => id === user.departmentId,
)!,
})
const matchesPassword = async (user: AdminUser, password: string) => {
const credential = credentials.find(({ userId }) => userId === user.id)
return credential
? (await demoDigest(password, credential.salt)) === credential.digest
: user.id.startsWith('demo-user-') && password === '123456'
}
const replacePassword = async (
userId: string,
password: string,
recheck: () => void,
) => {
const salt = crypto.randomUUID()
const digest = await demoDigest(password, salt)
recheck()
commit({
credentials: [
...credentials.filter((entry) => entry.userId !== userId),
{ userId, salt, digest },
],
sessions: sessions.filter((entry) => entry.user.id !== userId),
})
}
const validateUser = (input: unknown, id?: string): UserInput => {
const value = parseInput(userInputSchema, input)
@ -193,21 +259,31 @@ export function createAdminDatabase(storage?: Storage) {
return {
authorize,
login(input: unknown) {
async login(input: unknown) {
const { username, password } = parseInput(loginInputSchema, input)
const aliases: Record<string, string> = {
'Ray Admin': 'user001',
admin: 'user001',
manager: 'user011',
member: 'user002',
}
const aliases = new Map(
Object.entries({
'ray admin': 'user001',
admin: 'user001',
manager: 'user011',
member: 'user002',
}),
)
const key = username.toLowerCase()
const user = users.find(
(item) =>
item.username === (aliases[username] ?? username) &&
item.username.toLowerCase() === (aliases.get(key) ?? key) &&
item.status === 'enabled',
)
if (!user || password !== '123456')
const snapshot = credentials
if (
!user ||
!(await matchesPassword(user, password)) ||
snapshot !== credentials ||
!users.includes(user)
)
throw new MockApiError(401, 'invalidCredentials')
const session = {
@ -226,14 +302,70 @@ export function createAdminDatabase(storage?: Storage) {
return session
},
logout(token: string | null) {
authorize(token)
commit({
sessions: sessions.filter((item) => item.accessToken !== token),
})
return null
},
getRoutes() {
return structuredClone(routes)
getRoutes(token: string | null, editor = false) {
const session = authorize(token, editor ? 'routes:write' : void 0)
return structuredClone(
editor
? routes
: filterRuntimeRoutes(routes, {
role: session.user.role,
permissions: session.permissions,
demoEnabled: true,
}),
)
},
getProfile(token: string | null) {
return accountProfile(findUser(authorize(token).user.id))
},
updateProfile(input: unknown, token: string | null) {
const user = findUser(authorize(token).user.id)
const updated = { ...user, ...parseInput(profileInputSchema, input) }
commit({
users: users.map((item) => (item.id === user.id ? updated : item)),
})
return accountProfile(updated)
},
async changePassword(input: unknown, token: string | null) {
const user = findUser(authorize(token).user.id)
const { currentPassword, newPassword } = parseInput(
changePasswordSchema,
input,
)
if (!(await matchesPassword(user, currentPassword)))
throw new MockApiError(400, 'invalidCurrentPassword')
if (currentPassword === newPassword)
throw new MockApiError(400, 'passwordUnchanged')
await replacePassword(user.id, newPassword, () => authorize(token))
return null
},
async setCredential(id: string, input: unknown, token: string | null) {
const { newPassword } = parseInput(credentialInputSchema, input)
const recheck = () => {
const session = authorize(token, 'users:credentials')
if (session.user.id === id) throw new MockApiError(409, 'selfProtected')
assertEditable(session, findUser(id))
}
recheck()
await replacePassword(id, newPassword, recheck)
return null
},
saveRoutes(input: unknown, token: string | null) {
authorize(token, 'routes:write')
@ -317,6 +449,13 @@ export function createAdminDatabase(storage?: Storage) {
)
throw new MockApiError(409, 'selfProtected')
if (
existing &&
existing.status !== value.status &&
!session.permissions.includes('users:status')
)
throw new MockApiError(403, 'forbidden')
const user = {
...value,
id: existing?.id ?? crypto.randomUUID(),
@ -327,6 +466,10 @@ export function createAdminDatabase(storage?: Storage) {
users: existing
? users.map((item) => (item.id === id ? user : item))
: [user, ...users],
...(existing &&
(existing.role !== user.role || user.status === 'disabled')
? { sessions: sessions.filter((entry) => entry.user.id !== user.id) }
: {}),
})
return structuredClone(user)
@ -346,7 +489,11 @@ export function createAdminDatabase(storage?: Storage) {
const remaining = users.filter((item) => !ids.includes(item.id))
const affected = users.length - remaining.length
commit({ users: remaining })
commit({
users: remaining,
sessions: sessions.filter((entry) => !ids.includes(entry.user.id)),
credentials: credentials.filter((entry) => !ids.includes(entry.userId)),
})
return { affected }
},
@ -365,6 +512,13 @@ export function createAdminDatabase(storage?: Storage) {
users: users.map((user) =>
ids.includes(user.id) ? { ...user, status } : user,
),
...(status === 'disabled'
? {
sessions: sessions.filter(
(entry) => !ids.includes(entry.user.id),
),
}
: {}),
})
return { affected: new Set(ids).size }
@ -373,7 +527,13 @@ export function createAdminDatabase(storage?: Storage) {
authorize(token, 'users:reset')
const next = createInitialUsers()
commit({ users: next })
commit({
users: next,
credentials: credentials.filter(
(entry) => entry.userId === authorize(token).user.id,
),
sessions: sessions.filter((entry) => entry.accessToken === token),
})
return { affected: next.length }
},

View File

@ -131,18 +131,27 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
http.post(url('admin/auth/logout'), ({ request }) =>
respond(() => database.logout(token(request))),
),
http.get(url('admin/auth/profile'), ({ request }) =>
respond(() => database.getProfile(token(request))),
),
http.patch(url('admin/auth/profile'), ({ request }) =>
respond(async () =>
database.updateProfile(await request.json(), token(request)),
),
),
http.patch(url('admin/auth/password'), ({ request }) =>
respond(async () =>
database.changePassword(await request.json(), token(request)),
),
),
http.get(url('admin/route-config'), ({ request }) =>
respond(() => {
const view = new URL(request.url).searchParams.getAll('view')
if (view.length) {
if (view.length !== 1 || view[0] !== 'editor')
throw new MockApiError(400, 'invalid')
if (view.length && (view.length !== 1 || view[0] !== 'editor'))
throw new MockApiError(400, 'invalid')
database.authorize(token(request), 'routes:write')
}
return database.getRoutes()
return database.getRoutes(token(request), view[0] === 'editor')
}),
),
http.put(url('admin/route-config'), ({ request }) =>
@ -191,6 +200,15 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
),
),
),
http.put(url('admin/users/:id/credential'), ({ request, params }) =>
respond(async () =>
database.setCredential(
String(params.id),
await request.json(),
token(request),
),
),
),
http.get(url('admin/demo/people'), ({ request }) =>
respond(async () => {
const query = readQuery(request, personListQuerySchema)

View File

@ -2,18 +2,18 @@
## Switching route sources
After login, open **路由管理** (Route management). Both child pages are registered by the application shell and use the same `admin` role guard.
After login, open **路由管理** (Route management). Both shell pages require the `routes:write` grant.
- **可视化配置** (Visual configuration, `/#/route-management/visual`): Edit pages, groups, redirects, and external links from the active menu tree. Adjust order, roles, visibility, and caching. Validate/export drafts or apply and reload. Saving and reloading use the standard API; mock-database changes apply only to the current browser. Drafts preserve advanced fields such as existing aliases and page props.
- **JSON 配置** (JSON configuration, `/#/route-management/json`): Manage static, browser-local, or backend sources. Edit/import full JSON, validate and preview the tree, and export JSON, standard JSON Schema, and available view IDs. The old `/#/route-management` URL redirects here.
| Source | Read behavior | Applying changes |
| ------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Static routes | Read the bundled [initial JSON](../mocks/data/routes.json) | Select static routes and apply |
| Local JSON | Read configuration saved in the current browser | Import a file or edit JSON, validate, then apply |
| Backend API | Request deployment-configured `VITE_ROUTE_CONFIG_URL` at startup | Select the backend source and apply. The URL comes from frontend deployment configuration. |
| Source | Read behavior | Applying changes |
| ------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------- |
| Static routes | Read the bundled [initial JSON](../../../../packages/demo-data/src/routes.json) | Select and apply in Mock or legacy route mode |
| Local JSON | Read configuration saved in the current browser | Import or edit JSON in Mock or legacy route mode |
| Backend API | Read the signed-in account’s `GET /admin/route-config` snapshot | Authorized editors save through `PUT /admin/route-config` |
Applying reloads the page and rebuilds route matching, menus, and tabs. With an API URL configured, a new browser defaults to the backend source. Explicit source choices are stored in the current browser. In real-backend mode, a failed configured remote source stops startup and shows the boot error; it does not silently substitute demo routes. The shell retains login, management, `/welcome`, `/403`, `/404`, and `/500`. No dashboard or other business page is injected into a custom source.
Applying reloads the page and rebuilds route matching, menus and tabs. The standard API mode uses the server snapshot regardless of saved source preferences, and fails closed on read errors. The shell retains login, profile, management, `/welcome`, `/403`, `/404` and `/500`. An empty snapshot never falls back to bundled pages.
## Neutral workspace and recovery
@ -21,13 +21,13 @@ Applying reloads the page and rebuilds route matching, menus, and tabs. With an
All business tabs, including the former home and the final tab, can close. Closing an active tab selects its adjacent remaining tab; closing the final tab or all tabs opens `/welcome` and removes their cached component names. One tab is retained per concrete pathname, with its latest full URL for query/hash restoration. System states clear active menu/breadcrumb state without fabricating a first-menu selection.
Authenticated forbidden direct links go to `/403`; unknown paths go to `/404`; route resolution or lazy-loader failures go to `/500`. Status routes carry the original attempted URL in `query.from`. The tab bar can close a 403 and return to an authorized previous page, a remaining tab, or the workspace. Recovery targets are checked through `resolveLandingPath`. Role changes prune unauthorized tabs and cached views and show `/403` for a revoked current page.
A denied registered route goes to `/403`; paths omitted from the account snapshot and unknown paths go to `/404`; route loading failures go to `/500`. Status pages keep the attempted address in `query.from`. Recovery checks destinations through `resolveLandingPath`. Session invalidation removes installed business routes; server-side grants continue to protect every API request.
System paths (including descendants and aliases) and route names are reserved by the application contract. The generic contract accepts `reservedPaths` and `reservedNames` supplied by its host. `homePath` is retained only as an ignored deprecated catalog option. Application `useAppRoot`/`appRootRoute` remain inert legacy preference accessors to avoid breaking stored settings and old consumers; they no longer affect landing, closing, permissions, or startup validation. The root-setting demo controls were removed. The old `redirectRouterToDashboard` export is a deprecated alias for neutral `redirectRouterToWorkspace`.
## Backend and AI contract
Set `VITE_ROUTE_CONFIG_URL=/api/route-config` at deployment, or use an HTTPS URL with CORS enabled. The client sends `GET`, accepts `application/json`, and times out after 5 seconds. Same-origin requests can use session cookies. Standard APIs place the route JSON below in `data` within `{ code: 200, msg: "OK", data }`; import/export uses route JSON directly. Legacy `VITE_ROUTE_CONFIG_URL` also accepts raw JSON. See the [backend contract](../../../docs/guide/backend.md) for the complete read/write API.
The standard API returns route JSON as `data` in the shared envelope. The explicit legacy `VITE_ROUTE_CONFIG_URL` is a read-only raw JSON source; use a same-origin URL or HTTPS with CORS enabled. See the [backend contract](../../../docs/guide/backend.md) for the complete API.
```json
{

View File

@ -10,7 +10,7 @@ const managementRoute: AppRouteRecordRaw = {
meta: {
i18nKey: 'menu.RouteManagement',
icon: 'action/setting',
role: ['admin'],
requiredPermission: 'routes:write',
order: 100,
},
children: [
@ -18,13 +18,19 @@ const managementRoute: AppRouteRecordRaw = {
path: 'visual',
name: 'RouteManagementVisual',
component: () => import('@/views/route-management/visual'),
meta: { i18nKey: 'menu.RouteManagementVisual' },
meta: {
i18nKey: 'menu.RouteManagementVisual',
requiredPermission: 'routes:write',
},
},
{
path: 'json',
name: 'RouteManagement',
component: () => import('@/views/route-management'),
meta: { i18nKey: 'menu.RouteManagementJson' },
meta: {
i18nKey: 'menu.RouteManagementJson',
requiredPermission: 'routes:write',
},
},
],
}

View File

@ -1,9 +1,12 @@
import {
ACCOUNT_PROFILE_NAME,
ACCOUNT_PROFILE_PATH,
LAYOUT,
ROUTE_MANAGEMENT_PATH,
SYSTEM_ROUTE_NAMES,
SYSTEM_ROUTE_PATHS,
} from '@/router/constant'
import { routeViewPermission } from '@ray-template/api-contracts/routes'
import { createRouteContract } from '@ray-template/routing/contract'
import { findRouteView, findRouteViewId } from './views'
@ -12,10 +15,12 @@ export const { parseRouteConfig, toRuntimeRoutes, exportRouteConfig } =
layout: LAYOUT,
findRouteView,
findRouteViewId,
viewPermission: routeViewPermission,
managementPath: ROUTE_MANAGEMENT_PATH,
reservedPaths: SYSTEM_ROUTE_PATHS,
reservedPaths: [...SYSTEM_ROUTE_PATHS, ACCOUNT_PROFILE_PATH],
reservedNames: [
...SYSTEM_ROUTE_NAMES,
ACCOUNT_PROFILE_NAME,
'RLogin',
'RLayout',
'RNotFound',

View File

@ -14,8 +14,12 @@ const storageKey = 'rayRouteConfig.v1'
export const remoteRouteUrl =
import.meta.env.VITE_ROUTE_CONFIG_URL?.trim() || apiUrl('admin/route-config')
export const serverRoutesRequired =
!apiMockEnabled && !import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()
function readPreference(): Preference {
if (serverRoutesRequired) return { source: 'remote' }
try {
const stored: unknown = JSON.parse(
localStorage.getItem(storageKey) ?? 'null',
@ -49,11 +53,12 @@ export const routeSourceStatus: {
export async function fetchRemoteRouteConfig(
view?: 'editor',
signal?: AbortSignal,
): Promise<RouteConfig> {
if (!import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()) {
const { parseRouteConfig } = await import('./contract')
return parseRouteConfig(JSON.stringify(await getAdminRoutes(view)))
return parseRouteConfig(JSON.stringify(await getAdminRoutes(view, signal)))
}
if (!remoteRouteUrl) throw new Error('VITE_ROUTE_CONFIG_URL is missing.')
@ -67,7 +72,9 @@ export async function fetchRemoteRouteConfig(
const { parseRouteConfig } = await import('./contract')
const response = await fetch(url, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(5000),
signal: signal
? AbortSignal.any([signal, AbortSignal.timeout(5000)])
: AbortSignal.timeout(5000),
cache: 'no-cache',
redirect: 'error',
credentials: 'same-origin',
@ -89,22 +96,28 @@ export async function saveRemoteRouteConfig(config: RouteConfig) {
saveRouteSource('remote')
}
export async function loadRouteConfig(): Promise<RouteConfig | undefined> {
export async function loadRouteConfig(
signal?: AbortSignal,
): Promise<RouteConfig | undefined> {
if (preference.source === 'static') return
try {
const config =
preference.source === 'remote'
? await fetchRemoteRouteConfig()
? await fetchRemoteRouteConfig(void 0, signal)
: (await import('./contract')).parseRouteConfig(
JSON.stringify(preference.local ?? null),
)
signal?.throwIfAborted()
routeSourceStatus.active = preference.source
routeSourceStatus.config = config
routeSourceStatus.error = void 0
return config
} catch (error) {
if (signal?.aborted) throw error
routeSourceStatus.error =
error instanceof Error ? error.message : String(error)
@ -113,9 +126,18 @@ export async function loadRouteConfig(): Promise<RouteConfig | undefined> {
}
export function saveRouteSource(source: RouteSource, local = preference.local) {
if (serverRoutesRequired && source !== 'remote')
throw new Error('The configured backend owns runtime routes.')
localStorage.setItem(storageKey, JSON.stringify({ source, local }))
sessionStorage.removeItem(APP_CATCH_KEY.appMenuTagOptions)
sessionStorage.removeItem(APP_CATCH_KEY.appMenuKey)
sessionStorage.removeItem(APP_CATCH_KEY.appPiniaKeepAliveStore)
location.reload()
}
export function resetRouteSource() {
routeSourceStatus.active = 'static'
routeSourceStatus.config = void 0
routeSourceStatus.error = void 0
}

View File

@ -6,6 +6,8 @@ export const WELCOME_ROUTE_PATH = '/welcome'
export const FORBIDDEN_ROUTE_PATH = '/403'
export const NOT_FOUND_PAGE_PATH = '/404'
export const SERVER_ERROR_ROUTE_PATH = '/500'
export const ACCOUNT_PROFILE_PATH = '/account/profile'
export const ACCOUNT_PROFILE_NAME = 'AccountProfile'
export const SYSTEM_ROUTE_PATHS = [
WELCOME_ROUTE_PATH,
FORBIDDEN_ROUTE_PATH,

View File

@ -1,8 +1,13 @@
import type { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { setAppRouteModules } from './app-route-modules'
import { loadRouteConfig } from './config/source'
import { constantRoutes, getLayoutRoutes } from './routes'
import { getStaticAppRoutes, setAppRouteModules } from './app-route-modules'
import { loadRouteConfig, resetRouteSource } from './config/source'
import {
constantRoutes,
getAccountProfileRoute,
getLayoutRoutes,
getSystemRoutes,
} from './routes'
import { scrollViewToTop, vueRouterRegister } from './utils'
export const router = createRouter({
@ -13,26 +18,62 @@ export const router = createRouter({
},
})
let initialize: Promise<void> | undefined
let pending: Promise<void> | undefined
let controller: AbortController | undefined
let removeRoutes: (() => void)[] = []
export async function setupRouter(app: App<Element>) {
initialize ??= (async () => {
const config = await loadRouteConfig()
export function clearAccountRoutes() {
controller?.abort()
pending = void 0
if (config) {
const { toRuntimeRoutes } = await import('./config/contract')
for (const remove of removeRoutes.splice(0)) remove()
setAppRouteModules(toRuntimeRoutes(config))
}
setAppRouteModules([])
resetRouteSource()
}
for (const route of getLayoutRoutes()) router.addRoute('RLayout', route)
export function loadAccountRoutes() {
if (pending) return pending
const current = new AbortController()
controller = current
const load = (async () => {
const config = await loadRouteConfig(current.signal)
const routes = config
? (await import('./config/contract')).toRuntimeRoutes(config)
: getStaticAppRoutes()
current.signal.throwIfAborted()
for (const remove of removeRoutes.splice(0)) remove()
setAppRouteModules(routes)
removeRoutes = getLayoutRoutes().map((route) =>
router.addRoute('RLayout', route),
)
})().finally(() => {
if (pending === load) pending = void 0
})
pending = load
return load
}
let registered = false
export async function setupRouter(app: App<Element>, authenticated: boolean) {
if (authenticated) await loadAccountRoutes()
else clearAccountRoutes()
if (!registered) {
for (const route of [...getSystemRoutes(), getAccountProfileRoute()])
router.addRoute('RLayout', route)
vueRouterRegister(router)
})().catch((error: unknown) => {
// 同页重挂载可以重试暂时失败的配置加载;成功初始化仍只注册一次守卫。
initialize = void 0
throw error
})
await initialize
registered = true
}
app.use(router)
}

View File

@ -2,6 +2,8 @@ import Layout from '@/layout'
import type { RouteRecordRaw } from 'vue-router'
import { appExpandRoutes } from './app-route-modules'
import {
ACCOUNT_PROFILE_NAME,
ACCOUNT_PROFILE_PATH,
FORBIDDEN_ROUTE_PATH,
NOT_FOUND_PAGE_PATH,
NOT_FOUND_ROUTE_PATH,
@ -39,11 +41,23 @@ export function getLayoutRoutes(): RouteRecordRaw[] {
({ path, redirect }) =>
!occupiedPaths.has(path) && occupiedPaths.has(redirect),
),
{ path: ROUTE_MANAGEMENT_PATH, redirect: ROUTE_MANAGEMENT_JSON_PATH },
...getSystemRoutes(),
{
path: ROUTE_MANAGEMENT_PATH,
redirect: ROUTE_MANAGEMENT_JSON_PATH,
meta: { requiredPermission: 'routes:write' },
},
]
}
export function getAccountProfileRoute(): RouteRecordRaw {
return {
path: ACCOUNT_PROFILE_PATH,
name: ACCOUNT_PROFILE_NAME,
component: () => import('@/views/account-profile'),
meta: { i18nKey: 'account.profile', hidden: true },
}
}
/**
*
* @returns 不进入业务菜单与标签的工作区状态路由,供应用与隔离文档示例复用。

View File

@ -1,10 +1,10 @@
import { APP_CATCH_KEY } from '@/app-config'
import {
FORBIDDEN_ROUTE_PATH,
isSystemRoute,
NOT_FOUND_PAGE_PATH,
SERVER_ERROR_ROUTE_PATH,
} from '@/router/constant'
import { getStorage } from '@/utils/cache'
import { piniaSigningStore } from '@/store/modules/signing'
import type { Router } from 'vue-router'
import { resolveLandingPath } from './resolve-landing-path'
import { getRouteAccess } from './route-access'
@ -14,16 +14,34 @@ import { getRouteAccess } from './route-access'
* @param router 应用的 Router 实例
*
* @description
* 注册 token、白名单与 meta.role 权限守卫,重定向返回值交给 Router 处理。
* 使用已核验的会话和路由权限,重定向返回值交给 Router 处理。
* 前端守卫不能替代后端鉴权。
*/
export const permissionRouter = (router: Router) => {
router.beforeEach((to) => {
const token = getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
export const permissionRouter = (
router: Router,
getSession: () => {
signingCallback: { id?: string }
revalidateSession: () => Promise<'active' | 'signedOut' | 'changed'>
} = piniaSigningStore,
) => {
router.beforeEach(async (to) => {
const session = getSession()
const isLogin = to.path === '/'
const attempted = to.redirectedFrom ?? to
if (typeof token !== 'string' || !token) {
if (session.signingCallback.id && !isLogin && !isSystemRoute(to)) {
try {
if ((await session.revalidateSession()) === 'changed') return false
} catch {
return {
path: SERVER_ERROR_ROUTE_PATH,
query: { from: attempted.fullPath },
replace: true,
}
}
}
if (!session.signingCallback.id) {
return isLogin
? true
: { path: '/', query: { redirect: attempted.fullPath }, replace: true }

View File

@ -1,5 +1,6 @@
import { WHITE_ROUTES } from '@/app-config'
import { isSystemRoute } from '@/router/constant'
import { piniaSigningStore } from '@/store/modules/signing'
import type { RouteLocationResolved, Router } from 'vue-router'
import { validRole } from './valid-role'
@ -8,6 +9,10 @@ export type RouteAccessLocation = Pick<
'fullPath' | 'hash' | 'matched' | 'name' | 'path' | 'query'
>
export const validRoutePermission = (permission: unknown) =>
typeof permission !== 'string' ||
piniaSigningStore().permissions.includes(permission)
/**
*
* @param router 当前已注册业务路由的实例
@ -33,8 +38,11 @@ export function getRouteAccess(
typeof current.name === 'string' && WHITE_ROUTES.includes(current.name)
if (
!white &&
!current.matched.every(({ meta }) => validRole(meta, currentRole))
!current.matched.every(
({ meta }) =>
validRoutePermission(meta.requiredPermission) &&
(white || validRole(meta, currentRole)),
)
)
return 'forbidden'

View File

@ -18,13 +18,21 @@ export const useSigningGetters = () => {
}
export const useSigningActions = () => {
const { signing, logout, clearSigningCallback, restoreSession } =
piniaSigningStore()
const {
signing,
logout,
clearSigningCallback,
restoreSession,
endSession,
updateDisplayName,
} = piniaSigningStore()
return {
signing,
logout,
clearSigningCallback,
restoreSession,
endSession,
updateDisplayName,
}
}

View File

@ -4,7 +4,10 @@ import { getAppRawRoutes } from '@/router/app-route-modules'
import { FORBIDDEN_ROUTE_PATH, isSystemRoute } from '@/router/constant'
import { validMenuItemShow, validRole } from '@/router/utils'
import { joinRoutePath } from '@/router/utils/join-route-path'
import { getRouteAccess } from '@/router/utils/route-access'
import {
getRouteAccess,
validRoutePermission,
} from '@/router/utils/route-access'
import type { RouteAccessLocation } from '@/router/utils/route-access'
import { useKeepAliveActions } from '@/store'
import type { MenuState } from '@/store/modules/menu/types'
@ -331,7 +334,11 @@ export const piniaMenuStore = defineStore(
const options: AppMenuOption[] = []
for (const curr of routes) {
if (!validRole(curr.meta, currentRole)) continue
if (
!validRole(curr.meta, currentRole) ||
!validRoutePermission(curr.meta.requiredPermission)
)
continue
const fullPath = joinRoutePath(parentPath, curr.path)
@ -436,6 +443,8 @@ export const piniaMenuStore = defineStore(
menuState.menuTagOptions = []
if (!current[1]) {
menuState.options = []
menuIndex.clear()
cacheTags()
clearActiveMenu()

View File

@ -1,144 +1,185 @@
import { getAdminSession, loginAdmin, logoutAdmin } from '@/api/admin'
import { AdminApiError } from '@/api/admin/client'
import {
AdminApiError,
advanceAdminSession,
apiMockEnabled,
browserSessionEnabled,
} from '@/api/admin/client'
import type { SessionInfo } from '@/api/admin/contracts'
import { APP_CATCH_KEY } from '@/app-config'
import { useVueRouter } from '@/hooks'
import { useMenuActions } from '@/store/hooks/useMenuStore'
import type {
SigningCallback,
SigningForm,
SigningResponse,
} from '@/store/modules/signing/types'
import { clearAccountRoutes, router } from '@/router'
import { isSystemRoute } from '@/router/constant'
import { getStorage, removeStorage, setStorage } from '@/utils/cache'
import { piniaLockScreenStore } from '../lock-screen'
import type { SigningCallback, SigningForm } from './types'
/** 登录状态仓库,使用 localStorage 持久化 signingCallback。 */
export const piniaSigningStore = defineStore(
'signing',
() => {
const { router } = useVueRouter()
const permissions = ref<string[]>([])
const state = reactive({
/** 用户资料由会话接口刷新;role 用于现有路由和菜单守卫。 */
signingCallback: {} as SigningCallback,
})
export const adminSessionChangeKey = 'rayAdminSessionChanged'
/**
*
* @param signingFormValue 用户登录信息
*
* @description
* 请求标准登录接口,保存返回的会话 token、资料与权限码。
* 保留组件侧 code=0 的成功约定;接口错误通过 Promise 拒绝。
*/
const signing = async (
signingFormValue: SigningForm,
): Promise<SigningResponse> => {
const session = await loginAdmin(
signingFormValue.name,
signingFormValue.pwd,
export const announceAdminSessionChange = () => {
setStorage(adminSessionChangeKey, crypto.randomUUID(), 'localStorage')
}
export const piniaSigningStore = defineStore('signing', () => {
const signingCallback = ref({} as SigningCallback)
const permissions = ref<string[]>([])
let revision = 0
let expiryTimer: ReturnType<typeof setTimeout> | undefined
const expireSession = () => {
if (!signingCallback.value.id) return
const route = router.currentRoute.value
const redirect =
route.path === '/' || isSystemRoute(route) ? void 0 : route.fullPath
clearSigningCallback()
void router.replace({ path: '/', query: { redirect } })
}
const setSession = (session: SessionInfo) => {
signingCallback.value = session.user
permissions.value = session.permissions
clearTimeout(expiryTimer)
const expiresAt = Date.parse(session.expiresAt ?? '')
if (Number.isFinite(expiresAt))
expiryTimer = setTimeout(
expireSession,
Math.min(2_147_483_647, Math.max(0, expiresAt - Date.now())),
)
}
const clearSigningCallback = () => {
revision++
advanceAdminSession()
clearTimeout(expiryTimer)
signingCallback.value = {} as SigningCallback
permissions.value = []
clearAccountRoutes()
for (const key of [
APP_CATCH_KEY.token,
APP_CATCH_KEY.signing,
APP_CATCH_KEY.appLockScreenPasswordKey,
])
removeStorage(key, 'localStorage')
localStorage.removeItem(APP_CATCH_KEY.appPiniaSigningStore)
for (const key of [
APP_CATCH_KEY.appMenuTagOptions,
APP_CATCH_KEY.appMenuKey,
APP_CATCH_KEY.appPiniaKeepAliveStore,
])
removeStorage(key, 'sessionStorage')
piniaLockScreenStore().setLocked(false)
}
const signing = async ({ name, pwd }: SigningForm) => {
const session = await loginAdmin(name, pwd)
revision++
advanceAdminSession()
if ('accessToken' in session)
setStorage(APP_CATCH_KEY.token, session.accessToken, 'localStorage')
state.signingCallback = session.user
permissions.value = session.permissions
return { code: 0, message: 'OK', data: state.signingCallback }
setSession(session)
}
const restoreSession = async () => {
localStorage.removeItem(APP_CATCH_KEY.appPiniaSigningStore)
removeStorage(APP_CATCH_KEY.signing, 'localStorage')
if (browserSessionEnabled)
removeStorage(APP_CATCH_KEY.token, 'localStorage')
else if (!getStorage<string>(APP_CATCH_KEY.token, 'localStorage')) return
const current = revision
try {
const session = await getAdminSession()
if (revision === current) setSession(session)
} catch (error) {
if (!(error instanceof AdminApiError) || error.code !== 401) throw error
if (revision === current) clearSigningCallback()
}
}
const restoreSession = async () => {
permissions.value = []
const revalidateSession = async (): Promise<
'active' | 'signedOut' | 'changed'
> => {
if (apiMockEnabled) return 'active'
if (!getStorage<string>(APP_CATCH_KEY.token, 'localStorage')) {
state.signingCallback = {} as SigningCallback
const current = revision
return
try {
const session = await getAdminSession()
if (revision !== current)
return signingCallback.value.id ? 'changed' : 'signedOut'
if (
session.user.id !== signingCallback.value.id ||
session.user.role !== signingCallback.value.role ||
new Set(session.permissions).size !== new Set(permissions.value).size ||
session.permissions.some(
(permission) => !permissions.value.includes(permission),
)
) {
location.reload()
return 'changed'
}
try {
const session = await getAdminSession()
setSession(session)
state.signingCallback = session.user
permissions.value = session.permissions
} catch (error) {
if (!(error instanceof AdminApiError) || error.code !== 401) throw error
return 'active'
} catch (error) {
if (!(error instanceof AdminApiError) || error.code !== 401) throw error
removeStorage(APP_CATCH_KEY.token, 'localStorage')
removeStorage(APP_CATCH_KEY.signing, 'localStorage')
state.signingCallback = {} as SigningCallback
}
if (revision === current) clearSigningCallback()
return 'signedOut'
}
}
const endSession = async (redirect?: string) => {
clearSigningCallback()
announceAdminSessionChange()
await router.replace({ path: '/', query: { redirect } })
}
const logout = async (redirect?: string) => {
try {
await logoutAdmin()
} catch (error) {
if (!(error instanceof AdminApiError) || error.code !== 401) throw error
}
/**
*
* @param toSigning 是否需要退出登录,并且重定向至登录页
*
* @description
* 清除所有登录缓存信息。
* 如果 toSigning 传递 true 则会重定向至登录页。
*/
const clearSigningCallback = (toSigning: boolean) => {
const { setMenuTagOptions } = useMenuActions()
const {
appPiniaMenuStore,
appPiniaSigningStore,
token,
signing,
appMenuKey,
} = APP_CATCH_KEY
await endSession(redirect)
}
// 提示信息
window.$message.info('账号退出中...')
state.signingCallback = {} as SigningCallback
permissions.value = []
// 移除所有 sessionStorage 缓存
removeStorage('__all_sessionStorage__', 'sessionStorage')
// 移除指定 localStorage 缓存
removeStorage(appPiniaSigningStore, 'localStorage')
removeStorage(appPiniaMenuStore, 'localStorage')
removeStorage(token, 'localStorage')
removeStorage(signing, 'localStorage')
removeStorage(appMenuKey, 'localStorage')
removeStorage(APP_CATCH_KEY.isAppLockScreen, 'localStorage')
// 关闭所有侧边栏标签
setMenuTagOptions([], false)
const updateDisplayName = (name: string) => {
signingCallback.value.name = name
}
if (toSigning) {
void router.replace('/')
onScopeDispose(() => clearTimeout(expiryTimer))
setTimeout(() => {
window.location.reload()
}, 0)
}
}
/**
*
* 退出登陆并且清空缓存数据
* 延迟 300ms 后强制刷新当前系统
*/
const logout = async () => {
try {
await logoutAdmin()
} catch {
// 服务端暂时不可达时,仍允许用户完成本地退出。
} finally {
clearSigningCallback(true)
}
}
return {
...toRefs(state),
permissions,
restoreSession,
signing,
logout,
clearSigningCallback,
}
},
{
persist: {
key: APP_CATCH_KEY.appPiniaSigningStore,
pick: ['signingCallback'],
storage: window.localStorage,
},
},
)
return {
signingCallback,
permissions,
restoreSession,
revalidateSession,
signing,
logout,
clearSigningCallback,
endSession,
expireSession,
updateDisplayName,
}
})

View File

@ -0,0 +1,319 @@
.r-account-profile {
container: account-profile / inline-size;
display: grid;
gap: 18px;
max-inline-size: 1160px;
margin-inline: auto;
padding-block: 10px 28px;
.r-page-header {
padding-block-end: 16px;
border-block-end: 1px solid var(--r-line);
}
&__summary,
&__navigation,
&__panel {
min-inline-size: 0;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface);
box-shadow: var(--r-shadow-soft);
}
&__cover {
position: relative;
overflow: hidden;
block-size: clamp(80px, 9.5cqi, 110px);
border-radius: var(--r-radius) var(--r-radius) 0 0;
background: linear-gradient(
112deg,
color-mix(in oklch, var(--r-theme-primary-color) 76%, var(--r-text)),
var(--r-theme-primary-color) 48%,
color-mix(in oklch, var(--r-theme-primary-color) 77%, var(--r-surface))
);
&::after {
position: absolute;
inset-block: 0;
inset-inline-end: 0;
inline-size: min(56%, 520px);
background: repeating-radial-gradient(
ellipse at 79% 8%,
transparent 0 17px,
color-mix(in srgb, var(--r-surface) 24%, transparent) 18px 19px,
transparent 20px 29px
);
mask-image: linear-gradient(90deg, transparent, black 43%);
content: '';
}
}
&__summary-body {
display: grid;
align-items: center;
gap: 16px 26px;
padding: 14px clamp(16px, 3cqi, 24px) 16px;
}
&__identity {
display: flex;
align-items: center;
gap: 14px;
min-inline-size: 0;
}
&__avatar-frame {
position: relative;
z-index: 1;
display: grid;
flex: none;
align-self: flex-start;
margin-block-start: -42px;
padding: 4px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface);
box-shadow: var(--r-shadow-soft);
}
&__avatar.r-account-avatar {
border-radius: var(--r-control-radius);
}
&__identity-copy {
min-inline-size: 0;
h2 {
color: var(--r-text);
font-size: 23px;
font-weight: 650;
line-height: 1.28;
letter-spacing: -0.02em;
overflow-wrap: anywhere;
}
}
&__handle {
margin-block-start: 4px;
color: var(--r-text-secondary);
font: 13px / 1.5 var(--r-font-mono);
overflow-wrap: anywhere;
}
&__facts {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: stretch;
gap: 8px;
margin: 0;
> div {
display: grid;
align-content: start;
gap: 4px;
padding: 8px 12px;
border: 1px solid var(--r-line);
border-radius: var(--r-control-radius);
background: var(--r-surface-muted);
}
dt {
color: var(--r-text-muted);
font-size: 11px;
line-height: 1.45;
}
dd {
min-block-size: 20px;
margin: 0;
color: var(--r-text);
font-size: 13px;
font-weight: 600;
line-height: 1.45;
overflow-wrap: anywhere;
}
}
&__workspace {
display: grid;
align-items: start;
gap: 16px;
}
&__navigation {
display: grid;
gap: 5px;
padding: 7px;
}
&__section {
display: grid;
grid-template-columns: 34px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
padding: 9px 10px;
border: 1px solid transparent;
border-radius: var(--r-control-radius);
background: transparent;
color: var(--r-text);
font: inherit;
text-align: start;
cursor: pointer;
&:hover {
background: var(--r-surface-hover);
}
&[aria-selected='true'] {
border-color: color-mix(
in srgb,
var(--r-theme-primary-color) 26%,
var(--r-line)
);
background: color-mix(
in srgb,
var(--r-theme-primary-color) 11%,
var(--r-surface)
);
color: var(--r-selected-text);
}
}
&__section-icon {
display: grid;
place-items: center;
inline-size: 34px;
block-size: 34px;
border-radius: var(--r-control-radius);
background: var(--r-surface-muted);
color: var(--r-text-secondary);
}
&__section[aria-selected='true'] &__section-icon {
background: var(--r-surface);
color: var(--r-primary-text);
}
&__section-copy {
display: grid;
gap: 3px;
min-inline-size: 0;
}
&__section-label {
font-size: 14px;
font-weight: 650;
line-height: 1.35;
}
&__section-hint {
color: var(--r-text-secondary);
font-size: 11px;
line-height: 1.4;
}
&__section-indicator {
display: grid;
visibility: hidden;
place-items: center;
}
&__section[aria-selected='true'] &__section-indicator {
visibility: visible;
}
&__panel {
container: account-panel / inline-size;
padding: clamp(16px, 3cqi, 24px);
}
&__panel[hidden] {
display: none;
}
&__panel-heading {
margin-block-end: 20px;
padding-block-end: 16px;
border-block-end: 1px solid var(--r-line);
h2 {
margin-block-end: 5px;
color: var(--r-text);
font-size: 19px;
font-weight: 650;
line-height: 1.35;
}
p {
color: var(--r-text-secondary);
font-size: 13px;
line-height: 1.65;
}
}
&__form,
&__fields {
display: grid;
gap: 16px;
min-inline-size: 0;
}
.r-account-password-form__hint {
margin-inline-start: 8px;
color: var(--r-text-muted);
font-size: 11px;
font-weight: 400;
}
.r-account-password-form__required {
margin-inline-start: 4px;
color: var(--n-asterisk-color, var(--r-text));
}
&__actions,
&__form > .r-account-password-form__actions {
display: flex;
justify-content: flex-end;
margin-block-start: 2px;
padding-block-start: 14px;
border-block-start: 1px solid var(--r-line);
}
&__loading {
display: grid;
min-block-size: 150px;
place-items: center;
}
}
@container account-profile (min-width: 49rem) {
.r-account-profile__summary-body {
grid-template-columns: minmax(0, 1fr) minmax(250px, 0.58fr);
}
.r-account-profile__workspace {
grid-template-columns: 238px minmax(0, 1fr);
}
}
@container account-panel (min-width: 36rem) {
.r-account-profile__fields,
.r-account-profile__password-form {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.r-account-profile__password-form {
> .r-account-password-form__current,
> .r-account-password-form__actions,
> [role='alert'] {
grid-column: 1 / -1;
}
}
}
@media (forced-colors: active) {
.r-account-profile__section[aria-selected='true'] {
border-color: Highlight;
}
}

View File

@ -0,0 +1,431 @@
import './index.scss'
import {
changeAccountPassword,
getAccountProfile,
updateAccountProfile,
} from '@/api/admin'
import { apiMockEnabled } from '@/api/admin/client'
import { profileInputSchema } from '@/api/admin/contracts'
import type { AccountProfile } from '@/api/admin/contracts'
import AccountPasswordForm from '@/app-components/app/AccountPasswordForm'
import AccountAvatar from '@/app-components/app/AppAvatar/AccountAvatar'
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { RIcon } from '@/components'
import { useI18n } from '@/hooks'
import { useSigningActions, useSigningGetters } from '@/store'
import {
NAlert,
NButton,
NForm,
NFormItem,
NInput,
NSpin,
NTag,
} from 'naive-ui'
import * as v from 'valibot'
const accountSections = [
{
key: 'profile',
icon: 'action/edit',
title: 'editProfile',
hint: 'profileNavHint',
},
{
key: 'security',
icon: 'action/lock',
title: 'securitySection',
hint: 'securityNavHint',
},
] as const
type AccountSection = (typeof accountSections)[number]['key']
const readonlyInputTheme = {
color: 'var(--r-surface-muted)',
colorFocus: 'var(--r-surface-muted)',
}
export default defineComponent({
name: 'AccountProfile',
setup() {
const { t } = useI18n('account')
const { t: translate, te } = useI18n()
const { updateDisplayName, endSession } = useSigningActions()
const { getSigningCallback } = useSigningGetters()
const profile = shallowRef<AccountProfile>()
const form = reactive({ name: '', phone: '' })
const loading = ref(false)
const saving = ref(false)
const loadError = ref(false)
const formError = ref('')
const activeSection = ref<AccountSection>('profile')
const nameId = useId()
const phoneId = useId()
const usernameId = useId()
const emailId = useId()
const navigationId = useId()
const request = new AbortController()
const tabId = (section: AccountSection) => `${navigationId}-tab-${section}`
const panelId = (section: AccountSection) =>
`${navigationId}-panel-${section}`
const moveSection = (event: KeyboardEvent) => {
if (event.altKey || event.ctrlKey || event.metaKey) return
const current = accountSections.findIndex(
({ key }) => key === activeSection.value,
)
const count = accountSections.length
let next: number
switch (event.key) {
case 'ArrowDown':
next = (current + 1) % count
break
case 'ArrowUp':
next = (current + count - 1) % count
break
case 'Home':
next = 0
break
case 'End':
next = count - 1
break
default:
return
}
event.preventDefault()
const section = accountSections[next].key
activeSection.value = section
const list = event.currentTarget as HTMLElement
list
.querySelector<HTMLButtonElement>(`[data-section="${section}"]`)
?.focus()
}
const setProfile = (value: AccountProfile) => {
profile.value = value
form.name = value.name
form.phone = value.phone
}
const load = async () => {
loading.value = true
loadError.value = false
try {
setProfile(await getAccountProfile(request.signal))
} catch {
if (!request.signal.aborted) loadError.value = true
} finally {
loading.value = false
}
}
const saveProfile = async (event: Event) => {
event.preventDefault()
if (saving.value) return
const result = v.safeParse(profileInputSchema, form)
if (!result.success) {
formError.value = t('invalidProfile')
return
}
formError.value = ''
saving.value = true
try {
const updated = await updateAccountProfile(result.output)
setProfile(updated)
updateDisplayName(updated.name)
window.$message.success(t('profileSaved'))
} catch {
formError.value = t('saveFailed')
} finally {
saving.value = false
}
}
const savePassword = async (
newPassword: string,
currentPassword: string,
) => {
await changeAccountPassword({ currentPassword, newPassword })
window.$message.success(t('passwordChanged'))
await endSession()
}
onMounted(load)
onBeforeUnmount(() => request.abort())
return () => {
const account = profile.value
const roleKey = account && `userManagement.roles.${account.role}`
return (
<section class="r-account-profile" aria-busy={loading.value}>
<AppPageHeader
eyebrow={t('eyebrow')}
title={t('profile')}
description={t('description')}
/>
{loading.value && (
<div class="r-account-profile__loading">
<NSpin show />
</div>
)}
{loadError.value && (
<NAlert type="error" title={t('loadFailed')}>
<NButton size="small" onClick={load}>
{t('retry')}
</NButton>
</NAlert>
)}
{account && (
<>
<section
class="r-account-profile__summary"
aria-label={t('details')}
>
<div class="r-account-profile__cover" aria-hidden="true" />
<div class="r-account-profile__summary-body">
<div class="r-account-profile__identity">
<div class="r-account-profile__avatar-frame">
<AccountAvatar
class="r-account-profile__avatar"
name={account.name}
src={account.avatar || getSigningCallback.value.avatar}
size={72}
objectFit="cover"
/>
</div>
<div class="r-account-profile__identity-copy">
<h2>{account.name}</h2>
<p class="r-account-profile__handle">
@{account.username}
</p>
</div>
</div>
<dl class="r-account-profile__facts">
<div>
<dt>{t('department')}</dt>
<dd>
{account.department.labelKey
? translate(account.department.labelKey)
: account.department.name}
</dd>
</div>
<div>
<dt>{t('role')}</dt>
<dd>
<NTag
type="primary"
size="small"
round
bordered={false}
>
{roleKey && te?.(roleKey)
? translate(roleKey)
: account.role}
</NTag>
</dd>
</div>
</dl>
</div>
</section>
<div class="r-account-profile__workspace">
<div
class="r-account-profile__navigation"
role="tablist"
aria-label={t('eyebrow')}
aria-orientation="vertical"
onKeydown={moveSection}
>
{accountSections.map(({ key, icon, title, hint }) => {
const id = tabId(key)
const selected = activeSection.value === key
return (
<button
key={key}
id={id}
data-section={key}
type="button"
role="tab"
class="r-account-profile__section"
aria-selected={selected}
aria-controls={panelId(key)}
aria-labelledby={`${id}-label`}
aria-describedby={`${id}-hint`}
tabindex={selected ? 0 : -1}
onClick={() => (activeSection.value = key)}
>
<span
class="r-account-profile__section-icon"
aria-hidden="true"
>
<RIcon name={icon} size={19} />
</span>
<span class="r-account-profile__section-copy">
<span
id={`${id}-label`}
class="r-account-profile__section-label"
>
{t(title)}
</span>
<span
id={`${id}-hint`}
class="r-account-profile__section-hint"
>
{t(hint)}
</span>
</span>
<span
class="r-account-profile__section-indicator"
aria-hidden="true"
>
<RIcon name="directional/right_arrow" size={14} />
</span>
</button>
)
})}
</div>
<section
id={panelId('profile')}
class="r-account-profile__panel"
role="tabpanel"
aria-labelledby={tabId('profile')}
hidden={activeSection.value !== 'profile'}
tabindex={0}
>
<header class="r-account-profile__panel-heading">
<h2>{t('editProfile')}</h2>
<p>{t('profileHint')}</p>
</header>
<NForm
class="r-account-profile__form"
{...{ method: 'post' }}
labelPlacement="top"
showFeedback={false}
onSubmit={saveProfile}
>
<div class="r-account-profile__fields">
<NFormItem
label={t('name')}
labelProps={{ for: nameId }}
required
>
<NInput
v-model:value={form.name}
disabled={saving.value}
inputProps={{
id: nameId,
name: 'name',
autocomplete: 'name',
required: true,
maxlength: 60,
}}
/>
</NFormItem>
<NFormItem
label={t('phone')}
labelProps={{ for: phoneId }}
>
<NInput
v-model:value={form.phone}
disabled={saving.value}
inputProps={{
id: phoneId,
name: 'phone',
type: 'tel',
autocomplete: 'tel',
maxlength: 24,
}}
/>
</NFormItem>
<NFormItem
label={t('username')}
labelProps={{ for: usernameId }}
>
<NInput
value={account.username}
readonly
themeOverrides={readonlyInputTheme}
inputProps={{ id: usernameId }}
/>
</NFormItem>
<NFormItem
label={t('email')}
labelProps={{ for: emailId }}
>
<NInput
value={account.email}
readonly
themeOverrides={readonlyInputTheme}
inputProps={{ id: emailId }}
/>
</NFormItem>
</div>
{formError.value && (
<NAlert type="error" {...{ role: 'alert' }}>
{formError.value}
</NAlert>
)}
<div class="r-account-profile__actions">
<NButton
attrType="submit"
type="primary"
loading={saving.value}
>
{t('saveProfile')}
</NButton>
</div>
</NForm>
</section>
<section
id={panelId('security')}
class="r-account-profile__panel"
role="tabpanel"
aria-labelledby={tabId('security')}
hidden={activeSection.value !== 'security'}
tabindex={0}
>
{activeSection.value === 'security' && (
<>
<header class="r-account-profile__panel-heading">
<h2>{t('changePassword')}</h2>
<p>
{t(
apiMockEnabled
? 'demoPasswordNotice'
: 'revokeNotice',
)}
</p>
</header>
<AccountPasswordForm
class="r-account-profile__form r-account-profile__password-form"
username={account.username}
compact
requireCurrent
save={savePassword}
/>
</>
)}
</section>
</div>
</>
)}
</section>
)
}
},
})

View File

@ -1,10 +1,10 @@
import { apiMockEnabled } from '@/api/admin/client'
import { APP_CATCH_KEY } from '@/app-config'
import { AdminApiError, apiMockEnabled } from '@/api/admin/client'
import { RForm, useForm } from '@/components'
import { useI18n } from '@/hooks'
import { loadAccountRoutes } from '@/router'
import { resolveLandingPath } from '@/router/utils/resolve-landing-path'
import { useSigningActions } from '@/store'
import { setStorage } from '@/utils'
import { announceAdminSessionChange } from '@/store/modules/signing'
import { NButton, NFlex, NFormItem, NInput } from 'naive-ui'
export default defineComponent({
@ -12,7 +12,7 @@ export default defineComponent({
setup() {
const [register, { validate }] = useForm()
const { t } = useI18n('views.login.index')
const { signing } = useSigningActions()
const { signing, clearSigningCallback } = useSigningActions()
const router = useRouter()
const route = useRoute()
const loading = ref(false)
@ -45,16 +45,30 @@ export default defineComponent({
}
loading.value = true
let signedIn = false
try {
const res = await signing(signingForm)
await signing(signingForm)
signedIn = true
await loadAccountRoutes()
if (res.code !== 0) throw new Error(res.message)
setStorage(APP_CATCH_KEY.signing, res.data, 'localStorage')
announceAdminSessionChange()
await router.replace(resolveLandingPath(router, route.query.redirect))
} catch {
window.$message.error(t('SignInError'))
} catch (error) {
if (signedIn) clearSigningCallback()
window.$message.error(
t(
signedIn
? 'RouteLoadError'
: error instanceof AdminApiError && error.code === 429
? 'RateLimit'
: error instanceof AdminApiError &&
error.key === 'invalidCredentials'
? 'SignInError'
: 'SignInUnavailable',
),
)
} finally {
loading.value = false
}

View File

@ -3,6 +3,7 @@ import { apiMockEnabled } from '@/api/admin/client'
import AppShareLink from '@/app-components/app/AppShareLink'
import { LOCAL_OPTIONS } from '@/app-config'
import { RIcon } from '@/components'
import { useI18n } from '@/hooks'
import ThemeSwitch from '@/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch'
import { useSettingActions } from '@/store'
import { NButton, NDropdown, NFlex, NTabPane, NTabs } from 'naive-ui'
@ -15,8 +16,13 @@ export default defineComponent({
name: 'RLogin',
setup() {
const { updateLocale } = useSettingActions()
const { t } = useI18n('views.login.index')
const tabsValue = ref('signing')
watchEffect(() => {
document.title = t('PageTitle')
})
return { updateLocale, tabsValue, copyright: __APP_CFG__.layout.copyright }
},
render() {

View File

@ -10,6 +10,7 @@ import {
routeSourceStatus,
saveRemoteRouteConfig,
saveRouteSource,
serverRoutesRequired,
} from '@/router/config/source'
import type { RouteSource } from '@/router/config/source'
import { routeViewCatalog } from '@/router/config/views'
@ -218,8 +219,12 @@ export default defineComponent({
<NCard title={t('source')}>
<NFlex align="center" justify="space-between">
<NRadioGroup v-model:value={source.value} aria-label={t('source')}>
<NRadioButton value="static">{t('static')}</NRadioButton>
<NRadioButton value="local">{t('local')}</NRadioButton>
{!serverRoutesRequired && (
<>
<NRadioButton value="static">{t('static')}</NRadioButton>
<NRadioButton value="local">{t('local')}</NRadioButton>
</>
)}
<NRadioButton value="remote" disabled={!remoteRouteUrl}>
{t('remote')}
</NRadioButton>

View File

@ -2,7 +2,7 @@ import { createUser, updateUser } from '@/api/admin'
import { AdminApiError } from '@/api/admin/client'
import type { AdminUser, UserInput, UserOptions } from '@/api/admin/contracts'
import { RForm, useForm } from '@/components'
import { useI18n } from '@/hooks'
import { useAccess, useI18n } from '@/hooks'
import {
NAlert,
NButton,
@ -29,6 +29,7 @@ export default defineComponent({
setup(props, { emit }) {
const { t } = useI18n('userManagement')
const { t: translate } = useI18n()
const { hasPermission } = useAccess()
const initial: UserInput = {
username: props.user?.username ?? '',
name: props.user?.name ?? '',
@ -275,7 +276,9 @@ export default defineComponent({
<NRadioGroup
v-model:value={model.value.status}
aria-labelledby={`${id}-status`}
disabled={self}
disabled={
self || (!!props.user && !hasPermission('users:status'))
}
name={`${id}-status`}
>
<NFlex>

View File

@ -5,10 +5,12 @@ import {
getUserOptions,
getUsers,
resetDemoUsers,
setUserCredential,
updateUserStatus,
} from '@/api/admin'
import { AdminApiError, apiMockEnabled } from '@/api/admin/client'
import type { AdminUser, UserOptions, UserStatus } from '@/api/admin/contracts'
import AccountPasswordForm from '@/app-components/app/AccountPasswordForm'
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { RIcon, RTablePro } from '@/components'
import type { TableProInst } from '@/components'
@ -73,6 +75,7 @@ export default defineComponent({
const editorOpen = ref(false)
const editing = shallowRef<AdminUser>()
const details = shallowRef<AdminUser>()
const credentialTarget = shallowRef<AdminUser>()
const loadingUser = ref('')
const busy = ref(false)
const abort = new AbortController()
@ -124,13 +127,28 @@ export default defineComponent({
return [{ key: '', label: t('allUsers'), children: visit(null) }]
})
const roleEditable = (user: AdminUser) =>
!options.value?.roles.find((role) => role.value === user.role)?.disabled
!!options.value?.roles.some(
(role) => role.value === user.role && !role.disabled,
)
const editable = (user: AdminUser) =>
hasPermission('users:update') && roleEditable(user)
const removable = (user: AdminUser) =>
hasPermission('users:delete') &&
roleEditable(user) &&
user.id !== getSigningCallback.value.id
const canSetCredential = (user: AdminUser) =>
hasPermission('users:credentials') &&
roleEditable(user) &&
user.id !== getSigningCallback.value.id
const saveCredential = async (password: string) => {
const target = credentialTarget.value
if (!target) return
await setUserCredential(target.id, password)
credentialTarget.value = void 0
window.$message.success(translate('account.credentialSaved'))
}
const reload = async () => {
checked.value = []
await table.value?.reload(true)
@ -247,7 +265,7 @@ export default defineComponent({
title: t('actions'),
key: 'actions',
fixed: stacked.value ? void 0 : 'right',
width: 240,
width: hasPermission('users:credentials') ? 300 : 240,
allowExport: false,
render: (row) => (
<NFlex size="small" wrap={false}>
@ -293,6 +311,18 @@ export default defineComponent({
{t(row.status === 'enabled' ? 'disable' : 'enable')}
</NButton>
)}
{canSetCredential(row) && (
<NButton
text
size="small"
aria-label={translate('account.setPasswordFor', {
name: row.name,
})}
onClick={() => (credentialTarget.value = row)}
>
{translate('account.setPassword')}
</NButton>
)}
{removable(row) && (
<NButton
text
@ -319,8 +349,12 @@ export default defineComponent({
editing.value = void 0
}
const saved = async (user: AdminUser) => {
const created = !editing.value
closeEditor()
window.$message.success(t('saved'))
window.$message.success(
created ? translate('account.userCreated') : t('saved'),
)
if (user.id === getSigningCallback.value.id) await restoreSession()
@ -524,6 +558,35 @@ export default defineComponent({
onSaved={(user) => void saved(user)}
/>
)}
<NModal
show={!!credentialTarget.value}
onUpdateShow={(show) => {
if (!show) credentialTarget.value = void 0
}}
preset="card"
class="user-management__modal user-management__modal--details"
title={translate('account.setPasswordFor', {
name: credentialTarget.value?.name ?? '',
})}
aria-label={translate('account.setPassword')}
maskClosable={false}
>
{credentialTarget.value && (
<NFlex vertical>
<p>
{translate(
apiMockEnabled
? 'account.demoPasswordNotice'
: 'account.credentialNotice',
)}
</p>
<AccountPasswordForm
username={credentialTarget.value.username}
save={saveCredential}
/>
</NFlex>
)}
</NModal>
<NModal
show={!!details.value}
onUpdateShow={(show) => {

View File

@ -40,15 +40,15 @@ Mock 在应用启动前完成 Service Worker 注册。每次 API 请求前检查
用户、部门、角色授权、会话、路由配置和操作审计持久化到 PostgreSQL。账号与邮箱通过规范化唯一字段避免大小写冲突;批量写入、账号保护与审计在事务内执行。初始化只补齐初始数据,重复运行保留已有配置、路由与账号。
认证保持 Bearer 协议,服务端用随机令牌建立可撤销会话,只保存令牌摘要;密码使用带随机盐的 scrypt 派生。每次请求重新校验用户状态、会话有效期和权限。退出、账号停用、角色变更或显式重设凭据会影响相应会话,前端权限显示不能替代接口授权。
配套服务用签名 JWT 标识会话,PostgreSQL 只保存令牌摘要;密码使用带随机盐的 scrypt 派生。每次请求校验 JWT 签名、有效期、数据库会话和实时权限。配套的同源 Admin 使用 HttpOnly Cookie,接口客户端仍可用 Bearer。退出撤销当前会话,停用、角色变更和改密撤销该账号的所有会话。
用户资料创建接口不接收密码,新建账号需由安全环境提供 `CREDENTIAL_USERNAME`、`CREDENTIAL_PASSWORD` 后执行 `pnpm server:credential:set`,才能登录。密码长度为 12–128 字符,修改凭据同时撤销已有会话。
用户资料创建接口不接收密码。管理员可从用户管理设置凭据,运维也可使用 `pnpm server:credential:set` 进行恢复。配套的 `dev:full` 与 Compose 已配置 `VITE_API_AUTH_TRANSPORT=cookie`;手动构建时配合 `VITE_API_BASE_URL=/api/` 使用同源代理,外部 HTTPS 部署启用 Secure Cookie。Cookie 模式请求携带 `X-Ray-Session: cookie`,写请求还必须来自允许的同源页面。
Redis 为 API 和登录提供跨进程限流,并缓存可重建的演示读取结果;会话与权限不经过该缓存。请求均带 `X-Request-Id`,JSON 日志记录路由模板、状态和耗时,排除请求体、查询串、凭据和原始连接错误。就绪接口为 `/api/health/ready`,同时检查数据库与 Redis;存活接口为 `/api/health/live`。
Redis 为 API、登录和改密提供跨进程限流,并缓存可重建的演示读取结果;会话与权限不经过该缓存。请求均带 `X-Request-Id`,JSON 日志记录路由模板、状态和耗时,排除请求体、查询串、凭据和原始连接错误。就绪接口 `/api/health/ready` 检查数据库已初始化且 Redis 可用;存活接口为 `/api/health/live`。
配置要求明确的 CORS 来源和可信代理,默认不信任转发头。非法 JSON、超大请求、限流和依赖故障分别返回标准错误包络。配套后端不提供 `POST /admin/users/reset`。Redis 故障时返回 503,不切回内存认证或 Mock 数据。
`DEMO_ENABLED` 在开发环境默认开启,生产环境默认关闭。开启时,`/admin/demo/*` 提供与 Mock 一致的公开演示数据;关闭时接口返回 404,公开运行配置移除演示视图及指向它们的重定向。已保存的路由保持完整,管理员可继续编辑。若显式选择本地或静态路由来源,这些浏览器草稿由使用者管理,服务端仍禁用演示接口。
`DEMO_ENABLED` 在开发环境默认开启,生产环境默认关闭。开启时,`/admin/demo/*` 提供与 Mock 一致的公开演示数据;关闭时接口返回 404,运行路由移除演示视图及指向它们的重定向。已保存的路由保持完整,有编辑权限的用户可继续维护。
<!-- fullstack:end -->
@ -81,11 +81,14 @@ Redis 为 API 和登录提供跨进程限流,并缓存可重建的演示读取
## 登录、会话与权限
| 方法和路径 | 输入 | 成功的 data |
| ------------------------- | ------------------------ | ----------------------------------------------- |
| `POST /admin/auth/login` | `{ username, password }` | `{ accessToken, expiresAt, user, permissions }` |
| `GET /admin/auth/session` | Bearer token | `{ user, permissions }` |
| `POST /admin/auth/logout` | Bearer token | `null` |
| 方法和路径 | 输入 | 成功的 data |
| ---------------------------- | ---------------------------------- | -------------------------------------------------------------------------------- |
| `POST /admin/auth/login` | `{ username, password }` | `{ accessToken, expiresAt, user, permissions }`,Cookie 模式不返回 `accessToken` |
| `GET /admin/auth/session` | 会话 | `{ user, permissions, expiresAt? }` |
| `POST /admin/auth/logout` | 会话 | `null` |
| `GET /admin/auth/profile` | 会话 | 当前账号资料与部门 |
| `PATCH /admin/auth/profile` | `{ name, phone }` | 更新后的当前账号资料 |
| `PATCH /admin/auth/password` | `{ currentPassword, newPassword }` | `null`,需要重新登录 |
```json
{
@ -100,7 +103,7 @@ Redis 为 API 和登录提供跨进程限流,并缓存可重建的演示读取
}
```
应用使用 `Authorization: Bearer <accessToken>`。每次启动重新请求会话资料与权限,401 清除失效会话;其他启动请求失败保留错误,避免用旧权限继续工作。当前模板的路由角色契约是单个 `user.role`,路由 `meta.role` 为允许访问的角色数组。权限码独立于角色名称,可由自有服务端自由组织。
自有后端默认用 `Authorization: Bearer <accessToken>`。每次启动重新请求会话资料与权限,401 清除失效会话;其他错误保留为失败状态。当前模板的路由角色契约是单个 `user.role`,路由 `meta.role` 为允许访问的角色数组。权限码独立于角色名称,可由自有服务端自由组织。个人资料只允许用户自行编辑姓名和电话,用户名、邮箱、角色和部门由用户管理维护。
```tsx
import { useAccess } from '@/hooks'
@ -116,16 +119,17 @@ hasPermission(['users:update', 'users:delete'], 'any')
## 用户管理
| 方法和路径 | 输入 | 需要的权限 |
| -------------------------------- | ----------------------------------------------------- | -------------- |
| `GET /admin/users/options` | 无 | `users:read` |
| `GET /admin/users` | 分页及 `name/username/email/departmentId/role/status` | `users:read` |
| `GET /admin/users/{id}` | 路径 id | `users:read` |
| `POST /admin/users` | `UserInput` | `users:create` |
| `PUT /admin/users/{id}` | 完整 `UserInput` | `users:update` |
| `POST /admin/users/batch-delete` | `{ ids: string[] }` | `users:delete` |
| `PATCH /admin/users/status` | `{ ids: string[], status: "enabled" 或 "disabled" }` | `users:status` |
| `POST /admin/users/reset` | 无,仅演示恢复入口 | `users:reset` |
| 方法和路径 | 输入 | 需要的权限 |
| ---------------------------------- | ----------------------------------------------------- | ------------------- |
| `GET /admin/users/options` | 无 | `users:read` |
| `GET /admin/users` | 分页及 `name/username/email/departmentId/role/status` | `users:read` |
| `GET /admin/users/{id}` | 路径 id | `users:read` |
| `POST /admin/users` | `UserInput` | `users:create` |
| `PUT /admin/users/{id}` | 完整 `UserInput` | `users:update` |
| `POST /admin/users/batch-delete` | `{ ids: string[] }` | `users:delete` |
| `PATCH /admin/users/status` | `{ ids: string[], status: "enabled" 或 "disabled" }` | `users:status` |
| `PUT /admin/users/{id}/credential` | `{ newPassword }`,目标不能是当前账号 | `users:credentials` |
| `POST /admin/users/reset` | 无,仅演示恢复入口 | `users:reset` |
```json
{
@ -142,13 +146,13 @@ hasPermission(['users:update', 'users:delete'], 'any')
响应用户增加稳定的 `id` 与 ISO 8601 `createdAt`。账号与邮箱不区分大小写检查唯一性,更新时保留 id 与创建时间。组织选项由接口返回 `{ departments: [{ id, parentId, name, labelKey? }], roles: [{ value, label, labelKey?, disabled? }] }`,部门过滤包含子组织。`labelKey` 可选,用于演示中的中英文翻译;自有后端直接提供名称即可。
批量操作在接口层整体校验后提交,避免一部分成功一部分失败;当前账号不可被删除、停用或通过编辑更换角色。Mock 数据库将用户、路由与会话持久化在当前浏览器;写入失败时保留原数据并返回错误,编辑表单可重试。用户页的恢复按钮只在 Mock 模式显示。
批量操作在接口层整体校验后提交,避免一部分成功一部分失败;当前账号不可被删除、停用或通过编辑更换角色。通过编辑修改状态也需要 `users:status`。只有账号管理权限的用户可以维护目标账号及其凭据,管理者不能操作管理员账号。Mock 数据库将用户、路由与会话持久化在当前浏览器;用户页的恢复按钮只在 Mock 模式显示。
## 路由管理
`GET /admin/route-config` 是公开的前端启动配置接口,返回 `data: { version: 1, routes: [...] }`;路由元数据不包含业务秘密。维护路由时,携带 `routes:write` 权限的会话请求 `GET /admin/route-config?view=editor` 读取完整配置,再以同一结构提交 `PUT /admin/route-config`。若自有系统需要受保护的菜单读取,可在 API 适配层把读取移到登录后,并保留登录与错误页的启动路由。
`GET /admin/route-config` 在登录后调用,返回当前会话可用的 `data: { version: 1, routes: [...] }`。服务端同时考虑父子角色约束、视图权限和演示开关;没有可用子项的分组和无法到达授权目标的重定向都会移除。没有 `routes:read` 或没有可用页面时返回 `routes: []`,外壳和个人信息仍可用。携带 `routes:write` 的会话可用 `GET /admin/route-config?view=editor` 读取完整配置,再通过 `PUT /admin/route-config` 保存。
现有菜单表已迁到 `packages/demo-data/src/routes.json`,作为 Mock 初始数据库和显式离线恢复来源。正常在线启动走 GET,路由可视化与 JSON 的接口模式保存走 PUT,成功后重新加载并从接口读回。真实后端模式下,远端读取失败会中止启动,不会自动展示内置业务菜单;用户显式选定的本地或静态来源仍可用于离线恢复。导入、导出与接口中的路由内容使用同一结构,详情见[路由契约](./routing)。
初始菜单表位于 `packages/demo-data/src/routes.json`。标准 API 模式以服务端为准,登录时注入运行路由,保存后重新加载。读取失败不会回退为内置菜单。已被裁剪的业务地址直接访问会进入 404;固定的路由管理入口没有编辑权限时进入 403;业务 API 独立授权。导入、导出与接口使用同一结构,详情见[路由契约](./routing)。
前端 `router/config/views.ts` 保留组件 ID 白名单,接口只返回 ID;后端或 AI 不需要传递组件代码。登录、404 和受保护的路由管理入口由外壳保留。原 `VITE_ROUTE_CONFIG_URL` 仍兼容旧的原始 JSON 读取接口;完整读写接入使用上面的标准 API 基址。

View File

@ -55,7 +55,7 @@ pnpm fullstack:setup
pnpm dev:full
```
`setup` 首次创建 `apps/server/.env.local`,生成数据库、Redis 和管理员随机密码,启动 PostgreSQL 与 Redis,执行迁移并初始化管理员。配置文件权限按私有文件创建,不应提交、上传或放进前端变量。管理员账号与密码从该文件读取;Mock 的 `123456` 只用于前端演示。
`setup` 首次创建 `apps/server/.env.local`,生成数据库、Redis、管理员随机密码和 JWT 签名密钥,启动 PostgreSQL 与 Redis,执行迁移并初始化管理员。配置文件按私有文件创建;请在本机读取初始用户名和密码,勿提交、上传或放进前端变量。Mock 的 `123456` 只用于前端演示。
再次执行 `setup` 会复用配置、保留已有账号和数据库内容。`dev:full` 等待后端就绪后再启动前端,通过 Vite 将同源 `/api/` 请求代理给后端,并关闭 Mock。默认地址为 `http://127.0.0.1:9527/ray-template/`;可用 `ADMIN_DEV_PORT` 和 `PORT` 分别指定前端和后端端口。按 `Ctrl+C` 关闭开发进程;`pnpm fullstack:stop` 停止 Compose 服务并保留数据卷。
@ -72,9 +72,9 @@ pnpm dev:full
### 创建真实登录账号
用户管理页创建的是用户资料,默认没有登录凭据。通过安全环境提供 `CREDENTIAL_USERNAME` 与 `CREDENTIAL_PASSWORD`,再执行 `pnpm server:credential:set`。密码要求 12–128 个字符;该命令设置凭据并撤销该账号已有会话。避免将密码直接写入 shell 历史。
在用户管理新增资料后,有 `users:credentials` 权限的管理员可以为该账号点击 **设置密码**。已登录用户可在头像菜单的 **个人信息** 页面修改自己的密码,需要输入当前密码。改密或重设会撤销该账号的所有会话。密码要求 12–128 个字符。
重复执行 `setup` 不会重置管理员密码。需要更换密码时,同样使用显式的凭据命令。服务端存储密码派生值和会话令牌摘要,认证继续使用已有 Bearer 契约。
无法登录时,运维可通过安全环境提供 `CREDENTIAL_USERNAME` 与 `CREDENTIAL_PASSWORD`,再执行 `pnpm server:credential:set`。该命令适用于直接访问项目数据库的运维终端。重复执行 `setup` 不会创建改名前的账号,也不会重置密码。不要把密码写进命令行、终端记录或 AI 对话。
### 服务与运行检查
@ -93,16 +93,25 @@ pnpm dev:full
### 容器启动
执行 `pnpm fullstack:setup` 后,可以使用 Compose 的 `app` profile 启动静态前端、NestJS 和数据服务:
准备仓库指定的 Node.js 26.13.0,以及已启动的 Docker 和 Compose v2 插件(`docker compose version`、`docker info` 均应成功)。从解压后的全栈源码或完整仓库根目录运行:
```sh
docker compose -p ray-template --env-file apps/server/.env.local \
-f deploy/compose.yaml --profile app up --build -d --wait
node scripts/fullstack.mjs up
# 使用 pnpm 时,也可以运行 pnpm fullstack:up
```
默认打开 `http://127.0.0.1:8080/ray-template/`。设置 `APP_PORT` 可改变本机入口端口;代理和自定义域名场景应把实际浏览器来源填入 `APP_ORIGINS`。容器用 `APP_DEMO_ENABLED=true` 开启演示。Nginx 覆盖转发头,后端仅信任 Nginx 的固定地址,且不映射宿主机端口。代理网段冲突时,设置 `APP_PROXY_NETWORK` 为其他私有 IPv4 前三段(例如 `172.30.68`)。默认连接串适用于初始化生成的 URL 安全密码;自定义密码需要在 `APP_DATABASE_URL`、`APP_REDIS_URL` 中正确编码。
此命令创建私有配置、构建 Admin 和 API、启动 PostgreSQL 与 Redis、执行迁移和初始化,等服务就绪后打印本机入口。宿主机无需预先安装前端依赖。默认入口为 `http://127.0.0.1:8080/ray-template/`,可通过 `APP_PORT` 改端口。使用 `node scripts/fullstack.mjs stop` 停止服务,数据卷保留。多个隔离实例要为每份配置指定不同的 `RAY_COMPOSE_PROJECT`、宿主机端口和 `APP_PROXY_NETWORK`。
`node deploy/smoke.mjs` 使用临时 Compose 项目检查迁移、前端构建、登录、CORS、演示开关和代理限流,并清理测试容器与数据卷。对外部署仍需要为目标环境验证 HTTPS、实际代理链、持久化存储和备份。
Nginx 将同源 `/api/` 转发给后端。默认只在回环地址暴露宿主机端口,生产模式关闭演示(可用 `APP_DEMO_ENABLED=true` 显式开启)。外部 HTTPS 入口设置 `APP_ORIGINS` 为实际浏览器来源、`APP_SESSION_COOKIE_SECURE=true`,保留同源的 `/ray-template/` 和 `/api/`。示例 Nginx 会覆盖转发头;如再接外层反代,应在 Nginx 的 real IP 设置中只信任实际上一跳,并验证转发头无法伪造限流地址。代理网段冲突时,修改 `APP_PROXY_NETWORK`(例如 `172.30.68`)。容器连接外部数据库或 Redis 时,用正确编码的 `APP_DATABASE_URL`、`APP_REDIS_URL` 指定目标;已有服务的本机开发走 `setup --external`。
### 给部署者和 AI 的验收清单
1. 先确认发行物含 `apps/server`、`deploy/compose.yaml` 和 `scripts/fullstack.mjs`。默认选容器方式;需要热更新时走本地开发;已有 PostgreSQL、Redis 时用专用数据库和 Redis 前缀。端口占用就换 `APP_PORT`(容器)或 `PORT`、`ADMIN_DEV_PORT`(本机开发);数据库和 Redis 映射分别用 `POSTGRES_PORT`、`REDIS_PORT`。
2. 准备 PostgreSQL 迁移权限、Redis 连接以及服务端私有配置。部署副本共享同一个 `JWT_SECRET`(32 个随机字节的 base64url 编码),不同环境使用不同密钥。升级旧工作区可重跑 `setup` 或 `up` 补齐缺少的密钥;先备份 PostgreSQL,再应用迁移,旧令牌需重新登录。初始化配置中的密码只用于第一次建号。
3. 验证 `GET /api/health/live`、`GET /api/health/ready` 均返回 200,匿名 `GET /api/admin/route-config` 返回 401。登录后检查用户管理、个人信息和路由管理;为测试账号设置密码,并确认只读账号不能调用写接口。空菜单账号仍应能打开个人信息。
4. 如只有存活检查通过,用 Compose 的 `ps -a`、`logs initialize server` 检查迁移、初始化与连接。命令需使用 `--env-file apps/server/.env.local -f deploy/compose.yaml --profile app -p <项目名>`。只看脱敏日志,不回显环境文件。若浏览器登录后仍返回 401,检查实际访问源、同源代理和 Cookie 的 Secure 设置。对外部署还要验证目标环境的 HTTPS、备份恢复与代理限流。
`node deploy/smoke.mjs` 使用独立的临时 Compose 项目检查迁移、构建、登录、路由、CORS、演示开关和代理限流,并只清理它创建的测试资源。
### 生成分支与 Release 资产

View File

@ -4,7 +4,7 @@
import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
</script>
正常启动从 `GET /admin/route-config` 读取版本化路由 JSON,按 `meta.order` 排序;路由树用于菜单与面包屑,页面记录展开后注册到 Vue Router。Mock 的初始路由表位于 `packages/demo-data/src/routes.json`,前端只保留组件 ID 注册表和外壳必需路由。默认使用 hash 路由,例如 `/ray-template/#/orders`。
登录后从 `GET /admin/route-config` 读取会话可用的路由 JSON,按 `meta.order` 排序;路由树用于菜单和面包屑,展开后的页面记录注册到 Vue Router。Mock 的初始路由表位于 `packages/demo-data/src/routes.json`。外壳保留登录、个人信息和状态页。默认使用 hash 路由,例如 `/ray-template/#/orders`。
## 路由配置交互校验
@ -18,7 +18,7 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
## 在线编辑与接口接入
路由管理的可视化和 JSON 页面从当前生效配置创建草稿。可视化保存及 JSON 的服务端模式通过 `PUT /admin/route-config` 提交,成功后重新加载并从接口读回;Mock 写入会在当前浏览器刷新后保留。JSON 页面仍可显式切换为本机配置或内置初始配置,用于离线恢复。真实后端模式下,选定的远端来源读取失败会中止启动并显示启动错误,不自动回退为演示菜单。
有 `routes:write` 权限时,可视化和 JSON 页面从编辑接口加载完整草稿,通过 `PUT /admin/route-config` 保存,随后刷新运行路由。Mock 写入会保存在当前浏览器,也可以切换本机或内置配置。标准后端模式以远端为准,读取失败时显示错误。
接口请求体为 `{ version: 1, routes: [...] }`,读取和写入响应都放在统一 `{ code, msg, data }` 包络的 `data` 中。`component` 必须是 `router/config/views.ts` 的注册 ID;新增前端页面先注册 ID,再由接口返回其路由记录。详见[服务端标准契约](./backend)。

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@ An optional NestJS application implementing the shared admin HTTP contract. It o
Use the repository's pinned Node.js and pnpm versions. PostgreSQL and Redis must be reachable before starting the server. Configuration is loaded from `apps/server/.env.local` by the development, start and credential scripts. The Prisma config loads the same file for migrations. The root fullstack setup command prepares local development configuration.
Required connection fields are `DATABASE_URL` and `REDIS_URL`. Keep credentials in local environment files or a deployment secret store; never in `VITE_*` variables. See [platform configuration](src/platform/README.md) for exact origin allowlists, trusted proxies, rate limits, logging and readiness settings.
Required fields are `DATABASE_URL`, `REDIS_URL`, and `JWT_SECRET` (32 random bytes encoded as base64url). The launcher generates the key once; replicas of the same environment must share it. Store secrets in private configuration. See [platform configuration](src/platform/README.md) for origins, limits and readiness, and the [deployment runbook](../docs/guide/distributions.md) for Compose and external services.
```sh
pnpm --filter @ray-template/server db:migrate
@ -14,21 +14,21 @@ pnpm --filter @ray-template/server db:seed
pnpm --filter @ray-template/server dev
```
Initialization requires `ADMIN_PASSWORD` (12–128 characters) when creating the first account. `ADMIN_USERNAME` defaults to `admin`; `ADMIN_EMAIL` is optional. There is no built-in login password and no HTTP database reset endpoint. Re-running the seed preserves existing users, credentials, role assignments, permission assignments and route configuration.
Initialization requires `ADMIN_PASSWORD` (12–128 characters) when creating the first administrator. `ADMIN_USERNAME` defaults to `admin`; `ADMIN_EMAIL` is optional. Re-running the seed preserves existing users, credentials, grants and route configuration even after the administrator is renamed. There is no HTTP database reset endpoint.
## API and ownership
The API prefix is `/api`. Controllers provide `/admin/auth/login`, `/admin/auth/session`, `/admin/auth/logout`, `/admin/users`, user options/status/batch deletion, and `/admin/route-config`. Success responses use `{ code: 200, msg: 'OK', data }`; failures return the corresponding HTTP status with `data: null` and a stable `error.key`.
The API prefix is `/api`. It covers login, session, logout, self profile and password, user and credential management, and route configuration. Success uses `{ code: 200, msg: 'OK', data }`; errors return the matching HTTP status, `data: null`, and a stable `error.key`. See the [HTTP contract](../docs/guide/backend.md).
The startup route configuration is public because the admin application needs it before login. `GET /admin/route-config?view=editor` and route writes require `routes:write`; writes use the same semantic validator and generated view/icon catalog as the frontend. Protected core endpoints require an active server session. The global guard enforces endpoint permissions; mutation services recheck the actor and targets inside serializable transactions.
The runtime route configuration requires an active session and filters by `routes:read`, ancestor and leaf roles, view grants, and the demo flag. It removes empty groups and unusable redirects. No accessible routes yields `{ version: 1, routes: [] }`. The complete editor view and route writes require `routes:write`. The global guard enforces endpoint permissions and mutations recheck them in serializable transactions.
When `DEMO_ENABLED=true`, the public `/admin/demo/*` endpoints use the same fixture queries as Mock. Redis caches only the fixed request and chart fixtures and the two search-option locales for five minutes. In production demos default to off: these endpoints are absent and the public route configuration omits demo views, empty groups and redirects that would point to hidden views. The authorized editor still receives the complete saved configuration.
When `DEMO_ENABLED=true`, public `/admin/demo/*` endpoints use the same fixtures as Mock. Redis caches only fixed request and chart fixtures and the two search-option locales for five minutes. Demos default to off in production.
Usernames and email addresses have normalized unique database keys. Department queries include descendants. Bulk updates and deletion are atomic, deduplicate IDs, and reject changes to missing/protected targets. A user cannot delete or disable their own account or change their own role. Non-admin actors cannot manage roles with permissions they do not hold.
Authentication uses random opaque bearer tokens. Only SHA-256 token digests are stored; authorization reads current account status and role permissions from PostgreSQL on every request. Passwords use salted Node.js scrypt. Expired sessions are rejected; logout, credential reset, account disabling and role changes revoke effective access. Mutations and authentication changes write audit records without passwords, tokens or request bodies.
Authentication verifies the JWT signature, issuer, audience and expiry, then checks the token digest and live account grants in PostgreSQL. Passwords use salted scrypt. Logout revokes the current session; password changes, credential reset, account disabling and role changes revoke all affected sessions. The upgrade requires existing opaque-token clients to sign in again. Audits omit passwords, tokens and request bodies.
New users created through the profile API have no password. Set or reset one explicitly through the credential command using environment variables, not command-line password arguments:
Users can edit their own name and phone and change their password by proving the current password. An authorized administrator can set another user's password from User Management. Operators can recover a credential from a trusted terminal using private environment variables:
```sh
pnpm --filter @ray-template/server credential:set
@ -36,7 +36,7 @@ pnpm --filter @ray-template/server credential:set
This command reads `CREDENTIAL_USERNAME` and `CREDENTIAL_PASSWORD`, preserves account status/role, and revokes all sessions for that user. Remove temporary credential variables from local files after use. Expired sessions can be pruned with `node --env-file-if-exists=.env.local dist/cli.mjs cleanup-sessions` from this application directory.
The initial browser integration preserves the existing Bearer contract. Moving browser credentials to HttpOnly cookies requires a coordinated login-contract, request-client and CSRF change; it is not implied by enabling the backend.
The bundled same-origin Admin uses an HttpOnly, SameSite=Strict cookie with `X-Ray-Session: cookie`; login does not return the token in JSON in this mode. Use Secure host-only cookies over HTTPS. Explicit Bearer login remains available to API clients.
## Build and checks

View File

@ -25,12 +25,13 @@
"@prisma/client": "7.10.1",
"@ray-template/api-contracts": "workspace:*",
"@ray-template/demo-data": "workspace:*",
"express": "5.3.0",
"jose": "6.2.12",
"pg": "8.23.1",
"redis": "6.3.1",
"reflect-metadata": "0.2.2",
"rxjs": "7.8.2",
"valibot": "1.5.0",
"express": "5.3.0"
"valibot": "1.5.0"
},
"devDependencies": {
"@types/express": "5.0.6",

View File

@ -0,0 +1,5 @@
INSERT INTO "Permission" ("code") VALUES ('users:credentials') ON CONFLICT DO NOTHING;
INSERT INTO "RolePermission" ("roleValue", "permissionCode")
SELECT "value", 'users:credentials' FROM "Role" WHERE "value" = 'admin'
ON CONFLICT DO NOTHING;

View File

@ -46,7 +46,7 @@ export async function createApp(
try {
const database = app.get(DatabaseService)
const runtime = await PlatformRuntime.create(config, {
checkDatabase: () => database.ping(),
checkDatabase: () => database.assertInitialized(),
logSink: options.logSink,
})

View File

@ -12,6 +12,8 @@ import { map } from 'rxjs'
import * as v from 'valibot'
import { standardLogSink, writeLog } from './platform/index'
export { tokenFrom } from './platform/session'
export class ApiError extends Error {
constructor(
readonly status: number,
@ -32,14 +34,6 @@ export function parseInput<S extends v.GenericSchema>(
return parsed.output
}
export function tokenFrom(request: Request) {
const header = request.headers.authorization
return /^Bearer [A-Za-z0-9_-]{32,128}$/u.test(header ?? '')
? header!.slice(7)
: null
}
export function requestIdFrom(request: Request) {
const id = request.res?.getHeader('x-request-id')

View File

@ -64,8 +64,13 @@ export class DatabaseService implements OnModuleInit, OnModuleDestroy {
await this.prisma.$disconnect()
}
async ping() {
await this.prisma.$queryRaw`SELECT 1`
async assertInitialized() {
const routes = await this.prisma.routeConfig.findUnique({
where: { id: 'admin' },
select: { id: true },
})
if (!routes) throw new Error('Database is not initialized.')
}
async write<T>(

View File

@ -1,26 +1,100 @@
import { Body, Controller, Get, Inject, Post, Req } from '@nestjs/common'
import type { Request } from 'express'
import {
Body,
Controller,
Get,
Inject,
Patch,
Post,
Req,
Res,
} from '@nestjs/common'
import type { Request, Response } from 'express'
import { SERVER_CONFIG } from '../../config'
import { requestIdFrom, tokenFrom } from '../../http'
import { Public } from './auth.guard'
import type { ServerConfig } from '../../platform/config'
import {
browserSessionRequested,
writeSessionCookie,
} from '../../platform/session'
import { authFrom, Public } from './auth.guard'
import type { AuthenticatedRequest } from './auth.guard'
import { AuthService } from './auth.service'
@Controller('admin/auth')
export class AuthController {
constructor(@Inject(AuthService) private readonly auth: AuthService) {}
constructor(
@Inject(AuthService) private readonly auth: AuthService,
@Inject(SERVER_CONFIG) private readonly config: ServerConfig,
) {}
@Public()
@Post('login')
login(@Body() input: unknown, @Req() request: Request) {
return this.auth.login(input, requestIdFrom(request))
async login(
@Body() input: unknown,
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
) {
const session = await this.auth.login(input, requestIdFrom(request))
if (!browserSessionRequested(request)) return session
writeSessionCookie(response, this.config.sessionCookieSecure, session)
const { user, permissions, expiresAt } = session
return { user, permissions, expiresAt }
}
@Get('session')
session(@Req() request: Request) {
return this.auth.session(tokenFrom(request))
session(@Req() request: AuthenticatedRequest) {
const { user, permissions, expiresAt } = authFrom(request)
return { user, permissions, expiresAt }
}
@Get('profile')
profile(@Req() request: AuthenticatedRequest) {
return this.auth.profile(authFrom(request).user.id)
}
@Patch('profile')
updateProfile(@Body() input: unknown, @Req() request: Request) {
return this.auth.updateProfile(
input,
tokenFrom(request),
requestIdFrom(request),
)
}
@Patch('password')
async changePassword(
@Body() input: unknown,
@Req() request: AuthenticatedRequest,
@Res({ passthrough: true }) response: Response,
) {
await this.auth.changePassword(
input,
tokenFrom(request),
authFrom(request).user.id,
requestIdFrom(request),
)
this.clearBrowserSession(request, response)
return null
}
@Post('logout')
logout(@Req() request: Request) {
return this.auth.logout(tokenFrom(request), requestIdFrom(request))
async logout(
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
) {
await this.auth.logout(tokenFrom(request), requestIdFrom(request))
this.clearBrowserSession(request, response)
return null
}
private clearBrowserSession(request: Request, response: Response) {
if (browserSessionRequested(request))
writeSessionCookie(response, this.config.sessionCookieSecure)
}
}

View File

@ -4,9 +4,14 @@ import { Reflector } from '@nestjs/core'
import type { Request } from 'express'
import { tokenFrom } from '../../http'
import { AuthService } from './auth.service'
import type { AuthContext } from './auth.service'
const PUBLIC = Symbol('public')
const PERMISSION = Symbol('permission')
const AUTH = Symbol('auth')
export type AuthenticatedRequest = Request & { [AUTH]: AuthContext }
export const authFrom = (request: AuthenticatedRequest) => request[AUTH]
export const Public = () => SetMetadata(PUBLIC, true)
export const RequirePermission = (permission: string) =>
@ -28,9 +33,9 @@ export class AuthGuard implements CanActivate {
PERMISSION,
targets,
)
const request = context.switchToHttp().getRequest<Request>()
const request = context.switchToHttp().getRequest<AuthenticatedRequest>()
await this.auth.authenticate(tokenFrom(request), permission)
request[AUTH] = await this.auth.authenticate(tokenFrom(request), permission)
return true
}

View File

@ -1,12 +1,17 @@
import { Inject, Injectable } from '@nestjs/common'
import { loginInputSchema } from '@ray-template/api-contracts/admin'
import {
changePasswordSchema,
loginInputSchema,
profileInputSchema,
} from '@ray-template/api-contracts/admin'
import type { SessionInfo } from '@ray-template/api-contracts/admin'
import { SERVER_CONFIG } from '../../config'
import { ApiError, parseInput } from '../../http'
import { DatabaseService } from '../../infrastructure/database'
import type { Database } from '../../infrastructure/database'
import type { ServerConfig } from '../../platform/index'
import { createToken, tokenHash, verifyPassword } from './password'
import { signSession, verifySession } from './jwt'
import { hashPassword, tokenHash, verifyPassword } from './password'
export interface AuthContext extends SessionInfo {
tokenHash: string
@ -26,6 +31,10 @@ export class AuthService {
): Promise<AuthContext> {
if (!token) throw new ApiError(401, 'unauthorized')
const subject = await verifySession(this.config.jwtSecret, token)
if (!subject) throw new ApiError(401, 'unauthorized')
const hash = tokenHash(token)
const session = await database.session.findUnique({
where: { tokenHash: hash },
@ -36,6 +45,7 @@ export class AuthService {
if (
!session ||
session.userId !== subject ||
session.expiresAt.getTime() <= Date.now() ||
session.user.status !== 'enabled'
)
@ -49,7 +59,12 @@ export class AuthService {
if (permission && !permissions.includes(permission))
throw new ApiError(403, 'forbidden')
return { user: { id, username, name, role }, permissions, tokenHash: hash }
return {
user: { id, username, name, role },
permissions,
expiresAt: session.expiresAt.toISOString(),
tokenHash: hash,
}
}
async login(input: unknown, requestId: string | null) {
@ -70,11 +85,12 @@ export class AuthService {
throw new ApiError(401, 'invalidCredentials')
}
const accessToken = createToken()
const hash = tokenHash(accessToken)
const expiresAt = new Date(
Date.now() + this.config.sessionTtlSeconds * 1000,
const { token: accessToken, expiresAt } = await signSession(
this.config.jwtSecret,
user.id,
this.config.sessionTtlSeconds,
)
const hash = tokenHash(accessToken)
return this.database.write(async (transaction) => {
const current = await transaction.user.findUnique({
@ -119,10 +135,95 @@ export class AuthService {
})
}
async session(token: string | null): Promise<SessionInfo> {
const { user, permissions } = await this.authenticate(token)
async profile(id: string, database: Database = this.database.prisma) {
const user = await database.user.findUnique({
where: { id },
select: {
id: true,
username: true,
name: true,
role: true,
email: true,
phone: true,
department: {
select: { id: true, parentId: true, name: true, labelKey: true },
},
},
})
return { user, permissions }
if (!user) throw new ApiError(401, 'unauthorized')
const { labelKey, ...department } = user.department
return {
...user,
department: { ...department, ...(labelKey ? { labelKey } : {}) },
}
}
async updateProfile(
input: unknown,
token: string | null,
requestId: string | null,
) {
const profile = parseInput(profileInputSchema, input)
return this.database.write(async (transaction) => {
const { user } = await this.authenticate(token, void 0, transaction)
await transaction.user.update({ where: { id: user.id }, data: profile })
await transaction.auditLog.create({
data: { actorId: user.id, action: 'auth.profile.update', requestId },
})
return this.profile(user.id, transaction)
})
}
async changePassword(
input: unknown,
token: string | null,
actorId: string,
requestId: string | null,
) {
const { currentPassword, newPassword } = parseInput(
changePasswordSchema,
input,
)
const credential = await this.database.prisma.credential.findUnique({
where: { userId: actorId },
})
if (
!(await verifyPassword(
currentPassword,
credential?.passwordHash ?? null,
)) ||
!credential
)
throw new ApiError(400, 'invalidCurrentPassword')
if (currentPassword === newPassword)
throw new ApiError(400, 'passwordUnchanged')
const passwordHash = await hashPassword(newPassword)
await this.database.write(async (transaction) => {
const { user } = await this.authenticate(token, void 0, transaction)
const changed = await transaction.credential.updateMany({
where: { userId: user.id, passwordHash: credential.passwordHash },
data: { passwordHash },
})
if (!changed.count) throw new ApiError(409, 'credentialChanged')
await transaction.session.deleteMany({ where: { userId: user.id } })
await transaction.auditLog.create({
data: { actorId: user.id, action: 'auth.password.change', requestId },
})
})
return null
}
async logout(token: string | null, requestId: string | null) {

View File

@ -0,0 +1,24 @@
import type { Prisma } from '../../generated/prisma/client'
export async function replaceCredential(
transaction: Prisma.TransactionClient,
userId: string,
passwordHash: string,
actorId: string | null = null,
requestId: string | null = null,
) {
await transaction.credential.upsert({
where: { userId },
create: { userId, passwordHash },
update: { passwordHash },
})
await transaction.session.deleteMany({ where: { userId } })
await transaction.auditLog.create({
data: {
action: 'credentials.reset',
resourceId: userId,
actorId,
requestId,
},
})
}

View File

@ -0,0 +1,44 @@
import { randomUUID } from 'node:crypto'
import { jwtVerify, SignJWT } from 'jose'
const algorithm = 'HS256'
const issuer = 'ray-template'
const audience = 'ray-admin'
const type = 'JWT'
export async function signSession(
secret: Uint8Array,
userId: string,
ttl: number,
) {
const issuedAt = Math.floor(Date.now() / 1000)
const expiration = issuedAt + ttl
const token = await new SignJWT()
.setProtectedHeader({ alg: algorithm, typ: type })
.setIssuer(issuer)
.setAudience(audience)
.setSubject(userId)
.setJti(randomUUID())
.setIssuedAt(issuedAt)
.setExpirationTime(expiration)
.sign(secret)
return { token, expiresAt: new Date(expiration * 1000) }
}
export async function verifySession(secret: Uint8Array, token: string) {
try {
const { payload } = await jwtVerify(token, secret, {
algorithms: [algorithm],
issuer,
audience,
typ: type,
requiredClaims: ['sub', 'jti', 'iat', 'exp'],
})
if (typeof payload.sub === 'string' && typeof payload.jti === 'string')
return payload.sub
} catch {
// 校验失败统一按无效会话处理,避免暴露签名和过期细节。
}
}

View File

@ -45,5 +45,3 @@ export async function verifyPassword(password: string, stored: string | null) {
export const tokenHash = (token: string) =>
createHash('sha256').update(token).digest('hex')
export const createToken = () => randomBytes(32).toString('base64url')

View File

@ -1,4 +1,5 @@
import { Body, Controller, Get, Inject, Put, Query, Req } from '@nestjs/common'
import { filterRuntimeRoutes } from '@ray-template/api-contracts/routes'
import { parseApplicationRoutes } from '@ray-template/demo-data'
import type { Request } from 'express'
import { SERVER_CONFIG } from '../../config'
@ -6,9 +7,9 @@ import type { Prisma } from '../../generated/prisma/client'
import { ApiError, requestIdFrom, tokenFrom } from '../../http'
import { DatabaseService } from '../../infrastructure/database'
import type { ServerConfig } from '../../platform/index'
import { Public, RequirePermission } from '../auth/auth.guard'
import { authFrom, RequirePermission } from '../auth/auth.guard'
import type { AuthenticatedRequest } from '../auth/auth.guard'
import { AuthService } from '../auth/auth.service'
import { withoutDemoRoutes } from './runtime-routes'
@Controller('admin/route-config')
export class RoutesController {
@ -18,13 +19,17 @@ export class RoutesController {
@Inject(SERVER_CONFIG) private readonly config: ServerConfig,
) {}
@Public()
@Get()
async get(@Req() request: Request, @Query('view') view: unknown) {
async get(
@Req() request: AuthenticatedRequest,
@Query('view') view: unknown,
) {
if (view !== void 0 && view !== 'editor') throw new ApiError(400, 'invalid')
if (view === 'editor')
await this.auth.authenticate(tokenFrom(request), 'routes:write')
const session = authFrom(request)
if (view === 'editor' && !session.permissions.includes('routes:write'))
throw new ApiError(403, 'forbidden')
const record = await this.database.prisma.routeConfig.findUnique({
where: { id: 'admin' },
@ -35,9 +40,13 @@ export class RoutesController {
try {
const routes = parseApplicationRoutes(JSON.stringify(record.config))
return this.config.demoEnabled || view === 'editor'
return view === 'editor'
? routes
: withoutDemoRoutes(routes)
: filterRuntimeRoutes(routes, {
role: session.user.role,
permissions: session.permissions,
demoEnabled: this.config.demoEnabled,
})
} catch {
throw new ApiError(503, 'invalidRoutes')
}

View File

@ -1,48 +0,0 @@
import type {
RouteConfig,
RouteConfigRecord,
} from '@ray-template/api-contracts/routes'
export function withoutDemoRoutes(config: RouteConfig): RouteConfig {
const leaves = new Map<string, RouteConfigRecord>()
const visit = (routes: RouteConfigRecord[], parent = '') => {
for (const route of routes) {
const path = route.path.startsWith('/')
? route.path
: `${parent}/${route.path}`
if (route.children) visit(route.children, path)
else {
leaves.set(path.toLowerCase(), route)
for (const alias of [route.alias ?? []].flat())
leaves.set(alias.toLowerCase(), route)
}
}
}
visit(config.routes)
const isVisible = (route: RouteConfigRecord): boolean => {
if (route.component?.startsWith('demo/')) return false
if (!route.redirect) return true
// 校验已排除循环;指向关闭页面的别名与重定向也不能留在运行菜单中。
const target = leaves.get(route.redirect.toLowerCase())
return !!target && isVisible(target)
}
const prune = (routes: RouteConfigRecord[]): RouteConfigRecord[] =>
routes.flatMap((route) => {
if (!isVisible(route)) return []
if (!route.children) return [route]
const children = prune(route.children)
return children.length ? [{ ...route, children }] : []
})
return { ...config, routes: prune(config.routes) }
}

View File

@ -12,7 +12,8 @@ import {
} from '@nestjs/common'
import type { Request } from 'express'
import { queryInput, requestIdFrom, tokenFrom } from '../../http'
import { RequirePermission } from '../auth/auth.guard'
import { authFrom, RequirePermission } from '../auth/auth.guard'
import type { AuthenticatedRequest } from '../auth/auth.guard'
import { UsersService } from './users.service'
@Controller('admin/users')
@ -21,8 +22,8 @@ export class UsersController {
@Get('options')
@RequirePermission('users:read')
options(@Req() request: Request) {
return this.users.options(tokenFrom(request))
options(@Req() request: AuthenticatedRequest) {
return this.users.options(authFrom(request))
}
@Get()
@ -73,4 +74,19 @@ export class UsersController {
requestIdFrom(request),
)
}
@Put(':id/credential')
@RequirePermission('users:credentials')
setCredential(
@Param('id') id: string,
@Body() input: unknown,
@Req() request: Request,
) {
return this.users.setCredential(
id,
input,
tokenFrom(request),
requestIdFrom(request),
)
}
}

View File

@ -1,5 +1,6 @@
import { Inject, Injectable } from '@nestjs/common'
import {
credentialInputSchema,
idsSchema,
statusInputSchema,
userInputSchema,
@ -12,6 +13,8 @@ import { DatabaseService } from '../../infrastructure/database'
import type { Database } from '../../infrastructure/database'
import { AuthService } from '../auth/auth.service'
import type { AuthContext } from '../auth/auth.service'
import { replaceCredential } from '../auth/credentials'
import { hashPassword } from '../auth/password'
export function userView(user: User): AdminUser {
return {
@ -35,8 +38,7 @@ export class UsersService {
@Inject(AuthService) private readonly auth: AuthService,
) {}
async options(token: string | null) {
const session = await this.auth.authenticate(token, 'users:read')
async options(session: AuthContext) {
const [departments, roles] = await Promise.all([
this.database.prisma.department.findMany({ orderBy: { id: 'asc' } }),
this.database.prisma.role.findMany({
@ -56,10 +58,11 @@ export class UsersService {
...(labelKey ? { labelKey } : {}),
disabled:
session.user.role !== 'admin' &&
permissions.some(
({ permissionCode }) =>
!session.permissions.includes(permissionCode),
),
(value === 'admin' ||
permissions.some(
({ permissionCode }) =>
!session.permissions.includes(permissionCode),
)),
})),
}
}
@ -150,9 +153,10 @@ export class UsersService {
if (
session.user.role !== 'admin' &&
target.permissions.some(
({ permissionCode }) => !session.permissions.includes(permissionCode),
)
(role === 'admin' ||
target.permissions.some(
({ permissionCode }) => !session.permissions.includes(permissionCode),
))
)
throw new ApiError(403, 'forbidden')
}
@ -215,6 +219,13 @@ export class UsersService {
)
throw new ApiError(409, 'selfProtected')
if (
existing &&
existing.status !== value.status &&
!session.permissions.includes('users:status')
)
throw new ApiError(403, 'forbidden')
await this.validateUnique(transaction, value, id)
const data = {
@ -281,6 +292,39 @@ export class UsersService {
})
}
async setCredential(
id: string,
input: unknown,
token: string | null,
requestId: string | null,
) {
const { newPassword } = parseInput(credentialInputSchema, input)
const passwordHash = await hashPassword(newPassword)
await this.database.write(async (transaction) => {
const session = await this.auth.authenticate(
token,
'users:credentials',
transaction,
)
if (id === session.user.id) throw new ApiError(409, 'selfProtected')
const user = await this.findUser(transaction, id)
await this.assertManageRole(transaction, session, user.role)
await replaceCredential(
transaction,
user.id,
passwordHash,
session.user.id,
requestId,
)
})
return null
}
async changeStatus(
input: unknown,
token: string | null,

View File

@ -6,30 +6,32 @@ Create the Nest application with `bodyParser: false`, install the runtime before
## Configuration
| Variable | Default | Meaning |
| ---------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `NODE_ENV` | `development` | `development`, `test`, or `production` |
| `HOST` | `127.0.0.1` | Listening interface; containers explicitly use `0.0.0.0` |
| `PORT` | `3000` | HTTP port; port zero is allowed only in tests |
| `DATABASE_URL` | Required | PostgreSQL connection URL |
| `REDIS_URL` | Required | Redis connection URL; use `rediss:` for TLS |
| `REDIS_KEY_PREFIX` | `ray:<NODE_ENV>` | Isolate applications and environments sharing Redis |
| `CORS_ORIGINS` | Empty | Comma-separated exact origins, including the web application's origin; no wildcard or paths |
| `TRUST_PROXY` | `false` | Comma-separated trusted proxy IP addresses/CIDRs; unrestricted trust and hop counts are rejected |
| `DEMO_ENABLED` | `false` in production, otherwise `true` | Whether the host registers read-only demonstration endpoints |
| `SESSION_TTL_SECONDS` | `28800` | Session expiry consumed by the authentication module |
| `BODY_LIMIT_BYTES` | `262144` | JSON payload limit, up to 1 MiB |
| `REQUEST_TIMEOUT_MS` | `15000` | Node's request reception timeout, not a controller execution deadline |
| `RATE_LIMIT_MAX` | `300` | Requests per client IP per fixed 60-second window |
| `LOGIN_RATE_LIMIT_MAX` | `10` | Login attempts per normalized account per fixed 15-minute window; IP limit is five times this value |
| Variable | Default | Meaning |
| ----------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `NODE_ENV` | `development` | `development`, `test`, or `production` |
| `HOST` | `127.0.0.1` | Listening interface; containers explicitly use `0.0.0.0` |
| `PORT` | `3000` | HTTP port; port zero is allowed only in tests |
| `DATABASE_URL` | Required | PostgreSQL connection URL |
| `REDIS_URL` | Required | Redis connection URL; use `rediss:` for TLS |
| `JWT_SECRET` | Required | 32 random bytes encoded as base64url, shared by replicas of this deployment |
| `SESSION_COOKIE_SECURE` | `true` in production, otherwise `false` | Secure host-only cookie for HTTPS; use `false` only with loopback HTTP |
| `REDIS_KEY_PREFIX` | `ray:<NODE_ENV>` | Isolate applications and environments sharing Redis |
| `CORS_ORIGINS` | Empty | Comma-separated exact origins, including the web application's origin; no wildcard or paths |
| `TRUST_PROXY` | `false` | Comma-separated trusted proxy IP addresses/CIDRs; unrestricted trust and hop counts are rejected |
| `DEMO_ENABLED` | `false` in production, otherwise `true` | Whether the host registers read-only demonstration endpoints |
| `SESSION_TTL_SECONDS` | `28800` | Session expiry consumed by the authentication module |
| `BODY_LIMIT_BYTES` | `262144` | JSON payload limit, up to 1 MiB |
| `REQUEST_TIMEOUT_MS` | `15000` | Node's request reception timeout, not a controller execution deadline |
| `RATE_LIMIT_MAX` | `300` | Requests per client IP per fixed 60-second window |
| `LOGIN_RATE_LIMIT_MAX` | `10` | Login attempts per normalized account per fixed 15-minute window; IP limit is five times this value |
No-origin requests are accepted; browser origins must be explicitly listed. Credentials are Bearer tokens and CORS does not enable cookie credentials. A future cookie authentication mode must define CSRF protection and the corresponding contract separately.
Bearer requests can omit Origin. Browser cookie requests require `X-Ray-Session: cookie`; writes also require an exact allowlisted Origin. Cross-origin fetch metadata is rejected and credentialed CORS is disabled. Keep the bundled browser and API on the same origin.
Proxy trust defaults to the direct socket address. Configure only proxies that overwrite incoming forwarding headers; otherwise a caller may impersonate another IP. Exact CORS matching is a browser boundary, not authorization.
## Redis behavior
Rate counters use an atomic Lua increment/expiry operation. Account and IP identities are hashed before becoming Redis keys. Login limiting happens before password verification and covers case-insensitive Express routes. Limits count both successful and unsuccessful attempts. An unavailable Redis connection makes admin API requests fail closed with HTTP 503 and readiness fail; no per-process production fallback exists.
Rate counters use an atomic Lua increment/expiry operation. Account, session and IP identities are hashed before becoming Redis keys. Login and self password change limits run before password verification and cover case-insensitive paths. Limits count successful and unsuccessful attempts. Redis outages return HTTP 503 and fail readiness.
`runtime.cache.getOrLoad(key, ttlSeconds, loader, validator?)` is for reconstructible, non-sensitive reads such as demonstration chart data. Cache failures load the original data, while loader errors propagate. Validate cached payloads at the consuming contract when appropriate. `invalidate(key)` propagates Redis failures so callers cannot mistake failed invalidation for success.
@ -40,7 +42,7 @@ The client disables offline command queues, bounds connection and command waits,
Every response has `X-Request-Id`. A valid bounded incoming ID is reused; otherwise a random UUID is generated. Completion logs contain only timestamp, level, event, request ID, HTTP method, route template, status, and duration. Unmatched or rejected requests do not log raw paths. Request bodies, headers, query strings, resource IDs, and raw error messages are excluded. Dependency errors use a small allowlist of diagnostic codes.
- `GET /api/health/live` reports whether the process can answer HTTP.
- `GET /api/health/ready` checks PostgreSQL and Redis with a bounded read-only probe and returns 503 on failure. It exposes no connection details.
- `GET /api/health/ready` checks the seeded PostgreSQL route record and Redis with a bounded read-only probe and returns 503 on failure. It exposes no connection details.
Node's request/header timeouts bound slow request reception. They do not race a transaction against an HTTP response: the database layer owns query and transaction timeouts. There is no attempt to report a timed-out mutation as cancelled while it continues committing.

View File

@ -10,6 +10,8 @@ export interface ServerConfig {
corsOrigins: string[]
trustProxy: false | string[]
demoEnabled: boolean
jwtSecret: Uint8Array
sessionCookieSecure: boolean
sessionTtlSeconds: number
bodyLimitBytes: number
requestTimeoutMs: number
@ -127,6 +129,12 @@ export function loadServerConfig(
)
}
const secret = env.JWT_SECRET ?? ''
const jwtSecret = Buffer.from(secret, 'base64url')
if (jwtSecret.length !== 32 || jwtSecret.toString('base64url') !== secret)
throw new Error('JWT_SECRET must be 32 random bytes encoded as base64url.')
return {
nodeEnv: nodeEnv as ServerConfig['nodeEnv'],
host: env.HOST || '127.0.0.1',
@ -137,6 +145,11 @@ export function loadServerConfig(
corsOrigins,
trustProxy,
demoEnabled: boolean('DEMO_ENABLED', nodeEnv !== 'production'),
jwtSecret,
sessionCookieSecure: boolean(
'SESSION_COOKIE_SECURE',
nodeEnv === 'production',
),
sessionTtlSeconds: integer('SESSION_TTL_SECONDS', 28800, 60, 604800),
bodyLimitBytes: integer('BODY_LIMIT_BYTES', 262144, 1024, 1048576),
requestTimeoutMs: integer('REQUEST_TIMEOUT_MS', 15000, 1000, 120000),

View File

@ -17,6 +17,11 @@ import {
import type { LogSink } from './logging.js'
import { RedisJsonCache, RedisRateLimiter, RedisStore } from './redis.js'
import type { RedisCommands } from './redis.js'
import {
browserSessionRequested,
setSessionCookieMode,
tokenFrom,
} from './session.js'
interface RuntimeOptions {
checkDatabase: () => Promise<unknown>
@ -119,6 +124,20 @@ export class PlatformRuntime {
return
}
if (browserSessionRequested(request)) {
const site = request.get('Sec-Fetch-Site')
const safe = ['GET', 'HEAD', 'OPTIONS'].includes(request.method)
// 浏览器会话仅供同源前端使用;Cookie 本身不能授权写请求。
if ((site && site !== 'same-origin') || (!safe && !origin)) {
failure(response, 403, 'forbidden')
return
}
setSessionCookieMode(response, this.config.sessionCookieSecure)
}
if (origin) {
response.setHeader('Access-Control-Allow-Origin', origin)
response.setHeader(
@ -259,22 +278,34 @@ export class PlatformRuntime {
limit: this.config.loginRateLimitMax * 5,
windowMs: 900000,
})
const username: unknown = request.body?.username
const rawUsername: unknown = request.body?.username
const username = typeof rawUsername === 'string' ? rawUsername.trim() : ''
if (
typeof username === 'string' &&
username.length <= 80 &&
username.trim()
) {
if (username.length > 0 && username.length <= 80) {
limits.push({
bucket: 'login-account',
identity: username.trim().toLowerCase(),
identity: username.toLowerCase(),
limit: this.config.loginRateLimitMax,
windowMs: 900000,
})
}
}
if (
request.method === 'PATCH' &&
/^\/api\/admin\/auth\/password\/?$/iu.test(request.path)
) {
const token = tokenFrom(request)
if (token)
limits.push({
bucket: 'password-session',
identity: token,
limit: this.config.loginRateLimitMax,
windowMs: 900000,
})
}
for (const limit of limits) {
const result = await this.limiter.consume(
limit.bucket,

View File

@ -0,0 +1,57 @@
import type { Request, Response } from 'express'
const browserSessionHeader = 'X-Ray-Session'
const tokenPattern = /^[\w-]+\.[\w-]+\.[\w-]+$/u
const cookieName = (secure: boolean) =>
secure ? '__Host-ray-session' : 'ray-session'
export const browserSessionRequested = (request: Request) =>
request.get(browserSessionHeader) === 'cookie'
export function setSessionCookieMode(response: Response, secure: boolean) {
response.locals.sessionCookie = cookieName(secure)
}
export function tokenFrom(request: Request) {
let token: string | undefined
if (browserSessionRequested(request)) {
const name = request.res?.locals.sessionCookie
if (typeof name !== 'string') return null
const matches = request.headers.cookie
?.split(';')
.map((part) => part.trim())
.filter((part) => part.startsWith(`${name}=`))
if (matches?.length === 1) token = matches[0].slice(name.length + 1)
} else {
token = /^Bearer (\S+)$/iu.exec(request.headers.authorization ?? '')?.[1]
}
return token && token.length <= 2048 && tokenPattern.test(token)
? token
: null
}
export function writeSessionCookie(
response: Response,
secure: boolean,
session?: { accessToken: string; expiresAt: string },
) {
const name = cookieName(secure)
const options = {
httpOnly: true,
sameSite: 'strict',
secure,
path: secure ? '/' : '/api/admin',
} as const
if (session)
response.cookie(name, session.accessToken, {
...options,
expires: new Date(session.expiresAt),
})
else response.clearCookie(name, options)
}

View File

@ -6,6 +6,7 @@ import { initialRoutes, initialUserOptions } from '@ray-template/demo-data'
import type { Prisma, PrismaClient } from './generated/prisma/client'
import { parseInput } from './http'
import { writeTransaction } from './infrastructure/database'
import { replaceCredential } from './modules/auth/credentials'
import { hashPassword } from './modules/auth/password'
const permissionsFor = (role: string) =>
@ -25,99 +26,105 @@ export async function seedDatabase(
database: PrismaClient,
options: { username?: string; email?: string; password?: string },
) {
const username = options.username ?? 'admin'
const value = parseInput(userInputSchema, {
username,
email: options.email ?? `${username}@example.com`,
name: username,
phone: '',
role: 'admin',
status: 'enabled',
departmentId: 'engineering',
remark: '',
})
const existing = await database.user.findUnique({
where: { usernameKey: username.toLowerCase() },
})
if (!existing && !options.password)
throw new Error(
'ADMIN_PASSWORD is required to initialize the first administrator.',
)
const passwordHash = !existing ? await hashPassword(options.password!) : null
return database.$transaction(
async (transaction) => {
for (const department of initialUserOptions.departments) {
await transaction.department.upsert({
where: { id: department.id },
create: department,
update: {},
})
}
for (const code of permissionCodes.filter(
(code) => code !== 'users:reset',
)) {
await transaction.permission.upsert({
where: { code },
create: { code },
update: {},
})
}
for (const role of initialUserOptions.roles) {
await transaction.role.upsert({
where: { value: role.value },
create: {
value: role.value,
label: role.label,
labelKey: role.labelKey,
permissions: {
create: permissionsFor(role.value).map((permissionCode) => ({
permissionCode,
})),
},
},
update: {},
})
}
await transaction.routeConfig.upsert({
where: { id: 'admin' },
create: { id: 'admin', config: initialRoutes as Prisma.InputJsonValue },
return writeTransaction(database, async (transaction) => {
for (const department of initialUserOptions.departments) {
await transaction.department.upsert({
where: { id: department.id },
create: department,
update: {},
})
const current = await transaction.user.findUnique({
where: { usernameKey: username.toLowerCase() },
}
for (const code of permissionCodes.filter(
(code) => code !== 'users:reset',
)) {
await transaction.permission.upsert({
where: { code },
create: { code },
update: {},
})
}
if (current) return { userId: current.id, created: false }
if (!passwordHash)
throw new Error(
'ADMIN_PASSWORD is required to initialize the first administrator.',
)
const user = await transaction.user.create({
data: {
...value,
usernameKey: value.username.toLowerCase(),
emailKey: value.email.toLowerCase(),
credential: { create: { passwordHash } },
for (const role of initialUserOptions.roles) {
await transaction.role.upsert({
where: { value: role.value },
create: {
value: role.value,
label: role.label,
labelKey: role.labelKey,
permissions: {
create: permissionsFor(role.value).map((permissionCode) => ({
permissionCode,
})),
},
},
update: {},
})
}
await transaction.routeConfig.upsert({
where: { id: 'admin' },
create: { id: 'admin', config: initialRoutes as Prisma.InputJsonValue },
update: {},
})
// 初始化身份以审计记录为准,管理员改名或修改配置后不会创建旧账号。
const bootstrap = await transaction.auditLog.findFirst({
where: { action: 'system.bootstrap' },
orderBy: { createdAt: 'asc' },
})
if (bootstrap?.resourceId)
return { userId: bootstrap.resourceId, created: false }
const existing = await transaction.user.findFirst({
where: { role: 'admin' },
})
if (existing) {
await transaction.auditLog.create({
data: { action: 'system.bootstrap', resourceId: existing.id },
})
if (!existing)
await transaction.auditLog.create({
data: { action: 'system.bootstrap', resourceId: user.id },
})
return { userId: existing.id, created: false }
}
return { userId: user.id, created: !existing }
},
{ timeout: 15000 },
)
if (await transaction.user.count())
throw new Error(
'Existing users found without an administrator. Restore administrator access explicitly.',
)
if (!options.password)
throw new Error(
'ADMIN_PASSWORD is required to initialize the first administrator.',
)
const username = options.username ?? 'admin'
const value = parseInput(userInputSchema, {
username,
email: options.email ?? `${username}@example.com`,
name: username,
phone: '',
role: 'admin',
status: 'enabled',
departmentId: 'engineering',
remark: '',
})
const passwordHash = await hashPassword(options.password)
const user = await transaction.user.create({
data: {
...value,
usernameKey: value.username.toLowerCase(),
emailKey: value.email.toLowerCase(),
credential: { create: { passwordHash } },
},
})
await transaction.auditLog.create({
data: { action: 'system.bootstrap', resourceId: user.id },
})
return { userId: user.id, created: true }
})
}
export async function setPassword(
@ -134,14 +141,6 @@ export async function setPassword(
if (!user) throw new Error('The requested account does not exist.')
await transaction.credential.upsert({
where: { userId: user.id },
create: { userId: user.id, passwordHash },
update: { passwordHash },
})
await transaction.session.deleteMany({ where: { userId: user.id } })
await transaction.auditLog.create({
data: { action: 'credentials.reset', resourceId: user.id },
})
await replaceCredential(transaction, user.id, passwordHash)
})
}

View File

@ -14,6 +14,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { after, before, test } from 'node:test'
import {
accountProfileSchema,
loginResultSchema,
sessionSchema,
userListSchema,
@ -21,6 +22,7 @@ import {
userSchema,
} from '@ray-template/api-contracts/admin'
import type {
AccountProfile,
AdminUser,
ApiResponse,
LoginResult,
@ -43,7 +45,8 @@ import { createClient } from 'redis'
import * as v from 'valibot'
import { createApp } from '../src/app'
import { createDatabase } from '../src/infrastructure/database'
import { createToken, tokenHash } from '../src/modules/auth/password'
import { signSession } from '../src/modules/auth/jwt'
import { tokenHash } from '../src/modules/auth/password'
import { loadServerConfig } from '../src/platform/index'
import { seedDatabase, setPassword } from '../src/seed'
@ -67,12 +70,15 @@ const pool = new Pool({
max: 1,
})
const database = createDatabase(databaseUrl.toString())
const password = `integration-${createToken()}`
const password = `integration-${randomBytes(24).toString('base64url')}`
const browserOrigin = 'http://localhost:9527'
const config = loadServerConfig({
NODE_ENV: 'test',
DATABASE_URL: databaseUrl.toString(),
REDIS_URL: process.env.TEST_REDIS_URL,
REDIS_KEY_PREFIX: `ray:test:${suffix}`,
CORS_ORIGINS: browserOrigin,
JWT_SECRET: randomBytes(32).toString('base64url'),
PORT: '0',
SESSION_TTL_SECONDS: '3600',
LOGIN_RATE_LIMIT_MAX: '100',
@ -82,6 +88,7 @@ let app: Awaited<ReturnType<typeof createApp>> | null = null
let base = ''
let adminToken = ''
let adminId = ''
let beforeSeedStatus = 0
async function request<T = unknown>(
path: string,
@ -90,6 +97,7 @@ async function request<T = unknown>(
body?: unknown
token?: string
origin?: string
headers?: Record<string, string>
} = {},
) {
const response = await fetch(`${options.origin ?? base}/api/${path}`, {
@ -97,6 +105,7 @@ async function request<T = unknown>(
headers: {
'Content-Type': 'application/json',
...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),
...options.headers,
},
body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
})
@ -165,12 +174,16 @@ before(async () => {
)
}
const seeded = await seedDatabase(database, { username: 'admin', password })
adminId = seeded.userId
app = await createApp(config, { logSink: () => {} })
await app.listen(0, '127.0.0.1')
base = await app.getUrl()
beforeSeedStatus = (await request('health/ready')).status
const seeded = await seedDatabase(database, { username: 'admin', password })
adminId = seeded.userId
await database.role.create({
data: { value: 'no-grants', label: 'No grants' },
})
adminToken = (await login('admin')).accessToken
})
@ -196,11 +209,14 @@ after(async () => {
}
})
test('public startup routes, authentication, envelope and current permissions match shared contracts', async () => {
const routes = await request('admin/route-config')
test('route bootstrap requires authentication and JWTs match the shared session contract', async () => {
assert.equal(beforeSeedStatus, 503)
assert.equal((await request('health/ready')).status, 200)
const routes = await request('admin/route-config', { token: adminToken })
assert.equal(routes.status, 200)
parseApplicationRoutes(JSON.stringify(routes.body.data))
assert.equal((await request('admin/route-config')).status, 401)
assert.equal((await request('admin/users')).status, 401)
assert.equal((await request('admin/route-config?view=editor')).status, 401)
assert.equal(
@ -222,11 +238,325 @@ test('public startup routes, authentication, envelope and current permissions ma
assert.ok(stored)
assert.notEqual(stored.tokenHash, adminToken)
assert.equal(adminToken.split('.').length, 3)
const unissued = await signSession(config.jwtSecret, adminId, 3600)
assert.equal(
(await request('admin/auth/session', { token: unissued.token })).status,
401,
)
const options = await request('admin/users/options', { token: adminToken })
v.parse(userOptionsSchema, options.body.data)
})
test('browser sessions hide JWTs from scripts and deny cross-origin writes', async () => {
const browser = { 'X-Ray-Session': 'cookie', 'Sec-Fetch-Site': 'same-origin' }
const options = {
method: 'POST',
body: { username: 'admin', password },
headers: { ...browser, Origin: browserOrigin },
}
assert.equal(
(await request('admin/auth/login', { ...options, headers: browser }))
.status,
403,
)
const secureApp = await createApp(
{ ...config, sessionCookieSecure: true },
{ logSink: () => {} },
)
try {
await secureApp.listen(0, '127.0.0.1')
const origin = await secureApp.getUrl()
const result = await request('admin/auth/login', { ...options, origin })
assert.equal(result.status, 200)
assert.equal(
Object.hasOwn(result.body.data as object, 'accessToken'),
false,
)
assert.equal(result.headers.get('cache-control'), 'no-store')
const cookie = result.headers.get('set-cookie')!
assert.match(cookie, /^__Host-ray-session=/u)
for (const flag of ['Path=/', 'HttpOnly', 'Secure', 'SameSite=Strict'])
assert.ok(cookie.split('; ').includes(flag), flag)
const headers = { ...options.headers, Cookie: cookie.split(';')[0] }
assert.equal(
(await request('admin/auth/session', { origin, headers })).status,
200,
)
assert.equal(
(
await request('admin/auth/session', {
origin,
headers: { Cookie: headers.Cookie },
})
).status,
401,
)
assert.equal(
(
await request('admin/auth/logout', {
method: 'POST',
origin,
headers: { ...headers, 'Sec-Fetch-Site': 'same-site' },
})
).status,
403,
)
assert.equal(
(await request('admin/auth/session', { origin, headers })).status,
200,
)
const logout = await request('admin/auth/logout', {
method: 'POST',
origin,
headers,
})
assert.equal(logout.status, 200)
assert.match(logout.headers.get('set-cookie')!, /^__Host-ray-session=;/u)
assert.equal(
(await request('admin/auth/session', { origin, headers })).status,
401,
)
} finally {
await secureApp.close()
}
})
test('runtime routes respect grants, parent roles, aliases and empty groups', async () => {
const original = (
await request<RouteConfig>('admin/route-config?view=editor', {
token: adminToken,
})
).body.data
await database.role.create({
data: {
value: 'navigation-only',
label: 'Navigation only',
permissions: { create: { permissionCode: 'routes:read' } },
},
})
const limited = await create('route-limited', { role: 'navigation-only' })
const noGrants = await create('route-no-grants', { role: 'no-grants' })
await setPassword(database, limited.username, password)
await setPassword(database, noGrants.username, password)
const limitedToken = (await login(limited.username)).accessToken
const noGrantsToken = (await login(noGrants.username)).accessToken
const config: RouteConfig = {
version: 1,
routes: [
{
path: '/parent-admin',
meta: { role: ['admin'] },
children: [
{
path: 'page',
alias: '/private-alias',
component: 'dashboard',
meta: {},
},
],
},
{
path: '/all-hidden',
meta: {},
children: [
{ path: 'page', component: 'dashboard', meta: { role: ['admin'] } },
],
},
{
path: '/only-users',
meta: {},
children: [
{ path: 'renamed-users', component: 'system/users', meta: {} },
],
},
{ path: '/redirect-private', redirect: '/private-alias', meta: {} },
{ path: '/chained', redirect: '/redirect-private', meta: {} },
],
}
try {
assert.equal(
(
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: config,
})
).status,
200,
)
assert.deepEqual(
(await request('admin/route-config', { token: adminToken })).body.data,
config,
)
assert.deepEqual(
(await request('admin/route-config', { token: limitedToken })).body.data,
{ version: 1, routes: [] },
)
assert.deepEqual(
(await request('admin/route-config', { token: noGrantsToken })).body.data,
{ version: 1, routes: [] },
)
assert.equal(
(await request('admin/route-config?view=editor', { token: limitedToken }))
.status,
403,
)
assert.equal(
(await request('admin/users', { token: limitedToken })).status,
403,
)
config.routes[1].children!.push({
path: 'allowed',
component: 'dashboard',
meta: { role: ['navigation-only'] },
})
assert.equal(
(
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: config,
})
).status,
200,
)
assert.deepEqual(
(await request('admin/route-config', { token: limitedToken })).body.data,
{
version: 1,
routes: [
{ ...config.routes[1], children: [config.routes[1].children![1]] },
],
},
)
} finally {
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: original,
})
}
})
test('profiles are self-scoped and credential changes revoke every prior session', async () => {
const user = await create('profile-user', { role: 'no-grants' })
const setCredential = (token: string, id: string, newPassword: string) =>
request(`admin/users/${id}/credential`, {
method: 'PUT',
token,
body: { newPassword },
})
const loginRequest = (supplied: string) =>
request<LoginResult>('admin/auth/login', {
method: 'POST',
body: { username: user.username, password: supplied },
})
assert.equal((await loginRequest(password)).status, 401)
assert.equal((await setCredential(adminToken, adminId, password)).status, 409)
assert.equal((await setCredential(adminToken, user.id, 'weak')).status, 400)
assert.equal((await setCredential(adminToken, user.id, password)).status, 200)
const first = (await login(user.username)).accessToken
const second = (await login(user.username)).accessToken
const profile = await request<AccountProfile>('admin/auth/profile', {
token: first,
})
assert.equal(profile.status, 200)
assert.equal(v.parse(accountProfileSchema, profile.body.data).id, user.id)
assert.equal(Object.hasOwn(profile.body.data, 'credential'), false)
assert.equal((await setCredential(first, adminId, password)).status, 403)
const patch = (body: unknown) =>
request<AccountProfile>('admin/auth/profile', {
method: 'PATCH',
token: first,
body,
})
assert.equal(
(await patch({ id: adminId, name: 'Tampered', phone: '', role: 'admin' }))
.status,
400,
)
const updated = await patch({ name: 'Profile Display', phone: '+86 1234567' })
assert.equal(updated.status, 200)
assert.equal(updated.body.data.name, 'Profile Display')
assert.equal(updated.body.data.role, 'no-grants')
const change = (
token: string,
currentPassword: string,
newPassword: string,
) =>
request('admin/auth/password', {
method: 'PATCH',
token,
body: { currentPassword, newPassword },
})
assert.equal(
(await change(first, 'incorrect', password + 'a')).body.error?.key,
'invalidCurrentPassword',
)
assert.equal(
(await change(first, password, password)).body.error?.key,
'passwordUnchanged',
)
const next = [password + 'a', password + 'b']
const changes = await Promise.all([
change(first, password, next[0]),
change(second, password, next[1]),
])
assert.equal(changes.filter(({ status }) => status === 200).length, 1)
assert.ok(changes.every(({ status }) => [200, 401, 409].includes(status)))
for (const token of [first, second])
assert.equal((await request('admin/auth/session', { token })).status, 401)
assert.equal((await loginRequest(password)).status, 401)
const renewed = await login(
user.username,
next[changes.findIndex(({ status }) => status === 200)],
)
assert.equal(renewed.user.name, 'Profile Display')
assert.equal(
(await setCredential(adminToken, user.id, password + 'reset')).status,
200,
)
assert.equal(
(await request('admin/auth/session', { token: renewed.accessToken }))
.status,
401,
)
const audit = await database.auditLog.findMany({
where: { actorId: user.id },
})
assert.equal(
audit.filter(({ action }) => action === 'auth.password.change').length,
1,
)
assert.equal(JSON.stringify(audit).includes(password), false)
})
test('the development launcher refuses a port already serving backend readiness', async () => {
const fixture = await mkdtemp(join(tmpdir(), 'ray-launcher-'))
@ -324,6 +654,39 @@ test('read-only and manager accounts cannot bypass endpoint or role authorizatio
v.parse(userListSchema, list.body.data)
})
test('users:update cannot disable accounts without the separate status grant', async () => {
await database.role.create({
data: {
value: 'user-editor',
label: 'Editor',
permissions: {
create: ['users:read', 'users:update', 'routes:read'].map(
(permissionCode) => ({ permissionCode }),
),
},
},
})
const editor = await create('user-editor', { role: 'user-editor' })
const target = await create('user-status-target')
await setPassword(database, editor.username, password)
const token = (await login(editor.username)).accessToken
const update = (status: UserInput['status']) =>
request<AdminUser>(`admin/users/${target.id}`, {
method: 'PUT',
token,
body: input(target.username, { name: 'Edited', status }),
})
assert.equal((await update('disabled')).status, 403)
assert.equal((await update('enabled')).body.data.name, 'Edited')
assert.equal(
(await request<AdminUser>(`admin/users/${target.id}`, { token })).body.data
.status,
'enabled',
)
})
test('creation, case-insensitive uniqueness, filtering and serialization protect credentials', async () => {
const user = await create('CaseAccount', { departmentId: 'platform' })
const duplicate = await request('admin/users', {
@ -414,7 +777,7 @@ test('batch changes are all-or-none and current account remains protected', asyn
assert.equal(deleted.body.data.affected, 1)
})
test('logout, expiry, password reset and disabling an account revoke effective access', async () => {
test('logout, expiry, password reset, disabling and role changes revoke effective access', async () => {
const user = await create('sessions-user')
await setPassword(database, user.username, password)
@ -486,11 +849,35 @@ test('logout, expiry, password reset and disabling an account revoke effective a
(await request('admin/auth/session', { token: active.accessToken })).status,
401,
)
const beforeRoleChange = await login(user.username, nextPassword)
const changedRole = await request<AdminUser>(`admin/users/${user.id}`, {
method: 'PUT',
token: adminToken,
body: input(user.username, { role: 'no-grants' }),
})
assert.equal(changedRole.status, 200)
assert.equal(
(
await request('admin/auth/session', {
token: beforeRoleChange.accessToken,
})
).status,
401,
)
const downgraded = await login(user.username, nextPassword)
assert.deepEqual(downgraded.permissions, [])
assert.equal(
(await request('admin/users', { token: downgraded.accessToken })).status,
403,
)
})
test('route validation prevents unusable startup data and valid changes survive application restart', async () => {
const before = await request<{ version: number; routes: unknown[] }>(
'admin/route-config',
{ token: adminToken },
)
const bad = await request('admin/route-config', {
method: 'PUT',
@ -503,7 +890,7 @@ test('route validation prevents unusable startup data and valid changes survive
assert.equal(bad.status, 400)
assert.deepEqual(
(await request('admin/route-config')).body.data,
(await request('admin/route-config', { token: adminToken })).body.data,
before.body.data,
)
const valid = {
@ -532,15 +919,38 @@ test('route validation prevents unusable startup data and valid changes survive
app = await createApp(config, { logSink: () => {} })
await app.listen(0, '127.0.0.1')
base = await app.getUrl()
assert.deepEqual((await request('admin/route-config')).body.data, valid)
assert.deepEqual(
(await request('admin/route-config', { token: adminToken })).body.data,
valid,
)
assert.equal(
(await request('admin/auth/session', { token: adminToken })).status,
200,
)
const seeded = await seedDatabase(database, { username: 'admin' })
await database.user.update({
where: { id: adminId },
data: { username: 'renamed-admin', usernameKey: 'renamed-admin' },
})
assert.equal(seeded.created, false)
assert.deepEqual((await request('admin/route-config')).body.data, valid)
try {
const seeded = await seedDatabase(database, { username: 'admin', password })
assert.deepEqual(seeded, { created: false, userId: adminId })
assert.equal(
await database.user.count({ where: { usernameKey: 'admin' } }),
0,
)
} finally {
await database.user.update({
where: { id: adminId },
data: { username: 'admin', usernameKey: 'admin' },
})
}
assert.deepEqual(
(await request('admin/route-config', { token: adminToken })).body.data,
valid,
)
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
@ -656,7 +1066,9 @@ test('enabled demos implement the shared API, cache fixed reads and validate inp
})
test('disabling demos hides runtime routes and endpoints without dropping editable routes', async () => {
const original = (await request<RouteConfig>('admin/route-config')).body.data
const original = (
await request<RouteConfig>('admin/route-config', { token: adminToken })
).body.data
const full: RouteConfig = {
...original,
routes: [
@ -690,7 +1102,10 @@ test('disabling demos hides runtime routes and endpoints without dropping editab
try {
await disabled.listen(0, '127.0.0.1')
const origin = await disabled.getUrl()
const runtime = await request<RouteConfig>('admin/route-config', { origin })
const runtime = await request<RouteConfig>('admin/route-config', {
origin,
token: adminToken,
})
assert.equal(runtime.status, 200)
const effective = parseApplicationRoutes(JSON.stringify(runtime.body.data))

View File

@ -1,5 +1,5 @@
import assert from 'node:assert/strict'
import { randomUUID } from 'node:crypto'
import { randomBytes, randomUUID } from 'node:crypto'
import type { AddressInfo } from 'node:net'
import { test } from 'node:test'
import { Module } from '@nestjs/common'
@ -26,6 +26,7 @@ const config = (extra: NodeJS.ProcessEnv = {}) =>
DATABASE_URL: 'postgresql://test:test@127.0.0.1:5432/test',
REDIS_URL: process.env.TEST_REDIS_URL || 'redis://127.0.0.1:6379',
CORS_ORIGINS: 'http://localhost:9527',
JWT_SECRET: randomBytes(32).toString('base64url'),
REDIS_KEY_PREFIX: `ray:test:${randomUUID()}`,
...extra,
})
@ -234,7 +235,7 @@ test('login limit normalizes usernames, covers case-insensitive routes and ignor
})
const first = await request('Admin', '1.1.1.1', '/api/admin/auth/login')
const second = await request(
' ADMIN ',
' '.repeat(100) + 'ADMIN ',
'2.2.2.2',
'/API/ADMIN/AUTH/LOGIN/',
)

View File

@ -1,9 +1,11 @@
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { test } from 'node:test'
import { userInputSchema } from '@ray-template/api-contracts/admin'
import { SignJWT } from 'jose'
import { ApiError, parseInput, queryInput } from '../src/http'
import { signSession, verifySession } from '../src/modules/auth/jwt'
import {
createToken,
hashPassword,
tokenHash,
validateNewPassword,
@ -11,7 +13,7 @@ import {
} from '../src/modules/auth/password'
test('password credentials use independent salts and reject corrupt or incorrect credentials', async () => {
const password = `unit-${createToken()}`
const password = `unit-${randomBytes(24).toString('base64url')}`
const first = await hashPassword(password)
const second = await hashPassword(password)
@ -25,14 +27,32 @@ test('password credentials use independent salts and reject corrupt or incorrect
assert.throws(() => validateNewPassword('x'.repeat(129)))
})
test('session tokens are unguessable identifiers and only their digest is persisted', () => {
const first = createToken()
const second = createToken()
test('JWTs are distinct and reject tampering, expiry and a mismatched signing policy', async () => {
const secret = randomBytes(32)
const { token: first } = await signSession(secret, 'account-1', 60)
const { token: second } = await signSession(secret, 'account-1', 60)
const { token: expired } = await signSession(secret, 'account-1', -1)
const tampered = first.replace(/\.[^.]+$/u, `.${'A'.repeat(43)}`)
const wrongAudience = await new SignJWT()
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer('ray-template')
.setAudience('other-app')
.setSubject('account-1')
.setIssuedAt()
.setJti('wrong-audience')
.setExpirationTime('1m')
.sign(secret)
assert.notEqual(first, second)
assert.notEqual(tokenHash(first), first)
assert.equal(tokenHash(first), tokenHash(first))
assert.notEqual(tokenHash(first), tokenHash(second))
assert.equal(await verifySession(secret, first), 'account-1')
for (const token of [tampered, expired, wrongAudience])
assert.equal(await verifySession(secret, token), void 0)
assert.equal(await verifySession(randomBytes(32), first), void 0)
})
test('HTTP query conversion rejects arrays and ambiguous numeric strings', () => {

View File

@ -13,7 +13,7 @@ RUN pnpm server:build
RUN pnpm --filter @ray-template/server deploy --legacy /server
FROM workspace AS admin-build
RUN VITE_API_MOCK=false VITE_API_BASE_URL=/api/ pnpm build
RUN VITE_API_MOCK=false VITE_API_BASE_URL=/api/ VITE_API_AUTH_TRANSPORT=cookie pnpm build
FROM node-base AS server
WORKDIR /app

View File

@ -4,6 +4,8 @@ x-server-environment: &server-environment
PORT: '3000'
DATABASE_URL: ${APP_DATABASE_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-ray_template}}
REDIS_URL: ${APP_REDIS_URL:-redis://:${REDIS_PASSWORD}@redis:6379}
JWT_SECRET: ${JWT_SECRET:-}
SESSION_COOKIE_SECURE: ${APP_SESSION_COOKIE_SECURE:-false}
DEMO_ENABLED: ${APP_DEMO_ENABLED:-false}
CORS_ORIGINS: ${APP_ORIGINS:-http://127.0.0.1:${APP_PORT:-8080},http://localhost:${APP_PORT:-8080}}

View File

@ -43,10 +43,12 @@ const env = {
ADMIN_USERNAME: 'smoke_admin',
ADMIN_EMAIL: 'smoke-admin@example.test',
ADMIN_PASSWORD: password,
JWT_SECRET: randomBytes(32).toString('base64url'),
APP_PORT: String(appPort),
APP_ORIGINS: '',
APP_PROXY_NETWORK: subnet,
APP_DEMO_ENABLED: 'false',
APP_SESSION_COOKIE_SECURE: 'false',
APP_DATABASE_URL: '',
APP_REDIS_URL: '',
APP_LOGIN_RATE_LIMIT_MAX: '1',
@ -81,11 +83,16 @@ const api = (path, options) =>
signal: AbortSignal.timeout(5000),
...options,
})
const browser = {
Origin: origin,
'X-Ray-Session': 'cookie',
'Sec-Fetch-Site': 'same-origin',
}
const login = (username, forwarded) =>
api('admin/auth/login', {
method: 'POST',
headers: {
Origin: origin,
...browser,
'Content-Type': 'application/json',
'X-Forwarded-For': forwarded,
},
@ -111,6 +118,7 @@ try {
assert.match(await page.text(), /<script[^>]*src="\/ray-template\//u)
assert.equal((await api('health/ready')).status, 200)
assert.equal((await api('admin/demo/charts')).status, 404)
assert.equal((await api('admin/route-config')).status, 401)
const denied = await api('admin/route-config', {
headers: { Origin: 'https://untrusted.example.test' },
})
@ -121,15 +129,33 @@ try {
assert.equal(response.status, 200)
assert.equal(response.headers.get('access-control-allow-origin'), origin)
const { data } = await response.json()
const cookie = response.headers.get('set-cookie')
assert.equal(Object.hasOwn(data, 'accessToken'), false)
assert.match(cookie, /HttpOnly; SameSite=Strict/u)
const headers = { ...browser, Cookie: cookie.split(';')[0] }
assert.equal(
(
await api('admin/users', {
headers: { Authorization: `Bearer ${data.accessToken}` },
headers,
})
).status,
200,
)
const routes = await api('admin/route-config', { headers })
assert.equal(routes.status, 200)
assert.deepEqual(
(await routes.json()).data.routes.map(({ path }) => path),
['/dashboard', '/system'],
)
assert.equal((await api('admin/auth/profile', { headers })).status, 200)
assert.equal(
(await api('admin/auth/logout', { method: 'POST', headers })).status,
200,
)
assert.equal((await api('admin/auth/session', { headers })).status, 401)
for (let attempt = 1; attempt <= 5; attempt++) {
assert.equal(
@ -160,7 +186,7 @@ try {
assert.equal(count.trim(), '6')
console.log(
'Compose smoke passed: initialized data, built admin, readiness, login, CORS, demo gating and forwarded client rate limits.',
'Compose smoke passed: initialization, built admin, readiness, browser session, protected routes, profile, CORS, demo gating and forwarded client rate limits.',
)
} catch (error) {
try {

View File

@ -246,5 +246,11 @@ Added explicit browser/server/universal workspace ownership, universal route con
Full Harness verification passed with Node 26.13.0 and pnpm 12.16.1: 103 frontend test files / 535 tests, 13 backend unit/platform tests with real Redis, API and workspace checks, types, lint/format, and both application builds. Six backend HTTP integration tests separately passed on temporary PostgreSQL 18.6 and Redis 8.2.11. The real external-service setup command applied Prisma migrations and initialized a private local administrator. No fixed production passwords were introduced.
An exported frontend archive extracted outside the repository passed frozen dependency installation, API/package/Harness checks and production build. Frontend/fullstack archive projection and nine distribution regressions passed. Fullstack standalone install, container images, browser integration and remote workflows remain pending. Follow the [pause checkpoint](../harness/plan.md) for remaining scope and local evidence. No Git commit, push, branch publication or release was performed.
An exported frontend archive extracted outside the repository passed frozen dependency installation, API/package/Harness checks and production build. Frontend/fullstack archive projection and nine distribution regressions passed. At this checkpoint, standalone fullstack install, container images and browser integration were still pending.
## 2026-11-06: Fullstack PC acceptance and upgrade
The server pins JOSE 6.2.12 for JWT signing and verification. The browser defaults to same-origin cookie transport in the fullstack launcher and Compose image. A repeatable Compose command provisions the signing key, dependencies and migrations from clean source. The rollout adds the administrator credential grant without recreating a renamed administrator.
The [PC acceptance record](../harness/fullstack-acceptance.md) contains the full Harness, real PostgreSQL/Redis, clean archive, Docker Compose and desktop Chrome results. It also records the external-service upgrade and the required sign-in after replacing legacy tokens. No remote workflow or public deployment was used.
<!-- fullstack:end -->

View File

@ -2,11 +2,11 @@
Use this topic for the fullstack distribution, database persistence, authentication, permissions, Redis limits/cache, security, logs, and server startup.
Read the [server guide](../../apps/server/README.md), [platform contract](../../apps/server/src/platform/README.md), [shared contracts](../../packages/api-contracts/README.md), and [source distribution guide](../../apps/docs/guide/distributions.md).
Read the [server guide](../../apps/server/README.md), [platform contract](../../apps/server/src/platform/README.md), [shared contracts](../../packages/api-contracts/README.md), and [source distribution guide](../../apps/docs/guide/distributions.md). The [PC acceptance plan](../fullstack-acceptance.md) covers authentication, navigation, and setup from a clean environment.
- [Bootstrap](../../apps/server/src/app.ts) owns Nest modules and platform lifecycle. [Platform](../../apps/server/src/platform/index.ts) owns environment validation, Redis, request logging, security headers, CORS, limits, and health checks.
- [Database](../../apps/server/src/infrastructure/database.ts) owns Prisma lifetime and transaction retries. [Schema](../../apps/server/prisma/schema.prisma) and migrations are server-only. [Seed](../../apps/server/src/seed.ts) must preserve existing data.
- [Authentication](../../apps/server/src/modules/auth/auth.service.ts) checks live sessions and permission grants. Credential/session state must not use the reusable data cache.
- [Authentication](../../apps/server/src/modules/auth/auth.service.ts) checks signed JWTs against live sessions and permission grants. Credential/session state must not use the reusable data cache.
- [Users](../../apps/server/src/modules/users/users.service.ts) validates and authorizes writes inside transactions. [Routes](../../apps/server/src/modules/routes/routes.controller.ts) use the shared route parser and generated catalog.
- [Fullstack launcher](../../scripts/fullstack.mjs) creates local configuration and orchestrates services. [Distribution exporter](../../scripts/distributions.mjs) projects independent frontend/fullstack workspaces; it never publishes branches or releases.

View File

@ -0,0 +1,29 @@
# Fullstack PC acceptance plan
Scope: the optional backend, its Admin integration, the frontend-only Mock contract, and independent source setup. Acceptance uses one desktop Chrome session and disposable PostgreSQL, Redis, and Compose resources.
| Baseline finding | Implementation and acceptance |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A clean install and external setup start the existing Admin and Nest app. Anonymous `/admin/route-config` returns nine root entries; only the editor view is protected. Local browser route preferences can bypass the server's runtime configuration. | Authenticate the runtime snapshot and prune by live grants, inherited roles, view permissions, and demo policy. Drop empty groups and unusable redirects. Preserve the separate authorized editor snapshot. Inject only the current account's routes. Denied injected paths resolve as absent (404); reserved protected pages and API permissions still return 403. |
| Baseline login returns an opaque token to local storage. There is no self-service profile or password endpoint; the avatar entry is a placeholder. Account credentials require CLI access. | Sign and verify bounded JWT sessions while keeping the PostgreSQL revocation boundary. Use an HttpOnly cookie for the bundled same-origin Admin and preserve explicit Bearer access for API clients and Mock. Add self profile, current-password verification, all-session revocation, and a separately authorized administrator credential action. |
| Setup is repeatable by username, so a renamed bootstrap account can cause a second privileged account to be created. Readiness only checks connections. Container startup requires a separate local setup command. | Bootstrap once using the existing audit marker; preserve accounts, grants and route configuration across setup. Report uninitialized databases as unready. Provide a single Compose launch command and a runbook with external service, upgrade, secret, and troubleshooting instructions. |
| The local screen lock accepts a browser-stored password while the real API session remains active. | Keep the local privacy screen for Mock. In real mode, locking revokes the current session and keeps the current address for reauthentication. |
Plan review: The menu is not an authorization boundary. Protected data stays behind live endpoint checks, including writes inside transactions. The router must distinguish an intentionally empty snapshot from failed loading, and neither should select the packaged route list in server mode. The editor must still receive routes hidden by role or demo policy. Cookie transport requires a same-origin browser request and must not return the token in JSON. Credential changes must not permit self-promotion, target substitution, or use of the previous session. Upgrades may require a new login and signing secret, but must preserve database data and the frontend-only distribution.
Verification gates: full Harness; HTTP integration with real PostgreSQL and Redis (including denied requests and session races); desktop browser against real API with admin and limited accounts; extracted fullstack and frontend archives; actual Compose build, fresh start and smoke checks.
## Acceptance results — 2026-11-06
| Surface | Observed result |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Clean baseline | Frozen install, external database migration and login passed. The anonymous runtime route request returned nine root records; self profile and password APIs were absent. The profile menu produced a placeholder in Chrome. |
| Full Harness | 105 Vitest files, 546 tests, 13 server unit/platform tests with real Redis, types, lint, format, API/package boundaries, both site builds, and both distribution projections passed on Node.js 26.13.0 and pnpm 12.16.1. |
| Real HTTP | 13 integration tests passed against temporary PostgreSQL and Redis. They cover bootstrap readiness, cookie attributes and CSRF, JWT signature and revocation boundaries, self-only profile fields, concurrent password changes, user CRUD and grants, pruned route trees, and enabled/disabled demos. |
| Desktop Chrome | The production container preserved a protected deep link through sign-in. Admin updated profile data and saved routes; both persisted after reload and container rebuild. The read-only account could read users without write controls. With every child denied, the API returned `routes: []` and the workspace showed no entries, while self profile remained usable. Removed routes, aliases, and redirects resolved to 404; fixed route management resolved to 403. Account disabling rejected the already-open session on its next protected navigation. Locking ended the session and kept the return path. The final console inspection returned no warnings or errors. |
| Credential UI | Chrome displayed the self-service change form and the administrator credential dialog. Actual password changes, reset, concurrent writes and old-session invalidation were exercised by real HTTP tests; form submission, mismatch, error and retry behavior were exercised by frontend tests. |
| Fullstack archive and Compose | A clean extraction built Linux arm64 images, generated private settings, migrated empty volumes, initialized an administrator, and served the production Admin. A second unparameterized launch reused the project and non-default port. The Compose smoke verified readiness, auth cookie transport, the protected route snapshot, profile, logout, demo gating, CORS and forwarded-IP rate limits. |
| Existing external services | The extracted fullstack source upgraded the baseline database. Two setup runs preserved the renamed administrator and configured a signing key; the updated dev proxy authenticated the same account, rejected its old opaque token, and served enabled demos. |
| Frontend-only archive | Frozen install and its full check passed outside the repository, without server dependencies. Chrome signed in through Mock and displayed the demo routes. |
The browser scope was desktop Chrome only. Production HTTPS ingress, additional devices and themes, remote CI and public deployment were outside this run. Local logs are under `.harness-local/fullstack-pc-acceptance/`; full Harness report: `.harness-local/runs/all-W6KuPc/report.json`.

View File

@ -41,6 +41,7 @@
"dist:check": "node scripts/distributions.mjs --check",
"dev:full": "node scripts/fullstack.mjs dev",
"fullstack:stop": "node scripts/fullstack.mjs stop",
"fullstack:up": "node scripts/fullstack.mjs up",
"server:dev": "pnpm --filter @ray-template/server dev",
"server:build": "pnpm --filter @ray-template/server build",
"server:start": "pnpm --filter @ray-template/server start",

View File

@ -78,6 +78,7 @@ export const profileSchema = v.object({
export const sessionSchema = v.object({
user: profileSchema,
permissions: v.array(v.string()),
expiresAt: v.optional(v.pipe(v.string(), v.isoTimestamp())),
})
export type SessionInfo = v.InferOutput<typeof sessionSchema>
export const loginInputSchema = v.object({
@ -85,13 +86,41 @@ export const loginInputSchema = v.object({
password: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
})
export type LoginInput = v.InferInput<typeof loginInputSchema>
export const loginResultSchema = v.object({
export const browserLoginResultSchema = v.object({
...sessionSchema.entries,
accessToken: v.pipe(v.string(), v.minLength(1)),
expiresAt: v.pipe(v.string(), v.isoTimestamp()),
})
export const loginResultSchema = v.object({
...browserLoginResultSchema.entries,
accessToken: v.pipe(v.string(), v.minLength(1)),
})
export type LoginResult = v.InferOutput<typeof loginResultSchema>
export const profileInputSchema = v.strictObject({
name: userInputSchema.entries.name,
phone: userInputSchema.entries.phone,
})
export const accountProfileSchema = v.object({
...profileSchema.entries,
...profileInputSchema.entries,
email: userInputSchema.entries.email,
department: departmentSchema,
})
export type ProfileInput = v.InferInput<typeof profileInputSchema>
export type AccountProfile = v.InferOutput<typeof accountProfileSchema>
const newPasswordSchema = v.pipe(v.string(), v.minLength(12), v.maxLength(128))
export const credentialInputSchema = v.strictObject({
newPassword: newPasswordSchema,
})
export const changePasswordSchema = v.strictObject({
currentPassword: loginInputSchema.entries.password,
newPassword: newPasswordSchema,
})
export type CredentialInput = v.InferInput<typeof credentialInputSchema>
export type ChangePasswordInput = v.InferInput<typeof changePasswordSchema>
export interface ApiResponse<T> {
code: number
msg: string
@ -151,6 +180,7 @@ export const permissionCodes = [
'users:update',
'users:delete',
'users:status',
'users:credentials',
'users:reset',
'routes:read',
'routes:write',

View File

@ -1,11 +1,16 @@
import { toJsonSchema } from '@valibot/to-json-schema'
import * as v from 'valibot'
import {
accountProfileSchema,
browserLoginResultSchema,
changedSchema,
changePasswordSchema,
credentialInputSchema,
envelopeSchema,
idsSchema,
loginInputSchema,
loginResultSchema,
profileInputSchema,
sessionSchema,
statusInputSchema,
userInputSchema,
@ -42,7 +47,12 @@ export function getAdminOpenApi() {
UserOptions: userOptionsSchema,
LoginInput: loginInputSchema,
LoginResult: loginResultSchema,
BrowserLoginResult: browserLoginResultSchema,
Session: sessionSchema,
AccountProfile: accountProfileSchema,
ProfileInput: profileInputSchema,
ChangePassword: changePasswordSchema,
CredentialInput: credentialInputSchema,
Ids: idsSchema,
StatusInput: statusInputSchema,
Changed: changedSchema,
@ -84,7 +94,7 @@ export function getAdminOpenApi() {
const json = (schema: unknown) => ({ 'application/json': { schema } })
const operation = (
id: string,
result: string | null,
result: string | null | string[],
permission?: string,
input?: string,
publicEndpoint = false,
@ -93,8 +103,12 @@ export function getAdminOpenApi() {
summary: id,
description: permission
? `Required permission: ${permission}.`
: 'Session or public bootstrap endpoint.',
security: publicEndpoint ? [] : [{ bearerAuth: [] }],
: publicEndpoint
? 'Public endpoint.'
: 'Requires an active session.',
security: publicEndpoint
? []
: [{ bearerAuth: [] }, { browserSession: [] }],
...(input
? { requestBody: { required: true, content: json(ref(input)) } }
: {}),
@ -107,12 +121,16 @@ export function getAdminOpenApi() {
properties: {
code: { const: 200 },
msg: { type: 'string' },
data: result ? ref(result) : { type: 'null' },
data: Array.isArray(result)
? { anyOf: result.map(ref) }
: result
? ref(result)
: { type: 'null' },
},
}),
},
...Object.fromEntries(
[400, 401, 403, 404, 409, 503].map((status) => [
[400, 401, 403, 404, 409, 413, 429, 503].map((status) => [
status,
{
description: 'See error.key for a stable machine-readable reason.',
@ -133,7 +151,7 @@ export function getAdminOpenApi() {
openapi: '3.1.0',
info: {
title: 'Ray Admin API',
version: '1.0.0',
version: '1.1.0',
description:
'Mock and real backends share this contract. Route component values are identifiers from the frontend view catalog, never executable code.',
},
@ -146,7 +164,16 @@ export function getAdminOpenApi() {
],
components: {
schemas,
securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer' } },
securitySchemes: {
bearerAuth: { type: 'http', scheme: 'bearer' },
browserSession: {
type: 'apiKey',
in: 'cookie',
name: '__Host-ray-session',
description:
'Bundled server only. Send X-Ray-Session: cookie on same-origin requests. Loopback HTTP uses ray-session.',
},
},
},
paths: {
'/admin/demo/people': {
@ -223,16 +250,44 @@ export function getAdminOpenApi() {
),
},
'/admin/auth/login': {
post: operation('login', 'LoginResult', void 0, 'LoginInput', true),
post: {
...operation(
'login',
['LoginResult', 'BrowserLoginResult'],
void 0,
'LoginInput',
true,
),
description:
'Returns a Bearer token by default. The bundled server omits it and sets an HttpOnly cookie when X-Ray-Session is cookie.',
parameters: [
{
name: 'X-Ray-Session',
in: 'header',
schema: { const: 'cookie' },
},
],
},
},
'/admin/auth/session': { get: operation('getSession', 'Session') },
'/admin/auth/logout': { post: operation('logout', null) },
'/admin/auth/profile': {
get: operation('getProfile', 'AccountProfile'),
patch: operation(
'updateProfile',
'AccountProfile',
void 0,
'ProfileInput',
),
},
'/admin/auth/password': {
patch: operation('changePassword', null, void 0, 'ChangePassword'),
},
'/admin/route-config': {
get: {
...operation('getRouteConfig', 'RouteConfig', void 0, void 0, true),
...operation('getRouteConfig', 'RouteConfig'),
description:
'Public navigation snapshot. Request view=editor with routes:write to read the complete saved configuration, including disabled demo routes.',
security: [{}, { bearerAuth: [] }],
'Authorized navigation snapshot for the current session; returns an empty routes array without routes:read. Request view=editor with routes:write to read the complete saved configuration.',
parameters: [
{
name: 'view',
@ -252,6 +307,15 @@ export function getAdminOpenApi() {
'/admin/users/options': {
get: operation('getUserOptions', 'UserOptions', 'users:read'),
},
'/admin/users/{id}/credential': {
parameters: [pathId],
put: operation(
'setUserCredential',
null,
'users:credentials',
'CredentialInput',
),
},
'/admin/users': {
get: {
...operation('listUsers', 'UserList', 'users:read'),

View File

@ -177,3 +177,73 @@ export const routeConfigSchema = v.pipe(
)
export type RouteConfig = v.InferOutput<typeof routeConfigSchema>
export const routeViewPermission = (view?: string) =>
view === 'system/users' ? 'users:read' : void 0
export function filterRuntimeRoutes(
config: RouteConfig,
options: {
role: string | number
permissions: readonly string[]
demoEnabled: boolean
},
): RouteConfig {
const { role, permissions, demoEnabled } = options
if (!permissions.includes('routes:read')) return { ...config, routes: [] }
const accessible = new Map<string, RouteConfigRecord>()
const collect = (
routes: RouteConfigRecord[],
parent = '',
): RouteConfigRecord[] =>
routes.flatMap((route) => {
const permission = routeViewPermission(route.component)
if (
(route.meta.role?.length && !route.meta.role.includes(role)) ||
(permission && !permissions.includes(permission)) ||
(!demoEnabled && route.component?.startsWith('demo/'))
)
return []
const path = route.path.startsWith('/')
? route.path
: `${parent}/${route.path}`
if (route.children)
return [{ ...route, children: collect(route.children, path) }]
for (const address of [path, ...[route.alias ?? []].flat()])
accessible.set(address.toLowerCase(), route)
return [route]
})
// 重定向在角色、视图权限与演示开关裁剪之后再解析,避免保留空壳入口。
const canResolve = (route: RouteConfigRecord) => {
const visited = new Set<RouteConfigRecord>()
let current: RouteConfigRecord | undefined = route
while (current?.redirect) {
if (visited.has(current)) return false
visited.add(current)
current = accessible.get(current.redirect.toLowerCase())
}
return !!current && !current.meta.windowOpen
}
const prune = (routes: RouteConfigRecord[]): RouteConfigRecord[] =>
routes.flatMap((route) => {
if (!route.children)
return !route.redirect || canResolve(route) ? [route] : []
const children = prune(route.children)
return children.length ? [{ ...route, children }] : []
})
return { ...config, routes: prune(collect(config.routes)) }
}

View File

@ -162,7 +162,8 @@
"/welcome",
"/403",
"/404",
"/500"
"/500",
"/account/profile"
],
"reservedNames": [
"RWelcome",
@ -170,6 +171,7 @@
"ErrorPage404",
"ErrorPage500",
"RNotFound",
"AccountProfile",
"RLogin",
"RLayout",
"RNotFound",

View File

@ -11,6 +11,7 @@ export interface RouteCatalog {
| { name: string; load: NonNullable<AppRouteRecordRaw['component']> }
| undefined
findRouteViewId(loader: unknown): string | undefined
viewPermission?(id: string): string | undefined
/**
*
* @deprecated 首页不再具有路由校验或默认导航特权,保留字段仅兼容旧调用方。
@ -35,10 +36,16 @@ export function createRouteContract(catalog: RouteCatalog) {
children,
meta,
...record
}: RouteConfigRecord): AppRouteRecordRaw =>
({
}: RouteConfigRecord): AppRouteRecordRaw => {
const requiredPermission =
component && catalog.viewPermission?.(component)
return {
...record,
meta: meta as AppRouteRecordRaw['meta'],
meta: {
...meta,
...(requiredPermission ? { requiredPermission } : {}),
} as AppRouteRecordRaw['meta'],
component:
component === 'layout'
? LAYOUT
@ -46,7 +53,8 @@ export function createRouteContract(catalog: RouteCatalog) {
? findRouteView(component)?.load
: void 0,
children: children?.map(toRoute),
}) as AppRouteRecordRaw
} as AppRouteRecordRaw
}
return config.routes.map(toRoute)
}
@ -55,7 +63,7 @@ export function createRouteContract(catalog: RouteCatalog) {
const toRecord = ({
path,
name,
meta,
meta: { requiredPermission: _permission, ...meta },
component,
children,
props,

View File

@ -72,6 +72,8 @@ export interface AppRouteMeta {
role?: (string | number)[]
/** 展开菜单树后用于直接导航校验的父级权限。 */
ancestorRoles?: (string | number)[][]
/** 由视图目录绑定的运行时权限;不会写入动态路由 JSON。 */
requiredPermission?: string
/**
*
* @description

8
pnpm-lock.yaml generated
View File

@ -604,6 +604,9 @@ importers:
express:
specifier: 5.3.0
version: 5.3.0
jose:
specifier: 6.2.12
version: 6.2.12
pg:
specifier: 8.23.1
version: 8.23.1
@ -4192,6 +4195,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
jose@6.2.12:
resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}
js-beautify@2.0.3:
resolution: {integrity: sha512-cyFbh3tkPhknnTD/0bLf0T0yy2ZIbqL05mttzbt4y1Zfr7NxqXQZ62dkBLKs3oHH/lpjmDRAnciJiSUyOy8XwQ==}
engines: {node: '>=14'}
@ -9140,6 +9146,8 @@ snapshots:
jiti@2.7.0: {}
jose@6.2.12: {}
js-beautify@2.0.3:
dependencies:
config-chain: 1.1.13

View File

@ -3,6 +3,8 @@ import { getAdminOpenApi } from '@ray-template/api-contracts/openapi'
import { iconNames, retiredIcons } from '@ray-template/icons'
import { routeViewCatalog } from '../apps/admin/src/router/config/views.ts'
import {
ACCOUNT_PROFILE_NAME,
ACCOUNT_PROFILE_PATH,
ROUTE_MANAGEMENT_PATH,
SYSTEM_ROUTE_NAMES,
SYSTEM_ROUTE_PATHS,
@ -54,7 +56,7 @@ const catalogFile = new URL(
'../packages/demo-data/src/route-catalog.json',
import.meta.url,
)
const catalogContent = `${JSON.stringify({ views: routeViewCatalog, managementPath: ROUTE_MANAGEMENT_PATH, reservedPaths: SYSTEM_ROUTE_PATHS, reservedNames: [...SYSTEM_ROUTE_NAMES, 'RLogin', 'RLayout', 'RNotFound', 'RouteManagement', 'RouteManagementVisual', 'ErrorPage', 'RayTemplateDoc'], icons: iconNames, iconAliases: Object.fromEntries(retiredIcons) }, null, 2)}\n`
const catalogContent = `${JSON.stringify({ views: routeViewCatalog, managementPath: ROUTE_MANAGEMENT_PATH, reservedPaths: [...SYSTEM_ROUTE_PATHS, ACCOUNT_PROFILE_PATH], reservedNames: [...SYSTEM_ROUTE_NAMES, ACCOUNT_PROFILE_NAME, 'RLogin', 'RLayout', 'RNotFound', 'RouteManagement', 'RouteManagementVisual', 'ErrorPage', 'RayTemplateDoc'], icons: iconNames, iconAliases: Object.fromEntries(retiredIcons) }, null, 2)}\n`
if (process.argv.includes('--check')) {
if (readFileSync(catalogFile, 'utf8') !== catalogContent)

View File

@ -73,6 +73,7 @@ const fullstackPaths = [
'scripts/sync-frontend.sh',
'deploy',
'harness/context/server.md',
'harness/fullstack-acceptance.md',
'.github/workflows/distributions.yaml',
]
const excludedDirectories = new Set([

View File

@ -1,6 +1,12 @@
import { spawn } from 'node:child_process'
import { randomBytes } from 'node:crypto'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import {
appendFileSync,
chmodSync,
existsSync,
readFileSync,
writeFileSync,
} from 'node:fs'
import { createServer } from 'node:net'
import { setTimeout as delay } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'
@ -12,11 +18,11 @@ const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
const [action, ...flags] = process.argv.slice(2)
if (
!['setup', 'dev', 'stop'].includes(action) ||
!['setup', 'dev', 'up', 'stop'].includes(action) ||
(flags.length > 0 && (action !== 'setup' || flags.join(' ') !== '--external'))
) {
console.error(
'Use pnpm fullstack:setup [--external], pnpm dev:full, or pnpm fullstack:stop.',
'Use pnpm fullstack:setup [--external], pnpm dev:full, pnpm fullstack:up, or pnpm fullstack:stop.',
)
process.exit(1)
}
@ -54,15 +60,22 @@ function configuration() {
return { ...parseEnv(readFileSync(envFile, 'utf8')), ...process.env }
}
const compose = [
'compose',
'--project-name',
'ray-template',
'--env-file',
fileURLToPath(envFile),
'-f',
'deploy/compose.yaml',
]
function compose(env) {
const project = env.RAY_COMPOSE_PROJECT ?? 'ray-template'
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(project))
throw new Error('RAY_COMPOSE_PROJECT must be a valid Compose project name.')
return [
'compose',
'--project-name',
project,
'--env-file',
fileURLToPath(envFile),
'-f',
'deploy/compose.yaml',
]
}
function portFrom(env, key, fallback) {
const port = env[key] ?? fallback
@ -220,7 +233,9 @@ async function dev(env) {
if (!ready || signal.aborted) {
if (!signal.aborted)
stop('Backend readiness timed out. Check PostgreSQL and Redis.')
stop(
'Backend readiness timed out. Verify PostgreSQL, Redis and database initialization with pnpm fullstack:setup.',
)
await backend
@ -236,6 +251,7 @@ async function dev(env) {
...process.env,
VITE_API_MOCK: 'false',
VITE_API_BASE_URL: '/api/',
VITE_API_AUTH_TRANSPORT: 'cookie',
RAY_API_PROXY_TARGET: target,
},
true,
@ -248,7 +264,7 @@ async function dev(env) {
}
try {
if (action === 'setup') {
if (action === 'setup' || action === 'up') {
const external = flags.includes('--external')
if (!existsSync(envFile)) {
@ -262,6 +278,8 @@ try {
const adminPort = portFrom(process.env, 'ADMIN_DEV_PORT', '9527')
const values = {
NODE_ENV: 'development',
RAY_FULLSTACK_SERVICES: external ? 'external' : 'compose',
RAY_COMPOSE_PROJECT: process.env.RAY_COMPOSE_PROJECT || 'ray-template',
HOST: '127.0.0.1',
PORT: portFrom(process.env, 'PORT', '3000'),
ADMIN_DEV_PORT: adminPort,
@ -271,6 +289,8 @@ try {
POSTGRES_PORT: postgresPort,
REDIS_PASSWORD: redisPassword,
REDIS_PORT: redisPort,
APP_PORT: portFrom(process.env, 'APP_PORT', '8080'),
APP_PROXY_NETWORK: process.env.APP_PROXY_NETWORK || '172.30.67',
DATABASE_URL: external
? process.env.DATABASE_URL
: `postgresql://ray:${password}@127.0.0.1:${postgresPort}/ray_template`,
@ -284,6 +304,7 @@ try {
CORS_ORIGINS: devOrigins(adminPort).join(','),
TRUST_PROXY: 'false',
DEMO_ENABLED: 'true',
JWT_SECRET: randomBytes(32).toString('base64url'),
}
// 配置只创建一次,避免重复初始化覆盖用户配置和已修改的凭据。
@ -297,28 +318,79 @@ try {
console.log(
'Created apps/server/.env.local. Initial administrator credentials are stored there; keep this file private.',
)
} else {
const saved = parseEnv(readFileSync(envFile, 'utf8'))
const additions = []
// 升级时只补缺少的字段,保留已有连接和管理员配置。
if (!('JWT_SECRET' in saved))
additions.push(`JWT_SECRET=${randomBytes(32).toString('base64url')}`)
if (external && !('RAY_FULLSTACK_SERVICES' in saved))
additions.push('RAY_FULLSTACK_SERVICES=external')
if (additions.length) {
if (process.platform !== 'win32') chmodSync(envFile, 0o600)
appendFileSync(envFile, `\n${additions.join('\n')}\n`)
console.log('Updated apps/server/.env.local for this version.')
}
}
const env = configuration()
if (!external)
await run(
'docker',
[...compose, 'up', '-d', '--wait', 'postgres', 'redis'],
env,
if (!external && env.RAY_FULLSTACK_SERVICES === 'external')
throw new Error(
'This workspace uses external services. Run pnpm fullstack:setup --external or configure Compose in a separate checkout.',
)
await run(pnpm, ['server:db:migrate'], env)
await run(pnpm, ['server:db:seed'], env)
console.log(
'Fullstack setup complete. Run pnpm dev:full; use the administrator account from apps/server/.env.local.',
)
if (action === 'up') {
const port = portFrom(env, 'APP_PORT', '8080')
await run(
'docker',
[
...compose(env),
'--profile',
'app',
'up',
'--build',
'-d',
'--wait',
'--wait-timeout',
'180',
],
{ ...env, APP_PORT: port },
)
console.log(
`Fullstack services ready at http://127.0.0.1:${port}/ray-template/.`,
)
} else {
if (external && (!env.DATABASE_URL || !env.REDIS_URL))
throw new Error('External setup requires DATABASE_URL and REDIS_URL.')
if (!external)
await run(
'docker',
[...compose(env), 'up', '-d', '--wait', 'postgres', 'redis'],
env,
)
await run(pnpm, ['server:db:migrate'], env)
await run(pnpm, ['server:db:seed'], env)
console.log(
'Fullstack setup complete. Run pnpm dev:full; use the administrator account from apps/server/.env.local.',
)
}
} else if (action === 'stop') {
await run(
'docker',
[...compose, '--profile', 'app', 'stop'],
configuration(),
)
const env = configuration()
if (env.RAY_FULLSTACK_SERVICES === 'external')
throw new Error(
'Stop external services through their own deployment environment.',
)
await run('docker', [...compose(env), '--profile', 'app', 'stop'], env)
} else {
await dev(configuration())
}