feat: add control plane authentication baseline
This commit is contained in:
1 parent
a4c93ff1a7
commit
0d10e2d124
21 files changed
+1403
-18
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user