feat(fullstack): add optional backend and source distributions

Add the NestJS backend with PostgreSQL and Redis, local setup, and
independent frontend and fullstack source archives.

Enforce permissions across redirects, let users dismiss the 403 page,
and restore missing translation warnings in development.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-06 19:53:49 +08:00
parent b5c24a612c
commit 59c1090ea4
No known key found for this signature in database
140 changed files with 10535 additions and 1002 deletions

View File

@ -9,3 +9,11 @@ dist
**/node_modules
**/.vitepress/cache
**/.vitepress/dist
**/.env
**/.env.*
!apps/admin/.env.development
!apps/admin/.env.production
!apps/admin/.env.test
**/dist-test
**/src/generated
.pnpm-store

141
.github/workflows/distributions.yaml vendored Normal file
View File

@ -0,0 +1,141 @@
name: Source distributions
on:
workflow_dispatch:
inputs:
sync_frontend:
description: Update the generated frontend branch from main
type: boolean
default: false
release_tag:
description: Attach assets to the existing release for this tag (optional)
type: string
permissions:
contents: read
defaults:
run:
shell: bash
concurrency:
group: source-distributions
cancel-in-progress: false
jobs:
verify:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 30
outputs:
source: ${{ steps.source.outputs.commit }}
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Select the source revision
id: source
env:
RELEASE_TAG: ${{ inputs.release_tag }}
SYNC_FRONTEND: ${{ inputs.sync_frontend }}
run: |
if [[ -n "$RELEASE_TAG" ]]; then
[[ "$SYNC_FRONTEND" == false ]] || { echo "Run branch sync and release attachment separately."; exit 1; }
[[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([.-][a-zA-Z0-9.-]+)?$ ]]
source=$(git rev-parse --verify "refs/tags/$RELEASE_TAG^{commit}")
git merge-base --is-ancestor "$source" "$GITHUB_SHA"
git checkout --detach "$source"
[[ "v$(node -p 'require("./package.json").version')" == "$RELEASE_TAG" ]]
fi
echo "commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-node@v7.1.0
with:
node-version-file: .nvmrc
- uses: pnpm/action-setup@v6.1.0
- name: Export both source distributions
env:
HUSKY: '0'
run: |
pnpm install --frozen-lockfile
pnpm dist:frontend
pnpm dist:fullstack
cd dist/distributions
sha256sum ray-template-*.tar.gz > SHA256SUMS.txt
- name: Verify independent installations and builds
env:
HUSKY: '0'
run: |
version=$(node -p 'require("./package.json").version')
for edition in frontend fullstack; do
name="ray-template-$edition-$version"
tar -xzf "dist/distributions/$name.tar.gz" -C "$RUNNER_TEMP"
(
cd "$RUNNER_TEMP/$name"
pnpm install --frozen-lockfile
pnpm check
if [[ "$edition" == fullstack ]]; then
node deploy/smoke.mjs
fi
)
done
- uses: actions/upload-artifact@v7
with:
name: source-distributions
path: |
dist/distributions/ray-template-*.tar.gz
dist/distributions/SHA256SUMS.txt
if-no-files-found: error
compression-level: 0
sync-frontend:
if: inputs.sync_frontend && inputs.release_tag == ''
needs: verify
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
- uses: actions/download-artifact@v8
with:
name: source-distributions
path: ${{ runner.temp }}/source-distributions
- name: Update the generated branch
run: |
version=$(node -p 'require("./package.json").version')
name="ray-template-frontend-$version"
artifacts="$RUNNER_TEMP/source-distributions"
(cd "$artifacts" && sha256sum --check SHA256SUMS.txt)
tar -xzf "$artifacts/$name.tar.gz" -C "$RUNNER_TEMP"
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
bash scripts/sync-frontend.sh "$RUNNER_TEMP/$name"
attach-release:
if: inputs.release_tag != '' && !inputs.sync_frontend
needs: verify
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/download-artifact@v8
with:
name: source-distributions
path: ${{ runner.temp }}/source-distributions
- name: Attach source archives to the existing release
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.release_tag }}
SOURCE: ${{ needs.verify.outputs.source }}
run: |
[[ "$(git rev-parse --verify "refs/tags/$RELEASE_TAG^{commit}")" == "$SOURCE" ]]
gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json tagName >/dev/null
cd "$RUNNER_TEMP/source-distributions"
sha256sum --check SHA256SUMS.txt
gh release upload "$RELEASE_TAG" ray-template-*.tar.gz SHA256SUMS.txt --repo "$GITHUB_REPOSITORY"

1
.gitignore vendored
View File

@ -34,4 +34,5 @@ coverage/
.env.*.local
.ai-local/
.harness-local/
.pnpm-store/
apps/docs/.vitepress/cache/

View File

@ -15,6 +15,11 @@ coverage/
.husky/_/
.ai-local/
.harness-local/
**/dist-test/
apps/server/src/generated/
.pnpm-store/
CHANGELOG.md
packages/icons/src/
packages/ui/src/RChart/src/themes/
packages/demo-data/src/route-catalog.json

View File

@ -19,4 +19,12 @@ module.exports = {
singleAttributePerLine: false,
bracketSameLine: false,
plugins: ['@ianvs/prettier-plugin-sort-imports'],
overrides: [
{
files: 'apps/server/**/*.ts',
options: {
importOrderParserPlugins: ['typescript', 'decorators-legacy'],
},
},
],
}

View File

@ -6,7 +6,7 @@
Ray Template is an open-source frontend template for admin dashboards, operations consoles, and internal tools. It brings together a working application, reusable packages, and interactive documentation. Start with the demo, choose a look, and connect your business APIs.
**4 visual styles · 5 navigation layouts · 11 TablePro examples · 9 shared packages**
**4 visual styles · 5 navigation layouts · 11 TablePro examples · 10 shared packages**
[![The complete Ray Admin welcome page in the default Modern light style with side navigation](docs/assets/readme/welcome-modern-light.png)](https://xiaodaigua-ray.github.io/ray-template/#/dashboard)
@ -82,10 +82,10 @@ Ray Admin and the documentation live in one **pnpm monorepo**. Business integrat
flowchart TB
Admin["Ray Admin · apps/admin"]
Docs["Interactive docs · apps/docs"]
Shared["9 shared workspace packages"]
Shared["10 shared workspace packages"]
UI["Interface: ui · admin-shell"]
Interaction["Interaction: composables · directives · icons"]
Data["Data: http · api-contracts · routing · utils"]
Data["Data: http · api-contracts · demo-data · routing · utils"]
Admin --> Shared
Docs --> Shared
Shared --> UI
@ -121,6 +121,29 @@ Open [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/)
2. **Build a page.** Start with an [existing example](apps/admin/src/views/demo), register its view ID, and add a route with bilingual menu labels.
3. **Connect your API.** Keep the page contract and connect your backend using the [integration guide](apps/docs/guide/backend.md).
## Choose a source distribution
The frontend distribution contains Admin, documentation, shared packages, and Mock. It installs and runs independently without a database or Redis. Run `pnpm dist:frontend` to produce `ray-template-frontend-<version>.tar.gz` and its source directory under `dist/distributions/`. Extract it, then run `pnpm install --frozen-lockfile` and `pnpm dev`.
Each artifact includes `distribution.json` with its version, source commit and workspace state, workspace list, and content digest. Export prunes the lockfile, dependencies, commands, and fullstack-only documentation, and excludes local configuration, credentials, build output, and installed dependencies. See [distributions and startup](apps/docs/guide/distributions.md).
<!-- fullstack:start -->
The complete source also includes an optional [NestJS server](apps/server). PostgreSQL stores users, permissions, sessions, route configuration, and audits; Redis provides rate limits and cache for demonstration reads. Run `pnpm dist:fullstack` to export the matching fullstack source archive.
After installing dependencies, prepare Docker Compose and run:
```sh
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.
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#容器启动).
<!-- fullstack:end -->
## Development and delivery
**Vue 3 · TypeScript / TSX · Naive UI · Vite / Rolldown · Pinia · Vue Router · Vue I18n · Axios · MSW · Vitest**

View File

@ -6,7 +6,7 @@
Ray Template 是基于 Vue 3、TypeScript / TSX 和 Naive UI 的开源中后台模板,适合管理后台、运营工作台和内部工具。完整应用、共享包和交互文档放在同一工作区,克隆即可运行,再按业务调整界面、页面和接口。
**4 种视觉风格 · 5 种导航布局 · 11 个 TablePro 示例 · 9 个共享包**
**4 种视觉风格 · 5 种导航布局 · 11 个 TablePro 示例 · 10 个共享包**
[![默认 Modern 浅色风格的完整欢迎页,展示侧边导航和工作空间概览](docs/assets/readme/welcome-modern-light.png)](https://xiaodaigua-ray.github.io/ray-template/#/dashboard)
@ -82,10 +82,10 @@ Ray Admin 与文档站采用 **pnpm Monorepo**。业务接入留在应用层,
flowchart TB
Admin["Ray Admin · apps/admin"]
Docs["交互文档 · apps/docs"]
Shared["9 个共享 workspace 包"]
Shared["10 个共享 workspace 包"]
UI["界面:ui · admin-shell"]
Interaction["交互:composables · directives · icons"]
Data["数据:http · api-contracts · routing · utils"]
Data["数据:http · api-contracts · demo-data · routing · utils"]
Admin --> Shared
Docs --> Shared
Shared --> UI
@ -121,6 +121,29 @@ pnpm dev
2. **写第一个页面**:参考[现有示例](apps/admin/src/views/demo),登记页面组件 ID,添加路由及中英文菜单文案。
3. **接入业务接口**:保留页面契约,按[后端接入指南](apps/docs/guide/backend.md)连接自己的服务。
## 选择源码发行版本
纯前端发行包包含 Admin、文档、共享包和 Mock,独立安装与运行,不需要数据库或 Redis。执行 `pnpm dist:frontend`,在 `dist/distributions/` 得到 `ray-template-frontend-<version>.tar.gz` 和对应源码目录。解压后执行 `pnpm install --frozen-lockfile`、`pnpm dev`。
每份发行物都包含 `distribution.json`,记录版本、来源提交及工作区状态、工作区清单和内容摘要。导出会裁剪锁文件与依赖、命令和仅供全栈使用的说明,并排除本地配置、凭据、构建输出和依赖目录。详情见[发行版本与快速启动](apps/docs/guide/distributions.md)。
<!-- fullstack:start -->
完整源码还包含可选的 [NestJS 服务端](apps/server),以 PostgreSQL 保存用户、权限、会话、路由与审计,并使用 Redis 提供限流和演示数据缓存。执行 `pnpm dist:fullstack` 生成同版本的全栈源码归档。
安装依赖后,准备 Docker Compose,执行:
```sh
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 服务并保留数据卷。
[源码发行工作流](.github/workflows/distributions.yaml) 验证两个归档后,可以生成或更新 `frontend` 分支,也可以给已有 GitHub Release 附加源码归档。需要从 `main` 手动运行并选择对应操作。容器启动见[发行版本与快速启动](apps/docs/guide/distributions.md#容器启动)。
<!-- fullstack:end -->
## 开发与交付
**Vue 3 · TypeScript / TSX · Naive UI · Vite / Rolldown · Pinia · Vue Router · Vue I18n · Axios · MSW · Vitest**

View File

@ -0,0 +1,51 @@
import Signing from '@/views/login/components/Signing'
import { flushPromises, mount } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
const signing = vi.fn()
vi.mock('@/api/admin/client', () => ({ apiMockEnabled: false }))
vi.mock('@/hooks', () => ({
useI18n: () => ({ t: (key: string) => key }),
}))
vi.mock('@/store', () => ({
useSigningActions: () => ({ signing }),
}))
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' },
})
const router = createRouter({
history: createMemoryHistory(),
routes: ['/', '/welcome'].map((path) => ({
path,
component: { render: () => null },
})),
})
await router.push('/')
const wrapper = mount(Signing, { global: { plugins: [router] } })
try {
const username = wrapper.get('input[name="username"]')
const password = wrapper.get('input[name="password"]')
expect(username.attributes('autocomplete')).toBe('username')
expect(password.attributes('autocomplete')).toBe('current-password')
expect(password.attributes('type')).toBe('password')
expect(wrapper.text()).not.toMatch(/UseDemo|UseMember|UseManager/u)
await username.setValue('qa-account')
await password.setValue('qa-fixture-password')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(signing).toHaveBeenCalledExactlyOnceWith({
name: 'qa-account',
pwd: 'qa-fixture-password',
})
expect(router.currentRoute.value.path).toBe('/welcome')
} finally {
wrapper.unmount()
}
})

View File

@ -0,0 +1,479 @@
// @vitest-environment node
import { spawnSync } from 'node:child_process'
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { parse, parseAllDocuments, stringify } from 'yaml'
import {
checkDistributions,
exportDistribution,
pruneLockfile,
} from '../../scripts/distributions.mjs'
let fixture: string
const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf8'))
const reference = (version: string) => ({ specifier: version, version })
function write(path: string, value: string | object) {
const target = join(fixture, path)
mkdirSync(dirname(target), { recursive: true })
writeFileSync(
target,
typeof value === 'string' ? value : JSON.stringify(value),
)
}
function lockfile() {
const manager = {
lockfileVersion: '9.0',
importers: {
'.': { packageManagerDependencies: { pnpm: reference('12.0.0') } },
},
packages: { 'pnpm@12.0.0': {}, 'pm-native@1.0.0': {} },
snapshots: {
'pnpm@12.0.0': { optionalDependencies: { 'pm-native': '1.0.0' } },
'pm-native@1.0.0': {},
},
}
const workspace = {
lockfileVersion: '9.0',
settings: { autoInstallPeers: true },
importers: {
'.': { devDependencies: { yaml: reference('2.9.1') } },
'apps/admin': {
dependencies: {
'@ray-template/ui': reference('link:../../packages/ui'),
alias: reference('real-package@1.0.0(peer@2.0.0(nested@3.0.0))'),
},
},
'apps/docs': {
dependencies: {
'@ray-template/ui': reference('link:../../packages/ui'),
},
},
'apps/server': {
dependencies: {
'@ray-template/api-contracts': reference(
'link:../../packages/api-contracts',
),
'@ray-template/server-store': reference(
'link:../../packages/server-store',
),
'@nestjs/core': reference('12.0.0'),
},
},
'packages/ui': {
dependencies: {
'@ray-template/api-contracts': reference('link:../api-contracts'),
vue: reference('3.5.0'),
},
},
'packages/api-contracts': {
dependencies: { valibot: reference('1.5.0') },
},
'packages/server-store': { dependencies: { pg: reference('8.0.0') } },
},
packages: {
'yaml@2.9.1': {},
'vue@3.5.0': {},
'valibot@1.5.0': {},
'real-package@1.0.0': {},
'peer@2.0.0': {},
'nested@3.0.0': {},
'native-optional@1.0.0': {},
'@nestjs/core@12.0.0': {},
'pg@8.0.0': {},
'pg-protocol@1.0.0': {},
'unused@1.0.0': {},
},
snapshots: {
'yaml@2.9.1': {},
'vue@3.5.0': {},
'valibot@1.5.0': {},
'real-package@1.0.0(peer@2.0.0(nested@3.0.0))': {
optionalDependencies: { 'native-optional': '1.0.0' },
},
'peer@2.0.0(nested@3.0.0)': {},
'nested@3.0.0': {},
'native-optional@1.0.0': {},
'@nestjs/core@12.0.0': {},
'pg@8.0.0': { dependencies: { 'pg-protocol': '1.0.0' } },
'pg-protocol@1.0.0': {},
'unused@1.0.0': {},
},
}
return `---\n${stringify(manager)}\n---\n${stringify(workspace)}`
}
beforeEach(() => {
fixture = mkdtempSync(join(tmpdir(), 'ray-distribution-'))
write('package.json', {
name: 'ray-template',
version: '6.0.1',
private: true,
scripts: {
dev: 'vite',
'check:frontend': 'pnpm typecheck && pnpm test:run',
check: 'pnpm check:frontend && pnpm server:check && pnpm dist:check',
setup: 'node scripts/fullstack.mjs setup',
'dev:full': 'node scripts/fullstack.mjs dev',
'server:check': 'pnpm --filter @ray-template/server check',
'dist:frontend': 'node scripts/distributions.mjs frontend',
'dist:fullstack': 'node scripts/distributions.mjs fullstack',
'dist:check': 'node scripts/distributions.mjs --check',
},
devDependencies: { yaml: '2.9.1' },
})
write('apps/admin/package.json', {
name: '@ray-template/admin',
dependencies: {
'@ray-template/ui': 'workspace:*',
alias: 'npm:real-package@1.0.0',
},
})
write('apps/docs/package.json', {
name: '@ray-template/docs',
dependencies: { '@ray-template/ui': 'workspace:*' },
})
write('apps/server/package.json', {
name: '@ray-template/server',
dependencies: {
'@ray-template/api-contracts': 'workspace:*',
'@ray-template/server-store': 'workspace:*',
'@nestjs/core': '12.0.0',
},
})
write('packages/ui/package.json', {
name: '@ray-template/ui',
dependencies: { '@ray-template/api-contracts': 'workspace:*' },
peerDependencies: { vue: '3.5.0' },
})
write('packages/api-contracts/package.json', {
name: '@ray-template/api-contracts',
dependencies: { valibot: '1.5.0' },
})
write('packages/server-store/package.json', {
name: '@ray-template/server-store',
dependencies: { pg: '8.0.0' },
})
write('packages/ui/src/index.ts', 'export const shared = true\n')
write('apps/server/src/main.ts', 'export const server = true\n')
write('apps/admin/src/main.ts', 'export const admin = true\n')
write('scripts/distributions.mjs', '// exporter\n')
write('scripts/fullstack.mjs', '// server launcher\n')
write('deploy/compose.yaml', 'services: {}\n')
write('.github/workflows/ci.yaml', 'name: CI\n')
write('.github/workflows/distributions.yaml', 'name: Distributions\n')
write('.husky/pre-commit', 'pnpm lint-staged\n')
chmodSync(join(fixture, '.husky/pre-commit'), 0o755)
write(
'pnpm-workspace.yaml',
'packages:\n - apps/*\n - packages/*\nverifyDepsBeforeRun: false\n',
)
write('pnpm-lock.yaml', lockfile())
write('harness/scopes.json', {
toolchain: { checks: ['packages:check'] },
server: { checks: ['server:check'] },
})
write('harness/context/server.md', '# Server\n')
write('tsconfig.json', {
references: [
{ path: './tsconfig.app.json' },
{ path: './apps/server/tsconfig.json' },
],
})
write('tsconfig.app.json', '{}\n')
write(
'README.md',
'# Template\n\nFrontend instructions.\n\n<!-- fullstack:start -->\n[Server](apps/server/README.md)\n<!-- fullstack:end -->\n\nShared instructions.\n',
)
})
afterEach(() => {
rmSync(fixture, { recursive: true, force: true })
})
it('exports a real frontend workspace without server files, scripts or dependency graph', async () => {
const sourceManifest = readFileSync(join(fixture, 'package.json'), 'utf8')
const sourceLock = readFileSync(join(fixture, 'pnpm-lock.yaml'), 'utf8')
const { directory, manifest } = await exportDistribution(
fixture,
'frontend',
{
archive: false,
},
)
const exported = readJson(join(directory, 'package.json'))
const locks = parseAllDocuments(
readFileSync(join(directory, 'pnpm-lock.yaml'), 'utf8'),
).map((document) => document.toJS())
expect(exported.scripts).not.toHaveProperty('server:check')
expect(exported.scripts).not.toHaveProperty('setup')
expect(exported.scripts).not.toHaveProperty('dev:full')
expect(exported.scripts).not.toHaveProperty('dist:fullstack')
expect(exported.scripts.check).toBe('pnpm check:frontend && pnpm dist:check')
expect(exported.scripts.dev).toBe('vite')
expect(existsSync(join(directory, 'apps/server'))).toBe(false)
expect(existsSync(join(directory, 'packages/server-store'))).toBe(false)
expect(existsSync(join(directory, 'scripts/fullstack.mjs'))).toBe(false)
expect(existsSync(join(directory, 'deploy'))).toBe(false)
expect(
existsSync(join(directory, '.github/workflows/distributions.yaml')),
).toBe(false)
expect(existsSync(join(directory, '.github/workflows/ci.yaml'))).toBe(true)
expect(readJson(join(directory, 'harness/scopes.json'))).not.toHaveProperty(
'server',
)
expect(readJson(join(directory, 'tsconfig.json')).references).toEqual([
{ path: './tsconfig.app.json' },
])
expect(readFileSync(join(directory, 'README.md'), 'utf8')).toContain(
'Frontend instructions.',
)
expect(readFileSync(join(directory, 'README.md'), 'utf8')).not.toContain(
'[Server]',
)
expect(
parse(readFileSync(join(directory, 'pnpm-workspace.yaml'), 'utf8'))
.packages,
).toEqual([
'apps/admin',
'apps/docs',
'packages/api-contracts',
'packages/ui',
])
expect(locks).toHaveLength(2)
expect(locks[0].snapshots).toHaveProperty('pm-native@1.0.0')
expect(Object.keys(locks[1].snapshots)).toEqual(
expect.arrayContaining([
'real-package@1.0.0(peer@2.0.0(nested@3.0.0))',
'peer@2.0.0(nested@3.0.0)',
'nested@3.0.0',
'native-optional@1.0.0',
]),
)
expect(locks[1].snapshots).not.toHaveProperty('@nestjs/core@12.0.0')
expect(locks[1].snapshots).not.toHaveProperty('pg@8.0.0')
expect(locks[1].packages).not.toHaveProperty('pg-protocol@1.0.0')
expect(locks[1].packages).not.toHaveProperty('unused@1.0.0')
expect(manifest.edition).toBe('frontend')
expect(manifest.contentSha256).toMatch(/^[a-f0-9]{64}$/)
expect(manifest.workspaces).not.toContain('apps/server')
expect(readFileSync(join(fixture, 'package.json'), 'utf8')).toBe(
sourceManifest,
)
expect(readFileSync(join(fixture, 'pnpm-lock.yaml'), 'utf8')).toBe(sourceLock)
if (process.platform !== 'win32') {
expect(statSync(join(directory, '.husky/pre-commit')).mode & 0o777).toBe(
0o755,
)
}
})
it('exports fullstack with its backend and transitive packages', async () => {
const { directory, manifest } = await exportDistribution(
fixture,
'fullstack',
{
archive: false,
},
)
const lock = parseAllDocuments(
readFileSync(join(directory, 'pnpm-lock.yaml'), 'utf8'),
)[1].toJS()
expect(existsSync(join(directory, 'apps/server/src/main.ts'))).toBe(true)
expect(
existsSync(join(directory, 'packages/server-store/package.json')),
).toBe(true)
expect(existsSync(join(directory, 'deploy/compose.yaml'))).toBe(true)
expect(readJson(join(directory, 'package.json')).scripts).toHaveProperty(
'dev:full',
)
expect(lock.snapshots).toHaveProperty('pg-protocol@1.0.0')
expect(manifest.workspaces).toContain('apps/server')
})
it('omits local secrets, unapproved root files and generated output while including new source', async () => {
for (const path of [
'.env',
'.env.local',
'credentials.json',
'.git/config',
'apps/server/.env',
'apps/server/src/generated/client.ts',
'apps/server/dist-test/result.js',
'apps/admin/.env.local',
'apps/admin/node_modules/secret.txt',
'packages/ui/dist/index.js',
'apps/docs/.vitepress/cache/leak.json',
'scripts/private.pem',
'docs/.local/token',
'.husky/_/husky.sh',
])
write(path, 'private data')
write('apps/server/.env.example', 'DATABASE_URL=postgresql://example\n')
write('apps/server/.gitignore', '/src/generated/\n/dist-test/\n/.env.local\n')
write('apps/admin/.env.development', 'VITE_API_MOCK=true\n')
write(
'packages/ui/src/new-uncommitted.ts',
'export const uncommitted = true\n',
)
write('__test__/cache/keep.spec.ts', 'export const regression = true\n')
write('apps/admin/src/utils/cache/index.ts', 'export const storage = true\n')
const { directory } = await exportDistribution(fixture, 'fullstack', {
archive: false,
})
expect(existsSync(join(directory, 'apps/server/.env.example'))).toBe(true)
expect(existsSync(join(directory, 'apps/server/.gitignore'))).toBe(true)
expect(existsSync(join(directory, 'apps/server/src/generated'))).toBe(false)
expect(existsSync(join(directory, 'apps/server/dist-test'))).toBe(false)
expect(existsSync(join(directory, 'apps/admin/.env.development'))).toBe(true)
expect(
existsSync(join(directory, 'packages/ui/src/new-uncommitted.ts')),
).toBe(true)
expect(existsSync(join(directory, '__test__/cache/keep.spec.ts'))).toBe(true)
expect(
existsSync(join(directory, 'apps/admin/src/utils/cache/index.ts')),
).toBe(true)
expect(existsSync(join(directory, 'apps/admin/.env.local'))).toBe(false)
expect(existsSync(join(directory, 'apps/server/.env'))).toBe(false)
expect(existsSync(join(directory, '.env'))).toBe(false)
expect(existsSync(join(directory, 'credentials.json'))).toBe(false)
expect(existsSync(join(directory, '.git'))).toBe(false)
expect(existsSync(join(directory, 'packages/ui/dist'))).toBe(false)
expect(existsSync(join(directory, 'scripts/private.pem'))).toBe(false)
})
it('validates exports read-only and supports frontend-only extracted projects', async () => {
const entries = readdirSync(fixture)
expect(checkDistributions(fixture).map(({ edition }) => edition)).toEqual([
'frontend',
'fullstack',
])
expect(readdirSync(fixture)).toEqual(entries)
const { directory } = await exportDistribution(fixture, 'frontend', {
archive: false,
})
expect(checkDistributions(directory).map(({ edition }) => edition)).toEqual([
'frontend',
])
await expect(
exportDistribution(directory, 'fullstack', { archive: false }),
).rejects.toThrow('Workspace dependency is missing')
})
it('refuses broken dependency graphs and missing lockfile importers', async () => {
write('packages/ui/package.json', {
name: '@ray-template/ui',
dependencies: { '@ray-template/server': 'workspace:*' },
})
expect(() => checkDistributions(fixture)).toThrow(
'Frontend dependency reaches the server',
)
expect(() =>
pruneLockfile(lockfile(), new Set(['.', 'apps/missing'])),
).toThrow('Workspace importer is missing')
expect(() =>
pruneLockfile('lockfileVersion: 6\nimporters: {}', new Set()),
).toThrow('version 9')
})
it('refuses credentials in package-manager config and malformed section markers', async () => {
write('.npmrc', '//registry.npmjs.org/:_authToken=do-not-export\n')
expect(() => checkDistributions(fixture)).toThrow('Credential-bearing .npmrc')
rmSync(join(fixture, '.npmrc'))
write('README.md', '<!-- fullstack:start -->\nMissing end\n')
expect(() => checkDistributions(fixture)).toThrow(
'Unpaired fullstack section marker',
)
})
it('replaces only recognized generated output and keeps artifact content reproducible', async () => {
const output = 'dist/distributions/ray-template-frontend-6.0.1'
write(`${output}/keep.txt`, 'user data')
await expect(
exportDistribution(fixture, 'frontend', { archive: false }),
).rejects.toThrow('unrecognized distribution')
expect(readFileSync(join(fixture, output, 'keep.txt'), 'utf8')).toBe(
'user data',
)
rmSync(join(fixture, output), { recursive: true })
const first = await exportDistribution(fixture, 'frontend', {
archive: false,
})
const second = await exportDistribution(fixture, 'frontend', {
archive: false,
})
expect(first.manifest.contentSha256).toBe(second.manifest.contentSha256)
})
it.skipIf(process.platform === 'win32')(
'rejects existing and dangling output symlinks and source symlinks',
async () => {
const outside = mkdtempSync(join(tmpdir(), 'ray-distribution-outside-'))
try {
symlinkSync(outside, join(fixture, 'dist'), 'dir')
await expect(
exportDistribution(fixture, 'frontend', { archive: false }),
).rejects.toThrow('symlink')
expect(readdirSync(outside)).toEqual([])
rmSync(join(fixture, 'dist'))
mkdirSync(join(fixture, 'dist/distributions'), { recursive: true })
symlinkSync(
join(outside, 'new-file'),
join(fixture, 'dist/distributions/ray-template-frontend-6.0.1.tar.gz'),
)
await expect(exportDistribution(fixture, 'frontend')).rejects.toThrow(
'symlink',
)
expect(existsSync(join(outside, 'new-file'))).toBe(false)
rmSync(join(fixture, 'dist'), { recursive: true })
symlinkSync(
join(fixture, 'package.json'),
join(fixture, 'packages/ui/src/linked.json'),
)
expect(() => checkDistributions(fixture)).toThrow('Source symlinks')
} finally {
rmSync(outside, { recursive: true, force: true })
}
},
)
it('creates a portable archive containing one distribution root and its provenance', async () => {
const { archive } = await exportDistribution(fixture, 'frontend')
const result = spawnSync('tar', ['-tzf', archive!], { encoding: 'utf8' })
expect(result.status).toBe(0)
expect(result.stdout).toContain(
'ray-template-frontend-6.0.1/distribution.json',
)
expect(result.stdout).toContain(
'ray-template-frontend-6.0.1/apps/admin/package.json',
)
expect(result.stdout).not.toContain('apps/server')
})

