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

+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)