feat: add control plane authentication baseline

This commit is contained in:
wlx committed 2026-08-21 15:47:57 +08:00
1 parent a4c93ff1a7
commit 0d10e2d124
21 files changed
+1403 -18

No files matched your search

+5
View File
@@ -3,3 +3,8 @@ prototype/dist/
infra/otari/.env infra/otari/.env
infra/otari/config.yml infra/otari/config.yml
infra/otari/service_account.json infra/otari/service_account.json
control-plane/node_modules/
control-plane/dist/
control-plane/.env
infra/control-plane/.env
prototype/.env
+2
View File
@@ -305,6 +305,8 @@ MaaS 模型服务与应用开发
Otari 本地网关基座位于 `infra/otari/`,仅用于后续联调和开发环境,不包含真实供应商密钥。 Otari 本地网关基座位于 `infra/otari/`,仅用于后续联调和开发环境,不包含真实供应商密钥。
身份与权限服务位于 `control-plane/`,本地 PostgreSQL 基座位于 `infra/control-plane/`;认证接口、邀请码和角色守卫将在 D3 逐步接入前端。
```bash ```bash
cd prototype cd prototype
pnpm install pnpm install
+11
View File
@@ -0,0 +1,11 @@
NODE_ENV=development
CONTROL_PLANE_HOST=127.0.0.1
CONTROL_PLANE_PORT=8787
CONTROL_PLANE_CORS_ORIGINS=http://localhost:5173
DATABASE_URL=postgresql://moyi:replace-with-a-long-random-password@127.0.0.1:5434/moyi_control
SESSION_TTL_HOURS=168
AUTH_PASSWORD_PEPPER=replace-with-a-long-random-secret
ADMIN_ACCOUNT=admin@moyi.local
ADMIN_PASSWORD=replace-with-a-strong-initial-password
ADMIN_DISPLAY_NAME=平台管理员
+36
View File
@@ -0,0 +1,36 @@
# MOYI Control Plane
D3 的身份与权限服务,负责邀请码注册、登录会话、用户角色、管理员接口和认证审计。它与 Otari 分离,前端不直接持有 Otari Master Key 或供应商密钥。
## 本地开发
\`\`\`powershell
cd control-plane
Copy-Item .env.example .env
pnpm install
pnpm migrate
pnpm seed:admin
pnpm dev
\`\`\`
默认监听 \`http://127.0.0.1:8787\`。没有设置 \`DATABASE_URL\` 时,服务可以使用内存仓库启动,用于接口联调;正式开发和测试应使用 PostgreSQL。
## 接口
- \`POST /api/auth/register\`:邀请码注册,账号支持邮箱或手机号。
- \`POST /api/auth/login\`:账号密码登录,返回 HttpOnly 会话 Cookie。
- \`GET /api/auth/me\`:读取当前会话用户。
- \`POST /api/auth/logout\`:撤销当前会话。
- \`GET /api/admin/users\`:管理员用户列表。
- \`GET|POST /api/admin/invitations\`:管理员查看或生成邀请码。
- \`POST /api/admin/invitations/:id/revoke\`:停用邀请码。
- \`GET /api/admin/audit\`:管理员查看认证审计。
第一版暂不实现短信/邮件真实验证码;注册页面保留验证码入口但不以它作为后端注册条件,邀请码、邮箱/手机号和账号密码是当前有效的注册条件。
## 安全约束
- 数据库仅保存密码哈希、邀请码摘要和会话摘要,不保存明文密码、明文邀请码或会话 Token。
- 生产环境必须设置随机的 \`AUTH_PASSWORD_PEPPER\`、强管理员密码和 HTTPS。
- 管理员接口由 Control Plane 服务端角色校验保护,隐藏前端菜单不构成权限控制。
- 迁移文件只创建认证相关表,额度、模型和 Key 表在后续 D4 节点加入。
+61
View File
@@ -0,0 +1,61 @@
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
account varchar(320) NOT NULL UNIQUE,
account_kind varchar(16) NOT NULL CHECK (account_kind IN ('email', 'phone')),
password_hash text NOT NULL,
display_name varchar(80) NOT NULL,
role varchar(16) NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')),
status varchar(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
last_login_at timestamptz
);
CREATE TABLE IF NOT EXISTS invitation_codes (
id uuid PRIMARY KEY,
code_hash char(64) NOT NULL UNIQUE,
code_prefix varchar(12) NOT NULL,
label varchar(100) NOT NULL,
max_uses integer NOT NULL DEFAULT 1 CHECK (max_uses > 0),
used_count integer NOT NULL DEFAULT 0 CHECK (used_count >= 0 AND used_count <= max_uses),
expires_at timestamptz,
disabled_at timestamptz,
created_by uuid NOT NULL REFERENCES users(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS invitation_redemptions (
invitation_id uuid NOT NULL REFERENCES invitation_codes(id),
user_id uuid NOT NULL REFERENCES users(id),
redeemed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (invitation_id, user_id)
);
CREATE TABLE IF NOT EXISTS auth_sessions (
id uuid PRIMARY KEY,
token_hash char(64) NOT NULL UNIQUE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz NOT NULL DEFAULT now(),
user_agent text,
ip_address inet
);
CREATE INDEX IF NOT EXISTS auth_sessions_user_id_idx ON auth_sessions(user_id);
CREATE INDEX IF NOT EXISTS auth_sessions_expires_at_idx ON auth_sessions(expires_at);
CREATE TABLE IF NOT EXISTS auth_audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
actor_user_id uuid REFERENCES users(id),
event_type varchar(64) NOT NULL,
target_type varchar(32),
target_id text,
ip_address inet,
user_agent text,
details jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_audit_log_created_at_idx ON auth_audit_log(created_at DESC);
+23
View File
@@ -0,0 +1,23 @@
{
"name": "@moyi/control-plane",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "node --env-file=.env --import tsx --watch src/server.ts",
"build": "tsc -p tsconfig.json",
"start": "node --env-file=.env dist/src/server.js",
"migrate": "node --env-file=.env --import tsx src/migrate.ts",
"seed:admin": "node --env-file=.env --import tsx src/seed-admin.ts",
"test": "tsx --test tests/**/*.test.ts",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"pg": "^8.13.1"
},
"devDependencies": {
"@types/node": "^22.10.1",
"tsx": "^4.19.2",
"typescript": "~5.7.2"
}
}
+431
View File
@@ -0,0 +1,431 @@
import {
createHash,
randomBytes,
randomUUID,
scryptSync,
timingSafeEqual,
} from 'node:crypto'
export type UserRole = 'user' | 'admin'
export type UserStatus = 'active' | 'disabled'
export type AccountKind = 'email' | 'phone'
export interface UserRecord {
id: string
account: string
accountKind: AccountKind
passwordHash: string
displayName: string
role: UserRole
status: UserStatus
createdAt: string
updatedAt: string
lastLoginAt?: string
}
export interface InvitationRecord {
id: string
codeHash: string
codePrefix: string
label: string
maxUses: number
usedCount: number
expiresAt?: string
disabledAt?: string
createdBy: string
createdAt: string
}
export interface SessionRecord {
id: string
tokenHash: string
userId: string
expiresAt: string
revokedAt?: string
createdAt: string
lastSeenAt: string
userAgent?: string
ipAddress?: string
}
export interface AuditRecord {
id: string
actorUserId?: string
eventType: string
targetType?: string
targetId?: string
ipAddress?: string
userAgent?: string
details: Record<string, unknown>
createdAt: string
}
export interface RequestMeta {
ipAddress?: string
userAgent?: string
}
export interface AuthRepository {
findUserByAccount(account: string): Promise<UserRecord | undefined>
findUserById(id: string): Promise<UserRecord | undefined>
listUsers(): Promise<UserRecord[]>
createUser(user: UserRecord): Promise<void>
createInvitedUser(user: UserRecord, invitationId: string, at: string): Promise<boolean>
updateLastLogin(userId: string, at: string): Promise<void>
findInvitationByHash(codeHash: string): Promise<InvitationRecord | undefined>
createInvitation(invitation: InvitationRecord): Promise<void>
listInvitations(): Promise<InvitationRecord[]>
revokeInvitation(invitationId: string, at: string): Promise<boolean>
createSession(session: SessionRecord): Promise<void>
findSessionByHash(tokenHash: string): Promise<SessionRecord | undefined>
revokeSession(sessionId: string, at: string): Promise<void>
createAudit(record: AuditRecord): Promise<void>
listAudit(limit: number): Promise<AuditRecord[]>
}
export class MemoryAuthRepository implements AuthRepository {
private readonly users = new Map<string, UserRecord>()
private readonly invitations = new Map<string, InvitationRecord>()
private readonly sessions = new Map<string, SessionRecord>()
private readonly audits: AuditRecord[] = []
private readonly redemptions = new Set<string>()
async findUserByAccount(account: string) {
return [...this.users.values()].find((user) => user.account === account)
}
async findUserById(id: string) {
return this.users.get(id)
}
async listUsers() {
return [...this.users.values()].sort((left, right) => right.createdAt.localeCompare(left.createdAt))
}
async createUser(user: UserRecord) {
if ([...this.users.values()].some((existing) => existing.account === user.account)) {
throw new Error('ACCOUNT_EXISTS')
}
this.users.set(user.id, user)
}
async createInvitedUser(user: UserRecord, invitationId: string, at: string) {
const invitation = this.invitations.get(invitationId)
if (
!invitation
|| invitation.disabledAt
|| (invitation.expiresAt && invitation.expiresAt <= at)
|| invitation.usedCount >= invitation.maxUses
|| [...this.users.values()].some((existing) => existing.account === user.account)
) return false
const redemptionKey = `${invitationId}:${user.id}`
this.users.set(user.id, user)
this.redemptions.add(redemptionKey)
this.invitations.set(invitationId, { ...invitation, usedCount: invitation.usedCount + 1 })
return true
}
async updateLastLogin(userId: string, at: string) {
const user = this.users.get(userId)
if (user) this.users.set(userId, { ...user, lastLoginAt: at, updatedAt: at })
}
async findInvitationByHash(codeHash: string) {
return [...this.invitations.values()].find((invitation) => invitation.codeHash === codeHash)
}
async createInvitation(invitation: InvitationRecord) {
this.invitations.set(invitation.id, invitation)
}
async listInvitations() {
return [...this.invitations.values()].sort((left, right) => right.createdAt.localeCompare(left.createdAt))
}
async revokeInvitation(invitationId: string, at: string) {
const invitation = this.invitations.get(invitationId)
if (!invitation || invitation.disabledAt) return false
this.invitations.set(invitationId, { ...invitation, disabledAt: at })
return true
}
async createSession(session: SessionRecord) {
this.sessions.set(session.id, session)
}
async findSessionByHash(tokenHash: string) {
return [...this.sessions.values()].find((session) => session.tokenHash === tokenHash)
}
async revokeSession(sessionId: string, at: string) {
const session = this.sessions.get(sessionId)
if (session) this.sessions.set(sessionId, { ...session, revokedAt: at })
}
async createAudit(record: AuditRecord) {
this.audits.push(record)
}
async listAudit(limit: number) {
return this.audits.slice(-limit).reverse()
}
}
export interface AuthServiceOptions {
sessionTtlHours: number
passwordPepper: string
}
export interface PublicUser {
id: string
account: string
accountKind: AccountKind
displayName: string
role: UserRole
status: UserStatus
createdAt: string
lastLoginAt?: string
}
export class AuthError extends Error {
constructor(readonly code: string, message: string, readonly statusCode = 400) {
super(message)
}
}
export class AuthService {
constructor(
private readonly repository: AuthRepository,
private readonly options: AuthServiceOptions,
) {}
async ensureAdmin(account: string, password: string, displayName: string) {
const normalizedAccount = normalizeAccount(account)
if (!normalizedAccount || !password) throw new AuthError('INVALID_ADMIN_CONFIG', '管理员初始配置无效', 500)
if (await this.repository.findUserByAccount(normalizedAccount)) return
const now = new Date().toISOString()
await this.repository.createUser({
id: randomUUID(),
account: normalizedAccount,
accountKind: accountKind(normalizedAccount),
passwordHash: hashPassword(password, this.options.passwordPepper),
displayName: displayName.trim() || '平台管理员',
role: 'admin',
status: 'active',
createdAt: now,
updatedAt: now,
})
}
async register(input: { invitationCode: string; account: string; password: string; displayName?: string }, meta: RequestMeta) {
const account = normalizeAccount(input.account)
const displayName = input.displayName?.trim() || account.split('@')[0] || 'MOYI 用户'
validateAccount(account)
validatePassword(input.password)
if (!input.invitationCode.trim()) throw new AuthError('INVITATION_REQUIRED', '第一版注册需要邀请码')
if (await this.repository.findUserByAccount(account)) throw new AuthError('ACCOUNT_EXISTS', '账号已注册', 409)
const invitation = await this.repository.findInvitationByHash(hashSecret(input.invitationCode.trim()))
if (!invitation) throw new AuthError('INVITATION_INVALID', '邀请码无效或已失效', 403)
const now = new Date().toISOString()
const user: UserRecord = {
id: randomUUID(),
account,
accountKind: accountKind(account),
passwordHash: hashPassword(input.password, this.options.passwordPepper),
displayName,
role: 'user',
status: 'active',
createdAt: now,
updatedAt: now,
}
if (!await this.repository.createInvitedUser(user, invitation.id, now)) {
throw new AuthError('INVITATION_EXHAUSTED', '邀请码无效、已用尽或账号已注册', 403)
}
await this.audit('user.registered', user.id, meta, { invitationId: invitation.id })
return { user: toPublicUser(user), session: await this.createSession(user, meta) }
}
async login(input: { account: string; password: string }, meta: RequestMeta) {
const account = normalizeAccount(input.account)
const user = await this.repository.findUserByAccount(account)
if (!user || !verifyPassword(input.password, user.passwordHash, this.options.passwordPepper)) throw new AuthError('INVALID_CREDENTIALS', '账号或密码错误', 401)
if (user.status !== 'active') throw new AuthError('ACCOUNT_DISABLED', '账号已停用', 403)
const now = new Date().toISOString()
await this.repository.updateLastLogin(user.id, now)
await this.audit('user.logged_in', user.id, meta, {})
return { user: toPublicUser({ ...user, lastLoginAt: now }), session: await this.createSession(user, meta) }
}
async currentUser(token: string | undefined) {
const session = await this.session(token)
return session ? toPublicUser(session.user) : undefined
}
async revoke(token: string | undefined, meta: RequestMeta) {
const session = await this.session(token)
if (!session) return
const now = new Date().toISOString()
await this.repository.revokeSession(session.session.id, now)
await this.audit('user.logged_out', session.user.id, meta, {})
}
async requireUser(token: string | undefined) {
const session = await this.session(token)
if (!session) throw new AuthError('UNAUTHENTICATED', '请先登录', 401)
return session.user
}
async requireAdmin(token: string | undefined) {
const user = await this.requireUser(token)
if (user.role !== 'admin') throw new AuthError('FORBIDDEN', '需要管理员权限', 403)
return user
}
async listUsers(token: string | undefined) {
await this.requireAdmin(token)
return (await this.repository.listUsers()).map(toPublicUser)
}
async createInvitation(token: string | undefined, input: { label?: string; maxUses?: number; expiresAt?: string }, meta: RequestMeta) {
const admin = await this.requireAdmin(token)
const code = `moyi_${randomBytes(9).toString('base64url')}`
const now = new Date().toISOString()
const invitation: InvitationRecord = {
id: randomUUID(),
codeHash: hashSecret(code),
codePrefix: code.slice(0, 10),
label: input.label?.trim() || '内测邀请码',
maxUses: Math.max(1, Math.floor(input.maxUses || 1)),
usedCount: 0,
...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),
createdBy: admin.id,
createdAt: now,
}
await this.repository.createInvitation(invitation)
await this.audit('invitation.created', admin.id, meta, { invitationId: invitation.id, label: invitation.label })
return { code, invitation: redactInvitation(invitation) }
}
async listInvitations(token: string | undefined) {
await this.requireAdmin(token)
return (await this.repository.listInvitations()).map(redactInvitation)
}
async revokeInvitation(token: string | undefined, invitationId: string, meta: RequestMeta) {
const admin = await this.requireAdmin(token)
const changed = await this.repository.revokeInvitation(invitationId, new Date().toISOString())
if (!changed) throw new AuthError('INVITATION_NOT_FOUND', '邀请码不存在或已停用', 404)
await this.audit('invitation.revoked', admin.id, meta, { invitationId })
}
async audit(eventType: string, actorUserId: string | undefined, meta: RequestMeta, details: Record<string, unknown>) {
await this.repository.createAudit({
id: randomUUID(),
...(actorUserId ? { actorUserId } : {}),
eventType,
...(meta.ipAddress ? { ipAddress: meta.ipAddress } : {}),
...(meta.userAgent ? { userAgent: meta.userAgent } : {}),
details,
createdAt: new Date().toISOString(),
})
}
async listAudit(token: string | undefined, limit = 100) {
await this.requireAdmin(token)
return this.repository.listAudit(Math.min(Math.max(limit, 1), 200))
}
private async createSession(user: UserRecord, meta: RequestMeta) {
const token = randomBytes(32).toString('base64url')
const now = new Date()
const session: SessionRecord = {
id: randomUUID(),
tokenHash: hashSecret(token),
userId: user.id,
expiresAt: new Date(now.getTime() + this.options.sessionTtlHours * 60 * 60 * 1000).toISOString(),
createdAt: now.toISOString(),
lastSeenAt: now.toISOString(),
...(meta.userAgent ? { userAgent: meta.userAgent } : {}),
...(meta.ipAddress ? { ipAddress: meta.ipAddress } : {}),
}
await this.repository.createSession(session)
return token
}
private async session(token: string | undefined) {
if (!token) return undefined
const session = await this.repository.findSessionByHash(hashSecret(token))
if (!session || session.revokedAt || session.expiresAt <= new Date().toISOString()) return undefined
const user = await this.repository.findUserById(session.userId)
if (!user || user.status !== 'active') return undefined
return { session, user }
}
}
export function normalizeAccount(value: string) {
const normalized = value.trim().toLowerCase()
return normalized.includes('@') ? normalized : normalized.replace(/[\s-]/g, '')
}
export function accountKind(account: string): AccountKind {
return account.includes('@') ? 'email' : 'phone'
}
export function validateAccount(account: string) {
const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(account) || /^\+?[0-9][0-9\s-]{6,19}$/.test(account)
if (!valid) throw new AuthError('INVALID_ACCOUNT', '请输入有效的邮箱或手机号')
}
export function validatePassword(password: string) {
if (password.length < 8) throw new AuthError('WEAK_PASSWORD', '密码至少需要 8 位')
}
export function hashPassword(password: string, pepper: string) {
const salt = randomBytes(16)
const hash = scryptSync(password, Buffer.concat([salt, Buffer.from(pepper)]), 64, { N: 16384, r: 8, p: 1 })
return `scrypt$16384$8$1$${salt.toString('base64url')}$${hash.toString('base64url')}`
}
export function verifyPassword(password: string, encoded: string, pepper: string) {
const [, n, r, p, saltText, hashText] = encoded.split('$')
if (!n || !r || !p || !saltText || !hashText) return false
try {
const salt = Buffer.from(saltText, 'base64url')
const expected = Buffer.from(hashText, 'base64url')
const actual = scryptSync(password, Buffer.concat([salt, Buffer.from(pepper)]), expected.length, { N: Number(n), r: Number(r), p: Number(p) })
return expected.length === actual.length && timingSafeEqual(expected, actual)
} catch {
return false
}
}
export function hashSecret(value: string) {
return createHash('sha256').update(value).digest('hex')
}
function toPublicUser(user: UserRecord): PublicUser {
return {
id: user.id,
account: user.account,
accountKind: user.accountKind,
displayName: user.displayName,
role: user.role,
status: user.status,
createdAt: user.createdAt,
...(user.lastLoginAt ? { lastLoginAt: user.lastLoginAt } : {}),
}
}
function redactInvitation(invitation: InvitationRecord) {
return {
id: invitation.id,
codePrefix: invitation.codePrefix,
label: invitation.label,
maxUses: invitation.maxUses,
usedCount: invitation.usedCount,
expiresAt: invitation.expiresAt,
disabledAt: invitation.disabledAt,
createdBy: invitation.createdBy,
createdAt: invitation.createdAt,
}
}
+23
View File
@@ -0,0 +1,23 @@
import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { resolve } from 'node:path'
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) throw new Error('DATABASE_URL is required')
interface PgPool {
query(text: string, values?: unknown[]): Promise<unknown>
end(): Promise<void>
}
interface PgPoolConstructor {
new (options: { connectionString: string }): PgPool
}
const runtimeRequire = createRequire(import.meta.url)
const { Pool } = runtimeRequire('pg') as { Pool: PgPoolConstructor }
const pool = new Pool({ connectionString: databaseUrl })
const migration = await readFile(resolve(process.cwd(), 'migrations/001_auth.sql'), 'utf8')
await pool.query(migration)
await pool.end()
console.log('Applied migration 001_auth.sql')
+224
View File
@@ -0,0 +1,224 @@
import { createRequire } from 'node:module'
import type {
AuditRecord,
AuthRepository,
InvitationRecord,
SessionRecord,
UserRecord,
} from './auth.js'
interface QueryResult {
rows: Record<string, unknown>[]
rowCount: number | null
}
interface PgClient {
query(text: string, values?: unknown[]): Promise<QueryResult>
release(): void
}
interface PgPool {
query(text: string, values?: unknown[]): Promise<QueryResult>
connect(): Promise<PgClient>
end(): Promise<void>
}
interface PgPoolConstructor {
new (options: { connectionString: string; max?: number }): PgPool
}
const runtimeRequire = createRequire(import.meta.url)
const { Pool } = runtimeRequire('pg') as { Pool: PgPoolConstructor }
export class PostgresAuthRepository implements AuthRepository {
readonly pool: PgPool
constructor(databaseUrl: string) {
this.pool = new Pool({ connectionString: databaseUrl, max: 10 })
}
async findUserByAccount(account: string) {
const result = await this.pool.query('SELECT * FROM users WHERE account = $1 LIMIT 1', [account])
return result.rows[0] ? userFromRow(result.rows[0]) : undefined
}
async findUserById(id: string) {
const result = await this.pool.query('SELECT * FROM users WHERE id = $1 LIMIT 1', [id])
return result.rows[0] ? userFromRow(result.rows[0]) : undefined
}
async listUsers() {
const result = await this.pool.query('SELECT * FROM users ORDER BY created_at DESC')
return result.rows.map(userFromRow)
}
async createUser(user: UserRecord) {
await this.pool.query(
`INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at, last_login_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[user.id, user.account, user.accountKind, user.passwordHash, user.displayName, user.role, user.status, user.createdAt, user.updatedAt, user.lastLoginAt ?? null],
)
}
async createInvitedUser(user: UserRecord, invitationId: string, at: string) {
const client = await this.pool.connect()
try {
await client.query('BEGIN')
const invitationResult = await client.query(
`SELECT * FROM invitation_codes
WHERE id = $1 AND disabled_at IS NULL AND used_count < max_uses
AND (expires_at IS NULL OR expires_at > $2)
FOR UPDATE`,
[invitationId, at],
)
if (!invitationResult.rows[0]) {
await client.query('ROLLBACK')
return false
}
await client.query(
`INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at, last_login_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[user.id, user.account, user.accountKind, user.passwordHash, user.displayName, user.role, user.status, user.createdAt, user.updatedAt, user.lastLoginAt ?? null],
)
await client.query(
'INSERT INTO invitation_redemptions (invitation_id, user_id, redeemed_at) VALUES ($1, $2, $3)',
[invitationId, user.id, at],
)
await client.query('UPDATE invitation_codes SET used_count = used_count + 1 WHERE id = $1', [invitationId])
await client.query('COMMIT')
return true
} catch (error) {
await client.query('ROLLBACK')
if (isUniqueViolation(error)) return false
throw error
} finally {
client.release()
}
}
async updateLastLogin(userId: string, at: string) {
await this.pool.query('UPDATE users SET last_login_at = $2, updated_at = $2 WHERE id = $1', [userId, at])
}
async findInvitationByHash(codeHash: string) {
const result = await this.pool.query('SELECT * FROM invitation_codes WHERE code_hash = $1 LIMIT 1', [codeHash])
return result.rows[0] ? invitationFromRow(result.rows[0]) : undefined
}
async createInvitation(invitation: InvitationRecord) {
await this.pool.query(
`INSERT INTO invitation_codes (id, code_hash, code_prefix, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[invitation.id, invitation.codeHash, invitation.codePrefix, invitation.label, invitation.maxUses, invitation.usedCount, invitation.expiresAt ?? null, invitation.disabledAt ?? null, invitation.createdBy, invitation.createdAt],
)
}
async listInvitations() {
const result = await this.pool.query('SELECT * FROM invitation_codes ORDER BY created_at DESC')
return result.rows.map(invitationFromRow)
}
async revokeInvitation(invitationId: string, at: string) {
const result = await this.pool.query(
'UPDATE invitation_codes SET disabled_at = $2 WHERE id = $1 AND disabled_at IS NULL',
[invitationId, at],
)
return result.rowCount === 1
}
async createSession(session: SessionRecord) {
await this.pool.query(
`INSERT INTO auth_sessions (id, token_hash, user_id, expires_at, revoked_at, created_at, last_seen_at, user_agent, ip_address)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[session.id, session.tokenHash, session.userId, session.expiresAt, session.revokedAt ?? null, session.createdAt, session.lastSeenAt, session.userAgent ?? null, session.ipAddress ?? null],
)
}
async findSessionByHash(tokenHash: string) {
const result = await this.pool.query('SELECT * FROM auth_sessions WHERE token_hash = $1 LIMIT 1', [tokenHash])
return result.rows[0] ? sessionFromRow(result.rows[0]) : undefined
}
async revokeSession(sessionId: string, at: string) {
await this.pool.query('UPDATE auth_sessions SET revoked_at = $2, last_seen_at = $2 WHERE id = $1', [sessionId, at])
}
async createAudit(record: AuditRecord) {
await this.pool.query(
`INSERT INTO auth_audit_log (actor_user_id, event_type, target_type, target_id, ip_address, user_agent, details, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)`,
[record.actorUserId ?? null, record.eventType, record.targetType ?? null, record.targetId ?? null, record.ipAddress ?? null, record.userAgent ?? null, JSON.stringify(record.details), record.createdAt],
)
}
async listAudit(limit: number) {
const result = await this.pool.query('SELECT * FROM auth_audit_log ORDER BY created_at DESC LIMIT $1', [limit])
return result.rows.map(auditFromRow)
}
async close() {
await this.pool.end()
}
}
function userFromRow(row: Record<string, unknown>): UserRecord {
return {
id: String(row.id),
account: String(row.account),
accountKind: row.account_kind as UserRecord['accountKind'],
passwordHash: String(row.password_hash),
displayName: String(row.display_name),
role: row.role as UserRecord['role'],
status: row.status as UserRecord['status'],
createdAt: new Date(String(row.created_at)).toISOString(),
updatedAt: new Date(String(row.updated_at)).toISOString(),
...(row.last_login_at ? { lastLoginAt: new Date(String(row.last_login_at)).toISOString() } : {}),
}
}
function invitationFromRow(row: Record<string, unknown>): InvitationRecord {
return {
id: String(row.id),
codeHash: String(row.code_hash),
codePrefix: String(row.code_prefix),
label: String(row.label),
maxUses: Number(row.max_uses),
usedCount: Number(row.used_count),
...(row.expires_at ? { expiresAt: new Date(String(row.expires_at)).toISOString() } : {}),
...(row.disabled_at ? { disabledAt: new Date(String(row.disabled_at)).toISOString() } : {}),
createdBy: String(row.created_by),
createdAt: new Date(String(row.created_at)).toISOString(),
}
}
function sessionFromRow(row: Record<string, unknown>): SessionRecord {
return {
id: String(row.id),
tokenHash: String(row.token_hash),
userId: String(row.user_id),
expiresAt: new Date(String(row.expires_at)).toISOString(),
...(row.revoked_at ? { revokedAt: new Date(String(row.revoked_at)).toISOString() } : {}),
createdAt: new Date(String(row.created_at)).toISOString(),
lastSeenAt: new Date(String(row.last_seen_at)).toISOString(),
...(row.user_agent ? { userAgent: String(row.user_agent) } : {}),
...(row.ip_address ? { ipAddress: String(row.ip_address) } : {}),
}
}
function auditFromRow(row: Record<string, unknown>): AuditRecord {
return {
id: String(row.id),
...(row.actor_user_id ? { actorUserId: String(row.actor_user_id) } : {}),
eventType: String(row.event_type),
...(row.target_type ? { targetType: String(row.target_type) } : {}),
...(row.target_id ? { targetId: String(row.target_id) } : {}),
...(row.ip_address ? { ipAddress: String(row.ip_address) } : {}),
...(row.user_agent ? { userAgent: String(row.user_agent) } : {}),
details: (row.details || {}) as Record<string, unknown>,
createdAt: new Date(String(row.created_at)).toISOString(),
}
}
function isUniqueViolation(error: unknown): boolean {
return Boolean(error && typeof error === 'object' && 'code' in error && error.code === '23505')
}
+26
View File
@@ -0,0 +1,26 @@
import { AuthService } from './auth.js'
import { PostgresAuthRepository } from './postgres.js'
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) throw new Error('DATABASE_URL is required')
const repository = new PostgresAuthRepository(databaseUrl)
const auth = new AuthService(repository, {
sessionTtlHours: Number(process.env.SESSION_TTL_HOURS || 168),
passwordPepper: process.env.AUTH_PASSWORD_PEPPER || 'development-only-pepper',
})
await auth.ensureAdmin(
process.env.ADMIN_ACCOUNT || 'admin@moyi.local',
requiredEnvironment('ADMIN_PASSWORD'),
process.env.ADMIN_DISPLAY_NAME || '平台管理员',
)
await repository.close()
console.log(`Admin account ensured: ${process.env.ADMIN_ACCOUNT || 'admin@moyi.local'}`)
function requiredEnvironment(name: string) {
const value = process.env[name]
if (!value || value.startsWith('replace-with-')) throw new Error(`${name} must be set to a non-placeholder value`)
return value
}
+228
View File
@@ -0,0 +1,228 @@
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
import { parse as parseUrl } from 'node:url'
import { AuthError, AuthService, MemoryAuthRepository, type AuthRepository } from './auth.js'
const config = {
host: process.env.CONTROL_PLANE_HOST || '127.0.0.1',
port: Number(process.env.CONTROL_PLANE_PORT || 8787),
corsOrigins: (process.env.CONTROL_PLANE_CORS_ORIGINS || 'http://localhost:5173').split(',').map((origin) => origin.trim()).filter(Boolean),
sessionTtlHours: Number(process.env.SESSION_TTL_HOURS || 168),
passwordPepper: process.env.AUTH_PASSWORD_PEPPER || 'development-only-pepper',
databaseUrl: process.env.DATABASE_URL,
nodeEnv: process.env.NODE_ENV || 'development',
}
let repository: AuthRepository = new MemoryAuthRepository()
if (config.databaseUrl) {
const { PostgresAuthRepository } = await import('./postgres.js')
repository = new PostgresAuthRepository(config.databaseUrl)
}
const auth = new AuthService(repository, {
sessionTtlHours: config.sessionTtlHours,
passwordPepper: config.passwordPepper,
})
if (config.nodeEnv === 'production' && (!process.env.AUTH_PASSWORD_PEPPER || process.env.AUTH_PASSWORD_PEPPER.length < 32)) {
throw new Error('AUTH_PASSWORD_PEPPER must contain at least 32 characters in production')
}
if (!config.databaseUrl) {
await auth.ensureAdmin(
process.env.ADMIN_ACCOUNT || 'demo@moyi.ai',
process.env.ADMIN_PASSWORD || 'moyi-demo',
process.env.ADMIN_DISPLAY_NAME || '林默',
)
}
const authAttempts = new Map<string, { count: number; resetAt: number }>()
const server = createServer(async (request, response) => {
const origin = request.headers.origin
if (origin && config.corsOrigins.includes(origin)) {
response.setHeader('Access-Control-Allow-Origin', origin)
response.setHeader('Access-Control-Allow-Credentials', 'true')
response.setHeader('Vary', 'Origin')
}
if (request.method === 'OPTIONS') {
response.setHeader('Access-Control-Allow-Headers', 'Content-Type')
response.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
response.writeHead(204)
response.end()
return
}
try {
await route(request, response)
} catch (error) {
handleError(response, error)
}
})
server.listen(config.port, config.host, () => {
console.log(`MOYI Control Plane listening on http://${config.host}:${config.port}`)
console.log(config.databaseUrl ? 'Persistence: PostgreSQL' : 'Persistence: in-memory development store')
})
async function route(request: IncomingMessage, response: ServerResponse) {
const parsed = parseUrl(request.url || '/', true)
const method = request.method || 'GET'
const path = parsed.pathname || '/'
const meta = {
...(request.socket.remoteAddress ? { ipAddress: request.socket.remoteAddress } : {}),
...(request.headers['user-agent'] ? { userAgent: request.headers['user-agent'] } : {}),
}
const token = readCookie(request.headers.cookie, 'moyi_session')
if (method === 'GET' && path === '/health') {
send(response, 200, { status: 'ok', service: 'moyi-control-plane' })
return
}
if (method === 'POST' && path === '/api/auth/register') {
enforceAuthRateLimit(request, 'register')
const body = await readJson(request)
const result = await auth.register({
invitationCode: stringValue(body.invitationCode),
account: stringValue(body.account),
password: stringValue(body.password),
...(body.displayName ? { displayName: stringValue(body.displayName) } : {}),
}, meta)
setSessionCookie(response, result.session)
send(response, 201, { user: result.user })
return
}
if (method === 'POST' && path === '/api/auth/login') {
enforceAuthRateLimit(request, 'login')
const body = await readJson(request)
const result = await auth.login({
account: stringValue(body.account),
password: stringValue(body.password),
}, meta)
setSessionCookie(response, result.session)
send(response, 200, { user: result.user })
return
}
if (method === 'POST' && path === '/api/auth/logout') {
await auth.revoke(token, meta)
clearSessionCookie(response)
send(response, 204, undefined)
return
}
if (method === 'GET' && path === '/api/auth/me') {
const user = await auth.requireUser(token)
send(response, 200, { user })
return
}
if (method === 'GET' && path === '/api/admin/users') {
send(response, 200, { users: await auth.listUsers(token) })
return
}
if (method === 'GET' && path === '/api/admin/invitations') {
send(response, 200, { invitations: await auth.listInvitations(token) })
return
}
if (method === 'POST' && path === '/api/admin/invitations') {
const body = await readJson(request)
const result = await auth.createInvitation(token, {
...(body.label ? { label: stringValue(body.label) } : {}),
...(body.maxUses !== undefined ? { maxUses: Number(body.maxUses) } : {}),
...(body.expiresAt ? { expiresAt: stringValue(body.expiresAt) } : {}),
}, meta)
send(response, 201, result)
return
}
const invitationMatch = path.match(/^\/api\/admin\/invitations\/([^/]+)\/revoke$/)
const invitationId = invitationMatch?.[1]
if (method === 'POST' && invitationId) {
await auth.revokeInvitation(token, invitationId, meta)
send(response, 204, undefined)
return
}
if (method === 'GET' && path === '/api/admin/audit') {
send(response, 200, { events: await auth.listAudit(token, Number(parsed.query.limit || 100)) })
return
}
send(response, 404, { error: { code: 'NOT_FOUND', message: '接口不存在' } })
}
async function readJson(request: IncomingMessage): Promise<Record<string, unknown>> {
let body = ''
for await (const chunk of request) {
body += chunk.toString()
if (body.length > 1_000_000) throw new AuthError('PAYLOAD_TOO_LARGE', '请求体过大', 413)
}
if (!body) return {}
try {
const value: unknown = JSON.parse(body)
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not object')
return value as Record<string, unknown>
} catch {
throw new AuthError('INVALID_JSON', '请求体必须是有效 JSON')
}
}
function stringValue(value: unknown) {
return typeof value === 'string' ? value : ''
}
function enforceAuthRateLimit(request: IncomingMessage, action: string) {
const now = Date.now()
const key = `${action}:${request.socket.remoteAddress || 'unknown'}`
const current = authAttempts.get(key)
if (!current || current.resetAt <= now) {
authAttempts.set(key, { count: 1, resetAt: now + 15 * 60 * 1000 })
return
}
current.count += 1
if (current.count > 20) throw new AuthError('TOO_MANY_ATTEMPTS', '尝试次数过多,请稍后重试', 429)
}
function readCookie(header: string | undefined, name: string) {
const pair = header?.split(';').map((part) => part.trim()).find((part) => part.startsWith(`${name}=`))
return pair ? decodeURIComponent(pair.slice(name.length + 1)) : undefined
}
function setSessionCookie(response: ServerResponse, token: string) {
const secure = config.nodeEnv === 'production' ? '; Secure' : ''
response.setHeader('Set-Cookie', `moyi_session=${encodeURIComponent(token)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=${config.sessionTtlHours * 60 * 60}${secure}`)
}
function clearSessionCookie(response: ServerResponse) {
response.setHeader('Set-Cookie', 'moyi_session=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0')
}
function send(response: ServerResponse, statusCode: number, payload: unknown) {
response.statusCode = statusCode
if (statusCode === 204) {
response.end()
return
}
response.setHeader('Content-Type', 'application/json; charset=utf-8')
response.end(JSON.stringify(payload))
}
function handleError(response: ServerResponse, error: unknown) {
if (error instanceof AuthError) {
send(response, error.statusCode, { error: { code: error.code, message: error.message } })
return
}
console.error(error)
send(response, 500, { error: { code: 'INTERNAL_ERROR', message: '服务暂时不可用' } })
}
async function close() {
if ('close' in repository && typeof repository.close === 'function') await repository.close()
server.close()
}
process.once('SIGINT', close)
process.once('SIGTERM', close)
+81
View File
@@ -0,0 +1,81 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
AuthError,
AuthService,
MemoryAuthRepository,
hashSecret,
} from '../src/auth.js'
function createHarness() {
const repository = new MemoryAuthRepository()
const auth = new AuthService(repository, {
sessionTtlHours: 24,
passwordPepper: 'test-pepper',
})
return { repository, auth }
}
test('administrator creates an invitation and a user redeems it once', async () => {
const { auth } = createHarness()
await auth.ensureAdmin('admin@moyi.test', 'admin-password', '测试管理员')
const adminLogin = await auth.login({ account: 'admin@moyi.test', password: 'admin-password' }, {})
const created = await auth.createInvitation(adminLogin.session, { label: '首批用户', maxUses: 1 }, {})
assert.match(created.code, /^moyi_/)
const registered = await auth.register({
invitationCode: created.code,
account: 'user@moyi.test',
password: 'user-password',
displayName: '测试用户',
}, {})
assert.equal(registered.user.role, 'user')
assert.equal(registered.user.displayName, '测试用户')
await assert.rejects(
auth.register({
invitationCode: created.code,
account: 'second@moyi.test',
password: 'user-password',
}, {}),
(error: unknown) => error instanceof AuthError && error.code === 'INVITATION_EXHAUSTED',
)
})
test('ordinary users cannot access administrator operations', async () => {
const { auth } = createHarness()
await auth.ensureAdmin('admin@moyi.test', 'admin-password', '测试管理员')
const adminLogin = await auth.login({ account: 'admin@moyi.test', password: 'admin-password' }, {})
const invitation = await auth.createInvitation(adminLogin.session, {}, {})
const registered = await auth.register({
invitationCode: invitation.code,
account: 'user@moyi.test',
password: 'user-password',
}, {})
await assert.rejects(
auth.listUsers(registered.session),
(error: unknown) => error instanceof AuthError && error.statusCode === 403,
)
})
test('logout revokes the server-side session', async () => {
const { auth } = createHarness()
await auth.ensureAdmin('admin@moyi.test', 'admin-password', '测试管理员')
const login = await auth.login({ account: 'admin@moyi.test', password: 'admin-password' }, {})
assert.equal((await auth.currentUser(login.session))?.role, 'admin')
await auth.revoke(login.session, {})
assert.equal(await auth.currentUser(login.session), undefined)
})
test('stored invitation values are hashes rather than plaintext', async () => {
const { auth, repository } = createHarness()
await auth.ensureAdmin('admin@moyi.test', 'admin-password', '测试管理员')
const login = await auth.login({ account: 'admin@moyi.test', password: 'admin-password' }, {})
const created = await auth.createInvitation(login.session, {}, {})
const stored = await repository.findInvitationByHash(hashSecret(created.code))
assert.equal(stored?.codeHash, hashSecret(created.code))
assert.notEqual(stored?.codeHash, created.code)
})
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": ".",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts", "tests/**/*.ts"]
}
@@ -113,7 +113,7 @@ POST /v1/tasks
| D0 原型基线 | 固化品牌、用户端、管理端和认证流程 | Vue 可交互原型 | 已完成,提交 `bebff16` | | D0 原型基线 | 固化品牌、用户端、管理端和认证流程 | Vue 可交互原型 | 已完成,提交 `bebff16` |
| D1 网关适配契约 | 固化开源边界和前端网关接口 | 本文档、类型化 Gateway Client、演示适配器 | 类型检查和前端构建通过 | | D1 网关适配契约 | 固化开源边界和前端网关接口 | 本文档、类型化 Gateway Client、演示适配器 | 类型检查和前端构建通过 |
| D2 Otari 本地基座 | 运行锁定版本的 Otari 与持久化数据库 | Compose、环境模板、健康检查、启动说明 | 重启后配置和用量可持久化 | | D2 Otari 本地基座 | 运行锁定版本的 Otari 与持久化数据库 | Compose、环境模板、健康检查、启动说明 | 重启后配置和用量可持久化 |
| D3 身份与权限 | 实现邀请码、登录、会话、角色与管理端守卫 | Control Plane 认证 API、数据库迁移、前端真实登录 | 普通用户无法访问管理 API | | D3 身份与权限 | 实现邀请码、登录、会话、角色与管理端守卫 | Control Plane 认证 API、数据库迁移、前端认证客户端、测试 | 普通用户无法访问管理 API |
| D4 密钥与模型目录 | 打通 MOYI Key、网关 Key、模型目录和权限 | Key API、模型 Schema、Otari 映射、管理页面 | 创建 Key 后可完成一次真实调用 | | D4 密钥与模型目录 | 打通 MOYI Key、网关 Key、模型目录和权限 | Key API、模型 Schema、Otari 映射、管理页面 | 创建 Key 后可完成一次真实调用 |
| D5 调用与计量 | 打通同步、流式、用量事件和额度账本 | 代理链路、SSE、幂等计量、用量页面 | 调用量与额度变更可追溯且不重复扣减 | | D5 调用与计量 | 打通同步、流式、用量事件和额度账本 | 代理链路、SSE、幂等计量、用量页面 | 调用量与额度变更可追溯且不重复扣减 |
| D6 异步任务与 3D | 打通任务提交、排队、进度和结果文件 | Task API、队列、对象存储、AI SoulMate 适配器 | 3D 任务完成正常/失败闭环 | | D6 异步任务与 3D | 打通任务提交、排队、进度和结果文件 | Task API、队列、对象存储、AI SoulMate 适配器 | 3D 任务完成正常/失败闭环 |
@@ -138,4 +138,4 @@ POST /v1/tasks
## 六、当前结论 ## 六、当前结论
当前正式进入 D1。D1 不启动真实供应商调用,也不要求提供生产密钥;它先建立稳定的代码边界。D2 开始部署 Otari 时,再由项目负责人确认服务器环境和至少一个可用于联调的供应商测试密钥。 当前 D3 已完成认证与权限基线。D3 不要求短信/邮件服务或生产密钥;本地可用内存仓库联调,正式开发使用独立 PostgreSQL。下一节点进入 D4,补充 MOYI Key、统一模型目录与 Otari 映射。
+4
View File
@@ -0,0 +1,4 @@
CONTROL_PLANE_POSTGRES_PORT=5434
CONTROL_PLANE_POSTGRES_USER=moyi
CONTROL_PLANE_POSTGRES_PASSWORD=replace-with-a-long-random-password
CONTROL_PLANE_POSTGRES_DB=moyi_control
+17
View File
@@ -0,0 +1,17 @@
# Control Plane 数据库
这是 D3 身份与权限服务使用的本地 PostgreSQL。它与 \`infra/otari/\` 的网关数据库独立,避免平台身份数据与网关执行数据混用。
\`\`\`powershell
cd infra/control-plane
Copy-Item .env.example .env
docker compose up -d
\`\`\`
然后在 \`control-plane/.env\` 中设置:
\`\`\`dotenv
DATABASE_URL=postgresql://moyi:你的数据库密码@127.0.0.1:5434/moyi_control
\`\`\`
再运行 \`pnpm migrate\` 与 \`pnpm seed:admin\`。
+22
View File
@@ -0,0 +1,22 @@
name: moyi-control-plane
services:
postgres:
image: postgres:16-alpine
restart: unless-stopped
ports:
- "${CONTROL_PLANE_POSTGRES_PORT:-5434}:5432"
environment:
POSTGRES_USER: ${CONTROL_PLANE_POSTGRES_USER:-moyi}
POSTGRES_PASSWORD: ${CONTROL_PLANE_POSTGRES_PASSWORD:?Set CONTROL_PLANE_POSTGRES_PASSWORD in infra/control-plane/.env}
POSTGRES_DB: ${CONTROL_PLANE_POSTGRES_DB:-moyi_control}
volumes:
- control_plane_postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 10
volumes:
control_plane_postgres_data:
+3
View File
@@ -0,0 +1,3 @@
VITE_CONTROL_PLANE_URL=http://127.0.0.1:8787
# 仅用于视觉原型预览;接入 D3 认证服务时保持 remote。
VITE_AUTH_MODE=remote
+28 -6
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue' import { computed, onMounted, ref } from 'vue'
import { import {
ArrowLeftRight, ArrowLeftRight,
Bell, Bell,
@@ -18,6 +18,7 @@ import AuthView from './views/AuthView.vue'
import AdminConsole from './views/AdminConsole.vue' import AdminConsole from './views/AdminConsole.vue'
import UserConsole from './views/UserConsole.vue' import UserConsole from './views/UserConsole.vue'
import type { Portal } from './types' import type { Portal } from './types'
import { authClient, type AuthUser } from './services/auth'
const portal = ref<Portal>('user') const portal = ref<Portal>('user')
const activeView = ref('overview') const activeView = ref('overview')
@@ -25,9 +26,23 @@ const sidebarCollapsed = ref(false)
const mobileNavigationOpen = ref(false) const mobileNavigationOpen = ref(false)
const toastMessage = ref('') const toastMessage = ref('')
const authenticated = ref(false) const authenticated = ref(false)
const authUser = ref<AuthUser>()
const accountMenuOpen = ref(false) const accountMenuOpen = ref(false)
const userName = ref('林默') const userName = ref('林默')
onMounted(async () => {
try {
const user = await authClient.currentUser()
if (user) {
authUser.value = user
userName.value = user.displayName
authenticated.value = true
}
} catch {
notify('认证服务暂不可用,请稍后重试')
}
})
const navigation = computed(() => portal.value === 'user' ? userNavigation : adminNavigation) const navigation = computed(() => portal.value === 'user' ? userNavigation : adminNavigation)
const activeLabel = computed(() => navigation.value.flatMap((group) => group.items).find((item) => item.id === activeView.value)?.label ?? '总览') const activeLabel = computed(() => navigation.value.flatMap((group) => group.items).find((item) => item.id === activeView.value)?.label ?? '总览')
@@ -39,6 +54,10 @@ function navigate(view: string) {
} }
function switchPortal() { function switchPortal() {
if (authUser.value?.role !== 'admin') {
notify('当前账号没有管理端权限')
return
}
portal.value = portal.value === 'user' ? 'admin' : 'user' portal.value = portal.value === 'user' ? 'admin' : 'user'
activeView.value = portal.value === 'user' ? 'overview' : 'admin-overview' activeView.value = portal.value === 'user' ? 'overview' : 'admin-overview'
mobileNavigationOpen.value = false mobileNavigationOpen.value = false
@@ -52,8 +71,9 @@ function notify(message: string) {
}, 2800) }, 2800)
} }
function signIn(name: string) { function signIn(user: AuthUser) {
userName.value = name userName.value = user.displayName
authUser.value = user
authenticated.value = true authenticated.value = true
activeView.value = 'overview' activeView.value = 'overview'
notify('登录成功,欢迎进入模亦灵枢') notify('登录成功,欢迎进入模亦灵枢')
@@ -64,6 +84,8 @@ function logout() {
portal.value = 'user' portal.value = 'user'
activeView.value = 'overview' activeView.value = 'overview'
authenticated.value = false authenticated.value = false
authUser.value = undefined
void authClient.logout().catch(() => undefined)
notify('已安全退出登录') notify('已安全退出登录')
} }
@@ -133,11 +155,11 @@ function openAccountSettings() {
</div> </div>
<div class="topbar-actions"> <div class="topbar-actions">
<button class="global-search desktop-only" @click="notify('全局搜索将在接入真实数据后开放')"><Search :size="16" /><span>搜索模型、用户或任务</span><kbd>⌘ K</kbd></button> <button class="global-search desktop-only" @click="notify('全局搜索将在接入真实数据后开放')"><Search :size="16" /><span>搜索模型、用户或任务</span><kbd>⌘ K</kbd></button>
<button class="portal-switch" @click="switchPortal"><ArrowLeftRight :size="16" /><span>{{ portal === 'admin' ? '返回用户端' : '进入管理端' }}</span></button> <button v-if="authUser?.role === 'admin'" class="portal-switch" @click="switchPortal"><ArrowLeftRight :size="16" /><span>{{ portal === 'admin' ? '返回用户端' : '进入管理端' }}</span></button>
<button class="icon-button desktop-only" aria-label="通知" @click="notify('当前没有新的通知')"><Bell :size="18" /></button> <button class="icon-button desktop-only" aria-label="通知" @click="notify('当前没有新的通知')"><Bell :size="18" /></button>
<div class="account-menu-wrap"> <div class="account-menu-wrap">
<button class="user-menu" :class="{ active: accountMenuOpen }" @click="accountMenuOpen = !accountMenuOpen"><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ portal === 'admin' ? '平台管理员' : '管理员账号' }}</small></div></button> <button class="user-menu" :class="{ active: accountMenuOpen }" @click="accountMenuOpen = !accountMenuOpen"><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ authUser?.role === 'admin' ? '平台管理员' : '普通用户' }}</small></div></button>
<Transition name="menu-pop"><div v-if="accountMenuOpen" class="account-popover"><header><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>demo@moyi.ai</small></div></header><button @click="openAccountSettings"><Settings :size="16" />账号设置</button><button class="logout-button" @click="logout"><LogOut :size="16" />退出登录</button></div></Transition> <Transition name="menu-pop"><div v-if="accountMenuOpen" class="account-popover"><header><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ authUser?.account }}</small></div></header><button @click="openAccountSettings"><Settings :size="16" />账号设置</button><button class="logout-button" @click="logout"><LogOut :size="16" />退出登录</button></div></Transition>
</div> </div>
</div> </div>
</header> </header>
+137
View File
@@ -0,0 +1,137 @@
export type AuthRole = 'user' | 'admin'
export interface AuthUser {
id: string
account: string
accountKind: 'email' | 'phone'
displayName: string
role: AuthRole
status: 'active' | 'disabled'
createdAt: string
lastLoginAt?: string
}
export interface RegisterInput {
invitationCode: string
account: string
password: string
displayName?: string
}
export interface LoginInput {
account: string
password: string
}
export interface AuthClient {
login(input: LoginInput): Promise<AuthUser>
register(input: RegisterInput): Promise<AuthUser>
currentUser(): Promise<AuthUser | undefined>
logout(): Promise<void>
}
class HttpAuthClient implements AuthClient {
constructor(private readonly baseUrl: string) {}
async login(input: LoginInput) {
const payload = await this.request<{ user: AuthUser }>('/api/auth/login', {
method: 'POST',
body: JSON.stringify(input),
})
return payload.user
}
async register(input: RegisterInput): Promise<AuthUser> {
const payload = await this.request<{ user: AuthUser }>('/api/auth/register', {
method: 'POST',
body: JSON.stringify(input),
})
return payload.user
}
async currentUser() {
try {
const payload = await this.request<{ user: AuthUser }>('/api/auth/me')
return payload.user
} catch (error) {
if (error instanceof AuthApiError && error.status === 401) return undefined
throw error
}
}
async logout() {
await this.request('/api/auth/logout', { method: 'POST' })
}
private async request<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response
try {
response = await fetch(`${this.baseUrl}${path}`, {
...init,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...init?.headers,
},
})
} catch {
throw new AuthApiError(0, '无法连接 Control Plane,请确认认证服务已启动。')
}
if (response.status === 204) return undefined as T
const payload = await response.json().catch(() => ({})) as { error?: { code?: string; message?: string } }
if (!response.ok) throw new AuthApiError(response.status, payload.error?.message || '认证请求失败', payload.error?.code)
return payload as T
}
}
class DemoAuthClient implements AuthClient {
private readonly sessionKey = 'moyi_demo_session'
private readonly user: AuthUser = {
id: 'demo_admin',
account: 'demo@moyi.ai',
accountKind: 'email',
displayName: '林默',
role: 'admin',
status: 'active',
createdAt: '2026-08-20T00:00:00.000Z',
}
async login(input: LoginInput) {
if (!input.account.trim() || !input.password) throw new AuthApiError(400, '请输入账号和密码')
sessionStorage.setItem(this.sessionKey, '1')
return this.user
}
async register(input: RegisterInput): Promise<AuthUser> {
if (!input.invitationCode.trim()) throw new AuthApiError(400, '第一版内测需要填写邀请码')
if (input.password.length < 8) throw new AuthApiError(400, '密码至少需要 8 位')
sessionStorage.setItem(this.sessionKey, '1')
return { ...this.user, account: input.account, displayName: input.displayName || input.account.split('@')[0] || 'MOYI 用户', role: 'user' }
}
async currentUser() {
return sessionStorage.getItem(this.sessionKey) ? this.user : undefined
}
async logout() {
sessionStorage.removeItem(this.sessionKey)
}
}
export class AuthApiError extends Error {
constructor(
readonly status: number,
message: string,
readonly code?: string,
) {
super(message)
}
}
const authMode = import.meta.env.VITE_AUTH_MODE || 'remote'
const controlPlaneUrl = (import.meta.env.VITE_CONTROL_PLANE_URL || 'http://127.0.0.1:8787').replace(/\/$/, '')
export const authClient: AuthClient = authMode === 'demo'
? new DemoAuthClient()
: new HttpAuthClient(controlPlaneUrl)
+22 -10
View File
@@ -16,12 +16,13 @@ import {
Sparkles, Sparkles,
Zap, Zap,
} from 'lucide-vue-next' } from 'lucide-vue-next'
import { AuthApiError, authClient, type AuthUser } from '../services/auth'
type AuthMode = 'login' | 'register' | 'forgot' type AuthMode = 'login' | 'register' | 'forgot'
type RegisterChannel = 'email' | 'phone' type RegisterChannel = 'email' | 'phone'
const emit = defineEmits<{ const emit = defineEmits<{
success: [name: string] success: [user: AuthUser]
notify: [message: string] notify: [message: string]
}>() }>()
@@ -61,28 +62,39 @@ function sendCode() {
emit('notify', '验证码已发送,原型阶段可输入任意 6 位数字') emit('notify', '验证码已发送,原型阶段可输入任意 6 位数字')
} }
function submitLogin() { async function submitLogin() {
if (!account.value.trim() || !password.value) return emit('notify', '请输入账号和密码') if (!account.value.trim() || !password.value) return emit('notify', '请输入账号和密码')
loading.value = true loading.value = true
window.setTimeout(() => { try {
const user = await authClient.login({ account: account.value, password: password.value })
loading.value = false loading.value = false
emit('success', '林默') emit('success', user)
}, 650) } catch (error) {
loading.value = false
emit('notify', error instanceof AuthApiError ? error.message : '登录失败,请稍后重试')
}
} }
function submitRegister() { async function submitRegister() {
if (!invitationCode.value.trim()) return emit('notify', '第一版内测需要填写邀请码') if (!invitationCode.value.trim()) return emit('notify', '第一版内测需要填写邀请码')
if (!account.value.trim()) return emit('notify', `请输入${accountLabel.value}`) if (!account.value.trim()) return emit('notify', `请输入${accountLabel.value}`)
if (verificationCode.value.trim().length < 4) return emit('notify', '请输入收到的验证码')
if (password.value.length < 8) return emit('notify', '密码至少需要 8 位') if (password.value.length < 8) return emit('notify', '密码至少需要 8 位')
if (password.value !== confirmPassword.value) return emit('notify', '两次输入的密码不一致') if (password.value !== confirmPassword.value) return emit('notify', '两次输入的密码不一致')
if (!agreeTerms.value) return emit('notify', '请先同意服务协议与隐私政策') if (!agreeTerms.value) return emit('notify', '请先同意服务协议与隐私政策')
loading.value = true loading.value = true
window.setTimeout(() => { try {
const user = await authClient.register({
invitationCode: invitationCode.value,
account: account.value,
password: password.value,
})
loading.value = false loading.value = false
switchMode('login') switchMode('login')
emit('notify', '注册成功,请使用新账号登录') emit('notify', '注册成功,欢迎 ' + user.displayName + '。请使用新账号登录')
}, 700) } catch (error) {
loading.value = false
emit('notify', error instanceof AuthApiError ? error.message : '注册失败,请稍后重试')
}
} }
function submitReset() { function submitReset() {