View File

@ -198,6 +198,59 @@ it('keeps status routes out of tabs and clears active business navigation', asyn
}
})
it('removes shortcuts that lead through or to a route the current role cannot open', async () => {
const shortcuts = [
{ path: '/private-link', redirect: '/private', meta: {} },
{
path: '/admin-link',
redirect: '/reports',
meta: { role: ['admin'] },
},
{ path: '/via-admin', redirect: '/admin-link', meta: {} },
{ path: '/open-link', redirect: '/reports', meta: {} },
]
for (const shortcut of shortcuts) router.addRoute(shortcut)
state.routes = [...state.routes, ...shortcuts]
await menu.setupAppMenu()
expect(menu.options.map(({ fullPath }) => fullPath)).toContain('/via-admin')
piniaSigningStore().signingCallback.role = 'member'
await flushPromises()
expect(menu.options.map(({ fullPath }) => fullPath)).toEqual([
'/reports',
'/orders',
'/open-link',
])
})
it('closes the 403 view back to an allowed tab without storing a denied tab', async () => {
piniaSigningStore().signingCallback.role = 'member'
await router.push('/reports?sort=desc#summary')
await router.push('/private')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/403')
expect(actions.getCurrentTagIndex()).toBe(-1)
await actions.closeForbiddenPage()
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/reports?sort=desc#summary')
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/reports?sort=desc#summary',
])
})
it('closes a directly opened 403 to the workspace with no business tags', async () => {
await router.push('/403')
await actions.closeForbiddenPage()
await flushPromises()
expect(router.currentRoute.value.path).toBe('/welcome')
expect(menu.menuTagOptions).toEqual([])
})
it('removes revoked tags and cached views without choosing another active page', async () => {
await router.push('/reports')
await router.push('/private?mode=edit#section')

View File

@ -21,8 +21,26 @@ function setupRouter(rootRole?: string[]) {
{ path: '/500', name: 'ErrorPage500', component },
{ path: '/dashboard', component, meta: { role: rootRole } },
{ path: '/allowed', component, meta: { role: ['admin'] } },
{ path: '/denied', component, meta: { role: ['editor'] } },
{
path: '/denied',
alias: '/denied-alias',
component,
meta: { role: ['editor'] },
},
{ path: '/legacy', redirect: '/allowed' },
{ path: '/alias-shortcut', redirect: '/denied-alias' },
{
path: '/private-shortcut',
redirect: '/allowed',
meta: { role: ['editor'] },
},
{ path: '/via-private', redirect: '/private-shortcut' },
{
path: '/restricted-group',
component,
meta: { role: ['editor'] },
children: [{ path: 'page', component, meta: { role: ['admin'] } }],
},
{
path: '/docs',
name: 'RayTemplateDoc',
@ -83,6 +101,34 @@ describe('Router 5 permission guard', () => {
expect(router.currentRoute.value.query.from).toBe('/denied')
})
it.each([
'/alias-shortcut',
'/private-shortcut',
'/via-private',
'/restricted-group/page',
])('blocks %s and keeps the attempted URL', async (path) => {
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
const router = setupRouter()
const attempted = `${path}?filter=open#row`
await router.push(attempted)
expect(router.currentRoute.value.path).toBe('/403')
expect(router.currentRoute.value.query.from).toBe(attempted)
})
it('retains a restricted redirect entry through sign-in for permission checking', async () => {
const router = setupRouter()
const attempted = '/via-private?source=link#report'
await router.push(attempted)
expect(router.currentRoute.value.query.redirect).toBe(attempted)
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
expect(
resolveLandingPath(router, router.currentRoute.value.query.redirect),
).toBe('/welcome')
})
it('does not depend on the legacy dashboard being permitted', async () => {
const router = setupRouter(['editor'])

View File

@ -0,0 +1,129 @@
// @vitest-environment node
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
const directories: string[] = []
const checker = resolve('scripts/check-package-boundaries.mjs')
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'ray-boundaries-'))
directories.push(root)
writeFileSync(
join(root, 'package.json'),
JSON.stringify({ version: '1.0.0' }),
)
mkdirSync(join(root, 'apps'))
mkdirSync(join(root, 'packages'))
return {
add(
group: string,
name: string,
runtime: string,
source = '',
dependencies = {},
) {
const directory = join(root, group, name)
mkdirSync(directory)
writeFileSync(
join(directory, 'package.json'),
JSON.stringify({
name: `@ray-template/${name}`,
version: '1.0.0',
rayTemplate: { runtime },
exports: { '.': './index.ts' },
dependencies,
}),
)
writeFileSync(join(directory, 'index.ts'), source)
},
check() {
const result = spawnSync(process.execPath, [checker, root], {
encoding: 'utf8',
})
return { status: result.status, output: result.stdout + result.stderr }
},
}
}
afterEach(() => {
for (const directory of directories.splice(0))
rmSync(directory, { recursive: true, force: true })
})
describe('workspace ownership', () => {
it('permits independent applications to share universal contracts', () => {
const project = fixture()
project.add(
'packages',
'contracts',
'universal',
'export const version = 1',
)
for (const [name, runtime] of [
['admin', 'browser'],
['server', 'server'],
]) {
project.add(
'apps',
name,
runtime,
"import { version } from '@ray-template/contracts'",
{ '@ray-template/contracts': 'workspace:*' },
)
}
expect(project.check().status).toBe(0)
})
it('rejects application dependencies even when their exports exist', () => {
const project = fixture()
project.add('apps', 'server', 'server')
project.add('apps', 'admin', 'browser', '', {
'@ray-template/server': 'workspace:*',
})
expect(project.check().output).toContain(
'applications cannot be dependencies',
)
})
it('rejects browser dependencies and Node builtins in universal packages', () => {
const project = fixture()
project.add('packages', 'ui', 'browser')
project.add(
'packages',
'contracts',
'universal',
"import fs from 'node:fs'",
{ '@ray-template/ui': 'workspace:*' },
)
const result = project.check()
expect(result.status).toBe(1)
expect(result.output).toContain('universal cannot depend on browser')
expect(result.output).toContain('node:fs')
})
it('rejects undeclared app imports and relative workspace escapes', () => {
const project = fixture()
project.add(
'apps',
'admin',
'browser',
"import missing from 'undeclared'\nimport other from '../server/index.ts'",
)
expect(project.check().output).toContain('undeclared')
expect(project.check().output).toContain('../server/index.ts')
})
})

View File

@ -38,6 +38,13 @@
"vue-i18n": "11.4.17",
"vue-router": "5.4.0",
"vue3-next-qrcode": "4.1.1",
"@ray-template/api-contracts": "workspace:*"
"@ray-template/api-contracts": "workspace:*",
"@ray-template/demo-data": "workspace:*"
},
"rayTemplate": {
"runtime": "browser"
},
"devDependencies": {
"vite": "8.3.5"
}
}

View File

@ -3036,8 +3036,13 @@
"get": {
"operationId": "getRouteConfig",
"summary": "getRouteConfig",
"description": "Session or public bootstrap endpoint.",
"security": [],
"description": "Public navigation snapshot. Request view=editor with routes:write to read the complete saved configuration, including disabled demo routes.",
"security": [
{},
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Success",
@ -3125,7 +3130,17 @@
}
}
}
}
},
"parameters": [
{
"name": "view",
"in": "query",
"required": false,
"schema": {
"const": "editor"
}
}
]
},
"put": {
"operationId": "updateRouteConfig",

View File

@ -21,8 +21,11 @@ export const getAdminSession = () =>
adminRequest('auth/session', sessionSchema, { method: 'get' })
export const logoutAdmin = () =>
adminRequest('auth/logout', v.null(), { method: 'post' })
export const getAdminRoutes = () =>
adminRequest('route-config', routeConfigSchema, { method: 'get' })
export const getAdminRoutes = (view?: 'editor') =>
adminRequest('route-config', routeConfigSchema, {
method: 'get',
params: view ? { view } : void 0,
})
export const updateAdminRoutes = (config: RouteConfig) =>
adminRequest('route-config', routeConfigSchema, {
method: 'put',

View File

@ -1,52 +1,10 @@
import type { PaginationResponse } from '@/types/modules/axios'
import { faker } from '@faker-js/faker/locale/zh_CN'
import type { Person, PersonListParams } from '@ray-template/api-contracts/demo'
import type { PersonListParams } from '@ray-template/api-contracts/demo'
import { listPeople as queryPeople } from '@ray-template/demo-data/people'
export type { Person, PersonListParams } from '@ray-template/api-contracts/demo'
let people: Person[] | undefined
export const listPeople = (params: PersonListParams = {}) => {
const { items, total } = queryPeople(params)
export const listPeople = ({
page,
pageSize,
email,
name,
sortAge,
}: PersonListParams = {}): PaginationResponse<Person[]> => {
// 同一会话内复用数据,让翻页和从上一页复制的搜索词都可重复使用。
people ??= Array.from({ length: 100 }, () => ({
id: faker.string.uuid(),
address: faker.location.state() + faker.location.city(),
email: faker.internet.email(),
name: faker.person.fullName(),
age: faker.number.int({ min: 18, max: 60 }),
createDate: faker.date.past().toISOString().slice(0, 10),
}))
const emailQuery = email?.trim().toLowerCase()
const nameQuery = name?.trim().toLowerCase()
const matches = people.filter(
(person) =>
(!emailQuery || person.email.toLowerCase().includes(emailQuery)) &&
(!nameQuery || person.name.toLowerCase().includes(nameQuery)),
)
if (sortAge) {
const direction = sortAge === 'ascend' ? 1 : -1
matches.sort((left, right) => direction * (left.age - right.age))
}
const validPage = page !== void 0 && Number.isSafeInteger(page) && page > 0
const validSize =
pageSize !== void 0 && Number.isSafeInteger(pageSize) && pageSize > 0
const start = validPage && validSize ? (page - 1) * pageSize : 0
return {
code: 200,
msg: '请求成功',
data:
validPage && validSize ? matches.slice(start, start + pageSize) : matches,
total: matches.length,
}
return { code: 200, msg: '请求成功', data: items, total }
}

View File

@ -1,4 +1,5 @@
import { WELCOME_ROUTE_PATH } from '@/router/constant'
import { FORBIDDEN_ROUTE_PATH, WELCOME_ROUTE_PATH } from '@/router/constant'
import { resolveLandingPath } from '@/router/utils/resolve-landing-path'
import { useMenuActions, useMenuGetters } from '@/store'
import type { Key, MenuTagOptions } from '@/types'
import { useVueRouter } from './useVueRouter'
@ -127,6 +128,21 @@ export function useSiderBar() {
return router.replace(WELCOME_ROUTE_PATH)
}
const closeForbiddenPage = () => {
if (router.currentRoute.value.path !== FORBIDDEN_ROUTE_PATH) return
const previous = resolveLandingPath(
router,
router.options.history.state.back,
)
const target =
previous === WELCOME_ROUTE_PATH
? resolveLandingPath(router, getMenuTagOptions.value.at(-1)?.fullPath)
: previous
return router.replace(target)
}
/**
*
* @param target 要保留的边界标签对象、索引或路径
@ -193,6 +209,7 @@ export function useSiderBar() {
return {
close,
closeAll,
closeForbiddenPage,
closeRight,
closeLeft,
closeOther,

View File

@ -1,5 +1,6 @@
import { RIcon, RMoreDropdown } from '@/components'
import { useI18n, useMaximize, useSiderBar, useSpinning } from '@/hooks'
import { FORBIDDEN_ROUTE_PATH } from '@/router/constant'
import { useMenuActions, useMenuGetters, useRuntimeGetters } from '@/store'
import type { AppMenuOption, MenuTagOptions } from '@/types'
import { ShellTab } from '@ray-template/admin-shell'
@ -21,6 +22,9 @@ export default defineComponent({
setup(_, { expose }) {
const scrollRef = useTemplateRef<ScrollbarInst | null>('scrollRef')
const tagsRef = useTemplateRef<HTMLElement>('tags')
const actionsButton = useTemplateRef<HTMLButtonElement>('actionsButton')
const route = useRoute()
const showingForbidden = computed(() => route.path === FORBIDDEN_ROUTE_PATH)
const { t } = useI18n('menuTag')
const { getCurrentMenuOption, getMenuTagOptions } = useMenuGetters()
const getMenuKey = computed(
@ -31,6 +35,7 @@ export default defineComponent({
const { reload } = useSpinning()
const {
close,
closeForbiddenPage,
closeAll: $closeAll,
closeRight: $closeRight,
closeLeft: $closeLeft,
@ -40,14 +45,27 @@ export default defineComponent({
} = useSiderBar()
// 当前右键标签页索引位置
const currentContextmenuIndex = ref(-1)
const closeStatus = async (restoreFocus: boolean) => {
const navigation = closeForbiddenPage()
if (!navigation || (await navigation) || !restoreFocus) return
await nextTick()
const active = tagsRef.value?.querySelector<HTMLButtonElement>(
'.menu-tag__tab[aria-current="page"]',
)
const focus = active ?? actionsButton.value
focus?.focus()
}
// 下拉菜单
const moreOptions = computed(() => [
{
label: t('closeCurrent'),
key: 'closeCurrentPage',
disabled: !canClose(
getMenuTagOptions.value[currentContextmenuIndex.value],
),
disabled:
!(showingForbidden.value && currentContextmenuIndex.value === -1) &&
!canClose(getMenuTagOptions.value[currentContextmenuIndex.value]),
icon: () => <RIcon name="action/close" size="1em" />,
},
{
@ -107,6 +125,9 @@ export default defineComponent({
])
const actionMap = {
closeCurrentPage: () => {
if (showingForbidden.value && currentContextmenuIndex.value === -1)
return closeStatus(true)
closeCurrentMenuTag(currentContextmenuIndex.value)
},
reloadCurrentPage: () => {
@ -218,7 +239,7 @@ export default defineComponent({
const fn = actionMap[key as keyof typeof actionMap]
fn?.()
return fn?.()
}
// 右键点击标签页
@ -284,6 +305,8 @@ export default defineComponent({
syncScroll,
scrollRef,
tagsRef,
showingForbidden,
closeStatus,
actionDropdownSelect,
actionState,
menuTagContextMenu,
@ -389,6 +412,17 @@ export default defineComponent({
<Chevron direction="right" />
</button>
<div class="menu-tag__tools">
{this.showingForbidden && (
<button
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.closeCurrent')}
title={$t('menuTag.closeCurrent')}
onClick={(event) => this.closeStatus(event.detail === 0)}
>
<RIcon name="action/close" size={16} aria-hidden="true" />
</button>
)}
<button
type="button"
class="menu-tag__control"
@ -422,6 +456,7 @@ export default defineComponent({
onSelect={actionDropdownSelect}
>
<button
ref="actionsButton"
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.actions')}

View File

@ -31,7 +31,6 @@ const createI18nOptions = async () => {
locale,
messages: messages as unknown as I18nOptions['messages'],
sync: true,
missingWarn: false,
silentFallbackWarn: true,
fallbackLocale: SYSTEM_FALLBACK_LOCALE,
})

View File

@ -16,6 +16,7 @@
"Access": "WORKSPACE ACCESS",
"Welcome": "Welcome to Ray Admin",
"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.",
"RegisterHint": "This registration example is ready to connect to your account service.",

View File

@ -16,6 +16,7 @@
"Access": "工作台入口",
"Welcome": "欢迎使用 Ray Admin",
"AccessDescription": "使用演示账号探索工作台与组件示例。",
"AccountDescription": "使用管理员或已开通的账号登录工作台。",
"UseDemo": "使用演示账号进入",
"SignInError": "登录失败,请重试。",
"RegisterHint": "此页面是注册流程的接入示例,可连接项目的账号服务。",

View File

@ -1,152 +1 @@
import type {
DemoOrder,
DemoOrderQuery,
SearchOptions,
} from '@ray-template/api-contracts/demo'
export const statuses = ['pending', 'paid', 'closed'] as const
export const organizations = ['north', 'south'] as const
export const products = ['notes', 'keyboard', 'notebook', 'monitor'] as const
export const warehouses = [
'north-main',
'north-backup',
'south-main',
'south-backup',
] as const
export const owners = [
{ id: 'n1', orgId: 'north' },
{ id: 'n2', orgId: 'north' },
{ id: 's1', orgId: 'south' },
{ id: 's2', orgId: 'south' },
] as const
const labels = {
'zh-CN': {
teams: ['北区', '南区'],
people: ['陈晨', '林岚', '周宁', '王雨'],
statuses: ['待处理', '已支付', '已关闭'],
products: ['便签', '键盘', '笔记本', '显示器'],
groups: ['办公用品', '电子设备'],
warehouses: ['北区主仓', '北区备仓', '南区主仓', '南区备仓'],
deliveries: ['普通', '加急'],
},
'en-US': {
teams: ['North', 'South'],
people: ['Chen', 'Lin', 'Zhou', 'Wang'],
statuses: ['Pending', 'Paid', 'Closed'],
products: ['Notes', 'Keyboard', 'Notebook', 'Monitor'],
groups: ['Office supplies', 'Electronics'],
warehouses: ['North main', 'North backup', 'South main', 'South backup'],
deliveries: ['Standard', 'Express'],
},
}
export const getOrderLabels = (locale: string) =>
labels[locale === 'zh-CN' ? 'zh-CN' : 'en-US']
export function getOrderOptions(locale: string): SearchOptions {
const copy = getOrderLabels(locale)
return {
statuses: statuses.map((value, index) => ({
value,
label: copy.statuses[index],
})),
organizations: organizations.map((value, index) => ({
value,
label: copy.teams[index],
})),
productCategories: copy.groups.map((label, group) => ({
value: `category-${group}`,
label,
children: products
.slice(group * 2, group * 2 + 2)
.map((value, index) => ({
value,
label: copy.products[group * 2 + index],
})),
})),
warehouseRegions: organizations.map((value, region) => ({
value,
label: copy.teams[region],
children: warehouses
.slice(region * 2, region * 2 + 2)
.map((value, index) => ({
value,
label: copy.warehouses[region * 2 + index],
})),
})),
deliveries: ['standard', 'express'].map((value, index) => ({
value,
label: copy.deliveries[index],
})),
}
}
export const orders = Array.from({ length: 96 }, (_, index) => {
const ownerIndex = index % owners.length
const { orgId, id: ownerId } = owners[ownerIndex]
const productIndex = Math.floor(index / 3) % products.length
const statusIndex = index % statuses.length
const warehouseIndex = Math.floor(index / 8) % warehouses.length
const day = 1 + (index % 12)
const hour = index % 3 === 0 ? 9 : 14
return {
id: index + 1,
orderNo: `ORD-${String(index + 1).padStart(3, '0')}`,
productIndex,
productId: products[productIndex],
statusIndex,
status: statuses[statusIndex],
createdAt: `2026-11-${String(day).padStart(2, '0')}`,
orgId,
ownerId,
ownerIndex,
warehouseIndex,
warehouseId: warehouses[warehouseIndex],
amount: [0, 59, 129, 199, 349, 699, 1299, 2499][index % 8],
invoiced: Math.floor(index / 4) % 2 === 0,
delivery: index % 3 === 0 ? 'express' : 'standard',
deliveryAt: new Date(2026, 10, day + 1, hour).getTime(),
deliveryTime: hour === 9 ? '09:00:00' : '14:00:00',
}
})
export function orderMatchesQuery(row: DemoOrder, query: DemoOrderQuery) {
const {
keyword,
status,
createdFrom,
createdTo,
orgId,
ownerId,
productId,
warehouseId,
minAmount,
invoiced,
delivery,
deliveryFrom,
deliveryTo,
deliveryTime,
} = query
return (
`${row.orderNo} ${row.product}`
.toLowerCase()
.includes(String(keyword ?? '').toLowerCase()) &&
(!status?.length || status.includes(row.status)) &&
(typeof createdFrom !== 'string' || row.createdAt >= createdFrom) &&
(typeof createdTo !== 'string' || row.createdAt <= createdTo) &&
(orgId == null || row.orgId === orgId) &&
(ownerId == null || row.ownerId === ownerId) &&
(productId == null || row.productId === productId) &&
(warehouseId == null || row.warehouseId === warehouseId) &&
(typeof minAmount !== 'number' || row.amount >= minAmount) &&
(invoiced == null || row.invoiced === invoiced) &&
(delivery == null || row.delivery === delivery) &&
(typeof deliveryFrom !== 'number' || row.deliveryAt >= deliveryFrom) &&
(typeof deliveryTo !== 'number' || row.deliveryAt <= deliveryTo) &&
(deliveryTime == null || row.deliveryTime === deliveryTime)
)
}
export * from '@ray-template/demo-data/orders'

View File

@ -1,11 +1 @@
import type { RouteDemoPerson } from '@ray-template/api-contracts/demo'
export const routeDemoPeople: RouteDemoPerson[] = Array.from(
{ length: 10 },
(_, index) => ({
key: index,
name: `张三${index}`,
address: 'New York No. 1 Lake Park',
phone: '010-121212',
}),
)
export * from '@ray-template/demo-data/route-people'

View File

@ -1,69 +1 @@
import type { AdminUser, UserOptions } from '@/api/admin/contracts'
const departments = [
{ id: 'product', parentId: 'company' },
{ id: 'engineering', parentId: 'company' },
{ id: 'platform', parentId: 'engineering' },
{ id: 'experience', parentId: 'engineering' },
{ id: 'operations', parentId: 'company' },
]
export const initialUserOptions: UserOptions = {
departments: [
{
id: 'company',
parentId: null,
name: 'Ray Studio',
labelKey: 'userManagement.departments.company',
},
...departments.map((item) => ({
...item,
name: item.id,
labelKey: `userManagement.departments.${item.id}`,
})),
],
roles: ['admin', 'manager', 'member'].map((value) => ({
value,
label: value,
labelKey: `userManagement.roles.${value}`,
})),
}
export const createInitialUsers = (): AdminUser[] =>
[
'Alex Chen',
'Jordan Lee',
'Casey Lin',
'Morgan Wu',
'Taylor Wang',
'Avery Liu',
'Riley Zhao',
'Jamie Sun',
'Robin Xu',
'Sam Zhou',
'Drew Huang',
'Quinn Yang',
'Skyler He',
'Cameron Lu',
'Reese Ma',
'Parker Guo',
'Charlie Yu',
'Dakota Shen',
'Emery Han',
'Finley Luo',
'Hayden Tang',
'Jules Gao',
'Kendall Song',
'Logan Feng',
].map((name, index) => ({
id: `demo-user-${index + 1}`,
username: `user${String(index + 1).padStart(3, '0')}`,
name,
email: `user${index + 1}@example.com`,
phone: '',
departmentId: departments[index % departments.length]!.id,
role: index === 0 ? 'admin' : index % 5 === 0 ? 'manager' : 'member',
status: index % 6 === 5 ? 'disabled' : 'enabled',
remark: '',
createdAt: new Date(Date.UTC(2026, 0, index + 1, 9)).toISOString(),
}))
export * from '@ray-template/demo-data/users'

View File

@ -16,8 +16,8 @@ import type {
} from '@/api/admin/contracts'
import { parseRouteConfig } from '@/router/config/contract'
import type { RouteConfig } from '@/router/config/schema'
import { initialRoutes } from '@ray-template/demo-data'
import * as v from 'valibot'
import initialRoutes from './data/routes.json'
import { createInitialUsers, initialUserOptions } from './data/users'
export class MockApiError extends Error {

View File

@ -2,7 +2,6 @@ import { userListQuerySchema } from '@/api/admin/contracts'
import { listPeople } from '@/demo-data/people'
import {
chartsQuerySchema,
orderSchema,
orderSearchInputSchema,
ownerSearchInputSchema,
personListQuerySchema,
@ -10,17 +9,16 @@ import {
routePeopleQuerySchema,
searchOptionsQuerySchema,
} from '@ray-template/api-contracts/demo'
import {
getDemoCharts,
getOrderOptions,
listRouteDemoPeople,
requestFixture,
searchDemoOrders,
searchDemoOwners,
} from '@ray-template/demo-data'
import { delay, http, HttpResponse } from 'msw'
import * as v from 'valibot'
import charts from './data/charts.json'
import {
getOrderLabels,
getOrderOptions,
orderMatchesQuery,
orders,
owners,
} from './data/orders'
import requestFixture from './data/request.json'
import { routeDemoPeople } from './data/route-people'
import { MockApiError } from './database'
import type { AdminDatabase } from './database'
@ -78,21 +76,9 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
),
http.get(url('admin/demo/request'), () => respond(() => requestFixture)),
http.get(url('admin/demo/charts'), ({ request }) =>
respond(() => {
const { refresh } = readQuery(request, chartsQuerySchema)
return refresh
? {
...charts,
lines: charts.lines.map((line) => ({
...line,
values: line.values.map(() =>
Math.floor((Math.random() + 1) * 100),
),
})),
}
: charts
}),
respond(() =>
getDemoCharts(readQuery(request, chartsQuerySchema).refresh),
),
),
http.get(url('admin/demo/search-options'), ({ request }) =>
respond(() =>
@ -102,21 +88,9 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
),
),
http.get(url('admin/demo/route-people'), ({ request }) =>
respond(() => {
const {
page = 1,
pageSize = 10,
name,
} = readQuery(request, routePeopleQuerySchema)
const matches = routeDemoPeople.filter(
(person) => name === void 0 || person.name === name,
)
return {
items: matches.slice((page - 1) * pageSize, page * pageSize),
total: matches.length,
}
}),
respond(() =>
listRouteDemoPeople(readQuery(request, routePeopleQuerySchema)),
),
),
http.get(url('admin/demo/route-people/:id'), ({ params }) =>
respond(() => {
@ -136,16 +110,7 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
if (body.fail) throw new MockApiError(503, 'requestFailed')
const copy = getOrderLabels(body.locale)
return owners.flatMap(({ id, orgId }, index) =>
orgId === body.orgId &&
copy.people[index]
.toLowerCase()
.includes(body.keyword.trim().toLowerCase())
? [{ label: copy.people[index], value: id }]
: [],
)
return searchDemoOwners(body.orgId, body.keyword, body.locale)
}),
),
http.post(url('admin/demo/orders/search'), ({ request }) =>
@ -154,27 +119,7 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
if (body.fail) throw new MockApiError(503, 'requestFailed')
const copy = getOrderLabels(body.locale)
const matches = orders
.map((row) =>
v.parse(orderSchema, {
...row,
product: copy.products[row.productIndex],
statusLabel: copy.statuses[row.statusIndex],
organization: copy.teams[row.orgId === 'north' ? 0 : 1],
owner: copy.people[row.ownerIndex],
warehouse: copy.warehouses[row.warehouseIndex],
deliveryLabel:
copy.deliveries[row.delivery === 'express' ? 1 : 0],
}),
)
.filter((row) => orderMatchesQuery(row, body.query))
const { page = 1, pageSize = 5 } = body.query
return {
items: matches.slice((page - 1) * pageSize, page * pageSize),
total: matches.length,
}
return searchDemoOrders(body.query, body.locale)
}),
),
http.post(url('admin/auth/login'), ({ request }) =>
@ -186,8 +131,19 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
http.post(url('admin/auth/logout'), ({ request }) =>
respond(() => database.logout(token(request))),
),
http.get(url('admin/route-config'), () =>
respond(() => database.getRoutes()),
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')
database.authorize(token(request), 'routes:write')
}
return database.getRoutes()
}),
),
http.put(url('admin/route-config'), ({ request }) =>
respond(async () =>

View File

@ -21,7 +21,7 @@ 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 attempted URL in `query.from`. Recovery actions validate it through `resolveLandingPath` before navigating, and error-page failures do not create redirect loops. Role changes prune unauthorized tags/cache entries and show `/403` for a revoked current page.
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.
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`.
@ -58,7 +58,7 @@ Set `VITE_ROUTE_CONFIG_URL=/api/route-config` at deployment, or use an HTTPS URL
| ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path`, `children` | Relative paths append to the parent group; absolute paths match from the root. Ordinary named and optional parameters are supported. Parameterized routes need `hidden` or `sameLevel`. Groups participate only in menus and permissions. |
| `name`, `component` | Names are unique. Pages may reference only IDs in the [registry](config/views.ts). With `keepAlive`, the route name must match the page component name. |
| `alias`, `redirect` | Support absolute leaf-page aliases and internal redirects to configured pages. Direct access through redirects uses the target page's permissions. |
| `alias`, `redirect` | Support absolute leaf-page aliases and internal redirects to configured pages. The menu and guard check permissions at the entry, every intermediate redirect, and the destination. |
| `props` | `true` forwards route params to the page; a JSON object is also supported. |
| `meta.i18nKey`, `meta.noLocalTitle`, `meta.icon`, `meta.extra` | Translation keys take precedence over literal titles. Icons use [IconName](../icons/manifest.ts). Badges can configure text, translation keys, colors, visibility, and icons. |
| `meta.role`, `meta.hidden`, `meta.env`, `meta.sameLevel` | Parent-group and leaf role restrictions both apply. Hidden, environment, and same-level settings affect menus. Same-level mode appends breadcrumbs under the current tab. |

View File

@ -1,4 +1,4 @@
import initialRoutes from '@/mocks/data/routes.json'
import { initialRoutes } from '@ray-template/demo-data'
import { parseRouteConfig, toRuntimeRoutes } from './config/contract'
import { ROUTE_MANAGEMENT_PATH } from './constant'
import type { AppRouteRecordRaw } from './types'

View File

@ -47,11 +47,13 @@ export const routeSourceStatus: {
config?: RouteConfig
} = { requested: preference.source, active: 'static' }
export async function fetchRemoteRouteConfig(): Promise<RouteConfig> {
export async function fetchRemoteRouteConfig(
view?: 'editor',
): Promise<RouteConfig> {
if (!import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()) {
const { parseRouteConfig } = await import('./contract')
return parseRouteConfig(JSON.stringify(await getAdminRoutes()))
return parseRouteConfig(JSON.stringify(await getAdminRoutes(view)))
}
if (!remoteRouteUrl) throw new Error('VITE_ROUTE_CONFIG_URL is missing.')

View File

@ -1,9 +1,13 @@
import { APP_CATCH_KEY, WHITE_ROUTES } from '@/app-config'
import { FORBIDDEN_ROUTE_PATH, NOT_FOUND_PAGE_PATH } from '@/router/constant'
import { APP_CATCH_KEY } from '@/app-config'
import {
FORBIDDEN_ROUTE_PATH,
isSystemRoute,
NOT_FOUND_PAGE_PATH,
} from '@/router/constant'
import { getStorage } from '@/utils/cache'
import type { Router } from 'vue-router'
import { resolveLandingPath } from './resolve-landing-path'
import { validRole } from './valid-role'
import { getRouteAccess } from './route-access'
/**
*
@ -17,16 +21,14 @@ export const permissionRouter = (router: Router) => {
router.beforeEach((to) => {
const token = getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
const isLogin = to.path === '/'
const attempted = to.redirectedFrom ?? to
if (typeof token !== 'string' || !token) {
return isLogin
? true
: { path: '/', query: { redirect: to.fullPath }, replace: true }
: { path: '/', query: { redirect: attempted.fullPath }, replace: true }
}
const isWhiteRoute =
typeof to.name === 'string' && WHITE_ROUTES.includes(to.name)
if (isLogin) {
const target = router.resolve(
resolveLandingPath(router, to.query.redirect),
@ -47,11 +49,16 @@ export const permissionRouter = (router: Router) => {
replace: true,
}
if (!isWhiteRoute && !validRole(to.meta))
// Router 在守卫执行前展开重定向;状态页不能再次校验其已被拦截的来源。
if (
!isSystemRoute(to) &&
(getRouteAccess(router, to) === 'forbidden' ||
(to.redirectedFrom &&
getRouteAccess(router, attempted) === 'forbidden'))
)
return {
path: FORBIDDEN_ROUTE_PATH,
query: { from: to.fullPath },
replace: true,
query: { from: attempted.fullPath },
}
return true

View File

@ -1,7 +1,6 @@
import { WHITE_ROUTES } from '@/app-config'
import { isSystemRoute, WELCOME_ROUTE_PATH } from '@/router/constant'
import { WELCOME_ROUTE_PATH } from '@/router/constant'
import type { Router } from 'vue-router'
import { validRole } from './valid-role'
import { getRouteAccess } from './route-access'
/**
*
@ -24,34 +23,8 @@ export function resolveLandingPath(router: Router, requested?: unknown) {
return WELCOME_ROUTE_PATH
const original = router.resolve(requested)
let current = original
const visited = new Set<string>()
while (!visited.has(current.fullPath)) {
visited.add(current.fullPath)
const record = current.matched.at(-1)
if (!record || current.path === '/' || isSystemRoute(current))
return WELCOME_ROUTE_PATH
if (record.redirect) {
if (typeof record.redirect !== 'string') return WELCOME_ROUTE_PATH
current = router.resolve({
path: record.redirect,
query: current.query,
hash: current.hash,
})
continue
}
const allowed =
(typeof current.name === 'string' &&
WHITE_ROUTES.includes(current.name)) ||
validRole(current.meta)
return allowed ? original.fullPath : WELCOME_ROUTE_PATH
}
return WELCOME_ROUTE_PATH
return getRouteAccess(router, original) === 'allowed'
? original.fullPath
: WELCOME_ROUTE_PATH
}

View File

@ -0,0 +1,54 @@
import { WHITE_ROUTES } from '@/app-config'
import { isSystemRoute } from '@/router/constant'
import type { RouteLocationResolved, Router } from 'vue-router'
import { validRole } from './valid-role'
export type RouteAccessLocation = Pick<
RouteLocationResolved,
'fullPath' | 'hash' | 'matched' | 'name' | 'path' | 'query'
>
/**
*
* @param router 当前已注册业务路由的实例
* @param origin 待访问的入口,包括尚未展开的重定向
* @param currentRole 指定角色;省略时使用当前会话
* @returns 入口和静态重定向链的访问结果;找不到业务目标时返回 unavailable。
*/
export function getRouteAccess(
router: Router,
origin: RouteAccessLocation,
currentRole?: string | number,
): 'allowed' | 'forbidden' | 'unavailable' {
const visited = new Set<string>()
let current = origin
while (!visited.has(current.path)) {
const record = current.matched.at(-1)
if (!record || current.path === '/' || isSystemRoute(current))
return 'unavailable'
const white =
typeof current.name === 'string' && WHITE_ROUTES.includes(current.name)
if (
!white &&
!current.matched.every(({ meta }) => validRole(meta, currentRole))
)
return 'forbidden'
if (!record.redirect) return 'allowed'
if (typeof record.redirect !== 'string') return 'unavailable'
visited.add(current.path)
current = router.resolve({
path: record.redirect,
query: current.query,
hash: current.hash,
})
}
return 'unavailable'
}

View File

@ -4,6 +4,8 @@ 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 type { RouteAccessLocation } from '@/router/utils/route-access'
import { useKeepAliveActions } from '@/store'
import type { MenuState } from '@/store/modules/menu/types'
import type { AnyFn, AppMenuOption, MenuTagOptions } from '@/types'
@ -12,7 +14,7 @@ import { equalRouterPath } from '@/utils/equal-router-path'
import { updateObjectValue } from '@/utils/update-object-value'
import { pick } from 'lodash-es'
import { NEllipsis } from 'naive-ui'
import type { LocationQuery, RouteRecordNormalized } from 'vue-router'
import type { LocationQuery } from 'vue-router'
import { piniaNavigationHistoryStore } from '../navigation-history'
import { piniaSigningStore } from '../signing'
import { pickRouteRecordNormalizedConstant } from './constant'
@ -47,7 +49,8 @@ export const depthSearchAppMenu = (
export const piniaMenuStore = defineStore(
'menu',
() => {
const { push, replace, resolve } = useRouter()
const router = useRouter()
const { push, replace, resolve } = router
const route = useRoute()
const { t } = useI18n()
const { setKeepAliveInclude, retainKeepAliveInclude } =
@ -285,15 +288,14 @@ export const piniaMenuStore = defineStore(
}
}
const optionForRoute = (path: string, matched: RouteRecordNormalized[]) => {
const optionForRoute = (location: RouteAccessLocation) => {
const { fullPath: path, matched } = location
const record = matched.at(-1)
if (
!record ||
record.path === '/' ||
record.redirect ||
isSystemRoute(record) ||
!validRole(record.meta)
getRouteAccess(router, location) !== 'allowed'
)
return
@ -332,6 +334,14 @@ export const piniaMenuStore = defineStore(
if (!validRole(curr.meta, currentRole)) continue
const fullPath = joinRoutePath(parentPath, curr.path)
if (
'redirect' in curr &&
typeof curr.redirect === 'string' &&
getRouteAccess(router, resolve(fullPath), currentRole) !== 'allowed'
)
continue
const children = curr.children?.length
? resolveRoutes(curr.children, fullPath)
: void 0
@ -358,17 +368,7 @@ export const piniaMenuStore = defineStore(
const restoredTags = menuState.menuTagOptions.flatMap(({ fullPath }) => {
if (typeof fullPath !== 'string' || !fullPath.startsWith('/')) return []
const restored = resolve(fullPath)
const record = restored.matched.at(-1)
if (
!record ||
!validRole(restored.meta, currentRole) ||
isSystemRoute(record)
)
return []
const option = optionForRoute(restored.fullPath, restored.matched)
const option = optionForRoute(resolve(fullPath))
return option && !option.meta.sameLevel && !option.meta.windowOpen
? [option]
@ -382,18 +382,13 @@ export const piniaMenuStore = defineStore(
]
cacheTags()
const active = optionForRoute(route.fullPath, route.matched)
const active = optionForRoute(route)
if (active) updateActiveMenu(active)
else {
clearActiveMenu()
if (
route.path !== '/' &&
!isSystemRoute(route) &&
route.matched.length &&
!validRole(route.meta, currentRole)
)
if (getRouteAccess(router, route, currentRole) === 'forbidden')
await replace({
path: FORBIDDEN_ROUTE_PATH,
query: { from: route.fullPath },
@ -455,8 +450,8 @@ export const piniaMenuStore = defineStore(
watch(
() => route.fullPath,
(path) => {
const option = optionForRoute(path, route.matched)
() => {
const option = optionForRoute(route)
if (option) updateActiveMenu(option)
else clearActiveMenu()

View File

@ -1,3 +1,4 @@
import { apiMockEnabled } from '@/api/admin/client'
import { APP_CATCH_KEY } from '@/app-config'
import { RForm, useForm } from '@/components'
import { useI18n } from '@/hooks'
@ -61,6 +62,8 @@ export default defineComponent({
return () => (
<RForm
{...{ method: 'post' }}
autocomplete="on"
model={signingForm}
onRegister={register}
rules={rules.value}
@ -71,8 +74,12 @@ export default defineComponent({
v-model:value={signingForm.name}
inputProps={{
id: nameId,
name: 'ray-demo-user',
autocomplete: 'off',
name: 'username',
autocomplete: 'username',
autocapitalize: 'off',
autocorrect: 'off',
spellcheck: false,
required: true,
enterkeyhint: 'next',
}}
placeholder={t('NamePlaceholder')}
@ -87,8 +94,9 @@ export default defineComponent({
v-model:value={signingForm.pwd}
inputProps={{
id: passwordId,
name: 'ray-demo-password',
autocomplete: 'off',
name: 'password',
autocomplete: 'current-password',
required: true,
enterkeyhint: 'go',
}}
type="password"
@ -105,34 +113,38 @@ export default defineComponent({
>
{t('Login')}
</NButton>
<NButton
block
secondary
attrType="button"
disabled={loading.value}
onClick={() => {
signingForm.name = 'Ray Admin'
signingForm.pwd = '123456'
void handleLogin()
}}
>
{t('UseDemo')}
</NButton>
<NFlex>
{(['manager', 'member'] as const).map((role) => (
{apiMockEnabled && (
<>
<NButton
block
secondary
attrType="button"
disabled={loading.value}
onClick={() => {
signingForm.name = role
signingForm.name = 'Ray Admin'
signingForm.pwd = '123456'
void handleLogin()
}}
>
{t(role === 'manager' ? 'UseManager' : 'UseMember')}
{t('UseDemo')}
</NButton>
))}
</NFlex>
<NFlex>
{(['manager', 'member'] as const).map((role) => (
<NButton
secondary
disabled={loading.value}
onClick={() => {
signingForm.name = role
signingForm.pwd = '123456'
void handleLogin()
}}
>
{t(role === 'manager' ? 'UseManager' : 'UseMember')}
</NButton>
))}
</NFlex>
</>
)}
</NFlex>
</RForm>
)

View File

@ -1,4 +1,5 @@
import './index.scss'
import { apiMockEnabled } from '@/api/admin/client'
import AppShareLink from '@/app-components/app/AppShareLink'
import { LOCAL_OPTIONS } from '@/app-config'
import { RIcon } from '@/components'
@ -64,23 +65,33 @@ export default defineComponent({
<div class="login__panel-heading">
<p class="login__eyebrow">{copy('Access')}</p>
<h2 id="login-panel-heading">{copy('Welcome')}</h2>
<p>{copy('AccessDescription')}</p>
</div>
<NTabs v-model:value={this.tabsValue} type="line" size="medium">
<NTabPane tab={copy('Signing')} name="signing">
<Signing />
</NTabPane>
<NTabPane tab={copy('Register')} name="register">
<Register />
</NTabPane>
<NTabPane tab={copy('QRCodeSigning')} name="qrcodeSigning">
<QRCodeSigning />
</NTabPane>
</NTabs>
<div class="login__secondary">
<span>{copy('OtherSignInOptions')}</span>
<SSOSigning />
<p>
{copy(
apiMockEnabled ? 'AccessDescription' : 'AccountDescription',
)}
</p>
</div>
{apiMockEnabled ? (
<>
<NTabs v-model:value={this.tabsValue} type="line" size="medium">
<NTabPane tab={copy('Signing')} name="signing">
<Signing />
</NTabPane>
<NTabPane tab={copy('Register')} name="register">
<Register />
</NTabPane>
<NTabPane tab={copy('QRCodeSigning')} name="qrcodeSigning">
<QRCodeSigning />
</NTabPane>
</NTabs>
<div class="login__secondary">
<span>{copy('OtherSignInOptions')}</span>
<SSOSigning />
</div>
</>
) : (
<Signing />
)}
</section>
</div>

View File

@ -1,6 +1,6 @@
import './index.scss'
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { useI18n } from '@/hooks'
import { useAccess, useI18n } from '@/hooks'
import { getStaticAppRoutes } from '@/router/app-route-modules'
import { exportRouteConfig, parseRouteConfig } from '@/router/config/contract'
import type { RouteConfig } from '@/router/config/schema'
@ -32,6 +32,7 @@ export default defineComponent({
name: 'RouteManagement',
setup() {
const { t } = useI18n('routeManagement')
const { hasPermission } = useAccess()
const source = ref<RouteSource>(routeSourceStatus.requested)
const draft = ref('')
const checked = shallowRef<RouteConfig>()
@ -66,9 +67,6 @@ export default defineComponent({
}
}
if (routeSourceStatus.config) setDraft(routeSourceStatus.config)
else loadStatic()
const validate = () => {
try {
const config = parseRouteConfig(draft.value)
@ -132,13 +130,22 @@ export default defineComponent({
busy.value = true
try {
setDraft(await fetchRemoteRouteConfig())
setDraft(
await fetchRemoteRouteConfig(
hasPermission('routes:write') ? 'editor' : void 0,
),
)
} catch (reason) {
report(reason)
} finally {
busy.value = false
}
}
if (routeSourceStatus.active === 'remote') void loadRemote()
else if (routeSourceStatus.config) setDraft(routeSourceStatus.config)
else loadStatic()
const apply = async () => {
if (busy.value) return

View File

@ -48,6 +48,8 @@ export default defineComponent({
const { t } = useI18n('routeManagement')
const { hasPermission } = useAccess()
const saving = ref(false)
const loading = ref(false)
const loaded = ref(false)
const text = (key: string) => t<string>(key)
const { t: translate } = useI18n()
const records = ref<RouteConfigRecord[]>([])
@ -104,10 +106,14 @@ export default defineComponent({
valid.value = false
}
const load = async () => {
loading.value = true
try {
const config =
routeSourceStatus.active === 'remote'
? await fetchRemoteRouteConfig()
? await fetchRemoteRouteConfig(
hasPermission('routes:write') ? 'editor' : void 0,
)
: (routeSourceStatus.config ??
exportRouteConfig(getStaticAppRoutes()))
@ -115,8 +121,11 @@ export default defineComponent({
selected.value = tree.value.options[0]?.key as number | undefined
expanded.value = []
clearResult()
loaded.value = true
} catch (reason) {
report(reason)
} finally {
loading.value = false
}
}
@ -138,7 +147,13 @@ export default defineComponent({
}
}
const apply = async () => {
if (saving.value || !hasPermission('routes:write')) return
if (
!loaded.value ||
loading.value ||
saving.value ||
!hasPermission('routes:write')
)
return
const config = validate()
@ -352,7 +367,9 @@ export default defineComponent({
type="primary"
onClick={apply}
loading={saving.value}
disabled={!hasPermission('routes:write')}
disabled={
!loaded.value || loading.value || !hasPermission('routes:write')
}
>
{text('apply')}
</NButton>

View File

@ -10,6 +10,7 @@ const guide = [
text: '入门',
items: [
entry('快速开始', '/guide/start'),
entry('发行版本与快速启动', '/guide/distributions'),
entry('v6 Monorepo 架构', '/guide/architecture'),
entry('v5 与 v6 的版本分界', '/migration'),
entry('第一个业务页面', '/guide/first-page'),

View File

@ -7,26 +7,36 @@ ray-template/
├── apps/
│ ├── admin/ # Ray Admin:登录、会话、路由和业务页面
│ └── docs/ # VitePress:指南、API 与交互示例
├── packages/ # 两个应用共用的八个私有 workspace 包
├── packages/ # 十个私有 workspace 包,按运行时边界复用
├── harness/ # 任务入口与验收命令
└── pnpm-lock.yaml # 工作区共用锁文件
```
## 各包负责什么
| 包 | 公开能力与使用方式 |
| --------------------------- | -------------------------------------------------------------------------------------------- |
| `@ray-template/utils` | 精度运算、对象和类型处理、文件工具、接收存储实现的 JSON 工具。精度运算从 `/precision` 导入。 |
| `@ray-template/composables` | 设备宽度、元素全屏、截图、打印和其他独立 Vue Hooks,例如 `/useElementFullscreen`。 |
| `@ray-template/directives` | 复制、防抖、节流、省略、水波纹等指令,可单独导入或统一注册。 |
| `@ray-template/icons` | SVG 资源、图标名称类型和资源查找。组件和路由配置使用同一套名称。 |
| `@ray-template/ui` | 组件、样式、主题与类型。通过 `/table-pro`、`/barcode` 或 `/chart` 等入口按需导入。 |
| `@ray-template/http` | `createHttpClient` 创建实例与独立的取消器。宿主提供地址、请求头和拦截器。 |
| `@ray-template/routing` | 路由 Schema、配置校验、路由展开和菜单处理。宿主提供页面注册表。 |
| `@ray-template/admin-shell` | 布局、顶部导航、标签、设置和路由过渡。宿主提供菜单、选中状态、偏好和内容。 |
| 包 | 公开能力与使用方式 |
| ----------------------------- | -------------------------------------------------------------------------------------------- |
| `@ray-template/utils` | 精度运算、对象和类型处理、文件工具、接收存储实现的 JSON 工具。精度运算从 `/precision` 导入。 |
| `@ray-template/composables` | 设备宽度、元素全屏、截图、打印和其他独立 Vue Hooks,例如 `/useElementFullscreen`。 |
| `@ray-template/directives` | 复制、防抖、节流、省略、水波纹等指令,可单独导入或统一注册。 |
| `@ray-template/icons` | SVG 资源、图标名称类型和资源查找。组件和路由配置使用同一套名称。 |
| `@ray-template/ui` | 组件、样式、主题与类型。通过 `/table-pro`、`/barcode` 或 `/chart` 等入口按需导入。 |
| `@ray-template/http` | `createHttpClient` 创建实例与独立的取消器。宿主提供地址、请求头和拦截器。 |
| `@ray-template/api-contracts` | 通用请求与响应、Valibot 校验、路由 Schema 和 OpenAPI;不依赖浏览器或服务端框架。 |
| `@ray-template/demo-data` | Mock 与后端演示共用的数据、查询辅助和初始路由,调用方决定是否启用。 |
| `@ray-template/routing` | 路由 Schema 兼容入口、浏览器路由展开和菜单处理。宿主提供页面注册表。 |
| `@ray-template/admin-shell` | 布局、顶部导航、标签、设置和路由过渡。宿主提供菜单、选中状态、偏好和内容。 |
共享包通过 `package.json` 的 `exports` 暴露入口,只依赖自己声明的包。`pnpm packages:check` 检查跨包导入和依赖循环。应用的登录、路由守卫、业务 API、Pinia 实例和语言加载由 `apps/admin` 负责。
应用不能作为其他工作区的依赖;包通过 `rayTemplate.runtime` 标明 `browser`、`server` 或 `universal`。通用包只依赖通用包,浏览器与服务端通过 HTTP 和共享契约交互。路由 Schema 的权威来源是 `packages/api-contracts/src/routes.ts`,旧 routing 入口保留转导出。源码发行方式见[发行版本与快速启动](./distributions)。
<!-- fullstack:start -->
可选的 `apps/server` 独立构建和运行,内部业务模块使用 NestJS、PostgreSQL 和 Redis。前端不会导入其控制器、数据库模型或配置。纯前端导出会移除整个服务端工作区及专属依赖。
<!-- fullstack:end -->
## Ray Admin 怎么组装
`apps/admin/src/main.ts` 安装 Pinia、国际化、路由和指令。应用入口为组件提供主题、翻译、图标和列偏好存储,路由层把注册的页面交给后台外壳。登录、角色和会话由应用处理,真实业务的服务端负责接口授权。

View File

@ -1,6 +1,6 @@
# 服务端接入与标准契约
登录、会话、用户管理与路由管理使用同一套 HTTP API。开发环境与静态在线演示都由 MSW 在网络层模拟响应;页面和 Store 不直接读取 Mock 数据库。接入自有服务端时,保留页面与调用方法,替换接口地址和实现即可。
登录、会话、用户管理与路由管理使用同一套 HTTP API。源码发行和启动方式见[发行版本与快速启动](./distributions)。开发环境与静态在线演示都由 MSW 在网络层模拟响应;页面和 Store 不直接读取 Mock 数据库。接入自有服务端时,保留页面与调用方法,替换接口地址和实现即可。
<script setup>
import { withBase } from 'vitepress'
@ -8,7 +8,7 @@ import { withBase } from 'vitepress'
<a :href="withBase('/contracts/admin-api.json')" target="_blank" rel="noreferrer">下载 OpenAPI 3.1 契约</a>
契约从 workspace 包 `@ray-template/api-contracts` 和路由 Schema 生成,含请求体、响应、查询参数、Bearer 认证与权限码。登录与用户契约通过 `/admin` 子路径导入,演示接口通过 `/demo` 导入,`/openapi` 导出 OpenAPI 生成函数。包不读取浏览器状态,前端、Mock 和自有服务端可共享类型与运行时校验;包当前随仓库使用,尚未发布到 npm。应用原有 `api/admin/contracts.ts`、`api/demo/contracts.ts` 路径仍为兼容入口。修改后运行 `pnpm api:generate`;全量验证中的 `pnpm api:check` 检查文件与运行时 Schema 一致。
契约从 workspace 包 `@ray-template/api-contracts` 和路由 Schema 生成,含请求体、响应、查询参数、Bearer 认证与权限码。登录与用户契约通过 `/admin` 子路径导入,演示接口通过 `/demo` 导入,路由 Schema 通过 `/routes` 导入,`/openapi` 导出 OpenAPI 生成函数。路由 Schema 的权威来源是 `packages/api-contracts/src/routes.ts`,routing 包中的旧入口保留转导出。包不读取浏览器状态,前端、Mock 和自有服务端可共享类型与运行时校验;包当前随仓库使用,尚未发布到 npm。应用原有 `api/admin/contracts.ts`、`api/demo/contracts.ts` 路径仍为兼容入口。修改后运行 `pnpm api:generate`;全量验证中的 `pnpm api:check` 检查文件与运行时 Schema 一致。
```ts
import type { ApiResponse, UserInput } from '@ray-template/api-contracts/admin'
@ -32,6 +32,26 @@ VITE_API_BASE_URL=https://your-api.example.com/api/
Mock 在应用启动前完成 Service Worker 注册。每次 API 请求前检查内部健康标记;浏览器回收 worker 后,在同一个 MSW 客户端实例上调用 `stop()` / `start()` 恢复,避免旧实例残留的监听器将请求放行。恢复失败则阻止业务请求继续发送,表单和演示数据保持原样。内部 `GET /admin/mock-health` 仅由 Mock 使用,关闭 Mock 后不请求这个接口。默认脚本路径为 `/ray-template/mockServiceWorker.js`,作用域为应用 base;静态服务器必须按原路径提供该文件。浏览器需要 HTTPS 或 localhost。GitHub Pages 只托管静态文件,这些 API 由已启动的页面中的 Mock 响应;直接在地址栏打开 API 地址会返回 404。真实后端模式不启动 Mock,也不会在请求失败时返回伪造业务数据。当前锁定 MSW 2.11.6,安装不自动执行其 worker 复制脚本;升级时显式运行 `pnpm exec msw init apps/admin/public --save`,再做契约和浏览器验证。
<!-- fullstack:start -->
## 配套 NestJS 服务端
完整源码中的 `apps/server` 实现相同的 `/api/admin/*` 协议,页面层继续使用现有 API 调用。默认开发入口为 `pnpm fullstack:setup`、`pnpm dev:full`;已有 PostgreSQL 和 Redis 时使用 `pnpm fullstack:setup --external`。管理员凭据保存在私有的 `apps/server/.env.local`,不使用 Mock 演示密码,详细步骤见[全栈发行包](./distributions#全栈发行包)。
用户、部门、角色授权、会话、路由配置和操作审计持久化到 PostgreSQL。账号与邮箱通过规范化唯一字段避免大小写冲突;批量写入、账号保护与审计在事务内执行。初始化只补齐初始数据,重复运行保留已有配置、路由与账号。
认证保持 Bearer 协议,服务端用随机令牌建立可撤销会话,只保存令牌摘要;密码使用带随机盐的 scrypt 派生。每次请求重新校验用户状态、会话有效期和权限。退出、账号停用、角色变更或显式重设凭据会影响相应会话,前端权限显示不能替代接口授权。
用户资料创建接口不接收密码,新建账号需由安全环境提供 `CREDENTIAL_USERNAME`、`CREDENTIAL_PASSWORD` 后执行 `pnpm server:credential:set`,才能登录。密码长度为 12–128 字符,修改凭据同时撤销已有会话。
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,公开运行配置移除演示视图及指向它们的重定向。已保存的路由保持完整,管理员可继续编辑。若显式选择本地或静态路由来源,这些浏览器草稿由使用者管理,服务端仍禁用演示接口。
<!-- fullstack:end -->
## 统一响应
成功使用 HTTP 200 和以下包络:
@ -57,7 +77,7 @@ Mock 在应用启动前完成 Service Worker 注册。每次 API 请求前检查
}
```
400 表示输入不合法,401 表示会话失效,403 表示权限不足,404 表示对象不存在,409 表示账号/邮箱冲突或当前账号保护,503 表示演示数据库写入失败。`error.key` 是稳定的业务错误标识;可选的 `error.fields` 为字段到错误键的映射。API 层把错误转换为 `AdminApiError`,用户页将已约定的错误键翻译为中英文提示。读取响应也会经过 Schema 校验。
400 表示输入不合法,401 表示会话失效,403 表示权限不足,404 表示对象不存在,409 表示账号/邮箱冲突或当前账号保护,413 表示请求体过大,429 表示请求受到限流,503 表示存储或依赖暂时不可用(Mock 中包括演示数据库写入失败)。`error.key` 是稳定的业务错误标识;可选的 `error.fields` 为字段到错误键的映射。API 层把错误转换为 `AdminApiError`,用户页将已约定的错误键翻译为中英文提示。读取响应也会经过 Schema 校验。
## 登录、会话与权限
@ -126,9 +146,9 @@ hasPermission(['users:update', 'users:delete'], 'any')
## 路由管理
`GET /admin/route-config` 是公开的前端启动配置接口,返回 `data: { version: 1, routes: [...] }`;路由元数据不包含业务秘密。`PUT /admin/route-config` 以同一结构提交,需要 `routes:write`。若自有系统需要受保护的菜单读取,可在 API 适配层把读取移到登录后,并保留登录与错误页的启动路由。
`GET /admin/route-config` 是公开的前端启动配置接口,返回 `data: { version: 1, routes: [...] }`;路由元数据不包含业务秘密。维护路由时,携带 `routes:write` 权限的会话请求 `GET /admin/route-config?view=editor` 读取完整配置,再以同一结构提交 `PUT /admin/route-config`。若自有系统需要受保护的菜单读取,可在 API 适配层把读取移到登录后,并保留登录与错误页的启动路由。
现有菜单表已迁到 `apps/admin/src/mocks/data/routes.json`,作为 Mock 初始数据库和显式离线恢复来源。正常在线启动走 GET,路由可视化与 JSON 的接口模式保存走 PUT,成功后重新加载并从接口读回。真实后端模式下,远端读取失败会中止启动,不会自动展示内置业务菜单;用户显式选定的本地或静态来源仍可用于离线恢复。导入、导出与接口中的路由内容使用同一结构,详情见[路由契约](./routing)。
现有菜单表已迁到 `packages/demo-data/src/routes.json`,作为 Mock 初始数据库和显式离线恢复来源。正常在线启动走 GET,路由可视化与 JSON 的接口模式保存走 PUT,成功后重新加载并从接口读回。真实后端模式下,远端读取失败会中止启动,不会自动展示内置业务菜单;用户显式选定的本地或静态来源仍可用于离线恢复。导入、导出与接口中的路由内容使用同一结构,详情见[路由契约](./routing)。
前端 `router/config/views.ts` 保留组件 ID 白名单,接口只返回 ID;后端或 AI 不需要传递组件代码。登录、404 和受保护的路由管理入口由外壳保留。原 `VITE_ROUTE_CONFIG_URL` 仍兼容旧的原始 JSON 读取接口;完整读写接入使用上面的标准 API 基址。

View File

@ -0,0 +1,111 @@
# 发行版本与快速启动
同一套前端通过源码导出提供独立使用方式。Admin、文档和公共包之间保留明确依赖边界,Mock 与自有后端遵循同一套 API 契约。源码归档包含可编辑的工程文件,需要安装依赖并构建后运行。
## 纯前端发行包
在仓库根目录执行:
```sh
pnpm dist:frontend
```
输出目录为 `dist/distributions/`,包含 `ray-template-frontend-<version>/` 和同名 `.tar.gz`。解压后进入源码目录,使用仓库指定的 Node.js 26.13.0 与 pnpm 12.16.1:
```sh
pnpm install --frozen-lockfile
pnpm dev
```
默认打开 `/ray-template/`,通过 MSW 体验登录、用户管理、路由和其他示例。纯前端包保留 Admin、文档、10 个共享包及必要工具;不包含后端工作区、数据库驱动、Redis 客户端、服务端启动脚本或数据库配置。前端开发、构建和文档使用不需要 Docker。
接入自己的服务时配置 `VITE_API_BASE_URL`、`VITE_API_MOCK=false`,具体协议见[服务端接入](./backend)。这些前端变量会进入浏览器产物,只能放公开配置。
## 发行物追溯
归档内的 `distribution.json` 记录:
- 发行类型和版本。
- 来源 Git 提交及是否含未提交改动;没有 Git 信息时保留已知的来源信息。
- 实际包含的 workspace 清单和源码文件数量。
- 导出内容的 SHA-256 摘要。
导出会按依赖图保留所需工作区、裁剪锁文件、移除不可用命令与专属说明,并排除 `.git`、`node_modules`、本地环境配置、凭据、构建结果和临时验证资料。`pnpm dist:check` 检查导出计划和依赖完整性;干净环境中的安装、构建、运行需要另行验证。
导出命令只生成本地源码目录和归档。
<!-- fullstack:start -->
## 全栈发行包
在完整仓库运行:
```sh
pnpm dist:fullstack
```
同一目录会生成 `ray-template-fullstack-<version>/` 与同名 `.tar.gz`。它包含相同的前端源码以及 `apps/server`、数据库迁移、Redis 配置和启动工具。后端采用 NestJS 12.3.3、Prisma 7.10.1、PostgreSQL 18,Redis 客户端为 6.3.1;Compose 配置使用 Redis 8.2.11。具体锁定版本以发行包清单和锁文件为准。
### 本地开发
安装依赖并准备 Docker Compose,然后运行:
```sh
pnpm fullstack:setup
pnpm dev:full
```
`setup` 首次创建 `apps/server/.env.local`,生成数据库、Redis 和管理员随机密码,启动 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 服务并保留数据卷。
### 使用已有数据库与 Redis
将 `DATABASE_URL` 和 `REDIS_URL` 放入当前进程的安全环境中,然后执行:
```sh
pnpm fullstack:setup --external
pnpm dev:full
```
`--external` 跳过 Docker 服务启动,仍执行迁移和初始化。已有 `apps/server/.env.local` 时保留该文件,进程环境优先。应使用为本项目准备的数据库;迁移和初始化会创建或更新本项目的数据结构。停止外部数据服务由其部署环境负责。
### 创建真实登录账号
用户管理页创建的是用户资料,默认没有登录凭据。通过安全环境提供 `CREDENTIAL_USERNAME` 与 `CREDENTIAL_PASSWORD`,再执行 `pnpm server:credential:set`。密码要求 12–128 个字符;该命令设置凭据并撤销该账号已有会话。避免将密码直接写入 shell 历史。
重复执行 `setup` 不会重置管理员密码。需要更换密码时,同样使用显式的凭据命令。服务端存储密码派生值和会话令牌摘要,认证继续使用已有 Bearer 契约。
### 服务与运行检查
| 命令或接口 | 用途 |
| ------------------------------ | ------------------------------------------------------------------- |
| `pnpm server:build` | 生成 Prisma Client 并构建独立服务端产物 |
| `pnpm server:start` | 从服务端构建产物启动 |
| `pnpm server:check` | 服务端类型、单元/平台测试和构建 |
| `pnpm server:test:integration` | 使用 `TEST_DATABASE_URL`、`TEST_REDIS_URL` 验证真实存储与 HTTP 行为 |
| `GET /api/health/live` | 进程存活检查 |
| `GET /api/health/ready` | PostgreSQL 与 Redis 就绪检查 |
全栈包含配置校验、接口授权、会话撤销、Redis 限流、安全响应头、CORS、请求 ID、脱敏日志和操作审计。Redis 不可用时管理接口返回 503,不切换到每进程的临时认证或限流数据。缓存只用于可重建的演示读取结果,权限和会话每次从数据库核验。
生产模式默认关闭演示接口,并从后端提供的运行菜单中移除演示页面。路由编辑器仍可维护完整配置。真实后端请求失败不会回退到 Mock。
### 容器启动
执行 `pnpm fullstack:setup` 后,可以使用 Compose 的 `app` profile 启动静态前端、NestJS 和数据服务:
```sh
docker compose -p ray-template --env-file apps/server/.env.local \
-f deploy/compose.yaml --profile app up --build -d --wait
```
默认打开 `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` 中正确编码。
`node deploy/smoke.mjs` 使用临时 Compose 项目检查迁移、前端构建、登录、CORS、演示开关和代理限流,并清理测试容器与数据卷。对外部署仍需要为目标环境验证 HTTPS、实际代理链、持久化存储和备份。
### 生成分支与 Release 资产
维护者在 GitHub Actions 从 `main` 手动运行 **Source distributions**。默认只验证并上传本次运行的归档。要更新生成的 `frontend` 分支,选择 `sync_frontend`;该分支从主线导出,不用于独立开发。要给已有 Release 附加两个源码包及 SHA-256 校验文件,另行填写 `release_tag`。工作流检查标签版本及提交、验证归档,并保留已上传的同名资产。
<!-- fullstack:end -->

View File

@ -40,7 +40,7 @@ export default defineComponent({
orders: { load: () => import('@/views/orders'), name: 'Orders' },
```
在 Mock 初始路由 JSON `apps/admin/src/mocks/data/routes.json` 中加入以下记录,或由自己的路由接口返回:
在 Mock 初始路由 JSON `packages/demo-data/src/routes.json` 中加入以下记录,或由自己的路由接口返回:
```json
{

View File

@ -4,7 +4,7 @@
import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
</script>
正常启动从 `GET /admin/route-config` 读取版本化路由 JSON,按 `meta.order` 排序;路由树用于菜单与面包屑,页面记录展开后注册到 Vue Router。Mock 的初始路由表位于 `apps/admin/src/mocks/data/routes.json`,前端只保留组件 ID 注册表和外壳必需路由。默认使用 hash 路由,例如 `/ray-template/#/orders`。
正常启动从 `GET /admin/route-config` 读取版本化路由 JSON,按 `meta.order` 排序;路由树用于菜单与面包屑,页面记录展开后注册到 Vue Router。Mock 的初始路由表位于 `packages/demo-data/src/routes.json`,前端只保留组件 ID 注册表和外壳必需路由。默认使用 hash 路由,例如 `/ray-template/#/orders`。
## 路由配置交互校验
@ -36,11 +36,11 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
| `ignoreAutoResetScroll` | 允许页面保留内容区滚动位置,详见滚动工具实现。 |
| `extra` | 菜单标记的文本、图标、类型和显隐,见 [useBadge](../reference/hooks/navigation#usebadge)。 |
嵌套子路由使用相对路径时会继承父路径。内置示例按用途分组,并以绝对路径保留原有页面地址。查看 [布局与路由示例](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/mocks/data/routes.json) 里的分组及多级菜单。
嵌套子路由使用相对路径时会继承父路径。内置示例按用途分组,并以绝对路径保留原有页面地址。查看 [布局与路由示例](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/demo-data/src/routes.json) 里的分组及多级菜单。
## 登录和角色
默认登录页为 `/`。无会话访问业务地址时,守卫将完整地址放入登录页的 `redirect` 参数;登录后仅恢复当前角色仍有权限的已注册业务地址,保留 query 和 hash。没有有效目标时进入 `/welcome`,不会自动选择仪表盘或第一个菜单。菜单隐藏的页面仍可能允许直达。接入真实业务时,在后端校验会话、权限和资源归属。
默认登录页为 `/`。无会话访问业务地址时,守卫将完整地址放入登录页的 `redirect` 参数;登录后仅恢复当前角色仍有权限的已注册业务地址,保留 query 和 hash。没有有效目标时进入 `/welcome`,不会自动选择仪表盘或第一个菜单。对重定向路由,菜单和守卫都会检查入口、各级跳转和最终目标的权限。菜单隐藏的页面仍可能允许直达。接入真实业务时,在后端校验会话、权限和资源归属。
## 空工作区和状态页
@ -48,7 +48,7 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
所有业务标签都可以关闭,包括原首页和最后一项。关闭当前标签后切换到相邻项;关闭最后一项或全部标签进入空工作区,同时释放对应 KeepAlive 缓存。一个具体 pathname 保留一个标签,查询参数或片段变化会更新标签保存的完整地址。角色变化后,失去权限的标签与缓存会被移除,不会自动激活其他业务页。
- `/403`:已登录,但当前页面无权限。
- `/403`:已登录,但当前页面无权限。页签栏的「关闭当前页面」会返回仍有权限的上一页或已打开页签,没有可恢复的页面时回到工作区。
- `/404`:目标页面不存在;原始目标保留在 `query.from`。
- `/500`:路由解析或页面懒加载失败;只对仍存在且允许访问的 `query.from` 显示重试。

View File

@ -2,6 +2,8 @@
本文使用 Ray Template v6。v5 项目请先查看[版本分界](../migration)。
可以选择独立的纯前端源码发行包;完整源码还提供可选的后端接入流程,见[发行版本与快速启动](./distributions)。
## 启动工作台
准备 Node.js 26.13.0 和 pnpm 12.16.1。以下以 nvm 为例:

View File

@ -26,5 +26,8 @@
"sass": "1.107.1",
"vite": "6.4.5",
"vitepress": "1.6.4"
},
"rayTemplate": {
"runtime": "browser"
}
}

View File

@ -3036,8 +3036,13 @@
"get": {
"operationId": "getRouteConfig",
"summary": "getRouteConfig",
"description": "Session or public bootstrap endpoint.",
"security": [],
"description": "Public navigation snapshot. Request view=editor with routes:write to read the complete saved configuration, including disabled demo routes.",
"security": [
{},
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Success",
@ -3125,7 +3130,17 @@
}
}
}
}
},
"parameters": [
{
"name": "view",
"in": "query",
"required": false,
"schema": {
"const": "editor"
}
}
]
},
"put": {
"operationId": "updateRouteConfig",

View File

@ -68,7 +68,7 @@ import AdminExample from '../examples/AdminExample.vue'
<<< ../../admin/src/api/demo/data.ts
<<< ../../admin/src/mocks/data/orders.ts
<<< ../../../packages/demo-data/src/orders.ts
:::
## 自适应高度与虚拟滚动

4
apps/server/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/dist/
/dist-test/
/src/generated/
/.env.local

52
apps/server/README.md Normal file
View File

@ -0,0 +1,52 @@
# Ray Template server
An optional NestJS application implementing the shared admin HTTP contract. It owns PostgreSQL persistence and API authorization. Browser applications consume the contract package, not this application or Prisma models.
## Runtime and configuration
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.
```sh
pnpm --filter @ray-template/server db:migrate
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.
## 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 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.
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.
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.
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:
```sh
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.
## Build and checks
```sh
pnpm --filter @ray-template/server check
pnpm --filter @ray-template/server test:integration
```
`check` generates the Prisma client, type-checks, runs unit/platform tests, and bundles production entry points. The bundler includes workspace TypeScript source; npm runtime dependencies remain external. Production runs `dist/main.mjs` with this application's installed dependencies.
Integration tests require `TEST_DATABASE_URL` and `TEST_REDIS_URL` pointing to disposable services. They create an isolated random PostgreSQL schema, apply the checked-in migration SQL, exercise HTTP requests against Nest, and drop only that schema afterward. Redis counters use a unique test prefix and expire. Tests never reset the configured database. They cover authorization, uniqueness, transaction atomicity, credential/session invalidation, route validation, restart persistence and repeatable initialization. The unit command does not claim that PostgreSQL integration passed.
Database migrations are explicit deployment operations; starting the HTTP server does not migrate or reseed data. Deployments must provide TLS at the proxy, database backups, bounded log retention and reviewed trusted proxy settings. Readiness depends on both PostgreSQL and Redis; rate-limit failures deny protected API traffic rather than bypassing throttling.

52
apps/server/package.json Normal file
View File

@ -0,0 +1,52 @@
{
"name": "@ray-template/server",
"version": "6.0.1",
"private": true,
"type": "module",
"scripts": {
"dev": "node --env-file-if-exists=.env.local scripts/build.mjs --watch",
"build": "pnpm db:generate && node scripts/build.mjs",
"start": "node --env-file-if-exists=.env.local dist/main.mjs",
"typecheck": "pnpm db:generate && tsc --noEmit",
"test": "pnpm db:generate && node scripts/build.mjs --tests && node --test dist-test/unit.test.mjs dist-test/platform.test.mjs",
"test:integration": "pnpm db:generate && node scripts/build.mjs --tests && node --test dist-test/integration.test.mjs",
"check": "pnpm typecheck && pnpm test && pnpm build",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate deploy",
"db:seed": "pnpm build && node --env-file-if-exists=.env.local dist/cli.mjs seed",
"credential:set": "pnpm build && node --env-file-if-exists=.env.local dist/cli.mjs password"
},
"dependencies": {
"@faker-js/faker": "10.6.0",
"@nestjs/common": "12.3.3",
"@nestjs/core": "12.3.3",
"@nestjs/platform-express": "12.3.3",
"@prisma/adapter-pg": "7.10.1",
"@prisma/client": "7.10.1",
"@ray-template/api-contracts": "workspace:*",
"@ray-template/demo-data": "workspace:*",
"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"
},
"devDependencies": {
"@types/express": "5.0.6",
"@types/node": "26.6.6",
"@types/pg": "8.23.1",
"esbuild": "0.28.2",
"prisma": "7.10.1",
"typescript": "6.0.3"
},
"rayTemplate": {
"runtime": "server"
},
"files": [
"dist",
"prisma",
"prisma.config.ts",
"README.md"
]
}

View File

@ -0,0 +1,15 @@
import { existsSync } from 'node:fs'
import { loadEnvFile } from 'node:process'
import { defineConfig } from 'prisma/config'
const envFile = new URL('.env.local', import.meta.url)
if (existsSync(envFile)) loadEnvFile(envFile)
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
datasource: {
url: process.env.DATABASE_URL ?? 'postgresql://127.0.0.1/ray_template',
},
})

View File

@ -0,0 +1,68 @@
CREATE TABLE "Department" (
"id" TEXT PRIMARY KEY,
"parentId" TEXT REFERENCES "Department"("id") ON DELETE RESTRICT,
"name" TEXT NOT NULL,
"labelKey" TEXT
);
CREATE INDEX "Department_parentId_idx" ON "Department"("parentId");
CREATE TABLE "Role" (
"value" TEXT PRIMARY KEY,
"label" TEXT NOT NULL,
"labelKey" TEXT
);
CREATE TABLE "Permission" ("code" TEXT PRIMARY KEY);
CREATE TABLE "RolePermission" (
"roleValue" TEXT NOT NULL REFERENCES "Role"("value") ON DELETE CASCADE,
"permissionCode" TEXT NOT NULL REFERENCES "Permission"("code") ON DELETE CASCADE,
PRIMARY KEY ("roleValue", "permissionCode")
);
CREATE TABLE "User" (
"id" TEXT PRIMARY KEY,
"username" TEXT NOT NULL,
"usernameKey" TEXT NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"emailKey" TEXT NOT NULL,
"phone" TEXT NOT NULL DEFAULT '',
"departmentId" TEXT NOT NULL REFERENCES "Department"("id") ON DELETE RESTRICT,
"role" TEXT NOT NULL REFERENCES "Role"("value") ON DELETE RESTRICT,
"status" TEXT NOT NULL DEFAULT 'enabled',
"remark" TEXT NOT NULL DEFAULT '',
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "User_status_check" CHECK ("status" IN ('enabled', 'disabled')),
CONSTRAINT "User_usernameKey_check" CHECK ("usernameKey" = lower("username")),
CONSTRAINT "User_emailKey_check" CHECK ("emailKey" = lower("email"))
);
CREATE UNIQUE INDEX "User_usernameKey_key" ON "User"("usernameKey");
CREATE UNIQUE INDEX "User_emailKey_key" ON "User"("emailKey");
CREATE INDEX "User_departmentId_idx" ON "User"("departmentId");
CREATE INDEX "User_role_status_idx" ON "User"("role", "status");
CREATE TABLE "Credential" (
"userId" TEXT PRIMARY KEY REFERENCES "User"("id") ON DELETE CASCADE,
"passwordHash" TEXT NOT NULL,
"updatedAt" TIMESTAMPTZ(3) NOT NULL
);
CREATE TABLE "Session" (
"tokenHash" TEXT PRIMARY KEY,
"userId" TEXT NOT NULL REFERENCES "User"("id") ON DELETE CASCADE,
"expiresAt" TIMESTAMPTZ(3) NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
CREATE INDEX "Session_expiresAt_idx" ON "Session"("expiresAt");
CREATE TABLE "RouteConfig" (
"id" TEXT PRIMARY KEY,
"config" JSONB NOT NULL,
"updatedAt" TIMESTAMPTZ(3) NOT NULL
);
CREATE TABLE "AuditLog" (
"id" TEXT PRIMARY KEY,
"actorId" TEXT,
"action" TEXT NOT NULL,
"resourceId" TEXT,
"requestId" TEXT,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
CREATE INDEX "AuditLog_actorId_createdAt_idx" ON "AuditLog"("actorId", "createdAt");

View File

@ -0,0 +1 @@
provider = "postgresql"

View File

@ -0,0 +1,101 @@
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model Department {
id String @id
parentId String?
name String
labelKey String?
parent Department? @relation("DepartmentTree", fields: [parentId], references: [id], onDelete: Restrict)
children Department[] @relation("DepartmentTree")
users User[]
@@index([parentId])
}
model Role {
value String @id
label String
labelKey String?
permissions RolePermission[]
users User[]
}
model Permission {
code String @id
roles RolePermission[]
}
model RolePermission {
roleValue String
permissionCode String
role Role @relation(fields: [roleValue], references: [value], onDelete: Cascade)
permission Permission @relation(fields: [permissionCode], references: [code], onDelete: Cascade)
@@id([roleValue, permissionCode])
}
model User {
id String @id @default(uuid())
username String
usernameKey String @unique
name String
email String
emailKey String @unique
phone String @default("")
departmentId String
role String
status String @default("enabled")
remark String @default("")
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime @updatedAt @db.Timestamptz(3)
department Department @relation(fields: [departmentId], references: [id], onDelete: Restrict)
roleRecord Role @relation(fields: [role], references: [value], onDelete: Restrict)
credential Credential?
sessions Session[]
@@index([departmentId])
@@index([role, status])
}
model Credential {
userId String @id
passwordHash String
updatedAt DateTime @updatedAt @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model Session {
tokenHash String @id
userId String
expiresAt DateTime @db.Timestamptz(3)
createdAt DateTime @default(now()) @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([expiresAt])
}
model RouteConfig {
id String @id
config Json
updatedAt DateTime @updatedAt @db.Timestamptz(3)
}
model AuditLog {
id String @id @default(uuid())
actorId String?
action String
resourceId String?
requestId String?
createdAt DateTime @default(now()) @db.Timestamptz(3)
@@index([createdAt])
@@index([actorId, createdAt])
}

View File

@ -0,0 +1,104 @@
import { spawn } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { build, context } from 'esbuild'
const tests = process.argv.includes('--tests')
const watch = process.argv.includes('--watch')
const options = {
absWorkingDir: fileURLToPath(new URL('../', import.meta.url)),
entryPoints: tests
? {
'unit.test': 'test/unit.test.ts',
'integration.test': 'test/integration.test.ts',
'platform.test': 'test/platform.test.ts',
}
: { main: 'src/main.ts', cli: 'src/cli.ts' },
outdir: tests ? 'dist-test' : 'dist',
outExtension: { '.js': '.mjs' },
bundle: true,
platform: 'node',
format: 'esm',
target: 'node26',
packages: 'external',
sourcemap: true,
tsconfig: 'tsconfig.json',
plugins: [
{
name: 'workspace-source',
setup(builder) {
// workspace 包导出源码;服务端产物内联这些入口,运行时只加载 npm 依赖。
builder.onResolve({ filter: /^@ray-template\// }, (args) => ({
path: fileURLToPath(import.meta.resolve(args.path)),
external: false,
}))
},
},
],
}
if (watch) {
let child
let stopping = false
const stopChild = async () => {
const running = child
child = void 0
if (!running || running.exitCode !== null || running.signalCode !== null)
return
await new Promise((resolve) => {
const timeout = setTimeout(() => running.kill('SIGKILL'), 5000)
running.once('exit', () => {
clearTimeout(timeout)
resolve()
})
running.kill('SIGTERM')
})
}
options.plugins.push({
name: 'restart-server',
setup(builder) {
builder.onEnd(async (result) => {
if (result.errors.length || stopping) return
await stopChild()
if (stopping) return
const running = spawn(process.execPath, ['dist/main.mjs'], {
cwd: options.absWorkingDir,
stdio: 'inherit',
env: process.env,
})
child = running
const failed = (code) => {
if (child === running && !stopping) {
process.exitCode = code || 1
void close()
}
}
running.once('error', () => failed(1))
running.once('exit', failed)
})
},
})
const watcher = await context(options)
const close = async () => {
if (stopping) return
stopping = true
await watcher.dispose()
await stopChild()
}
process.once('SIGINT', () => void close())
process.once('SIGTERM', () => void close())
await watcher.watch()
} else {
await build(options)
}

65
apps/server/src/app.ts Normal file
View File

@ -0,0 +1,65 @@
import 'reflect-metadata'
import { Module } from '@nestjs/common'
import type { DynamicModule } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import type { NestExpressApplication } from '@nestjs/platform-express'
import { ApiExceptionFilter, EnvelopeInterceptor } from './http'
import { DatabaseModule, DatabaseService } from './infrastructure/database'
import { AuthModule } from './modules/auth/auth.module'
import { DemoController } from './modules/demo/demo.controller'
import { RoutesModule } from './modules/routes/routes.module'
import { UsersModule } from './modules/users/users.module'
import { loadServerConfig, PlatformRuntime } from './platform/index'
import type { LogSink, ServerConfig } from './platform/index'
import { PlatformLifecycle } from './platform/lifecycle'
@Module({})
export class AppModule {
static register(config: ServerConfig): DynamicModule {
return {
module: AppModule,
imports: [
DatabaseModule.register(config),
AuthModule,
UsersModule,
RoutesModule,
],
controllers: config.demoEnabled ? [DemoController] : [],
providers: [PlatformLifecycle],
}
}
}
export async function createApp(
config: ServerConfig = loadServerConfig(),
options: { logSink?: LogSink } = {},
) {
const app = await NestFactory.create<NestExpressApplication>(
AppModule.register(config),
{
logger: false,
bodyParser: false,
abortOnError: false,
},
)
try {
const database = app.get(DatabaseService)
const runtime = await PlatformRuntime.create(config, {
checkDatabase: () => database.ping(),
logSink: options.logSink,
})
app.get(PlatformLifecycle).runtime = runtime
runtime.install(app)
app.setGlobalPrefix('api')
app.useGlobalInterceptors(new EnvelopeInterceptor())
app.useGlobalFilters(new ApiExceptionFilter())
await app.init()
return app
} catch (error) {
await app.close()
throw error
}
}

52
apps/server/src/cli.ts Normal file
View File

@ -0,0 +1,52 @@
import { createDatabase } from './infrastructure/database'
import { loadServerConfig } from './platform/index'
import { seedDatabase, setPassword } from './seed'
const config = loadServerConfig()
const database = createDatabase(config.databaseUrl)
const command = process.argv[2]
try {
if (command === 'seed') {
const result = await seedDatabase(database, {
username: process.env.ADMIN_USERNAME,
email: process.env.ADMIN_EMAIL,
password: process.env.ADMIN_PASSWORD,
})
console.log(
result.created
? 'Administrator initialized.'
: 'Existing administrator preserved.',
)
} else if (command === 'password') {
const username = process.argv[3] ?? process.env.CREDENTIAL_USERNAME
const password = process.env.CREDENTIAL_PASSWORD
if (!username || !password)
throw new Error(
'Set CREDENTIAL_USERNAME and CREDENTIAL_PASSWORD before running credential:set.',
)
await setPassword(database, username, password)
console.log('Credential updated and active sessions revoked.')
} else if (command === 'cleanup-sessions') {
const result = await database.session.deleteMany({
where: { expiresAt: { lte: new Date() } },
})
console.log(`Removed ${result.count} expired sessions.`)
} else {
throw new Error('Use seed, password, or cleanup-sessions.')
}
} catch (error) {
// Prisma 错误可能包含连接信息和参数;命令行只输出预期的操作错误。
console.error(
error instanceof Error && error.name === 'Error' && !('code' in error)
? error.message
: 'Database operation failed.',
)
process.exitCode = 1
} finally {
await database.$disconnect()
}

View File

@ -0,0 +1 @@
export const SERVER_CONFIG = Symbol('SERVER_CONFIG')

151
apps/server/src/http.ts Normal file
View File

@ -0,0 +1,151 @@
import { Catch, HttpException, Injectable } from '@nestjs/common'
import type {
ArgumentsHost,
CallHandler,
ExceptionFilter,
ExecutionContext,
NestInterceptor,
} from '@nestjs/common'
import type { ApiResponse } from '@ray-template/api-contracts/admin'
import type { Request, Response } from 'express'
import { map } from 'rxjs'
import * as v from 'valibot'
import { standardLogSink, writeLog } from './platform/index'
export class ApiError extends Error {
constructor(
readonly status: number,
readonly key: string,
) {
super(key)
}
}
export function parseInput<S extends v.GenericSchema>(
schema: S,
input: unknown,
) {
const parsed = v.safeParse(schema, input)
if (!parsed.success) throw new ApiError(400, 'invalid')
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')
return typeof id === 'string' ? id : null
}
export function queryInput(query: Request['query'], booleans: string[] = []) {
const values: Record<string, unknown> = { ...query }
for (const key of ['page', 'pageSize']) {
if (key in values) {
if (typeof values[key] !== 'string' || !/^\d+$/u.test(values[key]))
throw new ApiError(400, 'invalid')
values[key] = Number(values[key])
if (!Number.isSafeInteger(values[key])) throw new ApiError(400, 'invalid')
}
}
for (const key of booleans) {
if (values[key] === 'true') values[key] = true
else if (values[key] === 'false') values[key] = false
}
return values
}
@Injectable()
export class EnvelopeInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const response = context.switchToHttp().getResponse<Response>()
response.status(200)
return next.handle().pipe(
map((data: unknown): ApiResponse<unknown> => ({
code: 200,
msg: 'OK',
data: data ?? null,
})),
)
}
}
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
catch(error: unknown, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse<Response>()
if (response.headersSent) return
let status = 500
let key = 'internal'
if (error instanceof ApiError) {
status = error.status
key = error.key
} else if (error instanceof HttpException) {
status = error.getStatus()
key =
{
400: 'invalid',
401: 'unauthorized',
403: 'forbidden',
404: 'notFound',
413: 'invalid',
429: 'tooManyRequests',
503: 'serviceUnavailable',
}[status] ?? 'requestFailed'
} else if (error instanceof Error && 'code' in error) {
if (error.code === 'P2002') {
const meta = 'meta' in error ? error.meta : null
const target = JSON.stringify(meta)
status = 409
key = target?.includes('email') ? 'duplicateEmail' : 'duplicateUsername'
} else if (error.code === 'P2025') {
status = 404
key = 'notFound'
} else if (error.code === 'P2003') {
status = 400
key = 'invalid'
} else if (/^P10|^P20/u.test(String(error.code))) {
status = 503
key = 'storage'
}
}
if (status >= 500) {
const code =
error instanceof Error &&
'code' in error &&
/^P\d{4}$/u.test(String(error.code))
? String(error.code)
: 'UNEXPECTED_ERROR'
writeLog(standardLogSink, 'error', 'http.exception', {
requestId: String(response.getHeader('x-request-id') ?? ''),
code,
statusCode: status,
})
}
response
.status(status)
.json({ code: status, msg: key, data: null, error: { key } })
}
}

View File

@ -0,0 +1,91 @@
import { Global, Inject, Injectable, Module } from '@nestjs/common'
import type {
DynamicModule,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common'
import { PrismaPg } from '@prisma/adapter-pg'
import { SERVER_CONFIG } from '../config'
import { PrismaClient } from '../generated/prisma/client'
import type { Prisma } from '../generated/prisma/client'
import type { ServerConfig } from '../platform/index'
export function createDatabase(databaseUrl: string) {
const schema = new URL(databaseUrl).searchParams.get('schema') ?? 'public'
const adapter = new PrismaPg(
{ connectionString: databaseUrl, connectionTimeoutMillis: 5000, max: 10 },
{ schema },
)
return new PrismaClient({ adapter })
}
export type Database = PrismaClient | Prisma.TransactionClient
export async function writeTransaction<T>(
database: PrismaClient,
action: (transaction: Prisma.TransactionClient) => Promise<T>,
) {
// 权限复核和目标变更放在同一事务内,避免并发降权后仍写入数据。
for (let attempt = 0; ; attempt++) {
try {
return await database.$transaction(action, {
isolationLevel: 'Serializable',
maxWait: 5000,
timeout: 10000,
})
} catch (error) {
if (
attempt < 2 &&
error instanceof Error &&
'code' in error &&
error.code === 'P2034'
)
continue
throw error
}
}
}
@Injectable()
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
readonly prisma: PrismaClient
constructor(@Inject(SERVER_CONFIG) config: ServerConfig) {
this.prisma = createDatabase(config.databaseUrl)
}
async onModuleInit() {
await this.prisma.$connect()
}
async onModuleDestroy() {
await this.prisma.$disconnect()
}
async ping() {
await this.prisma.$queryRaw`SELECT 1`
}
async write<T>(
action: (transaction: Prisma.TransactionClient) => Promise<T>,
) {
return writeTransaction(this.prisma, action)
}
}
@Global()
@Module({})
export class DatabaseModule {
static register(config: ServerConfig): DynamicModule {
return {
module: DatabaseModule,
providers: [
{ provide: SERVER_CONFIG, useValue: config },
DatabaseService,
],
exports: [SERVER_CONFIG, DatabaseService],
}
}
}

22
apps/server/src/main.ts Normal file
View File

@ -0,0 +1,22 @@
import { createApp } from './app'
import { loadServerConfig, standardLogSink, writeLog } from './platform/index'
try {
const config = loadServerConfig()
const app = await createApp(config)
try {
app.enableShutdownHooks()
await app.listen(config.port, config.host)
} catch (error) {
await app.close()
throw error
}
writeLog(standardLogSink, 'info', 'server.started')
} catch (error) {
writeLog(standardLogSink, 'error', 'server.start_failed', {
code: error instanceof Error ? error.name : 'UnknownError',
})
process.exitCode = 1
}

View File

@ -0,0 +1,26 @@
import { Body, Controller, Get, Inject, Post, Req } from '@nestjs/common'
import type { Request } from 'express'
import { requestIdFrom, tokenFrom } from '../../http'
import { Public } from './auth.guard'
import { AuthService } from './auth.service'
@Controller('admin/auth')
export class AuthController {
constructor(@Inject(AuthService) private readonly auth: AuthService) {}
@Public()
@Post('login')
login(@Body() input: unknown, @Req() request: Request) {
return this.auth.login(input, requestIdFrom(request))
}
@Get('session')
session(@Req() request: Request) {
return this.auth.session(tokenFrom(request))
}
@Post('logout')
logout(@Req() request: Request) {
return this.auth.logout(tokenFrom(request), requestIdFrom(request))
}
}

View File

@ -0,0 +1,37 @@
import { Inject, Injectable, SetMetadata } from '@nestjs/common'
import type { CanActivate, ExecutionContext } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import type { Request } from 'express'
import { tokenFrom } from '../../http'
import { AuthService } from './auth.service'
const PUBLIC = Symbol('public')
const PERMISSION = Symbol('permission')
export const Public = () => SetMetadata(PUBLIC, true)
export const RequirePermission = (permission: string) =>
SetMetadata(PERMISSION, permission)
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
@Inject(Reflector) private readonly reflector: Reflector,
@Inject(AuthService) private readonly auth: AuthService,
) {}
async canActivate(context: ExecutionContext) {
const targets = [context.getHandler(), context.getClass()]
if (this.reflector.getAllAndOverride<boolean>(PUBLIC, targets)) return true
const permission = this.reflector.getAllAndOverride<string>(
PERMISSION,
targets,
)
const request = context.switchToHttp().getRequest<Request>()
await this.auth.authenticate(tokenFrom(request), permission)
return true
}
}

View File

@ -0,0 +1,13 @@
import { Global, Module } from '@nestjs/common'
import { APP_GUARD } from '@nestjs/core'
import { AuthController } from './auth.controller'
import { AuthGuard } from './auth.guard'
import { AuthService } from './auth.service'
@Global()
@Module({
controllers: [AuthController],
providers: [AuthService, { provide: APP_GUARD, useClass: AuthGuard }],
exports: [AuthService],
})
export class AuthModule {}

View File

@ -0,0 +1,142 @@
import { Inject, Injectable } from '@nestjs/common'
import { loginInputSchema } 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'
export interface AuthContext extends SessionInfo {
tokenHash: string
}
@Injectable()
export class AuthService {
constructor(
@Inject(DatabaseService) private readonly database: DatabaseService,
@Inject(SERVER_CONFIG) private readonly config: ServerConfig,
) {}
async authenticate(
token: string | null,
permission?: string,
database: Database = this.database.prisma,
): Promise<AuthContext> {
if (!token) throw new ApiError(401, 'unauthorized')
const hash = tokenHash(token)
const session = await database.session.findUnique({
where: { tokenHash: hash },
include: {
user: { include: { roleRecord: { include: { permissions: true } } } },
},
})
if (
!session ||
session.expiresAt.getTime() <= Date.now() ||
session.user.status !== 'enabled'
)
throw new ApiError(401, 'unauthorized')
const { id, username, name, role, roleRecord } = session.user
const permissions = roleRecord.permissions.map(
({ permissionCode }) => permissionCode,
)
if (permission && !permissions.includes(permission))
throw new ApiError(403, 'forbidden')
return { user: { id, username, name, role }, permissions, tokenHash: hash }
}
async login(input: unknown, requestId: string | null) {
const { username, password } = parseInput(loginInputSchema, input)
const user = await this.database.prisma.user.findUnique({
where: { usernameKey: username.toLowerCase() },
include: { credential: true },
})
const valid = await verifyPassword(
password,
user?.credential?.passwordHash ?? null,
)
if (!valid || !user || user.status !== 'enabled') {
await this.database.prisma.auditLog.create({
data: { action: 'auth.login.failed', requestId },
})
throw new ApiError(401, 'invalidCredentials')
}
const accessToken = createToken()
const hash = tokenHash(accessToken)
const expiresAt = new Date(
Date.now() + this.config.sessionTtlSeconds * 1000,
)
return this.database.write(async (transaction) => {
const current = await transaction.user.findUnique({
where: { id: user.id },
include: {
credential: true,
roleRecord: { include: { permissions: true } },
},
})
// 派生密码期间可能发生停用或重置;新会话必须以事务内的凭据状态为准。
if (
!current ||
current.status !== 'enabled' ||
current.credential?.passwordHash !== user.credential?.passwordHash
)
throw new ApiError(401, 'invalidCredentials')
await transaction.session.deleteMany({
where: { userId: user.id, expiresAt: { lte: new Date() } },
})
await transaction.session.create({
data: { tokenHash: hash, userId: user.id, expiresAt },
})
await transaction.auditLog.create({
data: { actorId: user.id, action: 'auth.login', requestId },
})
return {
accessToken,
expiresAt: expiresAt.toISOString(),
user: {
id: current.id,
username: current.username,
name: current.name,
role: current.role,
},
permissions: current.roleRecord.permissions.map(
({ permissionCode }) => permissionCode,
),
}
})
}
async session(token: string | null): Promise<SessionInfo> {
const { user, permissions } = await this.authenticate(token)
return { user, permissions }
}
async logout(token: string | null, requestId: string | null) {
await this.database.write(async (transaction) => {
const session = await this.authenticate(token, void 0, transaction)
await transaction.session.delete({
where: { tokenHash: session.tokenHash },
})
await transaction.auditLog.create({
data: { actorId: session.user.id, action: 'auth.logout', requestId },
})
})
return null
}
}

View File

@ -0,0 +1,49 @@
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
const keyLength = 64
const cost = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
function derive(password: string, salt: Buffer) {
return new Promise<Buffer>((resolve, reject) => {
scrypt(password, salt, keyLength, cost, (error, key) => {
if (error) reject(error)
else resolve(key)
})
})
}
export function validateNewPassword(password: string) {
if (password.length < 12 || password.length > 128)
throw new Error('Passwords must contain 12 to 128 characters.')
}
export async function hashPassword(password: string) {
validateNewPassword(password)
const salt = randomBytes(16)
const key = await derive(password, salt)
return `scrypt$${salt.toString('hex')}$${key.toString('hex')}`
}
export async function verifyPassword(password: string, stored: string | null) {
const parts = stored?.split('$') ?? []
const valid =
parts.length === 3 &&
parts[0] === 'scrypt' &&
/^[a-f\d]{32}$/u.test(parts[1]) &&
/^[a-f\d]{128}$/u.test(parts[2])
const salt = valid ? Buffer.from(parts[1], 'hex') : Buffer.alloc(16)
const expected = valid
? Buffer.from(parts[2], 'hex')
: Buffer.alloc(keyLength)
const actual = await derive(password, salt)
// 未配置凭据的账号也执行同样的派生工作,避免直接暴露账号是否存在。
return timingSafeEqual(actual, expected) && valid
}
export const tokenHash = (token: string) =>
createHash('sha256').update(token).digest('hex')
export const createToken = () => randomBytes(32).toString('base64url')

View File

@ -0,0 +1,140 @@
import {
Body,
Controller,
Get,
Inject,
Param,
Post,
Query,
} from '@nestjs/common'
import {
chartsQuerySchema,
chartsSchema,
orderSearchInputSchema,
ownerSearchInputSchema,
personListQuerySchema,
requestFixtureSchema,
routePeopleQuerySchema,
searchOptionsQuerySchema,
searchOptionsSchema,
} from '@ray-template/api-contracts/demo'
import {
getDemoCharts,
getOrderOptions,
listPeople,
listRouteDemoPeople,
requestFixture,
routeDemoPeople,
searchDemoOrders,
searchDemoOwners,
} from '@ray-template/demo-data'
import type { Request } from 'express'
import * as v from 'valibot'
import { ApiError, parseInput, queryInput } from '../../http'
import { PlatformLifecycle } from '../../platform/lifecycle'
import { Public } from '../auth/auth.guard'
@Public()
@Controller('admin/demo')
export class DemoController {
constructor(
@Inject(PlatformLifecycle) private readonly platform: PlatformLifecycle,
) {}
@Get('request')
requestFixture() {
return this.cached('request', () => requestFixture, requestFixtureSchema)
}
@Get('charts')
charts(@Query() query: Request['query']) {
const { refresh } = parseInput(
chartsQuerySchema,
queryInput(query, ['refresh']),
)
return refresh
? getDemoCharts(true)
: this.cached('charts', getDemoCharts, chartsSchema)
}
@Get('search-options')
options(@Query() query: Request['query']) {
const { locale = 'zh-CN' } = parseInput(searchOptionsQuerySchema, query)
const language = locale === 'zh-CN' ? 'zh-CN' : 'en-US'
return this.cached(
`options:${language}`,
() => getOrderOptions(language),
searchOptionsSchema,
)
}
@Get('people')
people(@Query() query: Request['query']) {
const input = parseInput(personListQuerySchema, queryInput(query, ['fail']))
if (input.fail) throw new ApiError(503, 'requestFailed')
return listPeople({
...input,
page: input.page ?? 1,
pageSize: input.pageSize ?? 10,
})
}
@Get('route-people')
routePeople(@Query() query: Request['query']) {
return listRouteDemoPeople(
parseInput(routePeopleQuerySchema, queryInput(query)),
)
}
@Get('route-people/:id')
routePerson(@Param('id') id: string) {
const key = Number(id)
if (!/^\d+$/u.test(id) || !Number.isSafeInteger(key))
throw new ApiError(400, 'invalid')
const person = routeDemoPeople.find((row) => row.key === key)
if (!person) throw new ApiError(404, 'notFound')
return person
}
@Post('owners/search')
owners(@Body() body: unknown) {
const { orgId, keyword, locale, fail } = parseInput(
ownerSearchInputSchema,
body,
)
if (fail) throw new ApiError(503, 'requestFailed')
return searchDemoOwners(orgId, keyword, locale)
}
@Post('orders/search')
orders(@Body() body: unknown) {
const { query, locale, fail } = parseInput(orderSearchInputSchema, body)
if (fail) throw new ApiError(503, 'requestFailed')
return searchDemoOrders(query, locale)
}
private cached<T>(
key: string,
load: () => T,
schema: v.GenericSchema<unknown, T>,
) {
return this.platform.cache.getOrLoad(
`demo:v1:${key}`,
300,
async () => load(),
(value): value is T => v.is(schema, value),
)
}
}

View File

@ -0,0 +1,81 @@
import { Body, Controller, Get, Inject, Put, Query, Req } from '@nestjs/common'
import { parseApplicationRoutes } from '@ray-template/demo-data'
import type { Request } from 'express'
import { SERVER_CONFIG } from '../../config'
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 { AuthService } from '../auth/auth.service'
import { withoutDemoRoutes } from './runtime-routes'
@Controller('admin/route-config')
export class RoutesController {
constructor(
@Inject(DatabaseService) private readonly database: DatabaseService,
@Inject(AuthService) private readonly auth: AuthService,
@Inject(SERVER_CONFIG) private readonly config: ServerConfig,
) {}
@Public()
@Get()
async get(@Req() request: Request, @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 record = await this.database.prisma.routeConfig.findUnique({
where: { id: 'admin' },
})
if (!record) throw new ApiError(503, 'notInitialized')
try {
const routes = parseApplicationRoutes(JSON.stringify(record.config))
return this.config.demoEnabled || view === 'editor'
? routes
: withoutDemoRoutes(routes)
} catch {
throw new ApiError(503, 'invalidRoutes')
}
}
@Put()
@RequirePermission('routes:write')
save(@Body() input: unknown, @Req() request: Request) {
let config: ReturnType<typeof parseApplicationRoutes>
try {
config = parseApplicationRoutes(JSON.stringify(input))
} catch {
throw new ApiError(400, 'invalidRoutes')
}
return this.database.write(async (transaction) => {
const session = await this.auth.authenticate(
tokenFrom(request),
'routes:write',
transaction,
)
await transaction.routeConfig.upsert({
where: { id: 'admin' },
create: { id: 'admin', config: config as Prisma.InputJsonValue },
update: { config: config as Prisma.InputJsonValue },
})
await transaction.auditLog.create({
data: {
actorId: session.user.id,
action: 'routes.update',
resourceId: 'admin',
requestId: requestIdFrom(request),
},
})
return config
})
}
}

View File

@ -0,0 +1,5 @@
import { Module } from '@nestjs/common'
import { RoutesController } from './routes.controller'
@Module({ controllers: [RoutesController] })
export class RoutesModule {}

View File

@ -0,0 +1,48 @@
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

@ -0,0 +1,76 @@
import {
Body,
Controller,
Get,
Inject,
Param,
Patch,
Post,
Put,
Query,
Req,
} from '@nestjs/common'
import type { Request } from 'express'
import { queryInput, requestIdFrom, tokenFrom } from '../../http'
import { RequirePermission } from '../auth/auth.guard'
import { UsersService } from './users.service'
@Controller('admin/users')
export class UsersController {
constructor(@Inject(UsersService) private readonly users: UsersService) {}
@Get('options')
@RequirePermission('users:read')
options(@Req() request: Request) {
return this.users.options(tokenFrom(request))
}
@Get()
@RequirePermission('users:read')
list(@Query() query: Request['query']) {
return this.users.list(queryInput(query))
}
@Get(':id')
@RequirePermission('users:read')
get(@Param('id') id: string) {
return this.users.get(id)
}
@Post()
@RequirePermission('users:create')
create(@Body() input: unknown, @Req() request: Request) {
return this.users.save(input, tokenFrom(request), requestIdFrom(request))
}
@Put(':id')
@RequirePermission('users:update')
update(
@Param('id') id: string,
@Body() input: unknown,
@Req() request: Request,
) {
return this.users.save(
input,
tokenFrom(request),
requestIdFrom(request),
id,
)
}
@Post('batch-delete')
@RequirePermission('users:delete')
delete(@Body() input: unknown, @Req() request: Request) {
return this.users.delete(input, tokenFrom(request), requestIdFrom(request))
}
@Patch('status')
@RequirePermission('users:status')
status(@Body() input: unknown, @Req() request: Request) {
return this.users.changeStatus(
input,
tokenFrom(request),
requestIdFrom(request),
)
}
}

View File

@ -0,0 +1,6 @@
import { Module } from '@nestjs/common'
import { UsersController } from './users.controller'
import { UsersService } from './users.service'
@Module({ controllers: [UsersController], providers: [UsersService] })
export class UsersModule {}

View File

@ -0,0 +1,328 @@
import { Inject, Injectable } from '@nestjs/common'
import {
idsSchema,
statusInputSchema,
userInputSchema,
userListQuerySchema,
} from '@ray-template/api-contracts/admin'
import type { AdminUser, UserInput } from '@ray-template/api-contracts/admin'
import type { Prisma, User } from '../../generated/prisma/client'
import { ApiError, parseInput } from '../../http'
import { DatabaseService } from '../../infrastructure/database'
import type { Database } from '../../infrastructure/database'
import { AuthService } from '../auth/auth.service'
import type { AuthContext } from '../auth/auth.service'
export function userView(user: User): AdminUser {
return {
id: user.id,
username: user.username,
name: user.name,
email: user.email,
phone: user.phone,
departmentId: user.departmentId,
role: user.role,
status: user.status as AdminUser['status'],
remark: user.remark,
createdAt: user.createdAt.toISOString(),
}
}
@Injectable()
export class UsersService {
constructor(
@Inject(DatabaseService) private readonly database: DatabaseService,
@Inject(AuthService) private readonly auth: AuthService,
) {}
async options(token: string | null) {
const session = await this.auth.authenticate(token, 'users:read')
const [departments, roles] = await Promise.all([
this.database.prisma.department.findMany({ orderBy: { id: 'asc' } }),
this.database.prisma.role.findMany({
include: { permissions: true },
orderBy: { value: 'asc' },
}),
])
return {
departments: departments.map(({ labelKey, ...department }) => ({
...department,
...(labelKey ? { labelKey } : {}),
})),
roles: roles.map(({ value, label, labelKey, permissions }) => ({
value,
label,
...(labelKey ? { labelKey } : {}),
disabled:
session.user.role !== 'admin' &&
permissions.some(
({ permissionCode }) =>
!session.permissions.includes(permissionCode),
),
})),
}
}
async list(input: unknown) {
const params = parseInput(userListQuerySchema, input)
const { page = 1, pageSize = 10 } = params
if (
!Number.isSafeInteger(page) ||
!Number.isSafeInteger((page - 1) * pageSize)
)
throw new ApiError(400, 'invalid')
const where: Prisma.UserWhereInput = {}
for (const field of ['name', 'username', 'email'] as const) {
if (params[field])
where[field] = { contains: params[field], mode: 'insensitive' }
}
if (params.role) where.role = params.role
if (params.status) where.status = params.status
if (params.departmentId) {
const departments = await this.database.prisma.department.findMany()
const included = new Set([params.departmentId])
let changed = true
while (changed) {
changed = false
for (const department of departments) {
if (
department.parentId &&
included.has(department.parentId) &&
!included.has(department.id)
) {
included.add(department.id)
changed = true
}
}
}
where.departmentId = { in: [...included] }
}
const [users, total] = await this.database.prisma.$transaction(
[
this.database.prisma.user.findMany({
where,
skip: (page - 1) * pageSize,
take: pageSize,
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
}),
this.database.prisma.user.count({ where }),
],
{ isolationLevel: 'RepeatableRead' },
)
return { items: users.map(userView), total }
}
async get(id: string) {
return userView(await this.findUser(this.database.prisma, id))
}
private async findUser(database: Database, id: string) {
const user = await database.user.findUnique({ where: { id } })
if (!user) throw new ApiError(404, 'notFound')
return user
}
private async assertManageRole(
database: Database,
session: AuthContext,
role: string,
) {
const target = await database.role.findUnique({
where: { value: role },
include: { permissions: true },
})
if (!target) throw new ApiError(400, 'invalid')
if (
session.user.role !== 'admin' &&
target.permissions.some(
({ permissionCode }) => !session.permissions.includes(permissionCode),
)
)
throw new ApiError(403, 'forbidden')
}
private async validateUnique(
database: Database,
value: UserInput,
id?: string,
) {
const duplicate = await database.user.findFirst({
where: {
usernameKey: value.username.toLowerCase(),
...(id ? { id: { not: id } } : {}),
},
})
if (duplicate) throw new ApiError(409, 'duplicateUsername')
const duplicateEmail = await database.user.findFirst({
where: {
emailKey: value.email.toLowerCase(),
...(id ? { id: { not: id } } : {}),
},
})
if (duplicateEmail) throw new ApiError(409, 'duplicateEmail')
}
async save(
input: unknown,
token: string | null,
requestId: string | null,
id?: string,
) {
const value = parseInput(userInputSchema, input)
return this.database.write(async (transaction) => {
const session = await this.auth.authenticate(
token,
id ? 'users:update' : 'users:create',
transaction,
)
const existing = id ? await this.findUser(transaction, id) : null
if (existing)
await this.assertManageRole(transaction, session, existing.role)
await this.assertManageRole(transaction, session, value.role)
if (
!(await transaction.department.findUnique({
where: { id: value.departmentId },
}))
)
throw new ApiError(400, 'invalid')
if (
id === session.user.id &&
(value.status !== 'enabled' || value.role !== session.user.role)
)
throw new ApiError(409, 'selfProtected')
await this.validateUnique(transaction, value, id)
const data = {
...value,
usernameKey: value.username.toLowerCase(),
emailKey: value.email.toLowerCase(),
}
const user = existing
? await transaction.user.update({ where: { id }, data })
: await transaction.user.create({ data })
if (
existing &&
(existing.role !== user.role || user.status === 'disabled')
) {
await transaction.session.deleteMany({ where: { userId: user.id } })
}
await transaction.auditLog.create({
data: {
actorId: session.user.id,
action: existing ? 'users.update' : 'users.create',
resourceId: user.id,
requestId,
},
})
return userView(user)
})
}
async delete(input: unknown, token: string | null, requestId: string | null) {
const ids = [...new Set(parseInput(idsSchema, input).ids)]
return this.database.write(async (transaction) => {
const session = await this.auth.authenticate(
token,
'users:delete',
transaction,
)
for (const id of ids) {
const user = await this.findUser(transaction, id)
await this.assertManageRole(transaction, session, user.role)
if (id === session.user.id) throw new ApiError(409, 'selfProtected')
}
const result = await transaction.user.deleteMany({
where: { id: { in: ids } },
})
await transaction.auditLog.createMany({
data: ids.map((id) => ({
actorId: session.user.id,
action: 'users.delete',
resourceId: id,
requestId,
})),
})
return { affected: result.count }
})
}
async changeStatus(
input: unknown,
token: string | null,
requestId: string | null,
) {
const parsed = parseInput(statusInputSchema, input)
const ids = [...new Set(parsed.ids)]
return this.database.write(async (transaction) => {
const session = await this.auth.authenticate(
token,
'users:status',
transaction,
)
for (const id of ids) {
const user = await this.findUser(transaction, id)
await this.assertManageRole(transaction, session, user.role)
if (id === session.user.id && parsed.status === 'disabled')
throw new ApiError(409, 'selfProtected')
}
const result = await transaction.user.updateMany({
where: { id: { in: ids } },
data: { status: parsed.status },
})
if (parsed.status === 'disabled')
await transaction.session.deleteMany({ where: { userId: { in: ids } } })
await transaction.auditLog.createMany({
data: ids.map((id) => ({
actorId: session.user.id,
action: `users.${parsed.status}`,
resourceId: id,
requestId,
})),
})
return { affected: result.count }
})
}
}

View File

@ -0,0 +1,47 @@
# Server platform
`PlatformRuntime` owns the Redis connection, HTTP security middleware, request logs, rate limits, read-through cache, and health probes. Authentication and authorization remain in the business modules; permission decisions and sessions must never use the optional read-through cache.
Create the Nest application with `bodyParser: false`, install the runtime before `app.init()` or `app.listen()`, and await `runtime.close()` during application shutdown. The runtime installs its bounded JSON parser after logging and security headers, so malformed and oversized payloads also receive the standard error envelope and request ID. The API exception filter remains responsible for controller failures.
## 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 |
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.
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.
`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.
The client disables offline command queues, bounds connection and command waits, reconnects after transient failures, and closes gracefully. A connection failure never prints the connection URL. Tests use a unique key prefix and TTL-bound keys; they must not flush a shared Redis database.
## HTTP observability and probes
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.
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.
Platform tests cover configuration, redaction, real HTTP security/CORS/body limits, forwarded-header spoofing, rate-limit denial, fail-closed Redis outages, readiness, and cache behavior. Set `TEST_REDIS_URL` to include the real Redis concurrency and expiry regression.

View File

@ -0,0 +1,146 @@
import { isIP } from 'node:net'
export interface ServerConfig {
nodeEnv: 'development' | 'test' | 'production'
host: string
port: number
databaseUrl: string
redisUrl: string
redisKeyPrefix: string
corsOrigins: string[]
trustProxy: false | string[]
demoEnabled: boolean
sessionTtlSeconds: number
bodyLimitBytes: number
requestTimeoutMs: number
rateLimitMax: number
loginRateLimitMax: number
}
export function loadServerConfig(
env: NodeJS.ProcessEnv = process.env,
): ServerConfig {
const nodeEnv = env.NODE_ENV ?? 'development'
if (!['development', 'test', 'production'].includes(nodeEnv)) {
throw new Error('NODE_ENV must be development, test or production.')
}
const integer = (key: string, fallback: number, min: number, max: number) => {
const input = env[key] ?? String(fallback)
const value = Number(input)
if (
!/^\d+$/u.test(input) ||
!Number.isSafeInteger(value) ||
value < min ||
value > max
) {
throw new Error(`${key} must be an integer between ${min} and ${max}.`)
}
return value
}
const boolean = (key: string, fallback: boolean) => {
const input = env[key]
if (input === void 0) return fallback
if (input === 'true') return true
if (input === 'false') return false
throw new Error(`${key} must be true or false.`)
}
const connection = (key: string, protocols: string[]) => {
const value = env[key]
try {
const parsed = new URL(value ?? '')
if (!protocols.includes(parsed.protocol) || !parsed.hostname)
throw new Error()
} catch {
// 配置错误只报告字段名,连接串可能携带数据库或 Redis 密码。
throw new Error(
`${key} must be a valid ${protocols.join('/')} connection URL.`,
)
}
return value!
}
const corsOrigins = (env.CORS_ORIGINS ?? '')
.split(',')
.map((item) => item.trim())
.filter(Boolean)
if (corsOrigins.length > 16)
throw new Error('CORS_ORIGINS accepts at most 16 origins.')
for (const origin of corsOrigins) {
try {
const parsed = new URL(origin)
if (
!['https:', 'http:'].includes(parsed.protocol) ||
parsed.origin !== origin
)
throw new Error()
} catch {
throw new Error(
'CORS_ORIGINS must contain exact HTTP(S) origins without paths or wildcards.',
)
}
}
const proxyValue = env.TRUST_PROXY?.trim() || 'false'
const trustProxy =
proxyValue === 'false'
? false
: proxyValue.split(',').map((item) => item.trim())
if (trustProxy) {
for (const entry of trustProxy) {
const [address, mask, extra] = entry.split('/')
const family = isIP(address)
if (
!family ||
extra !== void 0 ||
(mask !== void 0 &&
(!/^\d+$/u.test(mask) ||
Number(mask) < 1 ||
Number(mask) > (family === 4 ? 32 : 128)))
) {
throw new Error(
'TRUST_PROXY must be false or a comma-separated list of trusted IP addresses/CIDRs.',
)
}
}
}
const redisKeyPrefix = env.REDIS_KEY_PREFIX || `ray:${nodeEnv}`
if (!/^[a-zA-Z0-9:_-]{1,80}$/u.test(redisKeyPrefix)) {
throw new Error(
'REDIS_KEY_PREFIX accepts 1–80 letters, digits, colons, underscores or hyphens.',
)
}
return {
nodeEnv: nodeEnv as ServerConfig['nodeEnv'],
host: env.HOST || '127.0.0.1',
port: integer('PORT', 3000, nodeEnv === 'test' ? 0 : 1, 65535),
databaseUrl: connection('DATABASE_URL', ['postgres:', 'postgresql:']),
redisUrl: connection('REDIS_URL', ['redis:', 'rediss:']),
redisKeyPrefix,
corsOrigins,
trustProxy,
demoEnabled: boolean('DEMO_ENABLED', 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),
rateLimitMax: integer('RATE_LIMIT_MAX', 300, 1, 100000),
loginRateLimitMax: integer('LOGIN_RATE_LIMIT_MAX', 10, 1, 1000),
}
}

View File

@ -0,0 +1,7 @@
export { loadServerConfig } from './config.js'
export type { ServerConfig } from './config.js'
export { PlatformRuntime } from './runtime.js'
export { RedisJsonCache, RedisRateLimiter, RedisStore } from './redis.js'
export type { RedisCommands } from './redis.js'
export { standardLogSink, writeLog } from './logging.js'
export type { LogSink } from './logging.js'

View File

@ -0,0 +1,18 @@
import { Injectable } from '@nestjs/common'
import type { OnApplicationShutdown } from '@nestjs/common'
import type { PlatformRuntime } from './runtime'
@Injectable()
export class PlatformLifecycle implements OnApplicationShutdown {
runtime: PlatformRuntime | null = null
get cache() {
if (!this.runtime) throw new Error('Platform has not started.')
return this.runtime.cache
}
async onApplicationShutdown() {
await this.runtime?.close()
}
}

View File

@ -0,0 +1,63 @@
import { randomUUID } from 'node:crypto'
import type { Request } from 'express'
export type LogSink = (line: string) => void
export interface LogFields {
requestId?: string
method?: string
route?: string
statusCode?: number
durationMs?: number
code?: string
}
export const standardLogSink: LogSink = (line) =>
process.stdout.write(`${line}\n`)
export function writeLog(
sink: LogSink,
level: 'info' | 'warn' | 'error',
event: string,
fields: LogFields = {},
) {
// 只输出白名单字段,不序列化请求、错误对象、查询串或连接配置。
sink(
JSON.stringify({
timestamp: new Date().toISOString(),
level,
event,
requestId: fields.requestId,
method: fields.method,
route: fields.route,
statusCode: fields.statusCode,
durationMs: fields.durationMs,
code: fields.code,
}),
)
}
export function requestIdFor(value: unknown): string {
return typeof value === 'string' && /^[a-zA-Z0-9_-]{8,64}$/u.test(value)
? value
: randomUUID()
}
export function requestRoute(request: Request): string {
const route = request.route as { path?: unknown } | null
return typeof route?.path === 'string' ? route.path : '<unmatched>'
}
export function safeErrorCode(error: unknown): string {
const code =
typeof error === 'object' && error !== null && 'code' in error
? error.code
: null
return typeof code === 'string' &&
['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'EPIPE'].includes(
code,
)
? code
: 'DEPENDENCY_ERROR'
}

View File

@ -0,0 +1,197 @@
import { createHash } from 'node:crypto'
import { createClient } from 'redis'
import type { ServerConfig } from './config.js'
import { safeErrorCode, standardLogSink, writeLog } from './logging.js'
import type { LogSink } from './logging.js'
const windowScript = `
local count = redis.call('INCR', KEYS[1])
if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
local remaining = redis.call('PTTL', KEYS[1])
return {count, remaining}
`
export interface RedisCommands {
isReady: boolean
eval(
script: string,
options: { keys: string[]; arguments: string[] },
): Promise<unknown>
get(key: string): Promise<string | null>
set(key: string, value: string, options: { EX: number }): Promise<unknown>
del(key: string): Promise<unknown>
ping(): Promise<string>
}
function within<T>(operation: Promise<T>, milliseconds = 2000): Promise<T> {
let timeout: ReturnType<typeof setTimeout>
return Promise.race([
operation,
new Promise<never>((_, reject) => {
timeout = setTimeout(
() => reject(new Error('Redis command timed out.')),
milliseconds,
)
timeout.unref()
}),
]).finally(() => clearTimeout(timeout))
}
export class RedisStore {
private client: ReturnType<typeof createClient>
private closing = false
private closePromise?: Promise<void>
constructor(
config: ServerConfig,
private readonly sink: LogSink = standardLogSink,
) {
this.client = createClient({
url: config.redisUrl,
disableOfflineQueue: true,
socket: {
connectTimeout: 3000,
reconnectStrategy: (retries) => Math.min(100 * 2 ** retries, 3000),
},
})
this.client.on('error', (error: unknown) => {
if (!this.closing)
writeLog(this.sink, 'error', 'redis.error', {
code: safeErrorCode(error),
})
})
}
async connect(): Promise<void> {
try {
await within(this.client.connect(), 5000)
} catch {
if (this.client.isOpen) this.client.destroy()
throw new Error(
'Redis is unavailable. Check REDIS_URL and service readiness.',
)
}
}
get commands(): RedisCommands {
return this.client
}
close(): Promise<void> {
this.closePromise ??= this.closeClient()
return this.closePromise
}
private async closeClient(): Promise<void> {
this.closing = true
if (!this.client.isOpen) return
try {
await within(this.client.close())
} catch {
if (this.client.isOpen) this.client.destroy()
}
}
}
export class RedisRateLimiter {
constructor(
private readonly client: RedisCommands,
private readonly prefix: string,
) {}
async consume(
bucket: string,
identity: string,
limit: number,
windowMs: number,
): Promise<{ allowed: boolean; retryAfterSeconds: number }> {
if (!this.client.isReady) throw new Error('Redis is unavailable.')
const digest = createHash('sha256').update(identity).digest('hex')
const result = await within(
this.client.eval(windowScript, {
keys: [`${this.prefix}:limit:${bucket}:${digest}`],
arguments: [String(windowMs)],
}),
)
if (
!Array.isArray(result) ||
typeof result[0] !== 'number' ||
typeof result[1] !== 'number' ||
result[1] < 0
) {
throw new Error('Redis returned an invalid rate limit result.')
}
return {
allowed: result[0] <= limit,
retryAfterSeconds: Math.max(1, Math.ceil(result[1] / 1000)),
}
}
}
export class RedisJsonCache {
constructor(
private readonly client: RedisCommands,
private readonly prefix: string,
private readonly sink: LogSink = standardLogSink,
) {}
private key(key: string) {
return `${this.prefix}:cache:${createHash('sha256').update(key).digest('hex')}`
}
async getOrLoad<T>(
key: string,
ttlSeconds: number,
load: () => Promise<T>,
validate?: (value: unknown) => value is T,
): Promise<T> {
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > 86400)
throw new Error('Cache TTL must be between 1 and 86400 seconds.')
try {
if (this.client.isReady) {
const cached = await within(this.client.get(this.key(key)))
if (cached !== null) {
const value: unknown = JSON.parse(cached)
if (!validate || validate(value)) return value as T
}
}
} catch (error) {
writeLog(this.sink, 'warn', 'cache.read_failed', {
code: safeErrorCode(error),
})
}
const value = await load()
try {
if (this.client.isReady)
await within(
this.client.set(this.key(key), JSON.stringify(value), {
EX: ttlSeconds,
}),
)
} catch (error) {
// 缓存只供可重建的读取结果使用,权限和会话从不经过此降级路径。
writeLog(this.sink, 'warn', 'cache.write_failed', {
code: safeErrorCode(error),
})
}
return value
}
async invalidate(key: string): Promise<void> {
await within(this.client.del(this.key(key)))
}
}

View File

@ -0,0 +1,325 @@
import type { Server } from 'node:http'
import type { NestExpressApplication } from '@nestjs/platform-express'
import type {
ErrorRequestHandler,
NextFunction,
Request,
Response,
} from 'express'
import type { ServerConfig } from './config.js'
import {
requestIdFor,
requestRoute,
safeErrorCode,
standardLogSink,
writeLog,
} from './logging.js'
import type { LogSink } from './logging.js'
import { RedisJsonCache, RedisRateLimiter, RedisStore } from './redis.js'
import type { RedisCommands } from './redis.js'
interface RuntimeOptions {
checkDatabase: () => Promise<unknown>
logSink?: LogSink
}
function failure(response: Response, status: number, key: string) {
response
.status(status)
.json({ code: status, msg: key, data: null, error: { key } })
}
export class PlatformRuntime {
readonly cache: RedisJsonCache
private readonly limiter: RedisRateLimiter
private readonly sink: LogSink
private installed = false
constructor(
private readonly config: ServerConfig,
private readonly commands: RedisCommands,
private readonly options: RuntimeOptions,
private readonly closeRedis: () => Promise<void> = async () => {},
) {
this.sink = options.logSink ?? standardLogSink
this.limiter = new RedisRateLimiter(commands, config.redisKeyPrefix)
this.cache = new RedisJsonCache(commands, config.redisKeyPrefix, this.sink)
}
static async create(
config: ServerConfig,
options: RuntimeOptions,
): Promise<PlatformRuntime> {
const store = new RedisStore(config, options.logSink)
await store.connect()
return new PlatformRuntime(config, store.commands, options, () =>
store.close(),
)
}
install(app: NestExpressApplication): void {
if (this.installed)
throw new Error('PlatformRuntime has already been installed.')
this.installed = true
const instance = app.getHttpAdapter().getInstance() as {
set: (key: string, value: unknown) => void
disable: (key: string) => void
}
instance.disable('x-powered-by')
instance.set('trust proxy', this.config.trustProxy)
app.use((request: Request, response: Response, next: NextFunction) => {
const startedAt = performance.now()
const requestId = requestIdFor(request.headers['x-request-id'])
let logged = false
response.locals.requestId = requestId
response.setHeader('X-Request-Id', requestId)
response.setHeader('X-Content-Type-Options', 'nosniff')
response.setHeader('X-Frame-Options', 'DENY')
response.setHeader('Referrer-Policy', 'no-referrer')
response.setHeader('Cross-Origin-Resource-Policy', 'same-site')
response.setHeader(
'Content-Security-Policy',
"default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
)
response.setHeader(
'Permissions-Policy',
'camera=(), microphone=(), geolocation=()',
)
response.setHeader('Cache-Control', 'no-store')
response.vary('Origin')
if (this.config.nodeEnv === 'production')
response.setHeader('Strict-Transport-Security', 'max-age=31536000')
const logRequest = () => {
if (logged) return
logged = true
writeLog(this.sink, 'info', 'http.request', {
requestId,
method: request.method,
route: requestRoute(request),
statusCode: response.writableFinished ? response.statusCode : 499,
durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
})
}
response.once('finish', logRequest)
response.once('close', logRequest)
const origin = request.headers.origin
if (origin && !this.config.corsOrigins.includes(origin)) {
failure(response, 403, 'forbidden')
return
}
if (origin) {
response.setHeader('Access-Control-Allow-Origin', origin)
response.setHeader(
'Access-Control-Expose-Headers',
'X-Request-Id, Retry-After',
)
}
if (request.method === 'OPTIONS') {
response.setHeader(
'Access-Control-Allow-Methods',
'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS',
)
response.setHeader(
'Access-Control-Allow-Headers',
'Authorization, Content-Type, X-Request-Id',
)
response.setHeader('Access-Control-Max-Age', '600')
response.status(204).end()
return
}
next()
})
app.useBodyParser('json', {
limit: this.config.bodyLimitBytes,
strict: true,
})
const parserErrors: ErrorRequestHandler = (
error: unknown,
_request,
response,
next,
) => {
const status =
typeof error === 'object' && error !== null && 'status' in error
? error.status
: null
if (status === 400 || status === 413 || status === 415) {
failure(
response,
status,
status === 413 ? 'payloadTooLarge' : 'invalid',
)
return
}
next(error)
}
app.use(parserErrors)
app.use((request: Request, response: Response, next: NextFunction) => {
if (!request.path.toLowerCase().startsWith('/api/admin/')) {
next()
return
}
void this.limitRequest(request, response)
.then((allowed) => {
if (allowed) next()
})
.catch((error: unknown) => {
writeLog(this.sink, 'error', 'http.rate_limit_unavailable', {
requestId: String(response.locals.requestId),
code: safeErrorCode(error),
})
failure(response, 503, 'serviceUnavailable')
})
})
app.use(
'/api/health/live',
(request: Request, response: Response, next: NextFunction) => {
if (!['GET', 'HEAD'].includes(request.method) || request.path !== '/') {
next()
return
}
response.json({ code: 200, msg: 'OK', data: { status: 'ok' } })
},
)
app.use(
'/api/health/ready',
(request: Request, response: Response, next: NextFunction) => {
if (!['GET', 'HEAD'].includes(request.method) || request.path !== '/') {
next()
return
}
void this.readiness().then((ready) => {
if (ready)
response.json({ code: 200, msg: 'OK', data: { status: 'ready' } })
else failure(response, 503, 'serviceUnavailable')
})
},
)
const server = app.getHttpServer() as Server
server.requestTimeout = this.config.requestTimeoutMs
server.headersTimeout = Math.min(10000, this.config.requestTimeoutMs)
server.keepAliveTimeout = 5000
server.once('close', () => {
void this.close()
})
}
private async limitRequest(
request: Request,
response: Response,
): Promise<boolean> {
const ip = request.ip || request.socket.remoteAddress || 'unknown'
const limits: Array<{
bucket: string
identity: string
limit: number
windowMs: number
}> = [
{
bucket: 'api',
identity: ip,
limit: this.config.rateLimitMax,
windowMs: 60000,
},
]
if (
request.method === 'POST' &&
/^\/api\/admin\/auth\/login\/?$/u.test(request.path.toLowerCase())
) {
limits.push({
bucket: 'login-ip',
identity: ip,
limit: this.config.loginRateLimitMax * 5,
windowMs: 900000,
})
const username: unknown = request.body?.username
if (
typeof username === 'string' &&
username.length <= 80 &&
username.trim()
) {
limits.push({
bucket: 'login-account',
identity: username.trim().toLowerCase(),
limit: this.config.loginRateLimitMax,
windowMs: 900000,
})
}
}
for (const limit of limits) {
const result = await this.limiter.consume(
limit.bucket,
limit.identity,
limit.limit,
limit.windowMs,
)
if (!result.allowed) {
response.setHeader('Retry-After', result.retryAfterSeconds)
failure(response, 429, 'tooManyRequests')
return false
}
}
return true
}
async readiness(): Promise<boolean> {
if (!this.commands.isReady) return false
let timeout: ReturnType<typeof setTimeout>
try {
await Promise.race([
Promise.all([this.options.checkDatabase(), this.commands.ping()]),
new Promise<never>((_, reject) => {
timeout = setTimeout(
() => reject(new Error('Readiness timed out.')),
2000,
)
timeout.unref()
}),
])
return true
} catch {
return false
} finally {
clearTimeout(timeout!)
}
}
async close(): Promise<void> {
await this.closeRedis()
}
}

147
apps/server/src/seed.ts Normal file
View File

@ -0,0 +1,147 @@
import {
permissionCodes,
userInputSchema,
} from '@ray-template/api-contracts/admin'
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 { hashPassword } from './modules/auth/password'
const permissionsFor = (role: string) =>
role === 'admin'
? permissionCodes.filter((code) => code !== 'users:reset')
: role === 'manager'
? [
'users:read',
'users:create',
'users:update',
'users:status',
'routes:read',
]
: ['users:read', 'routes:read']
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 },
update: {},
})
const current = await transaction.user.findUnique({
where: { usernameKey: username.toLowerCase() },
})
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 } },
},
})
if (!existing)
await transaction.auditLog.create({
data: { action: 'system.bootstrap', resourceId: user.id },
})
return { userId: user.id, created: !existing }
},
{ timeout: 15000 },
)
}
export async function setPassword(
database: PrismaClient,
username: string,
password: string,
) {
const passwordHash = await hashPassword(password)
await writeTransaction(database, async (transaction) => {
const user = await transaction.user.findUnique({
where: { usernameKey: username.trim().toLowerCase() },
})
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 },
})
})
}

View File

@ -0,0 +1,725 @@
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { createHash, randomBytes } from 'node:crypto'
import {
copyFile,
mkdir,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { after, before, test } from 'node:test'
import {
loginResultSchema,
sessionSchema,
userListSchema,
userOptionsSchema,
userSchema,
} from '@ray-template/api-contracts/admin'
import type {
AdminUser,
ApiResponse,
LoginResult,
UserInput,
} from '@ray-template/api-contracts/admin'
import {
chartsSchema,
ordersResultSchema,
ownerOptionsSchema,
peopleResultSchema,
requestFixtureSchema,
routeDemoPersonSchema,
routePeopleResultSchema,
searchOptionsSchema,
} from '@ray-template/api-contracts/demo'
import type { RouteConfig } from '@ray-template/api-contracts/routes'
import { parseApplicationRoutes } from '@ray-template/demo-data'
import { Pool } from 'pg'
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 { loadServerConfig } from '../src/platform/index'
import { seedDatabase, setPassword } from '../src/seed'
assert.ok(
process.env.TEST_DATABASE_URL,
'Set TEST_DATABASE_URL to a disposable PostgreSQL database before running server integration tests.',
)
assert.ok(
process.env.TEST_REDIS_URL,
'Set TEST_REDIS_URL to a disposable Redis instance before running server integration tests.',
)
const suffix = randomBytes(8).toString('hex')
const schema = `ray_test_${suffix}`
const databaseUrl = new URL(process.env.TEST_DATABASE_URL)
databaseUrl.searchParams.set('schema', schema)
const pool = new Pool({
connectionString: process.env.TEST_DATABASE_URL,
max: 1,
})
const database = createDatabase(databaseUrl.toString())
const password = `integration-${createToken()}`
const config = loadServerConfig({
NODE_ENV: 'test',
DATABASE_URL: databaseUrl.toString(),
REDIS_URL: process.env.TEST_REDIS_URL,
REDIS_KEY_PREFIX: `ray:test:${suffix}`,
PORT: '0',
SESSION_TTL_SECONDS: '3600',
LOGIN_RATE_LIMIT_MAX: '100',
RATE_LIMIT_MAX: '10000',
})
let app: Awaited<ReturnType<typeof createApp>> | null = null
let base = ''
let adminToken = ''
let adminId = ''
async function request<T = unknown>(
path: string,
options: {
method?: string
body?: unknown
token?: string
origin?: string
} = {},
) {
const response = await fetch(`${options.origin ?? base}/api/${path}`, {
method: options.method ?? 'GET',
headers: {
'Content-Type': 'application/json',
...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),
},
body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
})
return {
status: response.status,
headers: response.headers,
body: (await response.json()) as ApiResponse<T>,
}
}
async function login(username: string, supplied = password) {
const result = await request<LoginResult>('admin/auth/login', {
method: 'POST',
body: { username, password: supplied },
})
assert.equal(result.status, 200)
v.parse(loginResultSchema, result.body.data)
return result.body.data
}
const input = (
username: string,
extra: Partial<UserInput> = {},
): UserInput => ({
username,
email: `${username}@example.com`,
name: username,
phone: '',
departmentId: 'engineering',
role: 'member',
status: 'enabled',
remark: '',
...extra,
})
async function create(username: string, extra: Partial<UserInput> = {}) {
const result = await request<AdminUser>('admin/users', {
method: 'POST',
token: adminToken,
body: input(username, extra),
})
assert.equal(result.status, 200)
v.parse(userSchema, result.body.data)
return result.body.data
}
before(async () => {
await pool.query(`CREATE SCHEMA "${schema}"`)
await pool.query(`SET search_path TO "${schema}"`)
const directory = new URL('../prisma/migrations/', import.meta.url)
const migrations = await readdir(directory, { withFileTypes: true })
for (const migration of migrations
.filter((entry) => entry.isDirectory())
.sort((left, right) => left.name.localeCompare(right.name))) {
await pool.query(
await readFile(
new URL(`${migration.name}/migration.sql`, directory),
'utf8',
),
)
}
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()
adminToken = (await login('admin')).accessToken
})
after(async () => {
await app?.close()
await database.$disconnect()
await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
await pool.end()
const redis = createClient({
url: config.redisUrl,
socket: { connectTimeout: 2000, reconnectStrategy: false },
})
redis.on('error', () => {})
try {
await redis.connect()
const keys = await redis.keys(`${config.redisKeyPrefix}:*`)
if (keys.length) await redis.del(keys)
} finally {
if (redis.isOpen) await redis.quit()
}
})
test('public startup routes, authentication, envelope and current permissions match shared contracts', async () => {
const routes = await request('admin/route-config')
assert.equal(routes.status, 200)
parseApplicationRoutes(JSON.stringify(routes.body.data))
assert.equal((await request('admin/users')).status, 401)
assert.equal((await request('admin/route-config?view=editor')).status, 401)
assert.equal(
(
await request('admin/auth/login', {
method: 'POST',
body: { username: 'admin', password: 'wrong' },
})
).status,
401,
)
const session = await request('admin/auth/session', { token: adminToken })
v.parse(sessionSchema, session.body.data)
assert.ok(session.headers.get('x-request-id'))
const stored = await database.session.findUnique({
where: { tokenHash: tokenHash(adminToken) },
})
assert.ok(stored)
assert.notEqual(stored.tokenHash, adminToken)
const options = await request('admin/users/options', { token: adminToken })
v.parse(userOptionsSchema, options.body.data)
})
test('the development launcher refuses a port already serving backend readiness', async () => {
const fixture = await mkdtemp(join(tmpdir(), 'ray-launcher-'))
try {
await mkdir(join(fixture, 'scripts'))
await mkdir(join(fixture, 'apps/server'), { recursive: true })
await writeFile(join(fixture, 'apps/server/.env.local'), '')
await copyFile(
new URL('../../../scripts/fullstack.mjs', import.meta.url),
join(fixture, 'scripts/fullstack.mjs'),
)
const port = new URL(base).port
const result = spawnSync(
process.execPath,
['scripts/fullstack.mjs', 'dev'],
{
cwd: fixture,
env: {
...process.env,
PORT: port,
ADMIN_DEV_PORT: port === '9527' ? '9528' : '9527',
},
encoding: 'utf8',
timeout: 5000,
},
)
assert.equal(result.status, 1)
assert.match(result.stderr, /Backend port \d+ is not available/u)
assert.equal((await fetch(`${base}/api/health/ready`)).status, 200)
} finally {
await rm(fixture, { force: true, recursive: true })
}
})
test('read-only and manager accounts cannot bypass endpoint or role authorization', async () => {
const reader = await create('reader')
const manager = await create('manager', { role: 'manager' })
await setPassword(database, reader.username, password)
await setPassword(database, manager.username, password)
const memberToken = (await login('reader')).accessToken
const managerToken = (await login('manager')).accessToken
assert.equal(
(await request('admin/route-config?view=editor', { token: memberToken }))
.status,
403,
)
assert.equal(
(
await request('admin/users', {
method: 'POST',
token: memberToken,
body: input('no-create'),
})
).status,
403,
)
assert.equal(
(
await request('admin/users', {
method: 'POST',
token: managerToken,
body: input('no-admin', { role: 'admin' }),
})
).status,
403,
)
assert.equal(
(
await request(`admin/users/${adminId}`, {
method: 'PUT',
token: managerToken,
body: input('admin'),
})
).status,
403,
)
assert.equal(
(
await request('admin/route-config', {
method: 'PUT',
token: memberToken,
body: { version: 1, routes: [] },
})
).status,
403,
)
const list = await request('admin/users?page=1&pageSize=10', {
token: memberToken,
})
v.parse(userListSchema, list.body.data)
})
test('creation, case-insensitive uniqueness, filtering and serialization protect credentials', async () => {
const user = await create('CaseAccount', { departmentId: 'platform' })
const duplicate = await request('admin/users', {
method: 'POST',
token: adminToken,
body: input('caseaccount'),
})
assert.equal(duplicate.status, 409)
assert.equal(duplicate.body.error?.key, 'duplicateUsername')
const duplicateEmail = await request('admin/users', {
method: 'POST',
token: adminToken,
body: input('other-name', { email: 'CASEACCOUNT@EXAMPLE.COM' }),
})
assert.equal(duplicateEmail.status, 409)
assert.equal(duplicateEmail.body.error?.key, 'duplicateEmail')
assert.equal(
(
await request('admin/auth/login', {
method: 'POST',
body: { username: user.username, password },
})
).status,
401,
)
const listed = await request<{ items: AdminUser[]; total: number }>(
'admin/users?departmentId=engineering&name=CaseAccount&page=1&pageSize=1',
{ token: adminToken },
)
assert.equal(listed.body.data.total, 1)
assert.equal(listed.body.data.items[0].id, user.id)
assert.equal(JSON.stringify(listed.body).includes('passwordHash'), false)
assert.equal(JSON.stringify(listed.body).includes('usernameKey'), false)
assert.equal(
(await request('admin/users?page=1&page=2', { token: adminToken })).status,
400,
)
assert.equal(
(await request('admin/users?pageSize=101', { token: adminToken })).status,
400,
)
assert.equal(
(await request('admin/users?page=9007199254740992', { token: adminToken }))
.status,
400,
)
})
test('batch changes are all-or-none and current account remains protected', async () => {
const user = await create('batch-target')
const failedStatus = await request('admin/users/status', {
method: 'PATCH',
token: adminToken,
body: { ids: [user.id, adminId], status: 'disabled' },
})
assert.equal(failedStatus.status, 409)
assert.equal(
(await database.user.findUniqueOrThrow({ where: { id: user.id } })).status,
'enabled',
)
const failedDelete = await request('admin/users/batch-delete', {
method: 'POST',
token: adminToken,
body: { ids: [user.id, 'missing-user'] },
})
assert.equal(failedDelete.status, 404)
assert.ok(await database.user.findUnique({ where: { id: user.id } }))
assert.equal(
(
await request(`admin/users/${adminId}`, {
method: 'PUT',
token: adminToken,
body: input('admin', { role: 'member' }),
})
).status,
409,
)
const deleted = await request<{ affected: number }>(
'admin/users/batch-delete',
{ method: 'POST', token: adminToken, body: { ids: [user.id, user.id] } },
)
assert.equal(deleted.body.data.affected, 1)
})
test('logout, expiry, password reset and disabling an account revoke effective access', async () => {
const user = await create('sessions-user')
await setPassword(database, user.username, password)
const first = await login(user.username)
assert.equal(
(
await request('admin/auth/logout', {
method: 'POST',
token: first.accessToken,
})
).status,
200,
)
assert.equal(
(await request('admin/auth/session', { token: first.accessToken })).status,
401,
)
const expired = await login(user.username)
await database.session.update({
where: { tokenHash: tokenHash(expired.accessToken) },
data: { expiresAt: new Date(Date.now() - 1000) },
})
assert.equal(
(await request('admin/auth/session', { token: expired.accessToken }))
.status,
401,
)
const reset = await login(user.username)
const nextPassword = `${password}x`
await setPassword(database, user.username, nextPassword)
assert.equal(
(await request('admin/auth/session', { token: reset.accessToken })).status,
401,
)
assert.equal(
(
await request('admin/auth/login', {
method: 'POST',
body: { username: user.username, password },
})
).status,
401,
)
const active = await login(user.username, nextPassword)
assert.equal(
(
await request('admin/users/status', {
method: 'PATCH',
token: adminToken,
body: { ids: [user.id], status: 'disabled' },
})
).status,
200,
)
assert.equal(
(await request('admin/auth/session', { token: active.accessToken })).status,
401,
)
await request('admin/users/status', {
method: 'PATCH',
token: adminToken,
body: { ids: [user.id], status: 'enabled' },
})
assert.equal(
(await request('admin/auth/session', { token: active.accessToken })).status,
401,
)
})
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',
)
const bad = await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: {
version: 1,
routes: [{ path: '/unknown', component: 'unknown-view', meta: {} }],
},
})
assert.equal(bad.status, 400)
assert.deepEqual(
(await request('admin/route-config')).body.data,
before.body.data,
)
const valid = {
version: 1,
routes: [
{
path: '/dashboard',
name: 'RDashboard',
component: 'dashboard',
meta: { keepAlive: true, noLocalTitle: 'Integration Dashboard' },
},
],
}
assert.equal(
(
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: valid,
})
).status,
200,
)
await app!.close()
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.equal(
(await request('admin/auth/session', { token: adminToken })).status,
200,
)
const seeded = await seedDatabase(database, { username: 'admin' })
assert.equal(seeded.created, false)
assert.deepEqual((await request('admin/route-config')).body.data, valid)
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: before.body.data,
})
const audit = await database.auditLog.findMany({
where: { action: 'routes.update' },
})
assert.ok(audit.length >= 2)
assert.ok(
audit.every((record) => record.actorId === adminId && record.requestId),
)
assert.equal(JSON.stringify(audit).includes(password), false)
})
test('enabled demos implement the shared API, cache fixed reads and validate input', async () => {
const get = async <S extends v.GenericSchema>(path: string, schema: S) => {
const result = await request(`admin/demo/${path}`)
assert.equal(result.status, 200)
return v.parse(schema, result.body.data)
}
const post = async <S extends v.GenericSchema>(
path: string,
schema: S,
body: unknown,
) => {
const result = await request(`admin/demo/${path}`, { method: 'POST', body })
assert.equal(result.status, 200)
return v.parse(schema, result.body.data)
}
await get('request', requestFixtureSchema)
const charts = await get('charts', chartsSchema)
const refreshed = await get('charts?refresh=true', chartsSchema)
assert.deepEqual(charts.days, refreshed.days)
assert.deepEqual(await get('charts?refresh=false', chartsSchema), charts)
const people = await get(
'people?page=2&pageSize=3&sortAge=ascend',
peopleResultSchema,
)
assert.equal(people.items.length, 3)
assert.ok(people.items[0].age <= people.items[2].age)
const routePeople = await get(
'route-people?page=2&pageSize=2',
routePeopleResultSchema,
)
assert.deepEqual(
routePeople.items.map(({ key }) => key),
[2, 3],
)
assert.deepEqual(
await get('route-people/2', routeDemoPersonSchema),
routePeople.items[0],
)
const english = await get('search-options?locale=en-US', searchOptionsSchema)
const chinese = await get('search-options', searchOptionsSchema)
assert.equal(english.organizations[0].label, 'North')
assert.equal(chinese.organizations[0].label, '北区')
assert.deepEqual(
await post('owners/search', ownerOptionsSchema, {
orgId: 'north',
keyword: 'chen',
locale: 'en-US',
}),
[{ label: 'Chen', value: 'n1' }],
)
const orders = await post('orders/search', ordersResultSchema, {
query: { ownerId: 'n1', page: 2, pageSize: 3 },
locale: 'en-US',
})
assert.ok(orders.total > 3)
assert.equal(orders.items.length, 3)
assert.ok(orders.items.every(({ owner }) => owner === 'Chen'))
assert.equal(
(await request('admin/demo/people?fail=true')).body.error?.key,
'requestFailed',
)
assert.equal((await request('admin/demo/people?fail=yes')).status, 400)
assert.equal((await request('admin/demo/route-people/999')).status, 404)
assert.equal(
(
await request('admin/demo/orders/search', {
method: 'POST',
body: { query: { pageSize: 101 }, locale: 'en-US' },
})
).status,
400,
)
const redis = createClient({ url: config.redisUrl })
await redis.connect()
try {
const digest = createHash('sha256').update('demo:v1:charts').digest('hex')
const key = `${config.redisKeyPrefix}:cache:${digest}`
assert.deepEqual(JSON.parse((await redis.get(key))!), charts)
assert.ok((await redis.ttl(key)) > 0)
} finally {
await redis.quit()
}
})
test('disabling demos hides runtime routes and endpoints without dropping editable routes', async () => {
const original = (await request<RouteConfig>('admin/route-config')).body.data
const full: RouteConfig = {
...original,
routes: [
...original.routes,
{
path: '/extra-demo',
component: 'demo/form',
alias: '/demo-alias',
meta: {},
},
{ path: '/go-demo', redirect: '/demo-alias', meta: {} },
{ path: '/go-home', redirect: '/dashboard', meta: {} },
],
}
assert.equal(
(
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: full,
})
).status,
200,
)
const disabled = await createApp(
{ ...config, demoEnabled: false },
{ logSink: () => {} },
)
try {
await disabled.listen(0, '127.0.0.1')
const origin = await disabled.getUrl()
const runtime = await request<RouteConfig>('admin/route-config', { origin })
assert.equal(runtime.status, 200)
const effective = parseApplicationRoutes(JSON.stringify(runtime.body.data))
assert.equal(JSON.stringify(effective).includes('demo/'), false)
assert.deepEqual(
effective.routes.map(({ path }) => path),
['/dashboard', '/system', '/go-home'],
)
assert.equal((await request('admin/demo/charts', { origin })).status, 404)
assert.equal(
(await request('admin/route-config?view=editor', { origin })).status,
401,
)
assert.deepEqual(
(
await request('admin/route-config?view=editor', {
origin,
token: adminToken,
})
).body.data,
full,
)
} finally {
await disabled.close()
await request('admin/route-config', {
method: 'PUT',
token: adminToken,
body: original,
})
}
})

View File

@ -0,0 +1,428 @@
import assert from 'node:assert/strict'
import { randomUUID } from 'node:crypto'
import type { AddressInfo } from 'node:net'
import { test } from 'node:test'
import { Module } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import type { NestExpressApplication } from '@nestjs/platform-express'
import type { Express, Request, Response } from 'express'
import { loadServerConfig } from '../src/platform/config.js'
import {
requestIdFor,
safeErrorCode,
writeLog,
} from '../src/platform/logging.js'
import {
RedisJsonCache,
RedisRateLimiter,
RedisStore,
} from '../src/platform/redis.js'
import type { RedisCommands } from '../src/platform/redis.js'
import { PlatformRuntime } from '../src/platform/runtime.js'
const config = (extra: NodeJS.ProcessEnv = {}) =>
loadServerConfig({
NODE_ENV: 'test',
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',
REDIS_KEY_PREFIX: `ray:test:${randomUUID()}`,
...extra,
})
class TestRedis implements RedisCommands {
isReady = true
readonly values = new Map<string, string>()
readonly counters = new Map<string, number>()
readonly consumedKeys: string[] = []
async eval(
_script: string,
options: { keys: string[]; arguments: string[] },
) {
const key = options.keys[0]
const count = (this.counters.get(key) ?? 0) + 1
this.counters.set(key, count)
this.consumedKeys.push(key)
return [count, Number(options.arguments[0])]
}
async get(key: string) {
return this.values.get(key) ?? null
}
async set(key: string, value: string) {
this.values.set(key, value)
}
async del(key: string) {
this.values.delete(key)
}
async ping() {
return 'PONG'
}
}
class TestModule {}
Module({})(TestModule)
async function withHttp(
options: {
env?: NodeJS.ProcessEnv
redis?: TestRedis
checkDatabase?: () => Promise<unknown>
},
run: (input: {
url: string
logs: string[]
redis: TestRedis
calls: () => number
}) => Promise<void>,
) {
const redis = options.redis ?? new TestRedis()
const logs: string[] = []
const app = await NestFactory.create<NestExpressApplication>(TestModule, {
logger: false,
bodyParser: false,
})
const runtime = new PlatformRuntime(config(options.env), redis, {
checkDatabase: options.checkDatabase ?? (async () => true),
logSink: (line) => logs.push(line),
})
runtime.install(app)
let calls = 0
const handler = (_request: Request, response: Response) => {
calls += 1
response.json({ code: 200, msg: 'OK', data: null })
}
const express = app.getHttpAdapter().getInstance() as Express
express.post('/api/admin/auth/login', handler)
express.get('/api/admin/users/:id', handler)
await app.listen(0, '127.0.0.1')
const address = app.getHttpServer().address() as AddressInfo
try {
await run({
url: `http://127.0.0.1:${address.port}`,
logs,
redis,
calls: () => calls,
})
} finally {
await app.close()
await runtime.close()
}
}
test('configuration rejects malformed and unsafe inputs without exposing secrets', () => {
const value = config()
assert.equal(value.trustProxy, false)
assert.equal(value.demoEnabled, true)
assert.equal(value.sessionTtlSeconds, 28800)
assert.equal(config({ NODE_ENV: 'production' }).demoEnabled, false)
assert.deepEqual(
config({ TRUST_PROXY: '127.0.0.1,10.0.0.0/8,::1' }).trustProxy,
['127.0.0.1', '10.0.0.0/8', '::1'],
)
for (const env of [
{ CORS_ORIGINS: '*' },
{ CORS_ORIGINS: 'https://example.com/path' },
{ TRUST_PROXY: 'true' },
{ TRUST_PROXY: '1' },
{ TRUST_PROXY: '0.0.0.0/0' },
{ TRUST_PROXY: '::/0' },
{ TRUST_PROXY: '10.0.0.0/99' },
{ NODE_ENV: 'prod' },
{ RATE_LIMIT_MAX: 'Infinity' },
{ SESSION_TTL_SECONDS: '0' },
{ DEMO_ENABLED: 'yes' },
{ REDIS_KEY_PREFIX: 'space is forbidden' },
])
assert.throws(() => config(env))
assert.throws(
() =>
config({ DATABASE_URL: 'mysql://root:private-password@localhost/db' }),
(error: unknown) =>
error instanceof Error && !error.message.includes('private-password'),
)
})
test('logs preserve diagnostic fields while omitting arbitrary secrets and error messages', () => {
const lines: string[] = []
writeLog((line) => lines.push(line), 'warn', 'dependency.failed', {
requestId: 'request-1234',
statusCode: 503,
password: 'secret-password',
accessToken: 'secret-token',
body: { password: 'secret-body' },
} as Parameters<typeof writeLog>[3])
assert.equal(lines.length, 1)
assert.equal(JSON.parse(lines[0]).requestId, 'request-1234')
assert.doesNotMatch(lines[0], /secret|password|accessToken|body/u)
assert.equal(
safeErrorCode({ code: 'ECONNREFUSED', message: 'secret' }),
'ECONNREFUSED',
)
assert.equal(safeErrorCode({ code: 'private-password' }), 'DEPENDENCY_ERROR')
assert.equal(requestIdFor('valid-request-123'), 'valid-request-123')
assert.notEqual(requestIdFor('line\nbreak'), 'line\nbreak')
})
test('HTTP security, CORS and JSON limits run before handlers', async () => {
await withHttp(
{ env: { BODY_LIMIT_BYTES: '1024' } },
async ({ url, calls }) => {
const request = (body: string, origin = 'http://localhost:9527') =>
fetch(`${url}/api/admin/auth/login`, {
method: 'POST',
headers: { 'content-type': 'application/json', origin },
body,
})
const denied = await request(
'{"username":"admin"}',
'https://attacker.example',
)
assert.equal(denied.status, 403)
assert.equal(calls(), 0)
assert.equal(denied.headers.get('x-content-type-options'), 'nosniff')
assert.equal(denied.headers.get('x-powered-by'), null)
const malformed = await request('{invalid-secret')
assert.equal(malformed.status, 400)
assert.doesNotMatch(await malformed.text(), /invalid-secret/u)
const oversized = await request(
JSON.stringify({ password: 'x'.repeat(2048) }),
)
assert.equal(oversized.status, 413)
assert.equal(calls(), 0)
const allowed = await request('{"username":"admin"}')
assert.equal(allowed.status, 200)
assert.equal(
allowed.headers.get('access-control-allow-origin'),
'http://localhost:9527',
)
assert.ok(allowed.headers.get('x-request-id'))
assert.equal(allowed.headers.get('cache-control'), 'no-store')
assert.equal(calls(), 1)
},
)
})
test('login limit normalizes usernames, covers case-insensitive routes and ignores spoofed proxy headers', async () => {
await withHttp(
{ env: { LOGIN_RATE_LIMIT_MAX: '1' } },
async ({ url, redis, calls }) => {
const request = (username: string, forwarded: string, path: string) =>
fetch(`${url}${path}`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-forwarded-for': forwarded,
},
body: JSON.stringify({ username, password: 'secret-password' }),
})
const first = await request('Admin', '1.1.1.1', '/api/admin/auth/login')
const second = await request(
' ADMIN ',
'2.2.2.2',
'/API/ADMIN/AUTH/LOGIN/',
)
assert.equal(first.status, 200)
assert.equal(second.status, 429)
assert.ok(Number(second.headers.get('retry-after')) > 0)
assert.equal(
((await second.json()) as { error: { key: string } }).error.key,
'tooManyRequests',
)
assert.equal(calls(), 1)
const ipKeys = redis.consumedKeys.filter((key) =>
key.includes(':limit:api:'),
)
assert.equal(ipKeys[0], ipKeys[1])
assert.ok(
redis.consumedKeys.every(
(key) => !key.includes('Admin') && !key.includes('secret-password'),
),
)
},
)
})
test('Redis outage fails closed for API access but liveness remains healthy', async () => {
const redis = new TestRedis()
redis.isReady = false
await withHttp({ redis }, async ({ url, calls }) => {
const blocked = await fetch(
`${url}/api/admin/users/secret-id?token=secret-query`,
{ headers: { authorization: 'Bearer secret-token' } },
)
assert.equal(blocked.status, 503)
assert.equal(calls(), 0)
assert.equal((await fetch(`${url}/api/health/live`)).status, 200)
assert.equal((await fetch(`${url}/api/health/ready`)).status, 503)
})
})
test('request logs use route templates and omit credentials, query strings and resource IDs', async () => {
await withHttp({}, async ({ url, logs }) => {
const response = await fetch(
`${url}/api/admin/users/private-user-id?token=private-query`,
{
headers: {
authorization: 'Bearer private-token',
cookie: 'session=private-cookie',
},
},
)
await response.text()
const requests = logs
.map((line) => JSON.parse(line))
.filter((entry) => entry.event === 'http.request')
assert.equal(requests.length, 1)
assert.equal(requests[0].route, '/api/admin/users/:id')
assert.equal(requests[0].statusCode, 200)
assert.doesNotMatch(logs.join('\n'), /private-|authorization|cookie/u)
})
})
test('readiness checks database as well as Redis without exposing connection errors', async () => {
await withHttp(
{
checkDatabase: async () => {
throw new Error('postgresql://private-secret')
},
},
async ({ url }) => {
const response = await fetch(`${url}/api/health/ready`)
assert.equal(response.status, 503)
assert.doesNotMatch(await response.text(), /postgresql|private-secret/u)
},
)
})
test('cache TTL, hits, invalid data and outages preserve loader failures and fresh results', async () => {
const redis = new TestRedis()
const cache = new RedisJsonCache(redis, 'test', () => {})
let calls = 0
const loader = async () => ({ value: ++calls })
const valid = (value: unknown): value is { value: number } =>
typeof value === 'object' &&
value !== null &&
'value' in value &&
typeof value.value === 'number'
assert.deepEqual(await cache.getOrLoad('key', 30, loader, valid), {
value: 1,
})
assert.deepEqual(await cache.getOrLoad('key', 30, loader, valid), {
value: 1,
})
for (const key of redis.values.keys()) redis.values.set(key, '{broken')
assert.deepEqual(await cache.getOrLoad('key', 30, loader, valid), {
value: 2,
})
await cache.invalidate('key')
assert.deepEqual(await cache.getOrLoad('key', 30, loader, valid), {
value: 3,
})
redis.isReady = false
assert.deepEqual(await cache.getOrLoad('key', 30, loader, valid), {
value: 4,
})
await assert.rejects(
() =>
cache.getOrLoad('bad', 30, async () => {
throw new Error('loader failed')
}),
/loader failed/u,
)
await assert.rejects(() => cache.getOrLoad('bad', 0, loader), /TTL/u)
})
test('Redis limiter rejects malformed counters and dependency failures', async () => {
const redis = new TestRedis()
const limiter = new RedisRateLimiter(redis, 'test')
redis.eval = async () => [1, -1]
await assert.rejects(
() => limiter.consume('login', 'admin', 1, 60000),
/invalid/u,
)
redis.isReady = false
await assert.rejects(
() => limiter.consume('login', 'admin', 1, 60000),
/unavailable/u,
)
})
test(
'real Redis rate limits atomically across concurrent callers and expires the bucket',
{ skip: !process.env.TEST_REDIS_URL },
async () => {
const value = config()
const store = new RedisStore(value, () => {})
await store.connect()
try {
const limiter = new RedisRateLimiter(store.commands, value.redisKeyPrefix)
const outcomes = await Promise.all(
Array.from({ length: 25 }, () =>
limiter.consume('login', 'test-user', 10, 10000),
),
)
assert.equal(outcomes.filter((item) => item.allowed).length, 10)
assert.equal(
(await limiter.consume('expiry', 'test-user', 1, 100)).allowed,
true,
)
assert.equal(
(await limiter.consume('expiry', 'test-user', 1, 100)).allowed,
false,
)
await new Promise((resolve) => setTimeout(resolve, 140))
assert.equal(
(await limiter.consume('expiry', 'test-user', 1, 100)).allowed,
true,
)
const cache = new RedisJsonCache(
store.commands,
value.redisKeyPrefix,
() => {},
)
assert.deepEqual(
await cache.getOrLoad('sample', 1, async () => ({ test: true })),
{ test: true },
)
assert.deepEqual(
await cache.getOrLoad('sample', 1, async () => ({ test: false })),
{ test: true },
)
await cache.invalidate('sample')
} finally {
await store.close()
}
},
)

View File

@ -0,0 +1,51 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { userInputSchema } from '@ray-template/api-contracts/admin'
import { ApiError, parseInput, queryInput } from '../src/http'
import {
createToken,
hashPassword,
tokenHash,
validateNewPassword,
verifyPassword,
} from '../src/modules/auth/password'
test('password credentials use independent salts and reject corrupt or incorrect credentials', async () => {
const password = `unit-${createToken()}`
const first = await hashPassword(password)
const second = await hashPassword(password)
assert.notEqual(first, second)
assert.equal(first.includes(password), false)
assert.equal(await verifyPassword(password, first), true)
assert.equal(await verifyPassword(`${password}wrong`, first), false)
assert.equal(await verifyPassword(password, null), false)
assert.equal(await verifyPassword(password, 'scrypt$bad$bad'), false)
assert.throws(() => validateNewPassword('short'))
assert.throws(() => validateNewPassword('x'.repeat(129)))
})
test('session tokens are unguessable identifiers and only their digest is persisted', () => {
const first = createToken()
const second = createToken()
assert.notEqual(first, second)
assert.notEqual(tokenHash(first), first)
assert.equal(tokenHash(first), tokenHash(first))
assert.notEqual(tokenHash(first), tokenHash(second))
})
test('HTTP query conversion rejects arrays and ambiguous numeric strings', () => {
assert.deepEqual(queryInput({ page: '2', pageSize: '25', name: 'Alex' }), {
page: 2,
pageSize: 25,
name: 'Alex',
})
assert.throws(() => queryInput({ page: ['1', '2'] }), ApiError)
assert.throws(() => queryInput({ pageSize: '1e2' }), ApiError)
assert.throws(() => queryInput({ page: '' }), ApiError)
assert.throws(
() => parseInput(userInputSchema, { username: 'bad' }),
ApiError,
)
})

18
apps/server/tsconfig.json Normal file
View File

@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2023"],
"types": ["node"],
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": false,
"skipLibCheck": true
},
"include": ["src/**/*.ts", "test/**/*.ts", "prisma.config.ts"]
}

28
deploy/Dockerfile Normal file
View File

@ -0,0 +1,28 @@
FROM node:26.13.0-bookworm-slim AS node-base
RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
FROM node-base AS workspace
WORKDIR /workspace
RUN npm install --global pnpm@12.16.1
COPY . .
RUN HUSKY=0 pnpm install --frozen-lockfile
FROM workspace AS server-build
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
FROM node-base AS server
WORKDIR /app
COPY --from=server-build --chown=node:node /server .
USER node
EXPOSE 3000
CMD ["node", "dist/main.mjs"]
FROM nginx:stable-alpine AS admin
COPY --from=admin-build /workspace/dist/production /usr/share/nginx/html/ray-template
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

115
deploy/compose.yaml Normal file
View File

@ -0,0 +1,115 @@
x-server-environment: &server-environment
NODE_ENV: production
HOST: 0.0.0.0
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}
DEMO_ENABLED: ${APP_DEMO_ENABLED:-false}
CORS_ORIGINS: ${APP_ORIGINS:-http://127.0.0.1:${APP_PORT:-8080},http://localhost:${APP_PORT:-8080}}
services:
postgres:
image: postgres:18-alpine
environment:
POSTGRES_USER: ${POSTGRES_USER:?Run pnpm fullstack:setup first}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Run pnpm fullstack:setup first}
POSTGRES_DB: ${POSTGRES_DB:-ray_template}
ports:
- '127.0.0.1:${POSTGRES_PORT:-5432}:5432'
volumes:
- postgres:/var/lib/postgresql
healthcheck:
test:
['CMD-SHELL', 'pg_isready -U "$${POSTGRES_USER}" -d "$${POSTGRES_DB}"']
interval: 3s
timeout: 3s
retries: 20
redis:
image: redis:8.2.11-alpine
environment:
REDIS_PASSWORD: ${REDIS_PASSWORD:?Run pnpm fullstack:setup first}
REDISCLI_AUTH: ${REDIS_PASSWORD:?Run pnpm fullstack:setup first}
command:
[
'sh',
'-c',
'exec redis-server --appendonly yes --requirepass "$${REDIS_PASSWORD}"',
]
ports:
- '127.0.0.1:${REDIS_PORT:-6379}:6379'
volumes:
- redis:/data
healthcheck:
test: ['CMD', 'redis-cli', 'ping']
interval: 3s
timeout: 3s
retries: 20
initialize:
profiles: ['app']
build:
context: ..
dockerfile: deploy/Dockerfile
target: server
environment:
<<: *server-environment
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@example.com}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?Run pnpm fullstack:setup first}
command:
[
'sh',
'-c',
'./node_modules/.bin/prisma migrate deploy && node dist/cli.mjs seed',
]
depends_on:
postgres: { condition: service_healthy }
redis: { condition: service_healthy }
server:
profiles: ['app']
build:
context: ..
dockerfile: deploy/Dockerfile
target: server
environment:
<<: *server-environment
TRUST_PROXY: ${APP_PROXY_NETWORK:-172.30.67}.2
LOGIN_RATE_LIMIT_MAX: ${APP_LOGIN_RATE_LIMIT_MAX:-10}
command: ['node', 'dist/main.mjs']
depends_on:
initialize: { condition: service_completed_successfully }
networks: [default, proxy]
healthcheck:
test:
[
'CMD',
'node',
'-e',
'fetch("http://127.0.0.1:3000/api/health/ready").then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))',
]
interval: 10s
timeout: 4s
retries: 5
admin:
profiles: ['app']
build:
context: ..
dockerfile: deploy/Dockerfile
target: admin
ports:
- '127.0.0.1:${APP_PORT:-8080}:80'
networks:
proxy:
ipv4_address: ${APP_PROXY_NETWORK:-172.30.67}.2
depends_on:
server: { condition: service_healthy }
volumes:
postgres:
redis:
networks:
default: {}
proxy:
ipam:
config:
- subnet: ${APP_PROXY_NETWORK:-172.30.67}.0/24
ip_range: ${APP_PROXY_NETWORK:-172.30.67}.128/25

20
deploy/nginx.conf Normal file
View File

@ -0,0 +1,20 @@
server {
listen 80;
server_tokens off;
absolute_redirect off;
root /usr/share/nginx/html;
location = / { return 302 /ray-template/; }
location /api/ {
proxy_pass http://server:3000;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 30s;
client_max_body_size 256k;
}
location /ray-template/ {
try_files $uri $uri/ /ray-template/index.html;
}
}

175
deploy/smoke.mjs Normal file
View File

@ -0,0 +1,175 @@
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { createHash, randomBytes } from 'node:crypto'
import { createServer } from 'node:net'
import { fileURLToPath } from 'node:url'
const root = fileURLToPath(new URL('../', import.meta.url))
const suffix = randomBytes(5).toString('hex')
const project = `ray-smoke-${suffix}`
const password = randomBytes(18).toString('base64url')
const subnet = `10.219.${randomBytes(1)[0]}`
const ports = []
async function reservePort() {
const server = createServer()
await new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', resolve)
})
ports.push(server)
return server.address().port
}
const [postgresPort, redisPort, appPort] = await Promise.all([
reservePort(),
reservePort(),
reservePort(),
])
for (const server of ports) server.close()
const origin = `http://127.0.0.1:${appPort}`
const env = {
...process.env,
POSTGRES_USER: 'ray',
POSTGRES_DB: 'ray_template',
POSTGRES_PASSWORD: randomBytes(18).toString('base64url'),
POSTGRES_PORT: String(postgresPort),
REDIS_PASSWORD: randomBytes(18).toString('base64url'),
REDIS_PORT: String(redisPort),
ADMIN_USERNAME: 'smoke_admin',
ADMIN_EMAIL: 'smoke-admin@example.test',
ADMIN_PASSWORD: password,
APP_PORT: String(appPort),
APP_ORIGINS: '',
APP_PROXY_NETWORK: subnet,
APP_DEMO_ENABLED: 'false',
APP_DATABASE_URL: '',
APP_REDIS_URL: '',
APP_LOGIN_RATE_LIMIT_MAX: '1',
}
function compose(args, capture = false) {
const result = spawnSync(
'docker',
[
'compose',
'--project-name',
project,
'--profile',
'app',
'-f',
'deploy/compose.yaml',
...args,
],
{ cwd: root, env, encoding: 'utf8', stdio: capture ? 'pipe' : 'inherit' },
)
if (result.error || result.status !== 0)
throw new Error(`Docker Compose ${args[0]} failed.`, {
cause: result.error,
})
return result.stdout
}
const api = (path, options) =>
fetch(`${origin}/api/${path}`, {
signal: AbortSignal.timeout(5000),
...options,
})
const login = (username, forwarded) =>
api('admin/auth/login', {
method: 'POST',
headers: {
Origin: origin,
'Content-Type': 'application/json',
'X-Forwarded-For': forwarded,
},
body: JSON.stringify({ username, password }),
})
compose(['config', '--quiet'])
try {
compose(['up', '--build', '--detach', '--wait', '--wait-timeout', '150'])
const entry = await fetch(origin, {
redirect: 'manual',
signal: AbortSignal.timeout(5000),
})
assert.equal(entry.status, 302)
assert.equal(entry.headers.get('location'), '/ray-template/')
const page = await fetch(`${origin}/ray-template/`, {
signal: AbortSignal.timeout(5000),
})
assert.equal(page.status, 200)
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)
const denied = await api('admin/route-config', {
headers: { Origin: 'https://untrusted.example.test' },
})
assert.equal(denied.status, 403)
const response = await login('smoke_admin', '198.51.100.10')
assert.equal(response.status, 200)
assert.equal(response.headers.get('access-control-allow-origin'), origin)
const { data } = await response.json()
assert.equal(
(
await api('admin/users', {
headers: { Authorization: `Bearer ${data.accessToken}` },
})
).status,
200,
)
for (let attempt = 1; attempt <= 5; attempt++) {
assert.equal(
(await login(`unknown-${attempt}`, `198.51.100.${10 + attempt}`)).status,
attempt < 5 ? 401 : 429,
)
}
// 使用 Nginx 实际看到的地址验证限流键,确保没有退回代理自身的地址。
const accessLog = compose(['logs', '--no-log-prefix', 'admin'], true)
const clientIp = /^(\S+) - .*"POST \/api\/admin\/auth\/login /mu.exec(
accessLog,
)?.[1]
assert.ok(clientIp, 'Expected a proxied login in the Nginx access log.')
const digest = createHash('sha256').update(clientIp).digest('hex')
const count = compose(
[
'exec',
'-T',
'redis',
'redis-cli',
'GET',
`ray:production:limit:login-ip:${digest}`,
],
true,
)
assert.equal(count.trim(), '6')
console.log(
'Compose smoke passed: initialized data, built admin, readiness, login, CORS, demo gating and forwarded client rate limits.',
)
} catch (error) {
try {
compose(['logs', '--tail', '25', 'initialize', 'server'])
} catch {
// 可能在镜像构建阶段已失败,保留最初的错误。
}
throw error
} finally {
compose(['down', '--volumes', '--remove-orphans'])
}

View File

@ -13,19 +13,38 @@ Ray Template is a pnpm workspace. The admin application owns host integration, t
| [docs](./), [harness](../harness/README.md) | Maintainer conventions and cross-module explanations. Harness owns task navigation, targeted checks, and evidence. Reader-facing documentation belongs in `apps/docs`. |
| [scripts](../scripts), [vite-helper](../vite-helper), [unplugin](../unplugin) | Repository checks, Vite plugin helpers, and generated auto-import declarations. Build, type, and CI configuration remains at the root. |
| Shared package | Implementation ownership | Host boundary |
| --------------------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| [@ray-template/utils](../packages/utils/package.json) | Precision, type checks, data/file utilities, and generic JSON storage | Callers supply Storage. Application keys, cache backends, and legacy AES formats stay in the application. |
| [@ray-template/composables](../packages/composables/package.json) | Vue composables and DOM, element, and scope utilities | Application-specific navigation, theme, and content-area hooks stay in the application. |
| [@ray-template/directives](../packages/directives/package.json) | Vue directives and registration | The host supplies copy notifications and decides when to register. |
| [@ray-template/icons](../packages/icons/package.json) | SVG files, manifests, icon-name types, and lookups | The build generates spritemaps. The host supplies icon-resolution services. |
| [@ray-template/ui](../packages/ui/package.json) | Shared components, themes, and UI service interfaces | The admin application injects translation, theme, storage, and other services. Application component entry points re-export shared components. |
| [@ray-template/http](../packages/http/package.json) | Independent HTTP clients, interceptors, and cancellation | The application supplies request configuration and interceptors, and wraps business APIs. |
| [@ray-template/api-contracts](../packages/api-contracts/package.json) | Business/demo API types, runtime schemas, and OpenAPI | Independent of browsers and mocks. The application, mocks, and integrating backends share the protocol. |
| [@ray-template/routing](../packages/routing/package.json) | Route configuration validation, expansion, and menu traversal | The application owns the view registry, configuration sources, roles, sessions, and guards. |
| [@ray-template/admin-shell](../packages/admin-shell/package.json) | Layout shell, settings, transitions, and cached-page rendering | The host supplies route state, preferences, navigation, and content slots. |
| Shared package | Implementation ownership | Host boundary |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| [@ray-template/utils](../packages/utils/package.json) | Precision, type checks, data/file utilities, and generic JSON storage | Callers supply Storage. Application keys, cache backends, and legacy AES formats stay in the application. |
| [@ray-template/composables](../packages/composables/package.json) | Vue composables and DOM, element, and scope utilities | Application-specific navigation, theme, and content-area hooks stay in the application. |
| [@ray-template/directives](../packages/directives/package.json) | Vue directives and registration | The host supplies copy notifications and decides when to register. |
| [@ray-template/icons](../packages/icons/package.json) | SVG files, manifests, icon-name types, and lookups | The build generates spritemaps. The host supplies icon-resolution services. |
| [@ray-template/ui](../packages/ui/package.json) | Shared components, themes, and UI service interfaces | The admin application injects translation, theme, storage, and other services. Application component entry points re-export shared components. |
| [@ray-template/http](../packages/http/package.json) | Independent HTTP clients, interceptors, and cancellation | The application supplies request configuration and interceptors, and wraps business APIs. |
| [@ray-template/api-contracts](../packages/api-contracts/package.json) | Business/demo API types, runtime schemas, route contracts, and OpenAPI | Independent of browsers and mocks. The application, mocks, and integrating backends share the protocol. |
| [@ray-template/demo-data](../packages/demo-data/package.json) | Runtime-neutral fixtures, initial route data, and demonstration query helpers | Mock and optional backend consumers decide when demonstration behavior is enabled. |
| [@ray-template/routing](../packages/routing/package.json) | Browser route expansion, menu traversal, and compatibility schema exports | The application owns the view registry, configuration sources, roles, sessions, and guards. |
| [@ray-template/admin-shell](../packages/admin-shell/package.json) | Layout shell, settings, transitions, and cached-page rendering | The host supplies route state, preferences, navigation, and content slots. |
Application `@/components`, `@/hooks`, and `@/utils` include compatibility entry points. Follow actual exports to determine ownership. Shared packages must not depend on application aliases or relative imports across workspaces. The [package-boundary check](../scripts/check-package-boundaries.mjs) validates dependency declarations, public entry points, and cycles.
Application `@/components`, `@/hooks`, and `@/utils` include compatibility entry points. Follow actual exports to determine ownership. Shared packages must not depend on application aliases or relative imports across workspaces. The [package-boundary check](../scripts/check-package-boundaries.mjs) validates dependency declarations, public entry points, and cycles. Each workspace declares `rayTemplate.runtime` as `browser`, `server`, or `universal`: applications cannot be dependencies; universal packages depend only on universal packages; browser/server workspaces cannot import each other. The canonical route schemas and structural validation live in `packages/api-contracts`; `packages/routing` retains compatibility exports and browser view binding. `packages/demo-data/src/routes.json` owns the initial route fixture.
## Source distributions
The [distribution exporter](../scripts/distributions.mjs) creates source directories and `.tar.gz` archives under `dist/distributions`. The frontend edition retains Admin, Docs, and their reachable workspace dependencies, with a pruned lockfile and usable scripts. `distribution.json` records the edition, version, source commit/worktree state, workspace set, file count, and content digest. Explicit source inputs exclude local credentials, dependencies, generated builds, and verification evidence.
Markdown blocks delimited by the HTML comment markers `fullstack:start` and `fullstack:end` are removed from frontend exports. Keep references to omitted server files inside these blocks. Export is local only; branch/Release publication is a separate integration step. Read the [distribution guide](../apps/docs/guide/distributions.md) for user commands.
<!-- fullstack:start -->
## Optional server workspace
[apps/server](../apps/server) owns NestJS controllers/services, PostgreSQL persistence through Prisma, migrations, credential initialization, authorization, and audit records. It consumes only universal workspace packages and keeps ORM models out of browser contracts. [Platform infrastructure](../apps/server/src/platform/README.md) owns Redis rate limits/cache, request IDs and redacted JSON logs, security headers, CORS, health probes, and resource shutdown. Database sessions and authorization are never cached.
The [fullstack launcher](../scripts/fullstack.mjs) creates private local configuration once, starts PostgreSQL/Redis through [Compose](../deploy/compose.yaml), migrates/seeds without resetting existing accounts, and waits for backend readiness before starting Vite with a same-origin API proxy. External databases are supported through `setup --external`. Fullstack source export adds this workspace and its deployment configuration. Docker and production deployment require independent runtime acceptance.
The server has its own [TypeScript configuration](../apps/server/tsconfig.json) and build output. Tests under `apps/server/test` use Node's test runner; database integration tests require explicit test PostgreSQL and Redis URLs. Frontend builds do not initialize server resources.
<!-- fullstack:end -->
## Key runtime flows
@ -45,13 +64,14 @@ Maintain guides and runnable examples for public behavior changes through [appli
The [root configuration](../tsconfig.json) references four projects. Strict mode, module resolution, and type-checking aliases live in the [shared configuration](../tsconfig.base.json). When changing aliases, check [Vite](../vite.custom.config.ts) and [Vitest](../vitest.config.ts) as well.
| Configuration | Coverage |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Application](../tsconfig.app.json) | Admin `apps/admin/src`, Vue JSX, and generated declarations. |
| [Node](../tsconfig.node.json) | Root build/test configuration, `vite-helper`, and build helpers. |
| [Tests](../tsconfig.test.json) | `__test__` and referenced source, loading Vitest and Node types. Vitest configuration and individual test files determine the runtime environment. |
| [Shared packages](../tsconfig.packages.json) | `packages/*/src`, without inheriting application aliases or auto-import declarations. |
| [Documentation site](../apps/docs/tsconfig.json) | Independent documentation-example checks, run by `pnpm docs:check`. |
| Configuration | Coverage |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Application](../tsconfig.app.json) | Admin `apps/admin/src`, Vue JSX, and generated declarations. |
| [Node](../tsconfig.node.json) | Root build/test configuration, `vite-helper`, and build helpers. |
| [Tests](../tsconfig.test.json) | `__test__` and referenced source, loading Vitest and Node types. Vitest configuration and individual test files determine the runtime environment. |
| [Shared packages](../tsconfig.packages.json) | `packages/*/src`, without inheriting application aliases or auto-import declarations. |
| [Universal contracts/data](../tsconfig.universal.json) | Node-only type-checking environment for API contracts and demo data; no browser DOM library. |
| [Documentation site](../apps/docs/tsconfig.json) | Independent documentation-example checks, run by `pnpm docs:check`. |
`pnpm typecheck` first validates icon synchronization, then runs `vue-tsc --build` for the four projects referenced by the root configuration. Incremental caches live in `node_modules/.cache/ray-template/`. Use `pnpm exec vue-tsc -p <configuration-file>` for an individual project.

View File

@ -23,7 +23,7 @@ The site targets v6. Source links use monorepo paths, and release builds use `RA
## Pending reader-guide updates
Application evidence is available in the [routing integration guide](../apps/admin/src/router/README.md), [schema](../packages/routing/src/schema.ts), [Segment notes](../packages/ui/src/RSegment/README.md), and [page design guide](ui-design.md). Add source switching, API examples, and version validation to `apps/docs/guide/routing.md`; document `fitContent` selection states and transitions in the component reference. Use updated login and management-page screenshots and check deployment subpaths.
Application evidence is available in the [routing integration guide](../apps/admin/src/router/README.md), [schema](../packages/api-contracts/src/routes.ts), [Segment notes](../packages/ui/src/RSegment/README.md), and [page design guide](ui-design.md). Add source switching, API examples, and version validation to `apps/docs/guide/routing.md`; document `fitContent` selection states and transitions in the component reference. Use updated login and management-page screenshots and check deployment subpaths.
Update `guide/layout.md` for reduced motion and the floating exit button. Add visual and JSON entry points to `guide/routing.md`, making clear that applying visual configuration stores it only in the current browser. Explain in `reference/hooks/layout.md` that loading indicators are positioned relative to the visible content area.

View File

@ -237,3 +237,14 @@ Translated agent entry points, Harness topics and workflow, internal architectur
### Remote CI follow-up
The [historical Ubuntu failure](https://github.com/XiaoDaiGua-Ray/ray-template/actions/runs/41588971650) was in `detectOperatingSystem.spec.ts`: the test read the Linux runner's actual user agent but always expected `Unknown`. Commit `83bada95` covers systems with mocked user agents and touch-point counts. [CI](https://github.com/XiaoDaiGua-Ray/ray-template/actions/runs/41612553267) for recorded baseline `80e80775` passed Ubuntu, macOS, Windows, and deployment. The matrix continues to run the same `pnpm check`.
<!-- fullstack:start -->
## 2026-11-06: Optional server and source distributions checkpoint
Added explicit browser/server/universal workspace ownership, universal route contracts and shared demo fixtures, and independent frontend/fullstack source exports with pruned lockfiles. The optional server pins NestJS 12.3.3, Prisma 7.10.1, node-redis 6.3.1 and esbuild 0.28.2. Prisma runtime checks and migration-engine downloads are explicitly allowed. The documentation still uses Vite 6; its Vue Router runtime does not load the optional Vite plugin, so that single peer combination is explicitly recorded in the workspace config.
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.
<!-- fullstack:end -->

View File

@ -14,6 +14,9 @@ export default defineConfig([
'**/coverage/**',
'**/.ai-local/**',
'**/.harness-local/**',
'**/dist-test/**',
'apps/server/src/generated/**',
'**/.pnpm-store/**',
'**/public/**',
'**/playground-dist/**',
'unplugin/**',

View File

@ -65,12 +65,12 @@ GitHub Actions runs the same `pnpm check` on Linux, Windows, and macOS. Use `pnp
Use browser verification only for changes to visible effects, user actions, or browser-specific capabilities. Maintainer documentation, comments, tests, Harness changes, and logic changes with no page impact do not trigger UI/UX verification. Reader-documentation wording corrections can be checked in source and with formatting tools; open the relevant page when rendering structure, example interaction, or layout is at risk. Report missing required browser evidence accurately; screenshots do not replace functional regressions.
By default, use `pnpm dev` and open `http://127.0.0.1:9527/ray-template/`. Reproduce the affected page and action flow with local demo data, and inspect relevant console errors. Add dimensions below only when their corresponding behavior changes. Do not exhaustively combine pages, languages, themes, and viewports.
By default, use `pnpm dev` and open `http://127.0.0.1:9527/ray-template/`. Verify the affected page and action flow in one locale with local demo data, and check the DevTools Console for relevant warnings and errors. Missing-key warnings cover translation lookups performed in development. Add dimensions below only when their corresponding behavior changes.
| Change | Additional checks |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local interaction, validation, or state | Affected action and relevant success, failure, or recovery paths. Check keyboard operation when keyboard/focus behavior changes. |
| Copy or internationalization | Chinese and English on the affected page, interpolation, and fallback behavior. Check wrapping when text length affects layout. |
| Copy or internationalization | Check changed keys in both language files. Test locale switching, interpolation, fallback, and text wrapping where affected. |
| Layout, sizing, scrolling, or responsiveness | The affected area at desktop and narrow widths, such as 390px. Check only affected layout modes and long content. |
| Themes, colors, or shared visual variables | Light/dark themes and relevant readability. Select representative actual consumers of shared styles. |
| Routing, permissions, or cache behavior | Menu entry, direct navigation, reload, and restoration for relevant roles/sources. Do not recheck unrelated pages. |

View File

@ -4,7 +4,7 @@ Use this topic to add pages or menus, debug direct navigation and reloads, or ch
| Question | Read first | Follow through |
| --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Static page registration and menu order | [Initial route JSON](../../apps/admin/src/mocks/data/routes.json), [route module assembly](../../apps/admin/src/router/app-route-modules.ts) | [Views](../../apps/admin/src/views), [menu store](../../apps/admin/src/store/modules/menu/index.ts), [shared route expansion](../../packages/routing/src/expand-routes.ts) |
| Static page registration and menu order | [Initial route JSON](../../packages/demo-data/src/routes.json), [route module assembly](../../apps/admin/src/router/app-route-modules.ts) | [Views](../../apps/admin/src/views), [menu store](../../apps/admin/src/store/modules/menu/index.ts), [shared route expansion](../../packages/routing/src/expand-routes.ts) |
| Dynamic JSON fields, validation errors, and allowed views | [Shared schema](../../packages/routing/src/schema.ts), [JSON Schema export](../../packages/routing/src/json-schema.ts), [application view-ID registry](../../apps/admin/src/router/config/views.ts) | [Application binding](../../apps/admin/src/router/config/contract.ts), [management page](../../apps/admin/src/views/route-management), [reader guide](../../apps/docs/guide/routing.md) |
| Static, local, and remote sources and fallback | [Source loading and saving](../../apps/admin/src/router/config/source.ts) | [Router initialization](../../apps/admin/src/router/index.ts), [registered routes](../../apps/admin/src/router/routes.ts) |
| Menu visibility, direct access, and post-login landing | [Navigation guards](../../apps/admin/src/router/utils/permission.ts), [route and allowlist configuration](../../apps/admin/src/app-config/router-config.ts) | [Menu visibility](../../apps/admin/src/router/utils/valid-menu-item-show.ts), [session store](../../apps/admin/src/store/modules/signing/index.ts), [shared navigation traversal](../../packages/routing/src/navigation.ts) |

13
harness/context/server.md Normal file
View File

@ -0,0 +1,13 @@
# Optional NestJS server
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).
- [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.
- [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.
`pnpm harness verify server` runs type checks, unit/platform tests, and the backend build without requiring PostgreSQL. Real HTTP integration is explicit: set `TEST_DATABASE_URL` and `TEST_REDIS_URL`, then run `pnpm server:test:integration`. Tests own random schemas/prefixes and clean only those resources. Run the full Harness at integration completion and browser verification for the affected login, user and routing flows. Container builds and remote publication require independent evidence.

View File

@ -1,5 +1,50 @@
# AI Harness development plan
<!-- fullstack:start -->
## 2026-11-06: Optional backend and source distributions
The approved scope is one development workspace with independently usable frontend and fullstack source distributions, followed by a NestJS backend. Backend security, authentication, Redis, logging, and operational foundations are part of this batch. No remote commit, branch publication, release, or deployment is authorized by this implementation task.
1. Establish application isolation and universal contract boundaries. Move route schemas and reusable demo fixtures into browser-independent workspace packages; preserve frontend compatibility entry points.
2. Export frontend and fullstack source trees and archives from the same source, including independent frozen-installable lockfiles. Exclude secrets, local evidence, dependencies, and build outputs. Prepare release/branch automation without publishing it.
3. Add NestJS and PostgreSQL persistence behind the existing API contract. Preserve Bearer sessions for this integration; cookie authentication is a separate protocol migration. Include revocation, RBAC, atomic writes, account protection, audit records, Redis limits/cache, configuration validation, sanitized logs, health checks, and graceful shutdown.
4. Provide repeatable setup, local fullstack orchestration, Compose configuration, database migrations, and credential provisioning without fixed passwords. Preserve existing data on repeated setup.
Acceptance: both distributions pass isolated frozen installation and their checks/builds; backend HTTP tests use real PostgreSQL and Redis; frontend mock mode and the real-backend login/user/route flows work in a browser; full Harness checks pass once after integration. Docker/remote workflows require separate evidence and must not be reported as verified without execution. Local reports belong in `.harness-local/`.
Parallel ownership: the lead owns integration, shared packages, package-boundary checks, launchers and documentation; distribution and backend agents own their assigned new files, with platform infrastructure isolated under the server's `src/platform` directory.
### Pause checkpoint requested by the user
The user requested an active pause before 17:55 Asia/Shanghai on 2026-11-06 because connectivity will end at 18:00. Resume this implementation in the same worktree; changes are uncommitted and unpublished.
Implemented: workspace runtime ownership checks; shared universal route schemas/semantic parser and generated view/icon catalog; shared demo fixtures; independent frontend/fullstack source export with pruned lockfiles and provenance; NestJS core auth/users/routes with PostgreSQL persistence, scrypt passwords, hashed opaque tokens, live authorization, atomic writes and audit; Redis limits/cache infrastructure, configuration validation, sanitized logs, CORS/security headers, health and shutdown; setup/Compose/development launchers; bilingual delivery and backend documentation. `pnpm fullstack:setup` replaces the proposed `pnpm setup` because the latter is a pnpm builtin. Login demo buttons are now restricted to Mock mode; real sign-in inputs use username/current-password autofill, stable names and required fields.
Observed validation before pause:
- Frontend checks: 103 Vitest files / 535 tests, types, lint, format, API/package checks, production build and documentation build passed. Full `pnpm harness verify all` passed; report: `.harness-local/runs/all-JcqVqb/report.json`, log: `.harness-local/full-check.log`.
- Server: type check/build and 13 unit/platform tests passed, including real Redis. Six HTTP integration tests passed on real PostgreSQL and Redis, covering authorization, uniqueness, transaction atomicity, revocation, semantic route validation, process restart persistence and repeat seed.
- Real `pnpm fullstack:setup --external` passed Prisma migrate deploy and administrator initialization in an isolated local PostgreSQL schema. The generated private `.env.local` is ignored and must never enter artifacts or logs.
- Frontend source archive extracted outside the repository passed frozen install, package/Harness/API checks and production build. The source exporter passed nine regression cases. Fullstack source projection passed structural checks; its standalone installation is still pending.
- Local PostgreSQL 18.6 and Redis 8.2.11 binaries are retained under `.harness-local/services/`. Their test endpoints were localhost ports 15432/16379; services must be restarted before real integration tests. Both temporary services were stopped before the pause.
Remaining work at the pause, in order:
1. Implement the optional Nest demo endpoints using shared fixtures and the Redis read cache. The backend currently implements core admin endpoints only; existing frontend demo/chart calls are not yet served. Ensure `DEMO_ENABLED=false` has an explicit menu/endpoint policy.
2. Run actual `pnpm dev:full` startup/shutdown/error-path checks and browser acceptance for mock and real-backend login, user operations, permissions, route saves and reloads. Login gating/autofill changes have source/build verification only.
3. Validate the isolated fullstack archive, package deploy output and Compose images. Docker is absent locally; the container definitions are unverified. Verify forwarded client IP trust, origins and non-default ports before calling container setup production-ready.
4. Implement source-release artifact and generated frontend-branch workflow (currently not written). No branch, tag, release, commit or deployment has been published; obtain required Git/publication authorization before those remote actions.
5. Review combined changes, add focused missing regressions (launcher and real-backend login/demo flows), rerun only affected checks after fixes, and regenerate final archives. Preserve the initial one-mainline/two-distribution design and production credential separation.
Modern Web Guidance applied: `autofill-sign-in-form` ("Use `autocomplete="current-password"` for the password input in a sign-in form") and `forms` ("turn off text correction on fields that hold identifiers rather than prose"). The retrieved guide is retained at `/var/folders/3n/76yvbw114mn8205ykb9npv2r0000gn/T/mwg-guide-73479-1793958308167.md`; browser acceptance is pending.
### Resumed implementation
The same worktree now includes the demo controllers and shared queries, the protected editor snapshot, the hardened dev launcher and Compose entry point, and a manually dispatched source distribution workflow. Mock and backend mode were exercised in Chrome with isolated test data, including real sign-in, user changes, read-only permissions, route persistence, and demo reads. The workflow can verify and archive a source revision, update the generated `frontend` branch, or attach assets to an existing release. Local acceptance evidence is kept in `.harness-local/fullstack-resume/`; remote workflow execution and publication require a separate authorized run.
<!-- fullstack:end -->
The goal is to help developers and AI agents taking over Ray Template find relevant code by task, reproduce checks independently, and pass observed results to the next maintainer. Entry points and commands are in the [AI Harness](README.md).
| Phase | Work | Acceptance criteria |

View File

@ -23,6 +23,7 @@ const allowedChecks = new Set([
'docs:check',
'icons:check',
'packages:check',
'server:check',
'typecheck',
])
const indexFiles = [

View File

@ -72,10 +72,15 @@
},
"toolchain": {
"description": "Workspaces, public exports, type checking, Vite, builds, and CI",
"checks": ["packages:check", "typecheck"]
"checks": ["packages:check", "typecheck"],
"tests": ["__test__/workspace/boundaries.spec.ts", "__test__/distribution/"]
},
"harness": {
"description": "Indexes, regression scope, verification commands, and local reports",
"tests": ["__test__/harness/"]
},
"server": {
"description": "Optional backend, PostgreSQL, Redis, security, sessions, and startup",
"checks": ["server:check"]
}
}

View File

@ -6,6 +6,10 @@ Follow [AGENTS.md](AGENTS.md) and select the entry point for the task. Read this
## Task index
<!-- fullstack:start -->
- [server](harness/context/server.md): Optional NestJS backend, PostgreSQL, Redis, security, authentication, logs, and source distributions.
<!-- fullstack:end -->
- [routing](harness/context/routing.md): Pages and menus, dynamic route JSON, view IDs, roles, and guards.
- [layout](harness/context/layout.md): Bootstrap, providers, navigation, KeepAlive, Pinia, and preference import/export.
- [ui](harness/context/ui.md): Shared components, pages and login, themes and bilingual copy, hooks, and directives.

Some files were not shown because too many files have changed in this diff Show More