import assert from 'node:assert/strict'; import { webcrypto } from 'node:crypto'; import fs from 'node:fs'; import { createRequire } from 'node:module'; import test from 'node:test'; import vm from 'node:vm'; const require = createRequire(import.meta.url); const ts = require(process.env.KEFU_SSO_TYPESCRIPT || 'typescript'); function loadTs(relative, dependencies = {}) { dependencies = { '#/locales/t': { t: key => key }, ...dependencies }; const source = fs.readFileSync(new URL(relative, import.meta.url), 'utf8'); const result = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true }, reportDiagnostics: true }); assert.deepEqual(result.diagnostics, []); const module = { exports: {} }; vm.runInNewContext(result.outputText, { module, exports: module.exports, require(name) { assert.ok(name in dependencies, `Unexpected import ${name}`); return dependencies[name]; }, URL, URLSearchParams, TextEncoder, Uint8Array, btoa, crypto: webcrypto, console }); return module.exports; } const sso = loadTs('../src/utils/group-sso.ts'); const config = { enabled: true, client_id: 'kefu', entry: 'http://127.0.0.1:5173', authorize_url: 'http://127.0.0.1:5173/sso/authorize', redirect_uri: 'http://127.0.0.1:5666/auth/group-login' }; const origin = 'http://127.0.0.1:5666'; const now = 1_000_000; const code = 'C'.repeat(43); test('不同访问地址先进入固定客服回调域,再在该域创建PKCE事务', async () => { assert.equal(sso.groupLoginEntry(config, origin), '/auth/group-login'); assert.equal(sso.groupLoginEntry(config, 'http://127.0.0.1:8766'), config.redirect_uri); assert.equal(sso.groupLoginEntry(config, 'http://localhost:5666'), config.redirect_uri); const pending = storage(); await assert.rejects(sso.beginGroupLogin(config, 'http://127.0.0.1:8766', pending, webcrypto, now)); assert.equal(pending.values.size, 0); assert.throws(() => sso.groupLoginEntry({...config, enabled: false}, origin)); assert.throws(() => sso.groupLoginEntry({...config, redirect_uri: 'https://evil.example/other'}, origin)); assert.throws(() => sso.groupLoginEntry({...config, authorize_url: 'https://evil.example/sso/authorize'}, origin)); assert.throws(() => sso.groupLoginEntry(config, `${origin}/auth/login`)); }); function storage() { const values = new Map(); return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key), values }; } async function transaction() { const state = storage(); const target = new URL(await sso.beginGroupLogin(config, origin, state, webcrypto, now)); const pending = JSON.parse(state.getItem(sso.GROUP_TRANSACTION_KEY)); return { state, target, pending, href: `${config.redirect_uri}?code=${code}&state=${pending.state}` }; } test('authorization uses random state, S256 PKCE and a fixed client/callback', async () => { const { state, target, pending, href } = await transaction(); assert.match(pending.state, /^[A-Za-z0-9_-]{43}$/); assert.match(pending.verifier, /^[A-Za-z0-9_-]{43}$/); assert.notEqual(pending.state, pending.verifier); assert.deepEqual(Object.keys(pending).sort(), ['created', 'state', 'verifier']); assert.equal(target.origin, 'http://127.0.0.1:5173'); assert.equal(target.pathname, '/sso/authorize'); assert.deepEqual([...target.searchParams.keys()].sort(), ['client_id', 'redirect_uri', 'state', 'code_challenge', 'code_challenge_method'].sort()); assert.equal(target.searchParams.get('client_id'), 'kefu'); assert.equal(target.searchParams.get('redirect_uri'), config.redirect_uri); assert.equal(target.searchParams.get('code_challenge_method'), 'S256'); const digest = Buffer.from(await webcrypto.subtle.digest('SHA-256', new TextEncoder().encode(pending.verifier))).toString('base64url'); assert.equal(target.searchParams.get('code_challenge'), digest); assert.equal(sso.consumeGroupCallback(href, state, now).code_verifier, pending.verifier); assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null); assert.throws(() => sso.consumeGroupCallback(href, state, now)); }); test('state mismatch, expiry, duplicates, fragments and browser profiles consume and reject', async () => { for (const mutation of [ href => href.replace(/state=.*/, `state=${'z'.repeat(43)}`), href => `${href}&state=duplicate`, href => `${href}&code=duplicate`, href => `${href}&profile=admin`, href => `${href}&redirect_uri=https://evil.example`, href => `${href}#fragment`, href => href.replace(`code=${code}`, 'code=x'), ]) { const { state, href } = await transaction(); assert.throws(() => sso.consumeGroupCallback(mutation(href), state, now)); assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null); } for (const time of [now - 1, now + 5 * 60 * 1000 + 1]) { const { state, href } = await transaction(); assert.throws(() => sso.consumeGroupCallback(href, state, time)); assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null); } }); test('entry/callback validation rejects insecure and attacker controlled configuration', () => { for (const entry of ['http://public.example', 'https://u:p@example.com', 'https://example.com/?x=1', 'https://example.com/#x', 'https://example.com/\\evil', 'https://example.com/%0a', 'https://example.com/\nx', 'javascript:alert(1)', 'https://example.com/a/../b']) { assert.throws(() => sso.validateGroupConfig({ ...config, entry, authorize_url: `${entry}/sso/authorize` }, origin)); } for (const change of [{ client_id: 'hospital' }, { enabled: false }, { authorize_url: 'https://evil.example/sso/authorize' }, { redirect_uri: 'https://evil.example/auth/group-login' }, { redirect_uri: `${origin}/other` }]) { assert.throws(() => sso.validateGroupConfig({ ...config, ...change }, origin)); } }); test('starting another login clears the old transaction', async () => { const { state, pending } = await transaction(); await sso.beginGroupLogin(config, origin, state, webcrypto, now); const next = JSON.parse(state.getItem(sso.GROUP_TRANSACTION_KEY)); assert.notEqual(next.state, pending.state); assert.notEqual(next.verifier, pending.verifier); await assert.rejects(sso.beginGroupLogin({ enabled: false }, origin, state, webcrypto, now)); assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null); }); function authHarness() { const events = []; const access = { accessToken: 'old-admin', accessCodes: ['user:write'], accessMenus: ['admin-menu'], accessRoutes: ['admin-route'], isAccessChecked: true, loginExpired: false, setAccessToken(value) { this.accessToken = value; events.push(`token:${value}`); }, setAccessCodes(value) { this.accessCodes = value; }, setLoginExpired(value) { this.loginExpired = value; } }; const user = { userInfo: { userId: '1', roles: ['user:write'] }, setUserInfo(value) { this.userInfo = value; } }; const persisted = { tabs: ['admin-users'], cachedUser: 'admin', lock: true }; const router = { async replace(path) { events.push(`route:${path}`); }, currentRoute: { value: { fullPath: '/admin' } } }; let loginUser = { userId: '7', username: 'zyt_a', realName: '源账号', roles: [], homePath: '/group/welcome' }; const api = { async getUserInfoApi() { events.push('me'); return loginUser; }, async groupExchangeApi() { return { accessToken: 'new-basic' }; }, async loginApi() { return { accessToken: 'local-user' }; }, async logoutApi() {} }; const store = loadTs('../src/store/auth.ts', { vue: { ref: value => ({ value }) }, 'vue-router': { useRouter: () => router }, '@vben/constants': { LOGIN_PATH: '/auth/login' }, '@vben/preferences': { preferences: { app: { defaultHomePath: '/model/stats' } } }, '@vben/stores': { useAccessStore: () => access, useUserStore: () => user, resetAllStores() { events.push('reset-stores'); Object.assign(access, { accessToken: null, accessCodes: [], accessMenus: [], accessRoutes: [], isAccessChecked: false }); user.userInfo = null; Object.assign(persisted, { tabs: [], cachedUser: null, lock: false }); } }, 'ant-design-vue': { notification: { success() {} } }, pinia: { defineStore: (_id, setup) => setup }, '#/api': api, '#/locales': { $t: key => key }, '#/router': { resetRoutes() { events.push('reset-routes'); } }, }).useAuthStore(); return { store, access, user, persisted, events, api, setUser: value => { loginUser = value; } }; } test('SSO from old admin clears dynamic routes, menus, tabs and persisted identity before token installation', async () => { const h = authHarness(); await h.store.authGroupLogin({ code, code_verifier: 'V'.repeat(43) }); assert.equal(h.access.accessToken, 'new-basic'); assert.equal(h.access.accessCodes.length, 0); assert.equal(h.access.accessMenus.length, 0); assert.equal(h.access.accessRoutes.length, 0); assert.equal(h.access.isAccessChecked, false); assert.equal(h.persisted.tabs.length, 0); assert.equal(h.persisted.cachedUser, null); assert.equal(h.persisted.lock, false); assert.deepEqual(h.events, ['reset-routes', 'reset-stores', 'token:new-basic', 'me', 'route:/group/welcome']); }); test('password login shares authoritative initialization and preserves forced password landing', async () => { const h = authHarness(); h.setUser({ userId: '2', roles: ['model:read'], homePath: '/profile/password' }); await h.store.authLogin({ username: 'local', password: 'Fixture@2026' }); assert.equal(h.access.accessToken, 'local-user'); assert.deepEqual(h.access.accessCodes, ['model:read']); assert.equal(h.events.at(-1), 'route:/profile/password'); }); test('local and ZYT credentials share password API and use only current /me permissions', async () => { for (const account of [ { username: 'local_operator', permissions: ['stats:read', 'conversation:read'], home: '/model/stats' }, { username: 'zyt_new', permissions: [], home: '/group/welcome' }, { username: 'zyt_authorized', permissions: ['stats:read', 'user:read'], home: '/model/stats' }, ]) { const h = authHarness(); const requests = []; const requestClient = { async post(path, body) { requests.push({ method: 'POST', path, body }); // Even stale/overbroad permissions in the login response are ignored. return { access_token: `token-${account.username}`, user: { permissions: ['user:write', 'role:write'] } }; }, async get(path) { requests.push({ method: 'GET', path }); return { id: 12, username: account.username, permissions: account.permissions, must_change_password: false, role: account.permissions.length ? 'operator' : 'zyt_basic' }; }, }; h.api.loginApi = loadTs('../src/api/core/auth.ts', { '#/api/request': { requestClient, baseRequestClient: { get() { assert.fail('Password login requested group config'); } } }, }).loginApi; h.api.getUserInfoApi = loadTs('../src/api/core/user.ts', { '#/api/request': { requestClient } }).getUserInfoApi; h.api.groupExchangeApi = async () => { assert.fail('Password login used group exchange'); }; await h.store.authLogin({ username: account.username, password: 'Fixture@2026' }); assert.equal(h.access.accessToken, `token-${account.username}`); assert.deepEqual(h.access.accessCodes, account.permissions); assert.deepEqual(h.user.userInfo.roles, account.permissions); assert.equal(h.user.userInfo.username, account.username); assert.equal(h.access.accessMenus.length, 0); assert.equal(h.access.accessRoutes.length, 0); assert.equal(h.access.isAccessChecked, false); assert.equal(h.persisted.tabs.length, 0); assert.equal(h.persisted.cachedUser, null); assert.equal(h.persisted.lock, false); assert.equal(h.store.loginLoading.value, false); assert.deepEqual(h.events, ['reset-routes', 'reset-stores', `token:token-${account.username}`, 'route:' + account.home]); assert.deepEqual(JSON.parse(JSON.stringify(requests)), [ { method: 'POST', path: '/auth/login', body: { username: account.username, password: 'Fixture@2026', device_name: 'web' } }, { method: 'GET', path: '/me' }, ]); } }); test('ordinary password errors release loading and permit retry through the same authLogin', async () => { const h = authHarness(); let attempts = 0; h.api.loginApi = async () => { if (++attempts === 1) throw new Error('账号或密码错误'); return { accessToken: 'retry-basic' }; }; const credentials = { username: 'zyt_new', password: 'Fixture@2026' }; await assert.rejects(h.store.authLogin(credentials), /账号或密码错误/); assert.equal(h.store.loginLoading.value, false); assert.deepEqual(h.events, []); h.setUser({ userId: '8', username: 'zyt_new', roles: [], homePath: '/group/welcome' }); await h.store.authLogin(credentials); assert.equal(attempts, 2); assert.equal(h.store.loginLoading.value, false); assert.equal(h.access.accessToken, 'retry-basic'); assert.deepEqual(h.access.accessCodes, []); assert.equal(h.events.at(-1), 'route:/group/welcome'); }); test('ordinary password /me failure clears new identity and allows a clean retry', async () => { const h = authHarness(); h.api.getUserInfoApi = async () => { throw new Error('revoked'); }; const credentials = { username: 'zyt_new', password: 'Fixture@2026' }; await assert.rejects(h.store.authLogin(credentials), /revoked/); assert.equal(h.store.loginLoading.value, false); assert.equal(h.access.accessToken, null); assert.equal(h.access.accessCodes.length, 0); assert.equal(h.access.accessMenus.length, 0); assert.equal(h.access.accessRoutes.length, 0); assert.equal(h.user.userInfo, null); assert.equal(h.persisted.cachedUser, null); h.api.getUserInfoApi = async () => ({ userId: '8', username: 'zyt_new', roles: [], homePath: '/group/welcome' }); await h.store.authLogin(credentials); assert.equal(h.access.accessToken, 'local-user'); assert.equal(h.access.accessCodes.length, 0); assert.equal(h.events.at(-1), 'route:/group/welcome'); }); test('failure to load current local identity clears the new token and authorization', async () => { const h = authHarness(); h.api.getUserInfoApi = async () => { throw new Error('revoked'); }; await assert.rejects(h.store.authGroupLogin({ code, code_verifier: 'V'.repeat(43) })); assert.equal(h.access.accessToken, null); assert.equal(h.access.accessCodes.length, 0); });