import test from 'node:test'; import assert from 'node:assert/strict'; import { EventEmitter } from 'node:events'; import { mkdtemp, readFile, writeFile, mkdir, rename, rm, readdir } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve, sep } from 'node:path'; import { createNetworkLogin } from '../src/network-login.js'; import { analyzeHar } from '../src/network-capture.js'; import { classifyPresenceCapture } from '../src/network-presence.js'; import { createNetworkRenewal } from '../src/network-renewal.js'; const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; }; async function until(condition) { for (let attempt = 0; attempt < 200; attempt++) { if (condition()) return; await pause(5); } assert.fail('Expected state transition did not complete'); } const message = { messages: [{ id: 'message-id', conversationid: 'chat-id', messagetype: 'RichText', content: 'Private message text' }] }; function request(payload = message, overrides = {}) { let reads = 0; const headers = overrides.headers || [{ name: 'Authorization', value: 'Bearer test-private-token' }, { name: 'X-Refresh-Token', value: 'do-not-save' }]; return { url: () => overrides.url || 'https://teams.cloud.microsoft/api/chatsvc/v1/users/ME/conversations/chat-id/messages', method: () => overrides.method || 'GET', postData: () => overrides.body ?? null, headersArray: async () => headers, headers: () => { throw new Error('Incomplete security headers must not be used'); }, reads: () => reads, response: async () => { reads++; return { status: () => overrides.status || 200, allHeaders: async () => ({ 'content-type': overrides.mimeType ?? 'application/json' }), body: async () => { if (overrides.bodyGate) await overrides.bodyGate; return Buffer.from(overrides.responseText ?? JSON.stringify(payload)); } }; } }; } async function fixture(t, options = {}) { const directory = await mkdtemp(join(tmpdir(), 'teams-network-login-test-')); const context = new EventEmitter(), launches = [], visits = [], probes = []; let closes = 0; context.pages = () => [{ goto: async (url, settings) => { visits.push({ url, settings }); } }]; context.close = async () => { closes++; context.emit('close'); }; const browserType = { launchPersistentContext: async (profile, settings) => { launches.push({ profile, settings }); if (options.launchGate) await options.launchGate; if (options.launchError) throw new Error('raw-private-token'); return context; } }; const probe = options.probe || (async (input, id) => { probes.push(id); return { ok: true, kind: analyzeHar(input).candidates.find(candidate => candidate.id === id).kind }; }); const login = createNetworkLogin({ dataDir: directory, browserType, probe, ...(options.renewal ? { renewal: options.renewal } : {}), ...(options.recoveryTimeoutMs ? { recoveryTimeoutMs: options.recoveryTimeoutMs } : {}), ...(options.validateSession ? { validateSession: options.validateSession } : {}), ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}), ...(options.fileOps ? { fileOps: options.fileOps } : {}) }); t.after(async () => { await login.stop(); const target = resolve(directory), root = resolve(tmpdir()) + sep; assert.ok(target.startsWith(root) && target.slice(root.length).startsWith('teams-network-login-test-')); await rm(target, { recursive: true, force: true }); }); return { login, context, directory, launches, visits, probes, closes: () => closes, ready: async () => { await login.start(); await until(() => login.status().state === 'waiting'); }, capture: async value => { context.emit('requestfinished', value); await until(() => login.status().pending === 0); } }; } test('start is nonblocking and concurrent calls own one visible isolated browser with fixed Teams navigation', async t => { const gate = deferred(), f = await fixture(t, { launchGate: gate.promise }); const result = await f.login.start(); assert.equal(result.state, 'opening'); await until(() => f.launches.length === 1); await f.login.start(); assert.equal(f.launches.length, 1); assert.equal(resolve(f.launches[0].profile).startsWith(resolve(join(f.directory, 'network-profile')) + sep), true); assert.match(f.launches[0].profile, /login-[a-f0-9-]{36}$/); assert.equal(f.launches[0].settings.headless, false); assert.equal(f.launches[0].settings.channel, 'msedge'); gate.resolve(); await until(() => f.login.status().state === 'waiting'); assert.deepEqual(f.visits.map(visit => visit.url), ['https://teams.cloud.microsoft/']); await assert.rejects(f.login.start({ browser: 'unknown' }), /只支持/); }); test('only recognized read business requests enter minimal HAR; status never exposes credential or message content', async t => { const f = await fixture(t); await f.ready(); const login = request({ password: 'never-read' }, { url: 'https://login.microsoftonline.com/tenant/oauth2/v2.0/token', method: 'POST', body: 'password=private' }); const mutation = request(message, { url: 'https://teams.cloud.microsoft/api/messages/send', method: 'POST' }); const writeGet = request(message, { url: 'https://teams.cloud.microsoft/api/messages/markRead' }); const external = request(message, { url: 'https://evil.example/messages' }); for (const value of [login, mutation, writeGet, external]) { await f.capture(value); assert.equal(value.reads(), 0); } await f.capture(request({ arbitrary: 'unknown' })); await f.capture(request(message, { mimeType: 'text/html' })); await f.capture(request()); assert.deepEqual(f.login.status().counts, { messages: 1, chats: 0, calendar: 0, presence: 0 }); assert.doesNotMatch(JSON.stringify(f.login.status()), /test-private-token|Private message|chat-id|do-not-save|password/); const result = await f.login.finish(); assert.equal(result.ok, true); assert.equal(result.status.state, 'complete'); const saved = JSON.parse(await readFile(result.path, 'utf8')); assert.equal(saved.log.entries.length, 1); assert.match(JSON.stringify(saved), /test-private-token/); assert.doesNotMatch(JSON.stringify(saved), /do-not-save|never-read|password|oauth2/); assert.equal(f.closes(), 1); assert.equal(f.probes.length, 1); }); test('finish waits for in-flight response capture and concurrent finish saves and verifies only once', async t => { const f = await fixture(t); await f.ready(); const gate = deferred(); f.context.emit('requestfinished', request(message, { bodyGate: gate.promise })); assert.equal(f.login.status().pending, 1); const first = f.login.finish(), second = f.login.finish(); await until(() => f.login.status().state === 'verifying'); assert.equal(f.probes.length, 0); gate.resolve(); const [a, b] = await Promise.all([first, second]); assert.equal(a.path, b.path); assert.equal(f.probes.length, 1); assert.equal(f.closes(), 1); }); test('missing message template keeps window open; optional failed calendar probe does not block validated messages', async t => { const f = await fixture(t, { probe: async (input, id) => { const kind = analyzeHar(input).candidates.find(candidate => candidate.id === id).kind; return { ok: kind === 'messages', kind }; } }); await f.ready(); await assert.rejects(f.login.finish(), /打开一个聊天/); assert.equal(f.login.status().state, 'waiting'); assert.equal(f.closes(), 0); await f.capture(request()); await f.capture(request({ value: [{ id: 'event-id', subject: 'Private event', start: { dateTime: '2026-09-08T00:00:00Z' }, end: { dateTime: '2026-09-08T01:00:00Z' } }] }, { url: 'https://graph.microsoft.com/v1.0/me/events' })); const result = await f.login.finish(); assert.equal(result.ok, true); assert.deepEqual(result.status.verified, { messages: true, chats: false, calendar: false }); assert.match(result.status.message, /日历尚未完成验证/); }); test('atomic rename failure preserves previous session and removes temporary files without exposing filesystem errors', async t => { const f = await fixture(t, { fileOps: { mkdir, writeFile, rename: async () => { throw new Error('private-token in OS error'); }, rm } }); const path = join(f.directory, 'network-session.har'); await writeFile(path, 'previous-session'); await f.ready(); await f.capture(request()); await assert.rejects(f.login.finish(), /已有会话保持不变/); assert.equal(await readFile(path, 'utf8'), 'previous-session'); assert.equal((await readdir(f.directory)).some(name => name.endsWith('.tmp')), false); assert.equal(f.login.status().state, 'waiting'); assert.doesNotMatch(JSON.stringify(f.login.status()), /private-token|OS error/); }); test('cancelling during probe aborts verification and cannot overwrite the previous session', async t => { const gate = deferred(); let probing = false; const f = await fixture(t, { probe: async () => { probing = true; await gate.promise; return { ok: true, kind: 'messages' }; } }); const path = join(f.directory, 'network-session.har'); await writeFile(path, 'previous-session'); await f.ready(); await f.capture(request()); const finishing = f.login.finish(); const rejection = assert.rejects(finishing, /取消|结束/); await until(() => probing); await f.login.stop(); gate.resolve(); await rejection; assert.equal(await readFile(path, 'utf8'), 'previous-session'); assert.equal(f.login.status().saved, false); assert.equal(f.login.status().state, 'cancelled'); assert.equal(f.closes(), 1); }); test('cancellation during browser launch closes a late-created context and never navigates it', async t => { const gate = deferred(), f = await fixture(t, { launchGate: gate.promise }); await f.login.start(); await until(() => f.launches.length === 1); const stopping = f.login.stop(); gate.resolve(); await stopping; assert.equal(f.closes(), 1); assert.equal(f.visits.length, 0); assert.equal(f.login.status().state, 'cancelled'); }); test('launch errors, abort signals and timeout produce fixed safe status and clean up owned contexts', async t => { const failed = await fixture(t, { launchError: true }); await failed.login.start(); await until(() => failed.login.status().state === 'error'); assert.doesNotMatch(JSON.stringify(failed.login.status()), /raw-private-token/); const timed = await fixture(t, { timeoutMs: 50 }); await timed.ready(); await until(() => timed.login.status().state === 'cancelled'); await until(() => timed.closes() === 1); assert.match(timed.login.status().message, /超时/); const signalled = await fixture(t), controller = new AbortController(); await signalled.login.start({ signal: controller.signal }); await until(() => signalled.login.status().state === 'waiting'); controller.abort(); await until(() => signalled.login.status().state === 'cancelled'); await until(() => signalled.closes() === 1); const alreadyAborted = new AbortController(); alreadyAborted.abort(); await assert.rejects(signalled.login.start({ signal: alreadyAborted.signal }), /取消/); }); test('successful login retains its isolated profile and later login reuses it even after cancellation', async t => { const f = await fixture(t); await f.ready(); await f.capture(request()); const first = resolve(f.launches[0].profile); await f.login.finish(); assert.equal((await readdir(join(f.directory, 'network-profile'))).length, 1); await f.ready(); assert.equal(f.launches.length, 2); const second = resolve(f.launches[1].profile); assert.equal(second, first); assert.equal(second.startsWith(resolve(join(f.directory, 'network-profile')) + sep), true); assert.match(second, /login-[a-f0-9-]{36}$/); assert.equal(f.login.status().counts.messages, 0); await f.login.stop(); assert.equal((await readdir(join(f.directory, 'network-profile'))).length, 1); assert.equal(f.closes(), 2); }); test('a later chat-only login preserves previously captured calendar templates', async t => { const f = await fixture(t); await f.ready(); await f.capture(request()); await f.capture(request({ value: [{ id: 'event-id', subject: 'Fixture event', start: { dateTime: '2026-09-08T00:00:00Z' }, end: { dateTime: '2026-09-08T01:00:00Z' } }] }, { url: 'https://graph.microsoft.com/v1.0/me/events' })); const first = await f.login.finish(); const previous = JSON.parse(await readFile(first.path, 'utf8')); await f.ready(); await f.capture(request()); const second = await f.login.finish(); const saved = JSON.parse(await readFile(second.path, 'utf8')); assert.equal(saved.log.entries.length, 2); assert.deepEqual(saved.log.entries.find(entry => entry.request.url.includes('graph.microsoft.com')), previous.log.entries.find(entry => entry.request.url.includes('graph.microsoft.com'))); }); test('instance validation rejects a session before writing and preserves the previous HAR', async t => { let validations = 0; const f = await fixture(t, { validateSession: input => { validations++; assert.equal(input.log.entries.length, 1); throw Object.assign(new Error('private-identity-details'), { code: 'instance_identity_mismatch' }); } }); const path = join(f.directory, 'network-session.har'); await writeFile(path, 'previous-validated-session'); await f.ready(); await f.capture(request()); await assert.rejects(f.login.finish(), /不属于此实例/); assert.equal(validations, 1); assert.equal(f.probes.length, 1); assert.equal(await readFile(path, 'utf8'), 'previous-validated-session'); assert.equal((await readdir(f.directory)).some(name => name.endsWith('.tmp')), false); assert.equal(f.login.status().saved, false); assert.equal(f.login.status().state, 'waiting'); assert.equal(f.closes(), 0); assert.doesNotMatch(JSON.stringify(f.login.status()), /private-identity-details|test-private-token|Private message/); }); test('silent recovery waits through expired MSAL cache until Teams supplies fresh credentials', async t => { const tenant = '11111111-1111-1111-1111-111111111111', self = '22222222-2222-2222-2222-222222222222', app = '33333333-3333-3333-3333-333333333333'; const audience = 'https://ic3.teams.office.com'; const token = expiry => `fake.${Buffer.from(JSON.stringify({ tid: tenant, oid: self, appid: app, aud: audience, scp: 'read', exp: expiry })).toString('base64url')}.private-signature`; const old = token(Math.floor(Date.now() / 1000) - 3600), fresh = token(Math.floor(Date.now() / 1000) + 7200); const original = { log: { entries: [{ request: { method: 'GET', url: request().url(), headers: [{ name: 'Authorization', value: `Bearer ${old}` }] }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(message) } } }] } }; const cache = [{ credentialType: 'AccessToken', clientId: app, homeAccountId: self, environment: 'login.microsoftonline.com', realm: tenant, secret: old, target: `${audience}/.default` }, { credentialType: 'RefreshToken', clientId: app, homeAccountId: self, environment: 'login.microsoftonline.com', secret: 'expired-private-refresh' }]; let calls = 0, reads = 0, state = 'browser_required'; const renewal = { load: async () => {}, profile: async () => ({ id: `login-${tenant}`, browser: 'msedge' }), status: () => ({ state, available: true, browserRequired: state === 'browser_required' }), install: async () => {}, recoveryFailed: () => { state = 'retrying'; }, renew: async options => { calls++; if (calls === 1) return { changed: false, status: renewal.status() }; state = 'renewed'; return { changed: true, har: options.har, status: renewal.status() }; } }; const f = await fixture(t, { renewal }); f.context.pages = () => [{ goto: async () => {}, evaluate: async () => { reads++; return cache; } }]; const recovering = f.login.renew({ har: original, force: true }); await until(() => reads > 0); await pause(30); assert.equal(f.login.status().state, 'waiting'); assert.equal(f.probes.length, 0); assert.equal(f.closes(), 0); await f.capture(request(message, { headers: [{ name: 'Authorization', value: `Bearer ${fresh}` }] })); const result = await recovering; assert.equal(result.status.state, 'renewed'); assert.equal(result.changed, true); assert.equal(f.closes(), 1); assert.equal(result.har.log.entries[0].request.headers[0].value, `Bearer ${fresh}`); }); test('cache evaluation interrupted by navigation retries within the bounded silent recovery window', async t => { let state = 'browser_required', failures = 0, reads = 0; const renewal = { load: async () => {}, profile: async () => ({ id: 'login-11111111-1111-1111-1111-111111111111', browser: 'msedge' }), status: () => ({ state, available: true, browserRequired: state === 'browser_required' }), renew: async () => ({ changed: false, status: renewal.status() }), recoveryFailed: () => { failures++; state = 'retrying'; } }; const f = await fixture(t, { renewal, recoveryTimeoutMs: 100 }); f.context.pages = () => [{ goto: async () => {}, evaluate: async () => { reads++; throw new Error('Execution context was destroyed: private URL'); } }]; const result = f.login.renew({ har: { log: { entries: [] } } }); await until(() => reads > 0); assert.equal(f.login.status().state, 'waiting'); assert.equal(f.closes(), 0); assert.equal(Date.parse(f.login.status().expiresAt) - Date.parse(f.login.status().startedAt), 100); assert.equal((await result).status.state, 'retrying'); assert.equal(failures, 1); assert.equal(f.closes(), 1); assert.doesNotMatch(JSON.stringify(f.login.status()), /private URL|Execution context/); }); test('OAuth renewal material is separate from HAR; expired refresh grant recovers through one short-lived isolated headless browser', async t => { const tenant = '11111111-1111-1111-1111-111111111111', self = '22222222-2222-2222-2222-222222222222', app = '33333333-3333-3333-3333-333333333333'; const access = expiry => `fake.${Buffer.from(JSON.stringify({ tid: tenant, oid: self, appid: app, aud: 'fixture-resource', scp: 'read', exp: expiry })).toString('base64url')}.private-signature`; const old = access(Math.floor(Date.now() / 1000) + 120), fresh = access(Math.floor(Date.now() / 1000) + 7200); let saved, calls = 0; const renewal = createNetworkRenewal({ dataDir: 'unused', vault: { read: async () => saved, write: async next => { saved = structuredClone(next); } }, fetch: async () => { calls++; return calls === 1 ? new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }) : new Response(JSON.stringify({ token_type: 'Bearer', access_token: fresh, refresh_token: 'rotated-refresh-material' }), { status: 200 }); } }); const f = await fixture(t, { renewal }); await f.ready(); await f.capture(request({ token_type: 'Bearer', access_token: old, refresh_token: 'private-refresh-material' }, { 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: app, scope: 'fixture-resource/read', grant_type: 'refresh_token', refresh_token: 'old-private-refresh-material' }).toString() })); await f.capture(request(message, { headers: [{ name: 'Authorization', value: `Bearer ${old}` }] })); const finished = await f.login.finish(), original = JSON.parse(await readFile(finished.path, 'utf8')); assert.equal(saved.grants.length, 1); assert.equal(saved.grants[0].refreshToken, 'private-refresh-material'); assert.doesNotMatch(JSON.stringify(original), /private-refresh-material|oauth2|grant_type/); assert.doesNotMatch(JSON.stringify(f.login.status()), /private-refresh-material|private-signature/); const recovery = f.login.renew({ har: original, force: true }); await until(() => f.launches.length === 2 && f.login.status().state === 'waiting'); assert.equal(f.launches[1].settings.headless, true); assert.equal(f.launches[1].profile, f.launches[0].profile); await f.capture(request(message, { headers: [{ name: 'Authorization', value: `Bearer ${fresh}` }] })); const result = await recovery; assert.equal(result.changed, true); assert.equal(calls, 2); assert.equal(f.closes(), 2); assert.equal(result.har.log.entries[0].request.headers[0].value, `Bearer ${fresh}`); assert.equal(f.login.status().state, 'complete'); }); test('validated self presence reads and empty endpoint responses enter minimal HAR without being replayed during login', async t => { const self = '11111111-1111-1111-1111-111111111111', tenant = '22222222-2222-2222-2222-222222222222'; const endpoint = '33333333-3333-3333-3333-333333333333', app = '44444444-4444-4444-4444-444444444444'; const token = 'Bearer fake.' + Buffer.from(JSON.stringify({ oid: self, tid: tenant, appid: app, aud: 'fixture-presence-service', exp: 2200000000 })).toString('base64url') + '.presence-private-signature'; const headers = [{ name: 'Authorization', value: token }, { name: 'Cookie', value: 'never-save-cookie' }, { name: 'x-ms-object-id', value: '' }]; const f = await fixture(t); await f.ready(); await f.capture(request()); await f.capture(request([{ mri: `8:orgid:${self}`, presence: { availability: 'Available', activity: 'Available', note: { message: 'never-save-presence-note' } } }], { method: 'POST', url: 'https://teams.cloud.microsoft/ups/apac/v1/presence/getpresence/', headers, body: JSON.stringify([{ mri: `8:orgid:${self}`, source: 'fixture-source' }]) })); await f.capture(request(null, { method: 'PUT', url: 'https://teams.cloud.microsoft/ups/apac/v1/me/endpoints/', status: 201, headers: [...headers, { name: 'x-ms-endpoint-id', value: endpoint }], mimeType: '', responseText: '', body: JSON.stringify({ id: endpoint, availability: 'Available', activity: 'Available', activityReporting: 'fixture-reporting', deviceType: 'Web' }) })); const preferred = request(null, { method: 'PUT', url: 'https://teams.cloud.microsoft/ups/apac/v1/me/forceavailability/', headers, body: JSON.stringify({ availability: 'Available' }) }); await f.capture(preferred); assert.equal(preferred.reads(), 0); assert.deepEqual(f.login.status().counts, { messages: 1, chats: 0, calendar: 0, presence: 2 }); assert.doesNotMatch(JSON.stringify(f.login.status()), /presence-private-signature|never-save|11111111|33333333|fixture-source|forceavailability/); const result = await f.login.finish(), saved = JSON.parse(await readFile(result.path, 'utf8')); assert.equal(saved.log.entries.length, 3); const presence = saved.log.entries.map(classifyPresenceCapture).filter(Boolean); assert.deepEqual(presence.map(item => item.operation), ['read', 'session']); assert.equal(new Set(presence.map(item => item.accountId)).size, 1); assert.deepEqual(f.probes, [0]); assert.doesNotMatch(JSON.stringify(saved), /never-save-cookie|never-save-presence-note|forceavailability/); assert.match(JSON.stringify(saved), /presence-private-signature/); assert.doesNotMatch(JSON.stringify(result.status), /presence-private-signature|11111111|33333333/); });