diff --git a/backend/.env.example b/backend/.env.example index b1bb689..bad6772 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -8,6 +8,10 @@ QIPAI_MYSQL_PORT=3306 QIPAI_MYSQL_DATABASE=qipai QIPAI_MYSQL_USER=qipai_app QIPAI_MYSQL_PASSWORD= +QIPAI_JWT_SECRET= +QIPAI_ACCESS_TOKEN_TTL_SECONDS=900 +QIPAI_SESSION_TTL_SECONDS=604800 +QIPAI_WECHAT_APP_SECRETS={} QIPAI_MQTT_URL=mqtt://101.42.38.246:1883 QIPAI_MQTT_USERNAME= QIPAI_MQTT_PASSWORD= diff --git a/backend/package.json b/backend/package.json index b8e212d..5c53f2c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -17,7 +17,7 @@ "db:migrate:verify": "npm run build && node dist/db/migrate-cli.js verify", "db:migrate:down": "npm run build && node dist/db/migrate-cli.js down", "test:mysql:migration": "npm run build && node tests/mysql-migration-roundtrip.test.mjs", - "test": "npm run build && node tests/backend-contract.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs" + "test": "npm run build && node tests/backend-contract.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs" }, "dependencies": { "@fastify/cors": "^11.2.0", diff --git a/backend/src/app.ts b/backend/src/app.ts index ab79270..0a42a7d 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -8,10 +8,12 @@ import { registerPlatformBootstrapRoutes, type PlatformConfigResolver } from './routes/platform-bootstrap.js'; +import { registerAuthRoutes, type AuthRouteOptions } from './routes/auth.js'; export interface BuildAppOptions { config?: AppConfig; platformConfigRepository?: PlatformConfigResolver; + auth?: AuthRouteOptions; } declare module 'fastify' { @@ -57,6 +59,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + const tenantFilter = tenantId ? 'AND ta.tenant_id = ?' : ''; + const [rows] = await this.pool.execute( + `SELECT ta.tenant_id AS tenantId, pa.id AS platformAppId, pa.appid AS appId + FROM qipai_platform_apps pa + INNER JOIN qipai_tenant_apps ta + ON ta.platform_app_id = pa.id + AND ta.status = 'ACTIVE' AND ta.deleted_at IS NULL + INNER JOIN qipai_tenants t + ON t.id = ta.tenant_id + AND t.status = 'ACTIVE' AND t.deleted_at IS NULL + WHERE pa.appid = ? AND pa.status = 'ACTIVE' AND pa.deleted_at IS NULL + ${tenantFilter} + ORDER BY ta.is_default DESC, ta.tenant_id ASC + LIMIT 2`, + tenantId ? [appId, tenantId] : [appId] + ); + if (!tenantId && rows.length > 1) throw new Error('TENANT_SELECTION_REQUIRED'); + const row = rows[0]; + return row ? { + tenantId: String(row.tenantId), + platformAppId: String(row.platformAppId), + appId: row.appId + } : null; + } + + async loginWithWechat(input: { + context: LoginContext; + openid: string; + unionid?: string; + sessionId: string; + expiresAt: Date; + ip: string; + userAgent: string; + }): Promise { + const connection = await this.pool.getConnection(); + try { + await connection.beginTransaction(); + let user = await this.findUserByIdentity(connection, input.context, input.openid); + if (!user) { + const [created] = await connection.execute( + `INSERT INTO qipai_users (tenant_id, user_type, status) + VALUES (?, 'CUSTOMER', 'ACTIVE')`, + [input.context.tenantId] + ); + const userId = String(created.insertId); + await connection.execute( + `INSERT INTO qipai_user_identities + (tenant_id, platform_app_id, user_id, openid, unionid) + VALUES (?, ?, ?, ?, ?)`, + [ + input.context.tenantId, + input.context.platformAppId, + userId, + input.openid, + input.unionid ?? null + ] + ); + user = await this.findUserById(connection, input.context.tenantId, userId); + } else if (input.unionid) { + await connection.execute( + `UPDATE qipai_user_identities SET unionid = COALESCE(unionid, ?) + WHERE tenant_id = ? AND platform_app_id = ? AND user_id = ?`, + [input.unionid, input.context.tenantId, input.context.platformAppId, user.id] + ); + } + if (!user || user.status !== 'ACTIVE') throw new Error('USER_DISABLED'); + await connection.execute( + `INSERT INTO qipai_auth_sessions + (id, tenant_id, platform_app_id, user_id, role_version, expires_at, ip, user_agent) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + [ + input.sessionId, + input.context.tenantId, + input.context.platformAppId, + user.id, + user.roleVersion, + input.expiresAt, + input.ip, + input.userAgent.slice(0, 255) + ] + ); + await connection.execute( + `UPDATE qipai_users SET last_login_at = UTC_TIMESTAMP(3) + WHERE tenant_id = ? AND id = ?`, + [input.context.tenantId, user.id] + ); + await connection.commit(); + return { + id: input.sessionId, + tenantId: input.context.tenantId, + platformAppId: input.context.platformAppId, + user, + expiresAt: input.expiresAt + }; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + } + + async validateSession(sessionId: string, tenantId: string, userId: string): Promise { + const [rows] = await this.pool.execute( + `SELECT s.id AS sessionId, s.tenant_id AS tenantId, + s.platform_app_id AS platformAppId, s.expires_at AS expiresAt, + u.id, u.user_type AS userType, u.status, + u.role_version AS roleVersion, u.nickname, + u.avatar_url AS avatarUrl, u.phone + FROM qipai_auth_sessions s + INNER JOIN qipai_users u + ON u.id = s.user_id AND u.tenant_id = s.tenant_id AND u.deleted_at IS NULL + WHERE s.id = ? AND s.tenant_id = ? AND s.user_id = ? + AND s.status = 'ACTIVE' AND s.revoked_at IS NULL + AND s.expires_at > UTC_TIMESTAMP(3) + AND u.status = 'ACTIVE' + AND u.role_version = s.role_version + LIMIT 1`, + [sessionId, tenantId, userId] + ); + const row = rows[0]; + if (!row) return null; + await this.pool.execute( + 'UPDATE qipai_auth_sessions SET last_seen_at = UTC_TIMESTAMP(3) WHERE id = ?', + [sessionId] + ); + return { + id: row.sessionId, + tenantId: String(row.tenantId), + platformAppId: String(row.platformAppId), + expiresAt: row.expiresAt, + user: mapUser(row) + }; + } + + async revokeSession(sessionId: string, reason = 'LOGOUT'): Promise { + const [result] = await this.pool.execute( + `UPDATE qipai_auth_sessions + SET status = 'REVOKED', revoked_at = UTC_TIMESTAMP(3), revoke_reason = ? + WHERE id = ? AND status = 'ACTIVE'`, + [reason, sessionId] + ); + return result.affectedRows === 1; + } + + private async findUserByIdentity( + connection: PoolConnection, + context: LoginContext, + openid: string + ): Promise { + const [rows] = await connection.execute( + `SELECT u.id, u.tenant_id AS tenantId, u.user_type AS userType, u.status, + u.role_version AS roleVersion, u.nickname, + u.avatar_url AS avatarUrl, u.phone + FROM qipai_user_identities i + INNER JOIN qipai_users u + ON u.id = i.user_id AND u.tenant_id = i.tenant_id AND u.deleted_at IS NULL + WHERE i.tenant_id = ? AND i.platform_app_id = ? + AND i.openid = ? AND i.deleted_at IS NULL + LIMIT 1 FOR UPDATE`, + [context.tenantId, context.platformAppId, openid] + ); + return rows[0] ? mapUser(rows[0]) : null; + } + + private async findUserById( + connection: PoolConnection, + tenantId: string, + userId: string + ): Promise { + const [rows] = await connection.execute( + `SELECT id, tenant_id AS tenantId, user_type AS userType, status, + role_version AS roleVersion, nickname, avatar_url AS avatarUrl, phone + FROM qipai_users WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL`, + [tenantId, userId] + ); + return rows[0] ? mapUser(rows[0]) : null; + } +} + +function mapUser(row: UserRow): AuthUser { + return { + id: String(row.id), + tenantId: String(row.tenantId), + userType: row.userType, + status: row.status, + roleVersion: row.roleVersion, + nickname: row.nickname, + avatarUrl: row.avatarUrl, + phone: row.phone + }; +} diff --git a/backend/src/auth/jwt.ts b/backend/src/auth/jwt.ts new file mode 100644 index 0000000..6fb5233 --- /dev/null +++ b/backend/src/auth/jwt.ts @@ -0,0 +1,62 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; +import { z } from 'zod'; + +const claimsSchema = z.object({ + iss: z.literal('qipai-api'), + aud: z.literal('qipai-miniapp'), + sub: z.string().regex(/^[1-9]\d*$/), + sid: z.string().uuid(), + tid: z.string().regex(/^[1-9]\d*$/), + aid: z.string().regex(/^[1-9]\d*$/), + rv: z.number().int().positive(), + iat: z.number().int(), + exp: z.number().int() +}); + +export type AccessTokenClaims = z.infer; + +function encode(value: string): string { + return Buffer.from(value).toString('base64url'); +} + +export function signAccessToken( + claims: Omit, + secret: string, + ttlSeconds: number, + nowSeconds = Math.floor(Date.now() / 1000) +): string { + const header = encode(JSON.stringify({ alg: 'HS256', typ: 'JWT' })); + const payload = encode(JSON.stringify({ + iss: 'qipai-api', + aud: 'qipai-miniapp', + ...claims, + iat: nowSeconds, + exp: nowSeconds + ttlSeconds + })); + const signature = createHmac('sha256', secret).update(`${header}.${payload}`).digest('base64url'); + return `${header}.${payload}.${signature}`; +} + +export function verifyAccessToken( + token: string, + secret: string, + nowSeconds = Math.floor(Date.now() / 1000) +): AccessTokenClaims { + const parts = token.split('.'); + if (parts.length !== 3) throw new Error('Invalid access token.'); + const [header, payload, signature] = parts; + const expected = createHmac('sha256', secret).update(`${header}.${payload}`).digest(); + const actual = Buffer.from(signature, 'base64url'); + if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) { + throw new Error('Invalid access token signature.'); + } + const parsedHeader = JSON.parse(Buffer.from(header, 'base64url').toString('utf8')); + if (parsedHeader.alg !== 'HS256' || parsedHeader.typ !== 'JWT') { + throw new Error('Unsupported access token.'); + } + const claims = claimsSchema.parse( + JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) + ); + if (claims.exp <= nowSeconds) throw new Error('Access token expired.'); + return claims; +} diff --git a/backend/src/auth/wechat-client.ts b/backend/src/auth/wechat-client.ts new file mode 100644 index 0000000..abfa43a --- /dev/null +++ b/backend/src/auth/wechat-client.ts @@ -0,0 +1,60 @@ +export interface WechatCodeSession { + openid: string; + unionid?: string; +} + +export interface WechatCodeExchange { + exchange(appId: string, code: string): Promise; +} + +export class WechatApiError extends Error { + constructor(message: string) { + super(message); + this.name = 'WechatApiError'; + } +} + +export class WechatHttpClient implements WechatCodeExchange { + constructor( + private readonly appSecrets: Readonly>, + private readonly fetcher: typeof fetch = fetch + ) {} + + async exchange(appId: string, code: string): Promise { + const secret = this.appSecrets[appId]; + if (!secret) throw new WechatApiError(`No WeChat secret configured for AppID ${appId}.`); + const url = new URL('https://api.weixin.qq.com/sns/jscode2session'); + url.searchParams.set('appid', appId); + url.searchParams.set('secret', secret); + url.searchParams.set('js_code', code); + url.searchParams.set('grant_type', 'authorization_code'); + const response = await this.fetcher(url); + if (!response.ok) throw new WechatApiError(`WeChat HTTP ${response.status}.`); + const payload = await response.json() as { + openid?: string; + unionid?: string; + errcode?: number; + errmsg?: string; + }; + if (!payload.openid || payload.errcode) { + throw new WechatApiError(`WeChat code exchange failed: ${payload.errcode ?? 'UNKNOWN'}.`); + } + return { openid: payload.openid, unionid: payload.unionid }; + } +} + +export function parseWechatAppSecrets(value: string): Readonly> { + if (!value.trim()) return {}; + const parsed = JSON.parse(value) as unknown; + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('QIPAI_WECHAT_APP_SECRETS must be a JSON object.'); + } + return Object.fromEntries( + Object.entries(parsed).map(([appId, secret]) => { + if (typeof secret !== 'string' || secret.length < 8) { + throw new Error(`Invalid WeChat secret for AppID ${appId}.`); + } + return [appId, secret]; + }) + ); +} diff --git a/backend/src/config.ts b/backend/src/config.ts index e57e1e7..5df93be 100644 --- a/backend/src/config.ts +++ b/backend/src/config.ts @@ -12,6 +12,10 @@ const configSchema = z.object({ QIPAI_MYSQL_USER: z.string().min(1).default('qipai_app'), QIPAI_MYSQL_PASSWORD: z.string().default(''), QIPAI_MYSQL_CONNECTION_LIMIT: z.coerce.number().int().min(1).max(50).default(10), + QIPAI_JWT_SECRET: z.string().min(32).default('development-only-change-this-jwt-secret'), + QIPAI_ACCESS_TOKEN_TTL_SECONDS: z.coerce.number().int().min(60).max(86400).default(900), + QIPAI_SESSION_TTL_SECONDS: z.coerce.number().int().min(300).max(2592000).default(604800), + QIPAI_WECHAT_APP_SECRETS: z.string().default('{}'), QIPAI_MQTT_URL: z.string().url().default('mqtt://101.42.38.246:1883'), QIPAI_MQTT_USERNAME: z.string().default(''), QIPAI_MQTT_PASSWORD: z.string().default('') @@ -21,6 +25,12 @@ export type AppConfig = ReturnType; export function loadConfig(env: NodeJS.ProcessEnv = process.env) { const parsed = configSchema.parse(env); + if ( + parsed.NODE_ENV === 'production' + && parsed.QIPAI_JWT_SECRET === 'development-only-change-this-jwt-secret' + ) { + throw new Error('QIPAI_JWT_SECRET must be explicitly configured in production.'); + } return { nodeEnv: parsed.NODE_ENV, @@ -37,6 +47,12 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env) { passwordConfigured: parsed.QIPAI_MYSQL_PASSWORD.length > 0, connectionLimit: parsed.QIPAI_MYSQL_CONNECTION_LIMIT }, + auth: { + jwtSecret: parsed.QIPAI_JWT_SECRET, + accessTokenTtlSeconds: parsed.QIPAI_ACCESS_TOKEN_TTL_SECONDS, + sessionTtlSeconds: parsed.QIPAI_SESSION_TTL_SECONDS, + wechatAppSecretsJson: parsed.QIPAI_WECHAT_APP_SECRETS + }, mqtt: { url: parsed.QIPAI_MQTT_URL, usernameConfigured: parsed.QIPAI_MQTT_USERNAME.length > 0, diff --git a/backend/src/db/migration-runner.ts b/backend/src/db/migration-runner.ts index 788b294..9a5fd37 100644 --- a/backend/src/db/migration-runner.ts +++ b/backend/src/db/migration-runner.ts @@ -23,14 +23,17 @@ const migrationFiles: Record = { up: [ 'database/migrations/2026061601_m01b_core_schema.up.sql', 'database/migrations/2026061802_m01c_async_tasks.up.sql', - 'database/migrations/2026061803_m02a_tenant_apps.up.sql' + 'database/migrations/2026061803_m02a_tenant_apps.up.sql', + 'database/migrations/2026061804_m02b_wechat_auth.up.sql' ], verify: [ 'database/migrations/2026061601_m01b_core_schema.verify.sql', 'database/migrations/2026061802_m01c_async_tasks.verify.sql', - 'database/migrations/2026061803_m02a_tenant_apps.verify.sql' + 'database/migrations/2026061803_m02a_tenant_apps.verify.sql', + 'database/migrations/2026061804_m02b_wechat_auth.verify.sql' ], down: [ + 'database/migrations/2026061804_m02b_wechat_auth.down.sql', 'database/migrations/2026061803_m02a_tenant_apps.down.sql', 'database/migrations/2026061802_m01c_async_tasks.down.sql', 'database/migrations/2026061601_m01b_core_schema.down.sql' @@ -149,7 +152,7 @@ export async function executeMigrationPlan( for (const [index, statement] of plan.statements.entries()) { const [result] = await pool.query(statement); if (plan.direction === 'verify') { - const minimumRows = [10, 26, 1, 2, 5, 1, 3, 5, 1][index] ?? 1; + const minimumRows = [10, 26, 1, 2, 5, 1, 3, 5, 1, 3, 7, 1][index] ?? 1; if (!Array.isArray(result) || result.length < minimumRows) { throw new Error( `Migration verification statement ${index + 1} returned fewer than ${minimumRows} rows.` diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts new file mode 100644 index 0000000..0d8ce8a --- /dev/null +++ b/backend/src/routes/auth.ts @@ -0,0 +1,150 @@ +import { randomUUID } from 'node:crypto'; +import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; +import type { AuthRepository } from '../auth/auth-repository.js'; +import { signAccessToken, verifyAccessToken } from '../auth/jwt.js'; +import { WechatApiError, type WechatCodeExchange } from '../auth/wechat-client.js'; + +const headersSchema = z.object({ + 'x-wechat-appid': z.string().trim().min(6).max(64), + 'tenant-id': z.string().regex(/^[1-9]\d{0,19}$/).optional() +}); +const loginBodySchema = z.object({ code: z.string().trim().min(4).max(128) }); + +export interface AuthRouteOptions { + repository: Pick; + wechat: WechatCodeExchange; + jwtSecret: string; + accessTokenTtlSeconds: number; + sessionTtlSeconds: number; +} + +export async function registerAuthRoutes(app: FastifyInstance, options: AuthRouteOptions): Promise { + app.post('/app-api/auth/wechat-login', async (request, reply) => { + const headers = headersSchema.safeParse(request.headers); + const body = loginBodySchema.safeParse(request.body); + if (!headers.success || !body.success) { + return reply.status(400).send({ + code: 'INVALID_LOGIN_REQUEST', + message: 'AppID, optional tenant-id and wx.login code are required.', + traceId: request.traceId + }); + } + try { + const context = await options.repository.resolveLoginContext( + headers.data['x-wechat-appid'], + headers.data['tenant-id'] + ); + if (!context) { + return reply.status(404).send({ + code: 'APP_TENANT_NOT_FOUND', + message: 'The application and tenant binding is not active.', + traceId: request.traceId + }); + } + const identity = await options.wechat.exchange(context.appId, body.data.code); + const sessionId = randomUUID(); + const expiresAt = new Date(Date.now() + options.sessionTtlSeconds * 1000); + const session = await options.repository.loginWithWechat({ + context, + ...identity, + sessionId, + expiresAt, + ip: request.ip, + userAgent: request.headers['user-agent'] ?? '' + }); + const accessToken = signAccessToken({ + sub: session.user.id, + sid: session.id, + tid: session.tenantId, + aid: session.platformAppId, + rv: session.user.roleVersion + }, options.jwtSecret, options.accessTokenTtlSeconds); + return { + code: 0, + data: { + accessToken, + expiresIn: options.accessTokenTtlSeconds, + user: publicUser(session.user) + }, + traceId: request.traceId + }; + } catch (error) { + if (error instanceof WechatApiError) { + return reply.status(401).send({ + code: 'WECHAT_LOGIN_FAILED', + message: 'WeChat login code is invalid or expired.', + traceId: request.traceId + }); + } + if (error instanceof Error && error.message === 'TENANT_SELECTION_REQUIRED') { + return reply.status(409).send({ + code: 'TENANT_SELECTION_REQUIRED', + message: 'tenant-id is required for an application bound to multiple tenants.', + traceId: request.traceId + }); + } + if (error instanceof Error && error.message === 'USER_DISABLED') { + return reply.status(403).send({ + code: 'USER_DISABLED', + message: 'The user account is disabled.', + traceId: request.traceId + }); + } + throw error; + } + }); + + app.get('/app-api/auth/me', async (request, reply) => { + const auth = await authenticate(request.headers.authorization, options); + if (!auth) return unauthorized(reply, request.traceId); + return { code: 0, data: { user: publicUser(auth.user) }, traceId: request.traceId }; + }); + + app.post('/app-api/auth/logout', async (request, reply) => { + const auth = await authenticate(request.headers.authorization, options); + if (!auth) return unauthorized(reply, request.traceId); + await options.repository.revokeSession(auth.sessionId); + return { code: 0, data: { revoked: true }, traceId: request.traceId }; + }); +} + +async function authenticate(authorization: string | undefined, options: AuthRouteOptions) { + if (!authorization?.startsWith('Bearer ')) return null; + try { + const claims = verifyAccessToken(authorization.slice(7), options.jwtSecret); + const session = await options.repository.validateSession(claims.sid, claims.tid, claims.sub); + if (!session || session.platformAppId !== claims.aid || session.user.roleVersion !== claims.rv) { + return null; + } + return { sessionId: claims.sid, user: session.user }; + } catch { + return null; + } +} + +function unauthorized(reply: { status(code: number): { send(payload: unknown): unknown } }, traceId: string) { + return reply.status(401).send({ + code: 'AUTH_SESSION_INVALID', + message: 'The access token or server-side session is invalid.', + traceId + }); +} + +function publicUser(user: { + id: string; + tenantId: string; + userType: string; + nickname: string; + avatarUrl: string; + phone: string; +}) { + return { + id: user.id, + tenantId: user.tenantId, + userType: user.userType, + nickname: user.nickname, + avatarUrl: user.avatarUrl, + phone: user.phone + }; +} diff --git a/backend/src/server.ts b/backend/src/server.ts index f04aea7..a9580b3 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -2,12 +2,21 @@ import { buildApp } from './app.js'; import { loadConfig } from './config.js'; import { closeMySqlPool, createMySqlPool } from './db/mysql.js'; import { PlatformConfigRepository } from './tenancy/platform-config-repository.js'; +import { AuthRepository } from './auth/auth-repository.js'; +import { parseWechatAppSecrets, WechatHttpClient } from './auth/wechat-client.js'; const config = loadConfig(); const pool = createMySqlPool(config); const app = await buildApp({ config, - platformConfigRepository: new PlatformConfigRepository(pool) + platformConfigRepository: new PlatformConfigRepository(pool), + auth: { + repository: new AuthRepository(pool), + wechat: new WechatHttpClient(parseWechatAppSecrets(config.auth.wechatAppSecretsJson)), + jwtSecret: config.auth.jwtSecret, + accessTokenTtlSeconds: config.auth.accessTokenTtlSeconds, + sessionTtlSeconds: config.auth.sessionTtlSeconds + } }); app.addHook('onClose', async () => { await closeMySqlPool(pool); diff --git a/backend/tests/auth.test.mjs b/backend/tests/auth.test.mjs new file mode 100644 index 0000000..667be54 --- /dev/null +++ b/backend/tests/auth.test.mjs @@ -0,0 +1,155 @@ +import assert from 'node:assert/strict'; +import { buildApp } from '../dist/app.js'; +import { signAccessToken, verifyAccessToken } from '../dist/auth/jwt.js'; +import { WechatApiError, parseWechatAppSecrets } from '../dist/auth/wechat-client.js'; + +const secret = 'test-only-jwt-secret-with-at-least-32-characters'; +const token = signAccessToken({ + sub: '21', + sid: '5c4d3af8-c63c-4edb-bf95-b84127bb3f6e', + tid: '7', + aid: '9', + rv: 3 +}, secret, 900, 1000); +assert.deepEqual(verifyAccessToken(token, secret, 1001), { + iss: 'qipai-api', + aud: 'qipai-miniapp', + sub: '21', + sid: '5c4d3af8-c63c-4edb-bf95-b84127bb3f6e', + tid: '7', + aid: '9', + rv: 3, + iat: 1000, + exp: 1900 +}); +assert.throws(() => verifyAccessToken(token, `${secret}-wrong`, 1001), /signature/); +assert.throws(() => verifyAccessToken(token, secret, 1900), /expired/); +assert.deepEqual(parseWechatAppSecrets('{"wx-app":"secret-value"}'), { + 'wx-app': 'secret-value' +}); + +let sessionValid = true; +let revokedSessionId = null; +const auth = { + repository: { + async resolveLoginContext(appId, tenantId) { + assert.equal(appId, 'wx-test-app'); + assert.equal(tenantId, '7'); + return { appId, tenantId, platformAppId: '9' }; + }, + async loginWithWechat(input) { + assert.equal(input.openid, 'openid-test'); + return { + id: input.sessionId, + tenantId: '7', + platformAppId: '9', + expiresAt: input.expiresAt, + user: { + id: '21', + tenantId: '7', + userType: 'CUSTOMER', + status: 'ACTIVE', + roleVersion: 1, + nickname: '', + avatarUrl: '', + phone: '' + } + }; + }, + async validateSession(sessionId, tenantId, userId) { + if (!sessionValid) return null; + return { + id: sessionId, + tenantId, + platformAppId: '9', + expiresAt: new Date(Date.now() + 60_000), + user: { + id: userId, + tenantId, + userType: 'CUSTOMER', + status: 'ACTIVE', + roleVersion: 1, + nickname: '', + avatarUrl: '', + phone: '' + } + }; + }, + async revokeSession(sessionId) { + revokedSessionId = sessionId; + sessionValid = false; + return true; + } + }, + wechat: { + async exchange(appId, code) { + assert.equal(appId, 'wx-test-app'); + assert.equal(code, 'valid-code'); + return { openid: 'openid-test', unionid: 'unionid-test' }; + } + }, + jwtSecret: secret, + accessTokenTtlSeconds: 900, + sessionTtlSeconds: 604800 +}; + +const app = await buildApp({ auth }); +const login = await app.inject({ + method: 'POST', + url: '/app-api/auth/wechat-login', + headers: { + 'x-wechat-appid': 'wx-test-app', + 'tenant-id': '7' + }, + payload: { code: 'valid-code' } +}); +assert.equal(login.statusCode, 200); +const accessToken = login.json().data.accessToken; +assert.equal(login.json().data.user.tenantId, '7'); + +const me = await app.inject({ + method: 'GET', + url: '/app-api/auth/me', + headers: { authorization: `Bearer ${accessToken}` } +}); +assert.equal(me.statusCode, 200); +assert.equal(me.json().data.user.id, '21'); + +const logout = await app.inject({ + method: 'POST', + url: '/app-api/auth/logout', + headers: { authorization: `Bearer ${accessToken}` } +}); +assert.equal(logout.statusCode, 200); +assert.ok(revokedSessionId); + +const afterLogout = await app.inject({ + method: 'GET', + url: '/app-api/auth/me', + headers: { authorization: `Bearer ${accessToken}` } +}); +assert.equal(afterLogout.statusCode, 401); +assert.equal(afterLogout.json().code, 'AUTH_SESSION_INVALID'); +await app.close(); + +const failedApp = await buildApp({ + auth: { + ...auth, + wechat: { + async exchange() { + throw new WechatApiError('invalid code'); + } + } + } +}); +const failedLogin = await failedApp.inject({ + method: 'POST', + url: '/app-api/auth/wechat-login', + headers: { 'x-wechat-appid': 'wx-test-app', 'tenant-id': '7' }, + payload: { code: 'bad-code' } +}); +assert.equal(failedLogin.statusCode, 401); +assert.equal(failedLogin.json().code, 'WECHAT_LOGIN_FAILED'); +await failedApp.close(); + +console.log('PASS: M02-B JWT, WeChat login and revocable session flow is present.'); diff --git a/backend/tests/backend-contract.test.mjs b/backend/tests/backend-contract.test.mjs index 777df9d..3a5f623 100644 --- a/backend/tests/backend-contract.test.mjs +++ b/backend/tests/backend-contract.test.mjs @@ -30,6 +30,8 @@ const configSource = read('src/config.ts'); assert.match(configSource, /z\.object/); assert.match(configSource, /QIPAI_MQTT_URL/); assert.match(configSource, /QIPAI_MYSQL_PASSWORD/); +assert.match(configSource, /QIPAI_JWT_SECRET/); +assert.match(configSource, /explicitly configured in production/); const healthSource = read('src/routes/health.ts'); for (const route of [ diff --git a/backend/tests/migration-contract.test.mjs b/backend/tests/migration-contract.test.mjs index a5c55af..0143699 100644 --- a/backend/tests/migration-contract.test.mjs +++ b/backend/tests/migration-contract.test.mjs @@ -18,6 +18,9 @@ const asyncVerifySql = read('database/migrations/2026061802_m01c_async_tasks.ver const tenantAppsUpSql = read('database/migrations/2026061803_m02a_tenant_apps.up.sql'); const tenantAppsDownSql = read('database/migrations/2026061803_m02a_tenant_apps.down.sql'); const tenantAppsVerifySql = read('database/migrations/2026061803_m02a_tenant_apps.verify.sql'); +const authUpSql = read('database/migrations/2026061804_m02b_wechat_auth.up.sql'); +const authDownSql = read('database/migrations/2026061804_m02b_wechat_auth.down.sql'); +const authVerifySql = read('database/migrations/2026061804_m02b_wechat_auth.verify.sql'); const coreTables = [ 'qipai_schema_migrations', @@ -99,4 +102,14 @@ assert.match(tenantAppsUpSql, /UNIQUE KEY uq_qipai_tenant_configs_tenant_app \(t assert.match(tenantAppsUpSql, /brand_name VARCHAR/); assert.match(tenantAppsUpSql, /theme_color VARCHAR/); -console.log('PASS: M01-B through M02-A migration contracts are present.'); +for (const table of ['qipai_users', 'qipai_user_identities', 'qipai_auth_sessions']) { + assert.match(authUpSql, new RegExp(`CREATE TABLE IF NOT EXISTS ${table}\\b`)); + assert.match(authDownSql, new RegExp(`DROP TABLE IF EXISTS ${table}\\b`)); + assert.match(authVerifySql, new RegExp(`'${table}'`)); +} +assert.match(authUpSql, /role_version INT UNSIGNED/); +assert.match(authUpSql, /UNIQUE KEY uq_qipai_user_identities_tenant_app_openid/); +assert.match(authUpSql, /revoked_at DATETIME\(3\)/); +assert.match(authUpSql, /expires_at DATETIME\(3\)/); + +console.log('PASS: M01-B through M02-B migration contracts are present.'); diff --git a/backend/tests/migration-runner.test.mjs b/backend/tests/migration-runner.test.mjs index 509c6b7..06c614e 100644 --- a/backend/tests/migration-runner.test.mjs +++ b/backend/tests/migration-runner.test.mjs @@ -14,7 +14,8 @@ const plan = await loadMigrationPlan('up'); assert.equal(plan.direction, 'up'); assert.match(plan.file, /2026061601_m01b_core_schema\.up\.sql/); assert.match(plan.file, /2026061802_m01c_async_tasks\.up\.sql/); -assert.match(plan.file, /2026061803_m02a_tenant_apps\.up\.sql$/); +assert.match(plan.file, /2026061803_m02a_tenant_apps\.up\.sql/); +assert.match(plan.file, /2026061804_m02b_wechat_auth\.up\.sql$/); assert.match(plan.checksum, /^[a-f0-9]{64}$/); assert.ok(plan.statements.length >= 11); diff --git a/backend/tests/mysql-migration-roundtrip.test.mjs b/backend/tests/mysql-migration-roundtrip.test.mjs index 8ac8c16..6d33ab6 100644 --- a/backend/tests/mysql-migration-roundtrip.test.mjs +++ b/backend/tests/mysql-migration-roundtrip.test.mjs @@ -10,6 +10,7 @@ import { AmbiguousAppTenantError, PlatformConfigRepository } from '../dist/tenancy/platform-config-repository.js'; +import { AuthRepository } from '../dist/auth/auth-repository.js'; import { executeMigrationPlan, loadMigrationPlan, @@ -19,6 +20,7 @@ import { const expectedTables = [ 'qipai_async_tasks', 'qipai_audit_logs', + 'qipai_auth_sessions', 'qipai_devices', 'qipai_legacy_table_mappings', 'qipai_members', @@ -31,7 +33,9 @@ const expectedTables = [ 'qipai_stores', 'qipai_tenant_apps', 'qipai_tenant_configs', - 'qipai_tenants' + 'qipai_tenants', + 'qipai_user_identities', + 'qipai_users' ]; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); @@ -52,9 +56,9 @@ async function readMigrationVersions(pool) { const [rows] = await pool.query( `SELECT version, name FROM qipai_schema_migrations - WHERE version IN (?, ?, ?) + WHERE version IN (?, ?, ?, ?) ORDER BY version`, - ['2026061601', '2026061802', '2026061803'] + ['2026061601', '2026061802', '2026061803', '2026061804'] ); return rows; } @@ -167,6 +171,55 @@ async function assertPlatformTenantIsolation(pool) { () => repository.resolveBootstrap('wx-m02a-shared'), AmbiguousAppTenantError ); + return { + tenantId: String(firstTenantId), + platformAppId: String(platformAppId), + appId: 'wx-m02a-shared' + }; +} + +async function assertRevocableAuthSession(pool, context) { + const repository = new AuthRepository(pool); + const resolved = await repository.resolveLoginContext(context.appId, context.tenantId); + assert.deepEqual(resolved, context); + const sessionId = '9c47fdb5-0c38-463a-858f-e1d85ce9b3fd'; + const session = await repository.loginWithWechat({ + context, + openid: 'm02b-openid-a', + unionid: 'm02b-unionid', + sessionId, + expiresAt: new Date(Date.now() + 60_000), + ip: '127.0.0.1', + userAgent: 'M02-B test' + }); + assert.equal(session.user.userType, 'CUSTOMER'); + assert.equal((await repository.loginWithWechat({ + context, + openid: 'm02b-openid-a', + unionid: 'm02b-unionid', + sessionId: 'c07df18c-a90d-4fa6-bea2-640d9710c84e', + expiresAt: new Date(Date.now() + 60_000), + ip: '127.0.0.1', + userAgent: 'M02-B repeat login' + })).user.id, session.user.id); + assert.ok(await repository.validateSession(sessionId, context.tenantId, session.user.id)); + assert.equal(await repository.revokeSession(sessionId), true); + assert.equal(await repository.validateSession(sessionId, context.tenantId, session.user.id), null); + + const roleSessionId = 'd8eb245b-e513-401e-9046-f574447909ad'; + await repository.loginWithWechat({ + context, + openid: 'm02b-openid-a', + sessionId: roleSessionId, + expiresAt: new Date(Date.now() + 60_000), + ip: '127.0.0.1', + userAgent: 'M02-B role test' + }); + await pool.query( + 'UPDATE qipai_users SET role_version = role_version + 1 WHERE tenant_id = ? AND id = ?', + [context.tenantId, session.user.id] + ); + assert.equal(await repository.validateSession(roleSessionId, context.tenantId, session.user.id), null); } const config = loadConfig(); @@ -195,12 +248,14 @@ try { assert.deepEqual(await readMigrationVersions(pool), [ { version: '2026061601', name: 'm01b_core_schema' }, { version: '2026061802', name: 'm01c_async_tasks' }, - { version: '2026061803', name: 'm02a_tenant_apps' } + { version: '2026061803', name: 'm02a_tenant_apps' }, + { version: '2026061804', name: 'm02b_wechat_auth' } ]); await assertTaskDurability(pool); - await assertPlatformTenantIsolation(pool); + const loginContext = await assertPlatformTenantIsolation(pool); + await assertRevocableAuthSession(pool, loginContext); await assertLegacyCompatibility(pool); - console.log('PASS: first up, verify, durable task and tenant isolation checks completed.'); + console.log('PASS: first up, verify, tenant isolation and revocable auth checks completed.'); await executeMigrationPlan(pool, plans.down); assert.deepEqual(await readCoreTables(pool), []); @@ -213,7 +268,8 @@ try { assert.deepEqual(await readMigrationVersions(pool), [ { version: '2026061601', name: 'm01b_core_schema' }, { version: '2026061802', name: 'm01c_async_tasks' }, - { version: '2026061803', name: 'm02a_tenant_apps' } + { version: '2026061803', name: 'm02a_tenant_apps' }, + { version: '2026061804', name: 'm02b_wechat_auth' } ]); await assertLegacyCompatibility(pool); console.log('PASS: second up and verify restored the schema.'); @@ -241,7 +297,10 @@ try { 'tenant isolation', 'decimal cents', 'app-to-tenant binding', - 'cross-tenant bootstrap rejection' + 'cross-tenant bootstrap rejection', + 'openid identity reuse', + 'session revocation', + 'role-version invalidation' ] }, null, 2)); } finally { diff --git a/database/migrations/2026061804_m02b_wechat_auth.down.sql b/database/migrations/2026061804_m02b_wechat_auth.down.sql new file mode 100644 index 0000000..24ba53e --- /dev/null +++ b/database/migrations/2026061804_m02b_wechat_auth.down.sql @@ -0,0 +1,4 @@ +DELETE FROM qipai_schema_migrations WHERE version = '2026061804'; +DROP TABLE IF EXISTS qipai_auth_sessions; +DROP TABLE IF EXISTS qipai_user_identities; +DROP TABLE IF EXISTS qipai_users; diff --git a/database/migrations/2026061804_m02b_wechat_auth.up.sql b/database/migrations/2026061804_m02b_wechat_auth.up.sql new file mode 100644 index 0000000..a5339eb --- /dev/null +++ b/database/migrations/2026061804_m02b_wechat_auth.up.sql @@ -0,0 +1,63 @@ +-- M02-B WeChat identities, users and revocable sessions. + +CREATE TABLE IF NOT EXISTS qipai_users ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + user_type VARCHAR(32) NOT NULL DEFAULT 'CUSTOMER', + status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE', + role_version INT UNSIGNED NOT NULL DEFAULT 1, + nickname VARCHAR(128) NOT NULL DEFAULT '', + avatar_url VARCHAR(512) NOT NULL DEFAULT '', + phone VARCHAR(32) NOT NULL DEFAULT '', + last_login_at DATETIME(3) NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3), + deleted_at DATETIME(3) NULL, + CONSTRAINT fk_qipai_users_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id), + KEY idx_qipai_users_tenant_status (tenant_id, status, deleted_at), + KEY idx_qipai_users_tenant_type (tenant_id, user_type, deleted_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS qipai_user_identities ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + platform_app_id BIGINT UNSIGNED NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + provider VARCHAR(32) NOT NULL DEFAULT 'WECHAT_MINIAPP', + openid VARCHAR(128) NOT NULL, + unionid VARCHAR(128) NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3), + deleted_at DATETIME(3) NULL, + CONSTRAINT fk_qipai_user_identities_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id), + CONSTRAINT fk_qipai_user_identities_app FOREIGN KEY (platform_app_id) REFERENCES qipai_platform_apps(id), + CONSTRAINT fk_qipai_user_identities_user FOREIGN KEY (user_id) REFERENCES qipai_users(id), + UNIQUE KEY uq_qipai_user_identities_tenant_app_openid (tenant_id, platform_app_id, openid), + UNIQUE KEY uq_qipai_user_identities_tenant_app_user (tenant_id, platform_app_id, user_id), + KEY idx_qipai_user_identities_tenant_unionid (tenant_id, unionid, deleted_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS qipai_auth_sessions ( + id CHAR(36) NOT NULL PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + platform_app_id BIGINT UNSIGNED NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + role_version INT UNSIGNED NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE', + expires_at DATETIME(3) NOT NULL, + revoked_at DATETIME(3) NULL, + revoke_reason VARCHAR(128) NOT NULL DEFAULT '', + last_seen_at DATETIME(3) NULL, + ip VARCHAR(64) NOT NULL DEFAULT '', + user_agent VARCHAR(255) NOT NULL DEFAULT '', + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3), + CONSTRAINT fk_qipai_auth_sessions_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id), + CONSTRAINT fk_qipai_auth_sessions_app FOREIGN KEY (platform_app_id) REFERENCES qipai_platform_apps(id), + CONSTRAINT fk_qipai_auth_sessions_user FOREIGN KEY (user_id) REFERENCES qipai_users(id), + KEY idx_qipai_auth_sessions_user_active (tenant_id, user_id, status, expires_at), + KEY idx_qipai_auth_sessions_expiry (status, expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT IGNORE INTO qipai_schema_migrations (version, name) +VALUES ('2026061804', 'm02b_wechat_auth'); diff --git a/database/migrations/2026061804_m02b_wechat_auth.verify.sql b/database/migrations/2026061804_m02b_wechat_auth.verify.sql new file mode 100644 index 0000000..0e8a167 --- /dev/null +++ b/database/migrations/2026061804_m02b_wechat_auth.verify.sql @@ -0,0 +1,32 @@ +SELECT table_name +FROM information_schema.tables +WHERE table_schema = DATABASE() + AND table_name IN ('qipai_users', 'qipai_user_identities', 'qipai_auth_sessions') +ORDER BY table_name; + +SELECT table_name, index_name +FROM information_schema.statistics +WHERE table_schema = DATABASE() + AND ( + (table_name = 'qipai_users' AND index_name IN ( + 'idx_qipai_users_tenant_status', + 'idx_qipai_users_tenant_type' + )) + OR + (table_name = 'qipai_user_identities' AND index_name IN ( + 'uq_qipai_user_identities_tenant_app_openid', + 'uq_qipai_user_identities_tenant_app_user', + 'idx_qipai_user_identities_tenant_unionid' + )) + OR + (table_name = 'qipai_auth_sessions' AND index_name IN ( + 'idx_qipai_auth_sessions_user_active', + 'idx_qipai_auth_sessions_expiry' + )) + ) +GROUP BY table_name, index_name +ORDER BY table_name, index_name; + +SELECT version, name +FROM qipai_schema_migrations +WHERE version = '2026061804'; diff --git a/scripts/dev/windows/check-backend.ps1 b/scripts/dev/windows/check-backend.ps1 index e25ecc3..1ecafcd 100644 --- a/scripts/dev/windows/check-backend.ps1 +++ b/scripts/dev/windows/check-backend.ps1 @@ -6,6 +6,9 @@ $requiredFiles = @( "backend/tsconfig.json", "backend/.env.example", "backend/src/app.ts", + "backend/src/auth/auth-repository.ts", + "backend/src/auth/jwt.ts", + "backend/src/auth/wechat-client.ts", "backend/src/config.ts", "backend/src/db/mysql.ts", "backend/src/db/migration-runner.ts", @@ -16,6 +19,7 @@ $requiredFiles = @( "backend/src/tasks/worker.ts", "backend/src/routes/health.ts", "backend/src/routes/platform-bootstrap.ts", + "backend/src/routes/auth.ts", "backend/src/tenancy/platform-config-repository.ts", "backend/src/server.ts", "backend/tests/backend-contract.test.mjs", @@ -26,6 +30,7 @@ $requiredFiles = @( "backend/tests/legacy-read-repository.test.mjs", "backend/tests/task-repository.test.mjs", "backend/tests/platform-config-repository.test.mjs", + "backend/tests/auth.test.mjs", "scripts/dev/wsl/mysql-migration-roundtrip.sh", "database/migrations/2026061601_m01b_core_schema.up.sql", "database/migrations/2026061601_m01b_core_schema.down.sql", @@ -36,6 +41,9 @@ $requiredFiles = @( "database/migrations/2026061803_m02a_tenant_apps.up.sql", "database/migrations/2026061803_m02a_tenant_apps.down.sql", "database/migrations/2026061803_m02a_tenant_apps.verify.sql", + "database/migrations/2026061804_m02b_wechat_auth.up.sql", + "database/migrations/2026061804_m02b_wechat_auth.down.sql", + "database/migrations/2026061804_m02b_wechat_auth.verify.sql", "database/seeds/2026061601_m01b_minimal_seed.sql", "deploy/pm2/ecosystem.config.cjs" ) diff --git a/scripts/dev/wsl/mysql-migration-roundtrip.sh b/scripts/dev/wsl/mysql-migration-roundtrip.sh index e211db2..b6e93a0 100644 --- a/scripts/dev/wsl/mysql-migration-roundtrip.sh +++ b/scripts/dev/wsl/mysql-migration-roundtrip.sh @@ -93,6 +93,6 @@ export QIPAI_MYSQL_USER="${username}" export QIPAI_MYSQL_PASSWORD="${password}" export QIPAI_MYSQL_CONNECTION_LIMIT=2 -echo "INFO: MySQL ${mysql_version}; running M01-B through M02-A migration roundtrip in a temporary database." +echo "INFO: MySQL ${mysql_version}; running M01-B through M02-B migration roundtrip in a temporary database." npm --prefix backend run test:mysql:migration -echo "PASS: M01-B through M02-A live MySQL migration roundtrip completed." +echo "PASS: M01-B through M02-B live MySQL migration roundtrip completed."