feat(M02-B): 实现微信登录与可撤销会话
This commit is contained in:
@@ -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.');
|
||||
@@ -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 [
|
||||
|
||||
@@ -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.');
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user