network-login.test.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { EventEmitter } from 'node:events';
  4. import { mkdtemp, readFile, writeFile, mkdir, rename, rm, readdir } from 'node:fs/promises';
  5. import { tmpdir } from 'node:os';
  6. import { join, resolve, sep } from 'node:path';
  7. import { createNetworkLogin } from '../src/network-login.js';
  8. import { analyzeHar } from '../src/network-capture.js';
  9. import { classifyPresenceCapture } from '../src/network-presence.js';
  10. import { createNetworkRenewal } from '../src/network-renewal.js';
  11. const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
  12. const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
  13. 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'); }
  14. const message = { messages: [{ id: 'message-id', conversationid: 'chat-id', messagetype: 'RichText', content: 'Private message text' }] };
  15. function request(payload = message, overrides = {}) {
  16. let reads = 0;
  17. const headers = overrides.headers || [{ name: 'Authorization', value: 'Bearer test-private-token' }, { name: 'X-Refresh-Token', value: 'do-not-save' }];
  18. return {
  19. url: () => overrides.url || 'https://teams.cloud.microsoft/api/chatsvc/v1/users/ME/conversations/chat-id/messages',
  20. method: () => overrides.method || 'GET', postData: () => overrides.body ?? null,
  21. headersArray: async () => headers,
  22. headers: () => { throw new Error('Incomplete security headers must not be used'); },
  23. reads: () => reads,
  24. response: async () => { reads++; return { status: () => overrides.status || 200,
  25. allHeaders: async () => ({ 'content-type': overrides.mimeType ?? 'application/json' }),
  26. body: async () => { if (overrides.bodyGate) await overrides.bodyGate; return Buffer.from(overrides.responseText ?? JSON.stringify(payload)); } }; }
  27. };
  28. }
  29. async function fixture(t, options = {}) {
  30. const directory = await mkdtemp(join(tmpdir(), 'teams-network-login-test-'));
  31. const context = new EventEmitter(), launches = [], visits = [], probes = [];
  32. let closes = 0;
  33. context.pages = () => [{ goto: async (url, settings) => { visits.push({ url, settings }); } }];
  34. context.close = async () => { closes++; context.emit('close'); };
  35. 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; } };
  36. const probe = options.probe || (async (input, id) => { probes.push(id); return { ok: true, kind: analyzeHar(input).candidates.find(candidate => candidate.id === id).kind }; });
  37. 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 } : {}) });
  38. t.after(async () => {
  39. await login.stop();
  40. const target = resolve(directory), root = resolve(tmpdir()) + sep;
  41. assert.ok(target.startsWith(root) && target.slice(root.length).startsWith('teams-network-login-test-'));
  42. await rm(target, { recursive: true, force: true });
  43. });
  44. return { login, context, directory, launches, visits, probes, closes: () => closes,
  45. ready: async () => { await login.start(); await until(() => login.status().state === 'waiting'); },
  46. capture: async value => { context.emit('requestfinished', value); await until(() => login.status().pending === 0); } };
  47. }
  48. test('start is nonblocking and concurrent calls own one visible isolated browser with fixed Teams navigation', async t => {
  49. const gate = deferred(), f = await fixture(t, { launchGate: gate.promise });
  50. const result = await f.login.start(); assert.equal(result.state, 'opening');
  51. await until(() => f.launches.length === 1);
  52. await f.login.start(); assert.equal(f.launches.length, 1);
  53. assert.equal(resolve(f.launches[0].profile).startsWith(resolve(join(f.directory, 'network-profile')) + sep), true);
  54. assert.match(f.launches[0].profile, /login-[a-f0-9-]{36}$/);
  55. assert.equal(f.launches[0].settings.headless, false); assert.equal(f.launches[0].settings.channel, 'msedge');
  56. gate.resolve(); await until(() => f.login.status().state === 'waiting');
  57. assert.deepEqual(f.visits.map(visit => visit.url), ['https://teams.cloud.microsoft/']);
  58. await assert.rejects(f.login.start({ browser: 'unknown' }), /只支持/);
  59. });
  60. test('only recognized read business requests enter minimal HAR; status never exposes credential or message content', async t => {
  61. const f = await fixture(t); await f.ready();
  62. const login = request({ password: 'never-read' }, { url: 'https://login.microsoftonline.com/tenant/oauth2/v2.0/token', method: 'POST', body: 'password=private' });
  63. const mutation = request(message, { url: 'https://teams.cloud.microsoft/api/messages/send', method: 'POST' });
  64. const writeGet = request(message, { url: 'https://teams.cloud.microsoft/api/messages/markRead' });
  65. const external = request(message, { url: 'https://evil.example/messages' });
  66. for (const value of [login, mutation, writeGet, external]) { await f.capture(value); assert.equal(value.reads(), 0); }
  67. await f.capture(request({ arbitrary: 'unknown' }));
  68. await f.capture(request(message, { mimeType: 'text/html' }));
  69. await f.capture(request());
  70. assert.deepEqual(f.login.status().counts, { messages: 1, chats: 0, calendar: 0, presence: 0 });
  71. assert.doesNotMatch(JSON.stringify(f.login.status()), /test-private-token|Private message|chat-id|do-not-save|password/);
  72. const result = await f.login.finish(); assert.equal(result.ok, true); assert.equal(result.status.state, 'complete');
  73. const saved = JSON.parse(await readFile(result.path, 'utf8')); assert.equal(saved.log.entries.length, 1);
  74. assert.match(JSON.stringify(saved), /test-private-token/);
  75. assert.doesNotMatch(JSON.stringify(saved), /do-not-save|never-read|password|oauth2/);
  76. assert.equal(f.closes(), 1); assert.equal(f.probes.length, 1);
  77. });
  78. test('finish waits for in-flight response capture and concurrent finish saves and verifies only once', async t => {
  79. const f = await fixture(t); await f.ready();
  80. const gate = deferred(); f.context.emit('requestfinished', request(message, { bodyGate: gate.promise }));
  81. assert.equal(f.login.status().pending, 1);
  82. const first = f.login.finish(), second = f.login.finish();
  83. await until(() => f.login.status().state === 'verifying'); assert.equal(f.probes.length, 0);
  84. gate.resolve(); const [a, b] = await Promise.all([first, second]);
  85. assert.equal(a.path, b.path); assert.equal(f.probes.length, 1); assert.equal(f.closes(), 1);
  86. });
  87. test('missing message template keeps window open; optional failed calendar probe does not block validated messages', async t => {
  88. 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 }; } });
  89. await f.ready(); await assert.rejects(f.login.finish(), /打开一个聊天/);
  90. assert.equal(f.login.status().state, 'waiting'); assert.equal(f.closes(), 0);
  91. await f.capture(request());
  92. 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' }));
  93. const result = await f.login.finish(); assert.equal(result.ok, true);
  94. assert.deepEqual(result.status.verified, { messages: true, chats: false, calendar: false });
  95. assert.match(result.status.message, /日历尚未完成验证/);
  96. });
  97. test('atomic rename failure preserves previous session and removes temporary files without exposing filesystem errors', async t => {
  98. const f = await fixture(t, { fileOps: { mkdir, writeFile, rename: async () => { throw new Error('private-token in OS error'); }, rm } });
  99. const path = join(f.directory, 'network-session.har'); await writeFile(path, 'previous-session');
  100. await f.ready(); await f.capture(request());
  101. await assert.rejects(f.login.finish(), /已有会话保持不变/);
  102. assert.equal(await readFile(path, 'utf8'), 'previous-session');
  103. assert.equal((await readdir(f.directory)).some(name => name.endsWith('.tmp')), false);
  104. assert.equal(f.login.status().state, 'waiting');
  105. assert.doesNotMatch(JSON.stringify(f.login.status()), /private-token|OS error/);
  106. });
  107. test('cancelling during probe aborts verification and cannot overwrite the previous session', async t => {
  108. const gate = deferred(); let probing = false;
  109. const f = await fixture(t, { probe: async () => { probing = true; await gate.promise; return { ok: true, kind: 'messages' }; } });
  110. const path = join(f.directory, 'network-session.har'); await writeFile(path, 'previous-session');
  111. await f.ready(); await f.capture(request());
  112. const finishing = f.login.finish(); const rejection = assert.rejects(finishing, /取消|结束/);
  113. await until(() => probing); await f.login.stop(); gate.resolve(); await rejection;
  114. assert.equal(await readFile(path, 'utf8'), 'previous-session'); assert.equal(f.login.status().saved, false);
  115. assert.equal(f.login.status().state, 'cancelled'); assert.equal(f.closes(), 1);
  116. });
  117. test('cancellation during browser launch closes a late-created context and never navigates it', async t => {
  118. const gate = deferred(), f = await fixture(t, { launchGate: gate.promise });
  119. await f.login.start(); await until(() => f.launches.length === 1);
  120. const stopping = f.login.stop(); gate.resolve(); await stopping;
  121. assert.equal(f.closes(), 1); assert.equal(f.visits.length, 0); assert.equal(f.login.status().state, 'cancelled');
  122. });
  123. test('launch errors, abort signals and timeout produce fixed safe status and clean up owned contexts', async t => {
  124. const failed = await fixture(t, { launchError: true }); await failed.login.start();
  125. await until(() => failed.login.status().state === 'error'); assert.doesNotMatch(JSON.stringify(failed.login.status()), /raw-private-token/);
  126. const timed = await fixture(t, { timeoutMs: 50 }); await timed.ready();
  127. await until(() => timed.login.status().state === 'cancelled'); await until(() => timed.closes() === 1);
  128. assert.match(timed.login.status().message, /超时/);
  129. const signalled = await fixture(t), controller = new AbortController();
  130. await signalled.login.start({ signal: controller.signal }); await until(() => signalled.login.status().state === 'waiting');
  131. controller.abort(); await until(() => signalled.login.status().state === 'cancelled'); await until(() => signalled.closes() === 1);
  132. const alreadyAborted = new AbortController(); alreadyAborted.abort();
  133. await assert.rejects(signalled.login.start({ signal: alreadyAborted.signal }), /取消/);
  134. });
  135. test('successful login retains its isolated profile and later login reuses it even after cancellation', async t => {
  136. const f = await fixture(t); await f.ready(); await f.capture(request());
  137. const first = resolve(f.launches[0].profile); await f.login.finish();
  138. assert.equal((await readdir(join(f.directory, 'network-profile'))).length, 1);
  139. await f.ready(); assert.equal(f.launches.length, 2);
  140. const second = resolve(f.launches[1].profile);
  141. assert.equal(second, first);
  142. assert.equal(second.startsWith(resolve(join(f.directory, 'network-profile')) + sep), true);
  143. assert.match(second, /login-[a-f0-9-]{36}$/);
  144. assert.equal(f.login.status().counts.messages, 0);
  145. await f.login.stop();
  146. assert.equal((await readdir(join(f.directory, 'network-profile'))).length, 1);
  147. assert.equal(f.closes(), 2);
  148. });
  149. test('a later chat-only login preserves previously captured calendar templates', async t => {
  150. const f = await fixture(t); await f.ready(); await f.capture(request());
  151. 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' }));
  152. const first = await f.login.finish(); const previous = JSON.parse(await readFile(first.path, 'utf8'));
  153. await f.ready(); await f.capture(request()); const second = await f.login.finish();
  154. const saved = JSON.parse(await readFile(second.path, 'utf8'));
  155. assert.equal(saved.log.entries.length, 2);
  156. 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')));
  157. });
  158. test('instance validation rejects a session before writing and preserves the previous HAR', async t => {
  159. let validations = 0;
  160. const f = await fixture(t, { validateSession: input => {
  161. validations++; assert.equal(input.log.entries.length, 1);
  162. throw Object.assign(new Error('private-identity-details'), { code: 'instance_identity_mismatch' });
  163. } });
  164. const path = join(f.directory, 'network-session.har'); await writeFile(path, 'previous-validated-session');
  165. await f.ready(); await f.capture(request());
  166. await assert.rejects(f.login.finish(), /不属于此实例/);
  167. assert.equal(validations, 1); assert.equal(f.probes.length, 1);
  168. assert.equal(await readFile(path, 'utf8'), 'previous-validated-session');
  169. assert.equal((await readdir(f.directory)).some(name => name.endsWith('.tmp')), false);
  170. assert.equal(f.login.status().saved, false); assert.equal(f.login.status().state, 'waiting'); assert.equal(f.closes(), 0);
  171. assert.doesNotMatch(JSON.stringify(f.login.status()), /private-identity-details|test-private-token|Private message/);
  172. });
  173. test('silent recovery waits through expired MSAL cache until Teams supplies fresh credentials', async t => {
  174. const tenant = '11111111-1111-1111-1111-111111111111', self = '22222222-2222-2222-2222-222222222222', app = '33333333-3333-3333-3333-333333333333';
  175. const audience = 'https://ic3.teams.office.com';
  176. const token = expiry => `fake.${Buffer.from(JSON.stringify({ tid: tenant, oid: self, appid: app, aud: audience, scp: 'read', exp: expiry })).toString('base64url')}.private-signature`;
  177. const old = token(Math.floor(Date.now() / 1000) - 3600), fresh = token(Math.floor(Date.now() / 1000) + 7200);
  178. const original = { log: { entries: [{ request: { method: 'GET', url: request().url(), headers: [{ name: 'Authorization', value: `Bearer ${old}` }] },
  179. response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(message) } } }] } };
  180. const cache = [{ credentialType: 'AccessToken', clientId: app, homeAccountId: self, environment: 'login.microsoftonline.com', realm: tenant, secret: old, target: `${audience}/.default` },
  181. { credentialType: 'RefreshToken', clientId: app, homeAccountId: self, environment: 'login.microsoftonline.com', secret: 'expired-private-refresh' }];
  182. let calls = 0, reads = 0, state = 'browser_required';
  183. const renewal = { load: async () => {}, profile: async () => ({ id: `login-${tenant}`, browser: 'msedge' }),
  184. status: () => ({ state, available: true, browserRequired: state === 'browser_required' }), install: async () => {},
  185. recoveryFailed: () => { state = 'retrying'; }, renew: async options => {
  186. calls++; if (calls === 1) return { changed: false, status: renewal.status() };
  187. state = 'renewed'; return { changed: true, har: options.har, status: renewal.status() };
  188. } };
  189. const f = await fixture(t, { renewal });
  190. f.context.pages = () => [{ goto: async () => {}, evaluate: async () => { reads++; return cache; } }];
  191. const recovering = f.login.renew({ har: original, force: true });
  192. await until(() => reads > 0); await pause(30);
  193. assert.equal(f.login.status().state, 'waiting'); assert.equal(f.probes.length, 0); assert.equal(f.closes(), 0);
  194. await f.capture(request(message, { headers: [{ name: 'Authorization', value: `Bearer ${fresh}` }] }));
  195. const result = await recovering;
  196. assert.equal(result.status.state, 'renewed'); assert.equal(result.changed, true); assert.equal(f.closes(), 1);
  197. assert.equal(result.har.log.entries[0].request.headers[0].value, `Bearer ${fresh}`);
  198. });
  199. test('cache evaluation interrupted by navigation retries within the bounded silent recovery window', async t => {
  200. let state = 'browser_required', failures = 0, reads = 0;
  201. const renewal = { load: async () => {}, profile: async () => ({ id: 'login-11111111-1111-1111-1111-111111111111', browser: 'msedge' }),
  202. status: () => ({ state, available: true, browserRequired: state === 'browser_required' }),
  203. renew: async () => ({ changed: false, status: renewal.status() }), recoveryFailed: () => { failures++; state = 'retrying'; } };
  204. const f = await fixture(t, { renewal, recoveryTimeoutMs: 100 });
  205. f.context.pages = () => [{ goto: async () => {}, evaluate: async () => { reads++; throw new Error('Execution context was destroyed: private URL'); } }];
  206. const result = f.login.renew({ har: { log: { entries: [] } } });
  207. await until(() => reads > 0);
  208. assert.equal(f.login.status().state, 'waiting'); assert.equal(f.closes(), 0);
  209. assert.equal(Date.parse(f.login.status().expiresAt) - Date.parse(f.login.status().startedAt), 100);
  210. assert.equal((await result).status.state, 'retrying'); assert.equal(failures, 1); assert.equal(f.closes(), 1);
  211. assert.doesNotMatch(JSON.stringify(f.login.status()), /private URL|Execution context/);
  212. });
  213. test('OAuth renewal material is separate from HAR; expired refresh grant recovers through one short-lived isolated headless browser', async t => {
  214. const tenant = '11111111-1111-1111-1111-111111111111', self = '22222222-2222-2222-2222-222222222222', app = '33333333-3333-3333-3333-333333333333';
  215. 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`;
  216. const old = access(Math.floor(Date.now() / 1000) + 120), fresh = access(Math.floor(Date.now() / 1000) + 7200);
  217. let saved, calls = 0;
  218. const renewal = createNetworkRenewal({ dataDir: 'unused', vault: { read: async () => saved, write: async next => { saved = structuredClone(next); } },
  219. fetch: async () => { calls++; return calls === 1 ? new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 })
  220. : new Response(JSON.stringify({ token_type: 'Bearer', access_token: fresh, refresh_token: 'rotated-refresh-material' }), { status: 200 }); } });
  221. const f = await fixture(t, { renewal }); await f.ready();
  222. await f.capture(request({ token_type: 'Bearer', access_token: old, refresh_token: 'private-refresh-material' }, {
  223. url: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`, method: 'POST',
  224. headers: [{ name: 'Origin', value: 'https://teams.cloud.microsoft' }],
  225. body: new URLSearchParams({ client_id: app, scope: 'fixture-resource/read', grant_type: 'refresh_token', refresh_token: 'old-private-refresh-material' }).toString()
  226. }));
  227. await f.capture(request(message, { headers: [{ name: 'Authorization', value: `Bearer ${old}` }] }));
  228. const finished = await f.login.finish(), original = JSON.parse(await readFile(finished.path, 'utf8'));
  229. assert.equal(saved.grants.length, 1); assert.equal(saved.grants[0].refreshToken, 'private-refresh-material');
  230. assert.doesNotMatch(JSON.stringify(original), /private-refresh-material|oauth2|grant_type/);
  231. assert.doesNotMatch(JSON.stringify(f.login.status()), /private-refresh-material|private-signature/);
  232. const recovery = f.login.renew({ har: original, force: true });
  233. await until(() => f.launches.length === 2 && f.login.status().state === 'waiting');
  234. assert.equal(f.launches[1].settings.headless, true); assert.equal(f.launches[1].profile, f.launches[0].profile);
  235. await f.capture(request(message, { headers: [{ name: 'Authorization', value: `Bearer ${fresh}` }] }));
  236. const result = await recovery;
  237. assert.equal(result.changed, true); assert.equal(calls, 2); assert.equal(f.closes(), 2);
  238. assert.equal(result.har.log.entries[0].request.headers[0].value, `Bearer ${fresh}`);
  239. assert.equal(f.login.status().state, 'complete');
  240. });
  241. test('validated self presence reads and empty endpoint responses enter minimal HAR without being replayed during login', async t => {
  242. const self = '11111111-1111-1111-1111-111111111111', tenant = '22222222-2222-2222-2222-222222222222';
  243. const endpoint = '33333333-3333-3333-3333-333333333333', app = '44444444-4444-4444-4444-444444444444';
  244. 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';
  245. const headers = [{ name: 'Authorization', value: token }, { name: 'Cookie', value: 'never-save-cookie' }, { name: 'x-ms-object-id', value: '' }];
  246. const f = await fixture(t); await f.ready(); await f.capture(request());
  247. await f.capture(request([{ mri: `8:orgid:${self}`, presence: { availability: 'Available', activity: 'Available', note: { message: 'never-save-presence-note' } } }], {
  248. method: 'POST', url: 'https://teams.cloud.microsoft/ups/apac/v1/presence/getpresence/', headers,
  249. body: JSON.stringify([{ mri: `8:orgid:${self}`, source: 'fixture-source' }])
  250. }));
  251. await f.capture(request(null, { method: 'PUT', url: 'https://teams.cloud.microsoft/ups/apac/v1/me/endpoints/', status: 201,
  252. headers: [...headers, { name: 'x-ms-endpoint-id', value: endpoint }], mimeType: '', responseText: '',
  253. body: JSON.stringify({ id: endpoint, availability: 'Available', activity: 'Available', activityReporting: 'fixture-reporting', deviceType: 'Web' })
  254. }));
  255. const preferred = request(null, { method: 'PUT', url: 'https://teams.cloud.microsoft/ups/apac/v1/me/forceavailability/', headers, body: JSON.stringify({ availability: 'Available' }) });
  256. await f.capture(preferred); assert.equal(preferred.reads(), 0);
  257. assert.deepEqual(f.login.status().counts, { messages: 1, chats: 0, calendar: 0, presence: 2 });
  258. assert.doesNotMatch(JSON.stringify(f.login.status()), /presence-private-signature|never-save|11111111|33333333|fixture-source|forceavailability/);
  259. const result = await f.login.finish(), saved = JSON.parse(await readFile(result.path, 'utf8'));
  260. assert.equal(saved.log.entries.length, 3);
  261. const presence = saved.log.entries.map(classifyPresenceCapture).filter(Boolean);
  262. assert.deepEqual(presence.map(item => item.operation), ['read', 'session']);
  263. assert.equal(new Set(presence.map(item => item.accountId)).size, 1);
  264. assert.deepEqual(f.probes, [0]);
  265. assert.doesNotMatch(JSON.stringify(saved), /never-save-cookie|never-save-presence-note|forceavailability/);
  266. assert.match(JSON.stringify(saved), /presence-private-signature/);
  267. assert.doesNotMatch(JSON.stringify(result.status), /presence-private-signature|11111111|33333333/);
  268. });