/** * Per-USER User Token isolation — the openId dimension. * * Before this, storage was keyed by appId alone: a second person running * `/login` on the same bot silently overwrote the first, and every later call * ran as whoever authorized last — no error, wrong name in the audit trail. * These tests pin the properties that make "act as the person who sent this * message" actually true: * * 1. two people on one bot coexist; * 2. asking for person A never returns person B's token; * 3. an unattributed legacy file is NEVER claimed for a named person * (we cannot prove whose it is); * 4. refreshing a person's token rewrites THAT person's file, not the * per-app path; * 5. `listAuthorizedUsers` reports who authorized without leaking tokens. * * Run: npx vitest run --project unit test/user-token-per-user.test.ts */ // Must stay the first import: this file fakes node:fs, so refuse to run outside // the data-dir fence instead of touching live botmux data (see the helper). import './helpers/require-fenced-data-dir.js'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import { homedir } from 'node:os'; import { join } from 'node:path'; const DIR = join(homedir(), '.botmux', 'data'); const legacyPath = join(DIR, 'user-token.json'); const perAppPath = (appId: string) => join(DIR, `user-token-${appId}.json`); const perUserPath = (appId: string, openId: string) => join(DIR, `user-token-${appId}-${openId}.json`); const files = new Map(); let afterRead: ((path: string) => void) | undefined; // The real atomicWriteFileSync goes through openSync/fsyncSync/realpathSync/rename; // stubbing it keeps these tests about WHICH FILE gets written, not about durable-write // mechanics (which atomic-write.test.ts already covers). vi.mock('../src/utils/atomic-write.js', () => ({ atomicWriteFileSync: vi.fn((p: string, data: string) => { files.set(p, data); }), })); vi.mock('../src/utils/file-lock.js', () => ({ withFileLockSync: vi.fn((_path: string, fn: () => unknown) => fn()), })); vi.mock('node:fs', async (importOriginal) => { const orig = await importOriginal(); return { ...orig, existsSync: vi.fn(() => true), mkdirSync: vi.fn(), writeFileSync: vi.fn((p: string, data: string) => { files.set(p, data); }), readdirSync: vi.fn(() => [...files.keys()] .filter(p => p.startsWith(`${DIR}/`)) .map(p => p.slice(DIR.length + 1))), readFileSync: vi.fn((p: string) => { const value = files.get(p); if (value === undefined) { const err: any = new Error('ENOENT'); err.code = 'ENOENT'; throw err; } afterRead?.(p); return value; }), }; }); function tokenFor(extra: Record = {}, ageMs = 3_600_000): string { const when = new Date(Date.now() + ageMs).toISOString(); return JSON.stringify({ access_token: 'AT', refresh_token: 'RT', token_type: 'Bearer', expires_at: when, refresh_expires_at: new Date(Date.now() + 30 * 86_400_000).toISOString(), scope: 's', ...extra, }); } async function fresh() { vi.resetModules(); return await import('../src/utils/user-token.js'); } const APP = 'cli_shared_bot'; const ALICE = 'ou_alice'; const BOB = 'ou_bob'; describe('resolveUserToken — per-user isolation', () => { beforeEach(() => { files.clear(); vi.unstubAllGlobals(); }); it('keeps two people on the same bot side by side', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_ALICE', appId: APP, brand: 'feishu', openId: ALICE })); files.set(perUserPath(APP, BOB), tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB })); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBe('TOK_ALICE'); expect(await resolveUserToken(APP, 'sec', 'feishu', BOB)).toBe('TOK_BOB'); }); it('returns access token and scopes from the same loaded credential', async () => { const path = perUserPath(APP, ALICE); files.set(path, tokenFor({ access_token: 'OLD', appId: APP, brand: 'feishu', openId: ALICE, scope: 'offline_access' })); afterRead = p => { if (p !== path) return; afterRead = undefined; // 第一次读取拿到 OLD 后换发文件;若实现再读一次补 scope,就会把 NEW 的元数据 // 错配到 OLD 上。快照必须仍返回第一次加载的完整凭证。 files.set(path, tokenFor({ access_token: 'NEW', appId: APP, brand: 'feishu', openId: ALICE, scope: 'offline_access im:resource' })); }; const { resolveUserTokenWithScopes } = await fresh(); await expect(resolveUserTokenWithScopes(APP, 'sec', 'feishu', ALICE)).resolves.toEqual({ accessToken: 'OLD', scopes: ['offline_access'], }); }); it('never hands back another person\'s token when the asked-for one is absent', async () => { files.set(perUserPath(APP, BOB), tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB })); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBeNull(); }); // The whole point of the boundary: a file with no recorded owner has no // provable owner. Claiming it for Alice would silently run as whoever // actually authorized it. it('refuses an unattributed per-app file when asked for a specific person', async () => { files.set(perAppPath(APP), tokenFor({ access_token: 'TOK_UNKNOWN', appId: APP, brand: 'feishu' })); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBeNull(); // …but the bot-level (no openId) path still reads it — legacy compatibility. expect(await resolveUserToken(APP, 'sec', 'feishu')).toBe('TOK_UNKNOWN'); }); it('refuses the pre-multi-bot legacy single file for a specific person', async () => { files.set(legacyPath, tokenFor({ access_token: 'TOK_LEGACY' })); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBeNull(); }); // Filename says Alice, content says Bob → trust neither. Guards a hand-edited // or renamed file from becoming an identity swap. it('rejects a per-user file whose inner openId contradicts its name', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK', appId: APP, brand: 'feishu', openId: BOB })); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBeNull(); }); it('cancels an expired-token refresh without overwriting the stored credential', async () => { const original = tokenFor({ appId: APP, brand: 'feishu', openId: ALICE }, -3_600_000); files.set(perUserPath(APP, ALICE), original); const controller = new AbortController(); const fetchMock = vi.fn((_url: unknown, init: RequestInit) => new Promise((_resolve, reject) => { init.signal!.addEventListener('abort', () => reject(init.signal!.reason), { once: true }); })); vi.stubGlobal('fetch', fetchMock); const { resolveUserToken } = await fresh(); const task = resolveUserToken(APP, 'sec', 'feishu', ALICE, controller.signal); const rejected = expect(task).rejects.toThrow('refresh budget expired'); expect(fetchMock.mock.calls[0][1].signal).toBe(controller.signal); controller.abort(new Error('refresh budget expired')); await rejected; expect(files.get(perUserPath(APP, ALICE))).toBe(original); }); it('does not persist a late refresh body after cancellation', async () => { const original = tokenFor({ appId: APP, brand: 'feishu', openId: ALICE }, -3_600_000); files.set(perUserPath(APP, ALICE), original); let release!: (body: unknown) => void; const json = vi.fn(() => new Promise(resolve => { release = resolve; })); vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json }))); const controller = new AbortController(); const { resolveUserToken } = await fresh(); const task = resolveUserToken(APP, 'sec', 'feishu', ALICE, controller.signal); const rejected = expect(task).rejects.toThrow('cancelled'); await vi.waitFor(() => expect(json).toHaveBeenCalled()); controller.abort(new Error('cancelled')); release({ access_token: 'LATE', refresh_token: 'NEW_RT', expires_in: 7200, refresh_token_expires_in: 1000, token_type: 'Bearer' }); await rejected; expect(files.get(perUserPath(APP, ALICE))).toBe(original); }); it('keeps a newer token that replaces the credential while refresh is in flight', async () => { const path = perUserPath(APP, ALICE); files.set(path, tokenFor({ access_token: 'EXPIRED', refresh_token: 'OLD_RT', appId: APP, brand: 'feishu', openId: ALICE, }, -60_000)); let release!: (body: unknown) => void; const json = vi.fn(() => new Promise(resolve => { release = resolve; })); vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json }))); const { resolveUserToken } = await fresh(); const task = resolveUserToken(APP, 'sec', 'feishu', ALICE); await vi.waitFor(() => expect(json).toHaveBeenCalled()); const newer = tokenFor({ access_token: 'NEWER', refresh_token: 'NEWER_RT', appId: APP, brand: 'feishu', openId: ALICE, }); files.set(path, newer); release({ access_token: 'LATE', refresh_token: 'LATE_RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 2_592_000, scope: 's', }); expect(await task).toBe('NEWER'); expect(files.get(path)).toBe(newer); }); it('refreshes into the same person\'s file, never the per-app path', async () => { // Access token already expired, refresh token still good. files.set(perUserPath(APP, ALICE), tokenFor( { access_token: 'OLD', appId: APP, brand: 'feishu', openId: ALICE, userName: 'Alice' }, -60_000, )); vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ access_token: 'NEW', refresh_token: 'RT2', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 2_592_000, scope: 's', }), { status: 200, headers: { 'content-type': 'application/json' } }))); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBe('NEW'); const written = JSON.parse(files.get(perUserPath(APP, ALICE))!); expect(written.access_token).toBe('NEW'); // Ownership survives the refresh — a refresh is the same person, and the // display name must not be lost either. expect(written.openId).toBe(ALICE); expect(written.userName).toBe('Alice'); expect(files.has(perAppPath(APP))).toBe(false); }); it('persists rotated credentials when refresh returns a reduced scope set', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'EXPIRED', refresh_token: 'OLD_RT', appId: APP, brand: 'feishu', openId: ALICE, scope: 'offline_access docs:document.comment:read', }, -60_000)); vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ access_token: 'FRESH', refresh_token: 'ROTATED_RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 2_592_000, scope: 'offline_access', }), { status: 200, headers: { 'content-type': 'application/json' } }))); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBe('FRESH'); const written = JSON.parse(files.get(perUserPath(APP, ALICE))!); expect(written).toMatchObject({ access_token: 'FRESH', refresh_token: 'ROTATED_RT', scope: 'offline_access', openId: ALICE, }); }); it('returns a refreshed snapshot and keeps the reduced-scope warning', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'EXPIRED', refresh_token: 'OLD_RT', appId: APP, brand: 'feishu', openId: ALICE, scope: 'offline_access im:resource', onDemandScopes: ['im:resource'], }, -60_000)); vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ access_token: 'FRESH', refresh_token: 'ROTATED_RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 2_592_000, scope: 'offline_access', }), { status: 200, headers: { 'content-type': 'application/json' } }))); const mod = await fresh(); const { logger } = await import('../src/utils/logger.js'); const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}); await expect(mod.resolveUserTokenWithScopes(APP, 'sec', 'feishu', ALICE)).resolves.toEqual({ accessToken: 'FRESH', scopes: ['offline_access'], }); expect(JSON.parse(files.get(perUserPath(APP, ALICE))!)).not.toHaveProperty('onDemandScopes'); expect(warn).toHaveBeenCalledWith(expect.stringContaining('im:resource')); warn.mockRestore(); }); it('does not invent an owner when refreshing an unattributed file', async () => { files.set(perAppPath(APP), tokenFor({ access_token: 'OLD', appId: APP, brand: 'feishu' }, -60_000)); vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ access_token: 'NEW', refresh_token: 'RT2', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 2_592_000, scope: 's', }), { status: 200, headers: { 'content-type': 'application/json' } }))); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu')).toBe('NEW'); expect(JSON.parse(files.get(perAppPath(APP))!).openId).toBeUndefined(); }); it('rejects an openId that could escape the token directory', async () => { const { resolveUserToken, isUsableOpenId } = await fresh(); expect(isUsableOpenId('../../etc/passwd')).toBe(false); expect(isUsableOpenId('ou_ok')).toBe(true); // A traversal-shaped id degrades to the bot-level lookup rather than // composing a path outside ~/.botmux/data. expect(await resolveUserToken(APP, 'sec', 'feishu', '../../etc/passwd')).toBeNull(); }); }); describe('listAuthorizedUsers', () => { beforeEach(() => { files.clear(); }); it('reports each authorizing person without exposing token material', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_ALICE', appId: APP, brand: 'feishu', openId: ALICE, userName: 'Alice' })); files.set(perUserPath(APP, BOB), tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB })); // Noise that must not be counted: another bot's user, and an unattributed file. files.set(perUserPath('cli_other', ALICE), tokenFor({ access_token: 'X', appId: 'cli_other', brand: 'feishu', openId: ALICE })); files.set(perAppPath(APP), tokenFor({ access_token: 'X', appId: APP, brand: 'feishu' })); const { listAuthorizedUsers } = await fresh(); const rows = listAuthorizedUsers(APP, 'feishu'); expect(rows.map(r => r.openId).sort()).toEqual([ALICE, BOB]); expect(rows.find(r => r.openId === ALICE)?.userName).toBe('Alice'); expect(JSON.stringify(rows)).not.toContain('TOK_'); }); it('is empty for a bot nobody authorized', async () => { const { listAuthorizedUsers } = await fresh(); expect(listAuthorizedUsers('cli_nobody', 'feishu')).toEqual([]); }); }); describe('userTokenAuthState — one person, no token contents', () => { beforeEach(() => { files.clear(); }); it('reports a live token as authorized with both expiry times and no secrets', async () => { const accessAt = new Date(Date.now() + 3_600_000).toISOString(); const refreshAt = new Date(Date.now() + 30 * 86_400_000).toISOString(); files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_ALICE', refresh_token: 'REFRESH_ALICE', appId: APP, brand: 'feishu', openId: ALICE, userName: 'Fixture', expires_at: accessAt, refresh_expires_at: refreshAt, })); files.set(perUserPath(APP, BOB), tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB, expires_at: '2099-02-02T00:00:00.000Z', refresh_expires_at: '2099-03-03T00:00:00.000Z', })); const { userTokenAuthState } = await fresh(); const alice = userTokenAuthState(APP, 'feishu', ALICE); expect(alice).toEqual({ state: 'authorized', expiresAt: accessAt, refreshExpiresAt: refreshAt }); expect(JSON.stringify(alice)).not.toContain('TOK_'); expect(JSON.stringify(alice)).not.toContain('REFRESH_'); expect(JSON.stringify(alice)).not.toContain('Fixture'); expect(userTokenAuthState(APP, 'feishu', BOB).expiresAt).toBe('2099-02-02T00:00:00.000Z'); }); it('stays authorized while the access token is expired but the refresh token is not', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_ALICE', refresh_token: 'REFRESH_ALICE', appId: APP, brand: 'feishu', openId: ALICE, expires_at: '2000-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-01T00:00:00.000Z', })); const { userTokenAuthState } = await fresh(); expect(userTokenAuthState(APP, 'feishu', ALICE)).toEqual({ state: 'authorized', expiresAt: '2000-01-01T00:00:00.000Z', refreshExpiresAt: '2099-01-01T00:00:00.000Z', }); }); it('needs a new login once both expiries are past, and still reports those times', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_DEAD', refresh_token: 'REFRESH_DEAD', appId: APP, brand: 'feishu', openId: ALICE, expires_at: '2000-01-01T00:00:00.000Z', refresh_expires_at: '2000-02-01T00:00:00.000Z', })); const { userTokenAuthState } = await fresh(); expect(userTokenAuthState(APP, 'feishu', ALICE)).toEqual({ state: 'needs-login', expiresAt: '2000-01-01T00:00:00.000Z', refreshExpiresAt: '2000-02-01T00:00:00.000Z', }); expect(userTokenAuthState(APP, 'feishu', BOB)).toEqual({ state: 'needs-login' }); }); it('does not treat another person or an unattributed file as this person', async () => { files.set(perUserPath(APP, BOB), tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB })); files.set(perAppPath(APP), tokenFor({ access_token: 'TOK_APP', appId: APP, brand: 'feishu' })); files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_MISFILED', appId: APP, brand: 'feishu', openId: BOB })); const { userTokenAuthState } = await fresh(); expect(userTokenAuthState(APP, 'feishu', ALICE)).toEqual({ state: 'needs-login' }); expect(userTokenAuthState(APP, 'feishu', '../../etc/passwd')).toEqual({ state: 'unknown' }); expect(JSON.stringify(userTokenAuthState(APP, 'feishu', ALICE))).not.toContain('TOK_'); }); }); describe('resolveOwnerUserToken — the one narrow fallback', () => { beforeEach(() => { files.clear(); }); // Feed-group labels live in the OWNER's own sidebar; a bot has no inbox, so // this call can only ever mean "as the owner". Existing installs stored the // owner's token in the unattributed per-app file, and refusing it would make // the label feature silently stop working right after an upgrade. it('accepts an unattributed per-app file as the owner', async () => { files.set(perAppPath(APP), tokenFor({ access_token: 'TOK_OLD_OWNER', appId: APP, brand: 'feishu' })); const { resolveOwnerUserToken, resolveUserToken } = await fresh(); expect(await resolveOwnerUserToken(APP, 'sec', 'feishu', ALICE)).toBe('TOK_OLD_OWNER'); // The strict per-person path still refuses it — the fallback is owner-only. expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBeNull(); }); it('prefers the owner\'s own file over the unattributed one', async () => { files.set(perAppPath(APP), tokenFor({ access_token: 'TOK_OLD', appId: APP, brand: 'feishu' })); files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK_ALICE', appId: APP, brand: 'feishu', openId: ALICE })); const { resolveOwnerUserToken } = await fresh(); expect(await resolveOwnerUserToken(APP, 'sec', 'feishu', ALICE)).toBe('TOK_ALICE'); }); // The fallback widens WHICH FILE counts as the owner's, never WHOSE identity // may be borrowed: another named person's file is still off limits. it('never falls back to a different named person', async () => { files.set(perUserPath(APP, BOB), tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB })); const { resolveOwnerUserToken } = await fresh(); expect(await resolveOwnerUserToken(APP, 'sec', 'feishu', ALICE)).toBeNull(); }); }); /** * Attribution at the moment of authorization. * * The OAuth token response carries no open_id, so who authorized is known only * by reading `user_info` back with the fresh token. That read-back is not a * formality: a /login link can be forwarded, so the person who clicked is not * reliably the person who asked. If it fails, guessing "probably the requester" * is exactly how B's credentials end up filed under A — after which every one * of A's commands runs with B's permissions, with nothing to show for it. */ describe('handleCallbackUrl — attribution must be proven, never assumed', () => { beforeEach(() => { files.clear(); vi.unstubAllGlobals(); }); /** @param userInfo how the user_info read-back behaves. */ async function runCallback(userInfo: { status?: number; body?: unknown; throws?: boolean }) { const mod = await fresh(); const { authUrl } = mod.generateAuthUrl(APP, 'sec', 'feishu', [], ALICE); const state = new URL(authUrl).searchParams.get('state')!; vi.stubGlobal('fetch', vi.fn(async (url: string) => { if (String(url).includes('/oauth/token')) { return { ok: true, json: async () => ({ access_token: 'AT', refresh_token: 'RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 604800, scope: 's', }), }; } if (userInfo.throws) throw new Error('network down'); return { ok: userInfo.status === undefined, status: userInfo.status ?? 200, json: async () => userInfo.body }; })); const msg = await mod.handleCallbackUrl(`http://127.0.0.1:9768/callback?code=abc&state=${state}`); return { msg, mod }; } it('files the token under the person who actually authorized', async () => { const { msg } = await runCallback({ body: { code: 0, data: { open_id: ALICE, name: '爱丽丝' } } }); expect(msg).toContain('✅'); expect(files.has(perUserPath(APP, ALICE))).toBe(true); }); it('includes the same user\'s existing scopes in an incremental browser authorization', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ appId: APP, brand: 'feishu', openId: ALICE, scope: 'docs:document.comment:read offline_access', })); const mod = await fresh(); const { authUrl } = mod.generateAuthUrl( APP, 'sec', 'feishu', ['contact:user.base:readonly'], ALICE, ); expect(new URL(authUrl).searchParams.get('scope')?.split(' ')).toEqual([ 'im:message:readonly', 'offline_access', 'contact:user.base:readonly', 'docs:document.comment:read', ]); }); it('records an explicit /login --scope im:resource and keeps requesting it afterwards', async () => { const mod = await fresh(); const { authUrl } = mod.generateAuthUrl(APP, 'sec', 'feishu', ['im:resource'], ALICE); const requested = new URL(authUrl).searchParams.get('scope')!; const state = new URL(authUrl).searchParams.get('state')!; vi.stubGlobal('fetch', vi.fn(async (url: string) => String(url).includes('/oauth/token') ? { ok: true, json: async () => ({ access_token: 'AT', refresh_token: 'RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 604800, scope: requested }) } : { ok: true, status: 200, json: async () => ({ code: 0, data: { open_id: ALICE } }) })); expect(await mod.handleCallbackUrl(`http://127.0.0.1:9768/callback?code=abc&state=${state}`)).toContain('✅'); expect(JSON.parse(files.get(perUserPath(APP, ALICE))!).onDemandScopes).toEqual(['im:resource']); const next = mod.generateAuthUrl(APP, 'sec', 'feishu', [], ALICE); expect(new URL(next.authUrl).searchParams.get('scope')!.split(' ')).toContain('im:resource'); }); it('does not record im:resource when Feishu did not actually grant it', async () => { const mod = await fresh(); const { authUrl } = mod.generateAuthUrl(APP, 'sec', 'feishu', ['im:resource'], ALICE); const granted = new URL(authUrl).searchParams.get('scope')!.split(' ').filter(s => s !== 'im:resource').join(' '); const state = new URL(authUrl).searchParams.get('state')!; vi.stubGlobal('fetch', vi.fn(async (url: string) => String(url).includes('/oauth/token') ? { ok: true, json: async () => ({ access_token: 'AT', refresh_token: 'RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 604800, scope: granted }) } : { ok: true, status: 200, json: async () => ({ code: 0, data: { open_id: ALICE } }) })); await mod.handleCallbackUrl(`http://127.0.0.1:9768/callback?code=abc&state=${state}`); expect(JSON.parse(files.get(perUserPath(APP, ALICE))!)).not.toHaveProperty('onDemandScopes'); }); it('keeps a newer explicit marker when an old pending callback retains the scope', async () => { const oldFlow = await fresh(); const { authUrl, state } = oldFlow.generateAuthUrl(APP, 'sec', 'feishu', ['im:resource'], ALICE); const requested = new URL(authUrl).searchParams.get('scope')!; // 升级前落盘的 pending 没有 onDemandScopes;重新 import 让回调只从持久文件读取它。 const pendingPath = join(DIR, 'oauth-pending', `${state}.json`); const pending = JSON.parse(files.get(pendingPath)!); delete pending.onDemandScopes; files.set(pendingPath, JSON.stringify(pending)); files.set(perUserPath(APP, ALICE), tokenFor({ appId: APP, brand: 'feishu', openId: ALICE, scope: requested, onDemandScopes: ['im:resource'], })); const mod = await fresh(); vi.stubGlobal('fetch', vi.fn(async (url: string) => String(url).includes('/oauth/token') ? { ok: true, json: async () => ({ access_token: 'NEW_AT', refresh_token: 'NEW_RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 604800, scope: requested }) } : { ok: true, status: 200, json: async () => ({ code: 0, data: { open_id: ALICE } }) })); expect(await mod.handleCallbackUrl(`http://127.0.0.1:9768/callback?code=abc&state=${state}`)).toContain('✅'); expect(JSON.parse(files.get(perUserPath(APP, ALICE))!).onDemandScopes).toEqual(['im:resource']); const later = mod.generateAuthUrl(APP, 'sec', 'feishu', ['base:field:read'], ALICE); expect(new URL(later.authUrl).searchParams.get('scope')!.split(' ')).toContain('im:resource'); }); it('does not invent an explicit marker for a legacy-default scope retained by a callback', async () => { const mod = await fresh(); files.set(perUserPath(APP, ALICE), tokenFor({ appId: APP, brand: 'feishu', openId: ALICE, scope: 'im:message:readonly im:resource offline_access', })); const { authUrl, state } = mod.generateAuthUrl(APP, 'sec', 'feishu', ['base:field:read'], ALICE); const requested = new URL(authUrl).searchParams.get('scope')!; expect(requested.split(' ')).not.toContain('im:resource'); const granted = `${requested} im:resource`; vi.stubGlobal('fetch', vi.fn(async (url: string) => String(url).includes('/oauth/token') ? { ok: true, json: async () => ({ access_token: 'NEW_AT', refresh_token: 'NEW_RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 604800, scope: granted }) } : { ok: true, status: 200, json: async () => ({ code: 0, data: { open_id: ALICE } }) })); expect(await mod.handleCallbackUrl(`http://127.0.0.1:9768/callback?code=abc&state=${state}`)).toContain('✅'); expect(JSON.parse(files.get(perUserPath(APP, ALICE))!)).not.toHaveProperty('onDemandScopes'); }); it('does not keep requesting an im:resource that only came with the old default login', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ appId: APP, brand: 'feishu', openId: ALICE, scope: 'im:message:readonly im:resource offline_access' })); const mod = await fresh(); const next = mod.generateAuthUrl(APP, 'sec', 'feishu', [], ALICE); expect(new URL(next.authUrl).searchParams.get('scope')!.split(' ')).not.toContain('im:resource'); }); // The forwarded-link case: Bob clicked Alice's link. Bob's token is Bob's. it('files under the clicker, not the requester, and says so', async () => { const { msg } = await runCallback({ body: { code: 0, data: { open_id: BOB, name: '鲍勃' } } }); expect(files.has(perUserPath(APP, BOB))).toBe(true); expect(files.has(perUserPath(APP, ALICE))).toBe(false); expect(msg).toContain('不是同一个人'); }); it('refuses to overwrite the clicker when a forwarded link would drop their existing scopes', async () => { const original = tokenFor({ access_token: 'TOK_BOB', appId: APP, brand: 'feishu', openId: BOB, scope: 'docs:document.comment:read offline_access', }); files.set(perUserPath(APP, BOB), original); const { msg } = await runCallback({ body: { code: 0, data: { open_id: BOB, name: '鲍勃' } } }); expect(files.get(perUserPath(APP, BOB))).toBe(original); expect(msg).toContain('避免覆盖后降权'); expect(msg).toContain('docs:document.comment:read'); }); it.each([ ['a non-2xx response', { status: 500, body: {} }], ['a Lark error code', { body: { code: 99991663, msg: 'invalid token' } }], ['a response with no usable open_id', { body: { code: 0, data: { name: 'nobody' } } }], ['a network failure', { throws: true }], ])('saves nothing when the read-back gives %s', async (_label, userInfo) => { const { msg } = await runCallback(userInfo as any); // Nothing written anywhere — not under the requester, not per-app. expect([...files.keys()].filter(p => p.includes('user-token'))).toEqual([]); // And the person is told to retry rather than left believing they are done. expect(msg).toContain('无法确认'); expect(msg).toContain('/login'); }); }); /** * /login 授权码回调拿回的 token 缺了申请的 scope(典型:那些权限还在应用新版本的企业审核 * 里)。这条链路的保存判定不变,但不能只回一句「授权成功」——用户紧接着重试会再撞缺权限。 */ describe('handleCallbackUrl — scopes the grant left out', () => { beforeEach(() => { files.clear(); vi.unstubAllGlobals(); }); async function callbackGranting( grantedScope: (requested: string[]) => string | undefined, versions: unknown, opts: { legacyPending?: boolean } = {}, ) { let mod = await fresh(); const { authUrl } = mod.generateAuthUrl(APP, 'sec', 'feishu', ['docx:document:create', 'im:feed.flag:read'], ALICE); const requested = new URL(authUrl).searchParams.get('scope')!.split(' '); const state = new URL(authUrl).searchParams.get('state')!; if (opts.legacyPending) { // 升级前生成的 pending 文件没有 scopes 字段;换一个模块实例,只能从盘上读到它。 const path = [...files.keys()].find(p => p.endsWith(`${state}.json`))!; const { scopes: _scopes, ...legacy } = JSON.parse(files.get(path)!); files.set(path, JSON.stringify(legacy)); mod = await fresh(); } const calls: string[] = []; vi.stubGlobal('fetch', vi.fn(async (url: string) => { calls.push(String(url)); if (String(url).includes('/oauth/token')) { return Response.json({ access_token: 'AT', refresh_token: 'RT', token_type: 'Bearer', expires_in: 7200, refresh_token_expires_in: 604800, scope: grantedScope(requested), }); } if (String(url).endsWith('/user_info')) return Response.json({ code: 0, data: { open_id: ALICE, name: '爱丽丝' } }); if (String(url).endsWith('/tenant_access_token/internal')) return Response.json({ code: 0, tenant_access_token: 'tt' }); if (String(url).includes(`/applications/${APP}/app_versions`)) return Response.json(versions); throw new Error(`unexpected ${url}`); })); const detailed = await mod.handleCallbackUrlDetailed(`http://127.0.0.1:9768/callback?code=abc&state=${state}`); const msg = detailed!.warning ? `${detailed!.message}\n${detailed!.warning}` : detailed!.message; return { msg, detailed: detailed!, calls }; } const inReview = { code: 0, data: { items: [{ version: '1.0.11', version_id: 'oav_p', status: 3 }] } }; it('still saves, but names the missing scope and the version under review', async () => { const { msg } = await callbackGranting(requested => requested.filter(s => s !== 'im:feed.flag:read').join(' '), inReview); expect(msg).toContain('✅'); expect(files.has(perUserPath(APP, ALICE))).toBe(true); expect(msg).toContain('im:feed.flag:read'); expect(msg).not.toContain('docx:document:create'); expect(msg).toContain('1.0.11'); }); it('names the missing scope without a review claim when the version state is unreadable', async () => { const { msg } = await callbackGranting( requested => requested.filter(s => s !== 'im:feed.flag:read').join(' '), { code: 99991672, msg: 'scope not applied' }, ); expect(msg).toContain('✅'); expect(msg).toContain('im:feed.flag:read'); // 查不到版本状态就不能声称「在审核」——审核是这里唯一被禁止猜测的原因。 expect(msg).not.toContain('1.0.11'); expect(msg).not.toContain('审核'); }); it('hands the note back separately so auto-callback pages can show it', async () => { const { detailed } = await callbackGranting(requested => requested.filter(s => s !== 'im:feed.flag:read').join(' '), inReview); expect(detailed.message).toContain('✅'); expect(detailed.message).not.toContain('im:feed.flag:read'); expect(detailed.warning).toContain('im:feed.flag:read'); expect(detailed.warning).toContain('1.0.11'); }); it('does not blame a pending version that does not carry the missing scope', async () => { const unrelated = { code: 0, data: { items: [{ version: '1.0.11', status: 3, scopes: [{ scope: 'contact:user.base:readonly', token_types: ['user'] }] }] } }; const { msg } = await callbackGranting(requested => requested.filter(s => s !== 'im:feed.flag:read').join(' '), unrelated); expect(msg).toContain('im:feed.flag:read'); expect(msg).not.toContain('审核'); }); it('treats an explicitly empty scope as granting none of the requested scopes', async () => { const { msg, detailed, calls } = await callbackGranting(() => '', inReview); expect(msg).toContain('✅'); expect(detailed.warning).toBeDefined(); expect(files.has(perUserPath(APP, ALICE))).toBe(true); // #3724 后 DEFAULT_SCOPES 不再含 im:resource:无既有 token 时申请集就是下面四项 for (const scope of [ 'im:message:readonly', 'offline_access', 'docx:document:create', 'im:feed.flag:read', ]) expect(msg).toContain(scope); expect(calls.some(url => url.includes('/app_versions'))).toBe(true); }); it.each([ ['the token response carries no scope field', { grant: () => undefined, legacyPending: false }], ['the pending file predates the scopes record', { grant: (requested: string[]) => requested.filter(s => s !== 'im:feed.flag:read').join(' '), legacyPending: true, }], ])('says nothing extra when %s', async (_label, { grant, legacyPending }) => { const { msg, calls } = await callbackGranting(grant, inReview, { legacyPending }); expect(msg).toContain('✅'); expect(msg).not.toContain('⚠️'); expect(calls.some(url => url.includes('/app_versions'))).toBe(false); }); it('adds nothing and queries nothing when every requested scope was granted', async () => { const { msg, calls } = await callbackGranting(requested => requested.join(' '), inReview); expect(msg).toContain('✅'); expect(msg).not.toContain('⚠️'); expect(calls.some(url => url.includes('/app_versions'))).toBe(false); }); }); /** * The readers, not the writer. * * Per-person storage is only half a feature: `/login` writes * `user-token--.json`, and every consumer that looks a token up * WITHOUT the openId then finds nothing. The failure is invisible in the worst * way — the person authorizes, is told it worked, and the feature still reports * "not logged in" with no error anywhere. * * It also does not wait for the feature to be switched on. Three of the * affected readers are on the default path, and the trigger is ordinary: the * legacy per-app file keeps working until it expires, so the breakage arrives * the first time someone re-authorizes. * * These tests pin the shape of the contract — a token written the way /login * writes it must be readable by the callers that consume it — rather than * asserting on any one call site's arguments, which a later refactor would * silently drift away from. */ describe('per-person tokens must be readable by the code that consumes them', () => { beforeEach(() => { files.clear(); vi.unstubAllGlobals(); }); /** Exactly what a completed /login leaves on disk. */ function authorizedAs(openId: string, token = 'TOK') { files.set(perUserPath(APP, openId), tokenFor({ access_token: token, appId: APP, brand: 'feishu', openId, userName: '孙晓雪', })); } it('finds the token when the reader passes the person', async () => { authorizedAs(ALICE, 'TOK_ALICE'); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu', ALICE)).toBe('TOK_ALICE'); }); // The regression itself. A reader that forgets the openId gets null even // though that exact person just authorized — which is how "/login says OK, // feature still broken" happens. it('finds nothing when the reader omits the person', async () => { authorizedAs(ALICE, 'TOK_ALICE'); const { resolveUserToken } = await fresh(); expect(await resolveUserToken(APP, 'sec', 'feishu')).toBeNull(); }); it('reports status per person, not per app', async () => { authorizedAs(ALICE); const { getTokenStatus } = await fresh(); expect(getTokenStatus(APP, 'feishu', ALICE)).toContain('已登录'); // Without the openId the same store reads as empty. expect(getTokenStatus(APP, 'feishu')).toContain('未登录'); }); // The Dashboard feed-group badge reads this. With no owner resolved it asks // with `undefined` and shows "not authorized" to someone who just authorized. it('reports feed-group auth per owner', async () => { files.set(perUserPath(APP, ALICE), tokenFor({ access_token: 'TOK', appId: APP, brand: 'feishu', openId: ALICE, scope: 'im:feed_group_v1:write im:feed_group_v1:read', })); const { getFeedGroupAuthStatus } = await fresh(); expect(getFeedGroupAuthStatus(APP, 'feishu', ALICE).authorized).toBe(true); expect(getFeedGroupAuthStatus(APP, 'feishu', undefined).authorized).toBe(false); }); });