import test from 'node:test'; import assert from 'node:assert/strict'; import { mkdtemp, readFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve, sep } from 'node:path'; import { captureRefreshGrant, createNetworkRenewal, sessionExpiry, mergeSessionCredentials, refreshGrantsFromMsalCache, hasMatchingRefreshGrant } from '../src/network-renewal.js'; import { createProtectedJson } from '../src/protected-json.js'; const instant = 1800000000000, tenant = '11111111-1111-1111-1111-111111111111', user = '22222222-2222-2222-2222-222222222222', client = '33333333-3333-3333-3333-333333333333'; const token = (changes = {}) => `fixture.${Buffer.from(JSON.stringify({ tid: tenant, oid: user, appid: client, aud: 'fixture-resource', scp: 'read history', exp: (instant + 120000) / 1000, ...changes })).toString('base64url')}.private-signature`; const session = (access = token()) => ({ log: { entries: [{ request: { url: 'https://teams.cloud.microsoft/api/chatsvc/v1/users/ME/conversations/test/messages', headers: [{ name: 'Authorization', value: `Bearer ${access}` }] }, response: { private: 'preserve-payload' } }] } }); const authCapture = (access = token()) => ({ url: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`, method: 'POST', headers: [{ name: 'Origin', value: 'https://teams.cloud.microsoft' }], body: new URLSearchParams({ client_id: client, scope: 'fixture-resource/read offline_access', redirect_uri: 'https://teams.cloud.microsoft/', grant_type: 'authorization_code', code: 'one-use-private-code', code_verifier: 'private-verifier' }).toString(), response: { token_type: 'Bearer', access_token: access, refresh_token: 'private-refresh', id_token: 'never-persist-id-token' }, now: instant }); function memoryVault() { let value; return { read: async () => structuredClone(value), write: async next => { value = structuredClone(next); }, value: () => value }; } const response = (payload, status = 200, headers = {}) => new Response(JSON.stringify(payload), { status, headers }); const freshResponse = (changes = {}) => response({ token_type: 'Bearer', access_token: token({ exp: (instant + 3600000) / 1000, ...changes }), refresh_token: 'rotated-private-refresh' }); async function fixture(options = {}) { const vault = options.vault || memoryVault(), requests = []; let clock = instant; const renewal = createNetworkRenewal({ dataDir: 'unused', vault, now: () => clock, fetch: async (...args) => { requests.push(args); return options.fetch ? options.fetch(...args) : freshResponse(); } }); await renewal.install([captureRefreshGrant(authCapture())], session(), options.profile); return { renewal, vault, requests, advance: milliseconds => { clock += milliseconds; } }; } test('expired or nearly expired MSAL access tokens cannot declare browser recovery complete', () => { const har = session(); for (const expiry of [instant - 60000, instant, instant + 30000]) { const grant = captureRefreshGrant({ ...authCapture(token({ exp: expiry / 1000 })), now: 0 }); assert.equal(hasMatchingRefreshGrant(har, [grant], instant), false); } const fresh = captureRefreshGrant(authCapture(token({ exp: (instant + 3600000) / 1000 }))); assert.equal(hasMatchingRefreshGrant(har, [fresh], instant), true); assert.equal(hasMatchingRefreshGrant(session(token({ oid: '44444444-4444-4444-4444-444444444444' })), [fresh], instant), false); assert.equal(hasMatchingRefreshGrant(session(token({ scp: 'read history extra' })), [fresh], instant), false); }); test('capture accepts only observed public-client grants on allowed Microsoft endpoints and never retains code or verifier', () => { const grant = captureRefreshGrant(authCapture()); assert.ok(grant); assert.doesNotMatch(JSON.stringify(grant), /private-code|private-verifier|never-persist|authorization_code/); for (const mutate of [c => c.url = 'https://evil.example/token', c => c.url += '?redirect=private', c => c.headers[0].value = 'https://evil.example', c => c.body += '&client_secret=private', c => c.body += '&client_id=other', c => c.response.access_token = token({ oid: 'unknown' }), c => c.response.access_token = token({ appid: tenant }), c => c.response.access_token = token({ tid: user }), c => c.body = c.body.replace(encodeURIComponent('https://teams.cloud.microsoft/'), encodeURIComponent('https://evil.example/'))]) { const c = authCapture(); mutate(c); assert.equal(captureRefreshGrant(c), null); } }); test('observed broker query and redirect parameters are retained while unknown token URL parameters stay blocked', () => { const captured = authCapture(); captured.url += `?client_id=${client}&brk_client_id=${user}&brk_redirect_uri=https%3A%2F%2Fteams.cloud.microsoft&client-request-id=${tenant}`; const form = new URLSearchParams(captured.body); form.set('redirect_uri', 'brk-multihub://outlook.office.com'); form.set('brk_client_id', user); form.set('brk_redirect_uri', 'https://teams.cloud.microsoft'); captured.body = form.toString(); const grant = captureRefreshGrant(captured); assert.ok(grant); assert.equal(grant.params.brk_client_id, user); assert.equal(captureRefreshGrant({ ...captured, url: captured.url + '&redirect_to=https://evil.example' }), null); }); test('MSAL cache establishes same-client same-account renewal even without a token POST for the captured resource', () => { const har = session(token({ aud: 'https://ic3.teams.office.com' })); const proof = { credentialType: 'AccessToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', realm: tenant, secret: token({ aud: 'https://other-resource.example', exp: (instant + 3600000) / 1000 }), target: 'https://other-resource.example/read' }; const refresh = { credentialType: 'RefreshToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', secret: 'private-own-refresh' }; const result = refreshGrantsFromMsalCache([proof, refresh], [], har, instant); assert.equal(result.length, 1); assert.equal(result[0].params.scope, 'https://ic3.teams.office.com/.default'); assert.equal(result[0].refreshToken, refresh.secret); for (const changes of [{ clientId: user }, { homeAccountId: 'foreign-home' }, { environment: 'evil.example' }]) assert.equal(refreshGrantsFromMsalCache([proof, { ...refresh, ...changes }], [], har, instant).length, 0); assert.equal(refreshGrantsFromMsalCache([{ ...proof, secret: token({ oid: tenant }) }, refresh], [], har, instant).length, 0); assert.equal(refreshGrantsFromMsalCache([proof, refresh], [], session(token({ aud: 'https://unobserved.example' })), instant).length, 0); }); test('Teams root-slash aliases match and expanded MSAL cache scopes cannot send an invalid dynamic/.default mix', async () => { const access = token({ aud: 'https://outlook.office.com/', exp: (instant + 3600000) / 1000 }); const cache = [{ credentialType: 'AccessToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', realm: tenant, secret: access, target: 'https://outlook.office.com//read https://outlook.office.com//.default' }, { credentialType: 'RefreshToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', secret: 'private-refresh' }]; const har = session(token({ aud: 'https://outlook.office.com' })), grants = refreshGrantsFromMsalCache(cache, [], har, instant); assert.equal(grants.length, 1); assert.equal(grants[0].params.scope, 'https://outlook.office.com/.default'); const vault = memoryVault(); let scope; const renewal = createNetworkRenewal({ dataDir: 'unused', vault, now: () => instant, fetch: async (_, options) => { scope = new URLSearchParams(options.body).get('scope'); return response({ token_type: 'Bearer', access_token: access, refresh_token: 'rotated' }); } }); await renewal.install(grants, har); const result = await renewal.renew({ har, force: true }); assert.equal(result.changed, true); assert.equal(result.status.state, 'renewed'); assert.equal(scope, 'https://outlook.office.com/.default'); }); test('fresh browser cookies never cross origins or account boundaries', () => { const old = session(); old.log.entries[0].request.headers.push({ name: 'Cookie', value: 'old' }); const fresh = session(token({ exp: (instant + 3600000) / 1000 })); fresh.log.entries[0].request.headers.push({ name: 'Cookie', value: 'new' }); assert.equal(mergeSessionCredentials(old, fresh, [], instant).log.entries[0].request.headers[1].value, 'new'); fresh.log.entries[0].request.url = 'https://outlook.office.com/api/events'; assert.equal(mergeSessionCredentials(old, fresh, [], instant).log.entries[0].request.headers[1].value, 'old'); }); test('renewal rotates a resource credential once, updates all matching headers and preserves payload and other resources', async () => { const f = await fixture(), har = session(); har.log.entries.push(...session(token({ aud: 'calendar-resource', exp: (instant + 7200000) / 1000 })).log.entries); const [a, b] = await Promise.all([f.renewal.renew({ har }), f.renewal.renew({ har })]); assert.equal(f.requests.length, 1); assert.equal(a, b); assert.equal(a.changed, true); const [url, options] = f.requests[0]; assert.equal(url, authCapture().url); assert.equal(options.redirect, 'error'); assert.equal(new URLSearchParams(options.body).get('grant_type'), 'refresh_token'); assert.equal(new URLSearchParams(options.body).get('refresh_token'), 'private-refresh'); assert.equal(options.headers.Origin, 'https://teams.cloud.microsoft'); assert.equal(a.har.log.entries[0].response.private, 'preserve-payload'); assert.deepEqual(a.har.log.entries[1], har.log.entries[1]); assert.equal(har.log.entries[0].request.headers[0].value, `Bearer ${token()}`); assert.equal(f.vault.value().grants[0].refreshToken, 'rotated-private-refresh'); assert.equal(a.status.state, 'renewed'); assert.equal(sessionExpiry(a.har), new Date(instant + 3600000).toISOString()); assert.doesNotMatch(JSON.stringify(a.status), /private|11111111|22222222|33333333|fixture-resource/); }); test('valid tokens make no refresh request; restart loads rotated cache without using a browser', async () => { const f = await fixture(); const valid = session(token({ exp: (instant + 7200000) / 1000 })); assert.equal((await f.renewal.renew({ har: valid })).changed, false); assert.equal(f.requests.length, 0); const renewed = await f.renewal.renew({ har: session() }); let calls = 0; const restarted = createNetworkRenewal({ dataDir: 'unused', vault: f.vault, now: () => instant, fetch: async () => { calls++; throw new Error(); } }); const result = await restarted.renew({ har: session() }); assert.equal(result.changed, true); assert.deepEqual(result.har, renewed.har); assert.equal(calls, 0); }); test('separate instances cannot install or use each other account refresh tokens', async () => { const first = await fixture(), secondVault = memoryVault(); let called = false; const second = createNetworkRenewal({ dataDir: 'second', vault: secondVault, now: () => instant, fetch: async () => { called = true; throw new Error(); } }); const other = session(token({ oid: tenant })); await second.install([captureRefreshGrant(authCapture())], other); assert.equal(secondVault.value().grants.length, 0); assert.equal((await second.renew({ har: other })).changed, false); assert.equal(called, false); assert.equal((await first.renewal.renew({ har: session() })).changed, true); }); test('wrong tenant, audience, account, client or reduced scopes cannot replace existing credentials', async () => { for (const changes of [{ tid: user }, { oid: tenant }, { appid: user }, { aud: 'another-resource' }, { scp: 'read' }, { exp: instant / 1000 }]) { const f = await fixture({ fetch: () => freshResponse(changes) }); const result = await f.renewal.renew({ har: session() }); assert.equal(result.changed, false); assert.equal(result.status.state, 'retrying'); assert.equal(f.vault.value().grants[0].refreshToken, 'private-refresh'); } }); test('429 respects Retry-After and transient outages back off without asking for MFA', async () => { const f = await fixture({ fetch: () => response({ error: 'temporarily_unavailable', error_description: 'never-output-private-details' }, 429, { 'Retry-After': '600' }) }); const result = await f.renewal.renew({ har: session() }); assert.equal(result.status.state, 'retrying'); assert.equal(result.status.interactionRequired, false); assert.equal(result.status.nextAttemptAt, new Date(instant + 600000).toISOString()); f.advance(599000); await f.renewal.renew({ har: session(), force: true }); assert.equal(f.requests.length, 1); f.advance(1001); await f.renewal.renew({ har: session() }); assert.equal(f.requests.length, 2); assert.doesNotMatch(JSON.stringify(result.status), /never-output|private/); }); test('invalid_grant requests saved browser session recovery before interaction and stops retrying after interaction is required', async () => { const f = await fixture({ profile: { id: 'login-44444444-4444-4444-4444-444444444444', browser: 'msedge' }, fetch: () => response({ error: 'invalid_grant', error_description: 'MFA-private' }, 400) }); const result = await f.renewal.renew({ har: session() }); assert.equal(result.status.browserRequired, true); assert.equal(result.status.interactionRequired, false); f.renewal.recoveryFailed({ interactive: true }); await f.renewal.renew({ har: session(), force: true }); assert.equal(f.requests.length, 1); assert.equal(f.renewal.status().state, 'interaction_required'); await f.renewal.install([captureRefreshGrant(authCapture())], session()); assert.equal(f.renewal.status().interactionRequired, false); }); test('cancellation cannot publish new credentials or classify an abort as MFA', async () => { const controller = new AbortController(); const f = await fixture({ fetch: async () => { controller.abort(); return freshResponse(); } }); const result = await f.renewal.renew({ har: session(), signal: controller.signal }); assert.equal(result.changed, false); assert.equal(result.status.interactionRequired, false); }); test('recovered browser tokens only replace same-account same-resource tokens with sufficient scopes', () => { const har = session(), candidate = session(token({ exp: (instant + 3600000) / 1000 })); assert.notDeepEqual(mergeSessionCredentials(har, candidate, [], instant), har); for (const changes of [{ oid: tenant }, { aud: 'wrong-resource' }, { scp: 'read' }]) assert.deepEqual(mergeSessionCredentials(har, session(token({ exp: (instant + 3600000) / 1000, ...changes })), [], instant), har); }); test('encrypted vault survives reconstruction and does not store raw tokens on Windows', async () => { const directory = await mkdtemp(join(tmpdir(), 'teams-renewal-vault-')), path = join(directory, 'network-renewal.json'); try { const value = { refreshToken: 'private-long-lived-token', profile: 'private-profile' }; await createProtectedJson(path).write(value); assert.deepEqual(await createProtectedJson(path).read(), value); if (process.platform === 'win32') assert.doesNotMatch(await readFile(path, 'utf8'), /private-long-lived-token|private-profile/); } finally { assert.ok(resolve(directory).startsWith(resolve(tmpdir()) + sep)); await rm(directory, { recursive: true, force: true }); } });