import test from 'node:test'; import assert from 'node:assert/strict'; import { analyzeHar, getReplayRequest } from '../src/network-capture.js'; const jwt = `header.${Buffer.from(JSON.stringify({ exp: 1900000000, name: 'Private Person' })).toString('base64url')}.signature`; const message = { id: 'private-message-id', body: { content: 'Private conversation text', contentType: 'html' } }; const entry = (json = { value: [message] }, overrides = {}) => ({ request: { method: 'GET', url: 'https://teams.cloud.microsoft/api/v1/users/private-user/conversations/private-chat/messages?syncToken=super-secret&$top=50', headers: [{ name: 'Authorization', value: `Bearer ${jwt}` }, { name: 'Cookie', value: 'Session=private-cookie' }] }, response: { status: 200, content: { mimeType: 'application/json; charset=utf-8', text: JSON.stringify(json) } }, ...overrides }); const har = entries => ({ log: { entries } }); test('recognizes Graph and Skype shapes without exposing credentials, IDs, query values or message samples', () => { const report = analyzeHar(har([ entry(), entry({ value: [{ id: 'chat-id', chatType: 'oneOnOne' }] }), entry({ value: [{ subject: 'Private meeting', start: { dateTime: '2026-09-08T10:00:00' }, end: { dateTime: '2026-09-08T11:00:00' } }] }), entry({ messages: [{ id: 123, content: 'Private Skype message', messagetype: 'RichText', conversationid: 'private-chat' }] }) ])); assert.equal(report.entryCount, 4); assert.deepEqual(report.candidates.map(item => item.kind), ['messages', 'chats', 'calendar', 'messages']); assert.ok(report.candidates.every(item => item.replayable && item.itemCount === 1)); assert.deepEqual(report.candidates[0].auth.headerNames, ['Authorization', 'Cookie']); assert.equal(report.candidates[0].auth.expiresAt, '2030-03-17T17:46:40.000Z'); assert.equal(report.candidates[0].endpoint, 'https://teams.cloud.microsoft/api/v1/users/{id}/conversations/{id}/messages'); assert.ok(report.candidates[0].shape.includes('body')); assert.doesNotMatch(JSON.stringify(report), /Private|private-user|private-chat|private-message|private-cookie|super-secret|syncToken|signature|Bearer|header\./); }); test('replay preserves actual URL and approved authentication values while restricting other headers', () => { const captured = entry(); captured.request.headers.push( { name: 'X-SkypeToken', value: 'opaque-private-token' }, { name: 'Authentication', value: 'session-private-token' }, { name: 'Accept', value: 'application/json' }, { name: 'Content-Type', value: 'application/json' }, { name: 'Origin', value: 'https://teams.microsoft.com/?secret=origin-secret' }, { name: 'Referer', value: 'https://teams.cloud.microsoft/v2/?token=referer-secret' }, { name: 'Host', value: 'evil.example' }, { name: 'X-Unneeded', value: 'secret' }, { name: 'Proxy-Authorization', value: 'private' }, { name: 'X-Refresh-Token', value: 'must-not-export' } ); const replay = getReplayRequest(har([captured]), 0); assert.equal(replay.method, 'GET'); assert.equal(replay.url, captured.request.url); assert.equal(replay.headers.Authorization, `Bearer ${jwt}`); assert.equal(replay.headers.Cookie, 'Session=private-cookie'); assert.equal(replay.headers['X-SkypeToken'], 'opaque-private-token'); assert.equal(replay.headers.Authentication, 'session-private-token'); assert.equal(replay.headers.Origin, 'https://teams.microsoft.com'); assert.equal(replay.headers.Referer, 'https://teams.cloud.microsoft/v2/'); assert.equal(replay.headers.Host, undefined); assert.equal(replay.headers['X-Unneeded'], undefined); assert.doesNotMatch(JSON.stringify(replay), /must-not-export|Proxy-Authorization|origin-secret|referer-secret/); }); test('base64 JSON is decoded, while HTML, malformed JSON and absent bodies remain nonreplayable metadata', () => { const base64 = entry(); base64.response.content.text = Buffer.from(base64.response.content.text).toString('base64'); base64.response.content.encoding = 'base64'; const html = entry(); html.response.content = { mimeType: 'text/html', text: 'Private login content' }; const invalid = entry(); invalid.response.content.text = '{invalid Private body'; const missing = entry(); delete missing.response.content.text; const corrupt = entry(); corrupt.response.content.encoding = 'base64'; corrupt.response.content.text = 'invalid%'; const report = analyzeHar(har([base64, html, invalid, missing, corrupt])); assert.equal(report.candidates[0].replayable, true); assert.ok(report.candidates.slice(1).every(item => item.kind === 'unknown' && !item.replayable)); assert.doesNotMatch(JSON.stringify(report), /Private|invalid%|/); assert.throws(() => getReplayRequest(har([html]), 0), /JSON/); }); test('observed Teams read requests retain only exact approved context headers with bounded lengths', () => { const context = ['x-ms-client-type', 'x-ms-client-version', 'x-ms-region', 'x-ms-partition', 'x-ms-user-type', 'x-ms-migration', 'x-ms-request-id', 'x-ms-session-id', 'x-ms-object-id', 'x-ms-synctoken', 'x-ringoverride', 'clientinfo', 'behavioroverride']; const captured = entry(); captured.request.headers.push(...context.map(name => ({ name, value: `captured-${name}` })), { name: 'x-ms-unapproved-secret', value: 'private' }); const replay = getReplayRequest(har([captured]), 0); for (const name of context) assert.equal(replay.headers[name], `captured-${name}`); assert.equal(replay.headers['x-ms-unapproved-secret'], undefined); assert.doesNotMatch(JSON.stringify(analyzeHar(har([captured]))), /captured-x-ms|captured-clientinfo/); captured.request.headers.push({ name: 'clientinfo', value: 'x'.repeat(8193) }); assert.throws(() => getReplayRequest(har([captured]), 0), /长度上限/); }); test('unknown, empty and mixed shapes cannot claim a working collection adapter', () => { const report = analyzeHar(har([entry({ value: [] }), entry({ items: [{ id: 'id', text: 'secret' }] }), entry({ value: [message, { unexpected: true }] }), entry({ 'private-account-key': 'secret' })])); assert.ok(report.candidates.every(item => item.kind === 'unknown' && !item.replayable)); assert.deepEqual(report.candidates.at(-1).shape, ['{other}']); assert.doesNotMatch(JSON.stringify(report), /private-account-key|secret/); assert.throws(() => getReplayRequest(har([entry({ value: [] })]), 0), /结构尚未识别/); }); test('observed Teams updates envelope identifies an empty chat delta without claiming full chat inventory', () => { const delta = entry({ conversationFolders: {}, teams: [], chats: [], engageCommunities: [], users: [], channels: [], privateFeeds: [], metadata: { syncToken: 'private-sync-token', forwardSyncToken: 'private-forward-token', isPartialData: false, hasMoreChats: false } }); delta.request.url = 'https://teams.cloud.microsoft/api/csa/emea/api/v3/teams/users/me/updates?isPrefetch=true'; const report = analyzeHar(har([delta])).candidates[0]; assert.equal(report.kind, 'chats'); assert.equal(report.itemCount, 0); assert.equal(report.replayable, true); assert.match(report.reason, /为空.*增量/); assert.doesNotMatch(JSON.stringify(report), /private-sync-token|private-forward-token/); assert.equal(getReplayRequest(har([delta]), 0).url, delta.request.url); const populated = structuredClone(delta); populated.response.content.text = JSON.stringify({ ...JSON.parse(delta.response.content.text), chats: [{ id: 'private-chat-id', title: 'Private chat title', threadType: 'chat', chatType: 'group', version: 1, members: [], lastMessage: { content: 'Private message' } }] }); const known = analyzeHar(har([populated])).candidates[0]; assert.equal(known.kind, 'chats'); assert.equal(known.itemCount, 1); assert.equal(known.replayable, true); assert.ok(known.shape.includes('threadType')); assert.doesNotMatch(JSON.stringify(known), /private-chat-id|Private chat title|Private message/); const unknownRows = structuredClone(delta); unknownRows.response.content.text = JSON.stringify({ ...JSON.parse(delta.response.content.text), chats: [{ unexpected: 'unknown row' }] }); assert.equal(analyzeHar(har([unknownRows])).candidates[0].kind, 'unknown'); }); test('observed Teams delta accepts a null title for untitled private chats', () => { const delta = entry({ conversationFolders: {}, teams: [], users: [], channels: [], metadata: { isPartialData: false, hasMoreChats: false }, chats: [{ id: 'private-chat-id', title: null, threadType: 'chat', isOneOnOne: true, members: [{ friendlyName: 'Private participant' }] }, { id: 'private-group-id', title: 'Private group title', threadType: 'chat', isOneOnOne: false }] }); delta.request.url = 'https://teams.cloud.microsoft/api/csa/apac/api/v3/teams/users/me/updates'; const report = analyzeHar(har([delta])).candidates[0]; assert.equal(report.kind, 'chats'); assert.equal(report.itemCount, 2); assert.equal(report.replayable, true); assert.equal(getReplayRequest(har([delta]), 0).url, delta.request.url); assert.doesNotMatch(JSON.stringify(report), /private-chat-id|private-group-id|Private participant|Private group title/); }); test('Teams chat title compatibility still rejects malformed title types and missing structural fields', () => { const envelope = { conversationFolders: {}, teams: [], users: [], channels: [], metadata: { isPartialData: false, hasMoreChats: false } }; const row = { id: 'private-chat-id', title: null, threadType: 'chat' }; const variants = [undefined, 0, false, {}, []].map(title => ({ ...row, title })); variants.push({ ...row, id: '' }, { ...row, id: 42 }, { ...row, threadType: undefined }); for (const invalidRow of variants) { const capture = entry({ ...envelope, chats: [invalidRow] }); const report = analyzeHar(har([capture])).candidates[0]; assert.equal(report.kind, 'unknown'); assert.equal(report.replayable, false); assert.throws(() => getReplayRequest(har([capture]), 0), /结构尚未识别/); } }); test('empty message sync response is recognized only with the observed tenant and complete typed metadata', () => { const json = { messages: [], tenantId: 'private-tenant', _metadata: { syncState: 'https://teams.cloud.microsoft/private-sync-url?secret=value', lastCompleteSegmentStartTime: 0, lastCompleteSegmentEndTime: 1700000000000 } }; const captured = entry(json); const report = analyzeHar(har([captured])).candidates[0]; assert.equal(report.kind, 'messages'); assert.equal(report.itemCount, 0); assert.equal(report.replayable, true); assert.doesNotMatch(JSON.stringify(report), /private-tenant|private-sync-url|secret=value/); const variants = [{ messages: [] }, { ...json, tenantId: null }, { ...json, _metadata: {} }, { ...json, _metadata: { ...json._metadata, lastCompleteSegmentStartTime: '0' } }, { ...json, _metadata: { ...json._metadata, syncState: '' } }]; for (const body of variants) { const unknown = analyzeHar(har([entry(body)])).candidates[0]; assert.equal(unknown.kind, 'unknown'); assert.equal(unknown.replayable, false); } }); test('observed Graph calendar GET paths support full and selected events without confusing body with chat messages', () => { const date = { dateTime: '2026-09-08T10:00:00', timeZone: 'UTC' }; for (const row of [{ id: 'private-event', subject: 'Private event', start: date, end: date, body: { content: 'Private description' } }, { id: 'private-event', start: date, end: date }]) { const captured = entry({ value: [row] }); captured.request.url = 'https://graph.microsoft.com/v1.0/me/events/private-event/instances?startDateTime=private-date'; const result = analyzeHar(har([captured])).candidates[0]; assert.equal(result.kind, 'calendar'); assert.equal(result.itemCount, 1); assert.equal(result.replayable, true); assert.doesNotMatch(JSON.stringify(result), /Private|private-event|private-date/); } const empty = entry({ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/private-user/events', value: [] }); empty.request.url = 'https://graph.microsoft.com/v1.0/me/events'; assert.equal(analyzeHar(har([empty])).candidates[0].kind, 'calendar'); const blocked = ['https://graph.microsoft.com/beta/me/events', 'https://graph.microsoft.com/v1.0/me/messages', 'https://graph.microsoft.com/v1.0/me/chats', 'https://graph.microsoft.com/v1.0/me/events/id/accept']; for (const url of blocked) { const item = structuredClone(empty); item.request.url = url; assert.throws(() => getReplayRequest(har([item]), 0), /白名单/); } }); function calendarRpc(action = 'GetCalendarView') { const calendarEvent = { __type: 'CalendarItem:#Exchange', ItemId: { Id: 'private-item', ChangeKey: 'private-change' }, Subject: 'Private calendar subject', Start: '2026-09-08T10:00:00Z', End: '2026-09-08T11:00:00Z' }; const items = { Items: [calendarEvent], ResponseCode: 'NoError', ResponseClass: 'Success' }; const captured = entry({ Header: {}, Body: action === 'GetCalendarView' ? items : { ResponseMessages: { Items: [items] } } }); captured.request.method = 'POST'; captured.request.url = `https://outlook.office.com/owa/service.svc?action=${action}`; captured.request.headers.push({ name: 'action', value: action }, { name: 'content-type', value: 'application/json' }, { name: 'Origin', value: 'https://outlook.office.com/?secret=private-origin' }, { name: 'Referer', value: 'https://outlook.office.com/calendar/?secret=private-referrer' }, { name: 'x-owa-sessionid', value: 'private-session' }, { name: 'prefer', value: 'outlook.timezone="UTC"' }); const Body = action === 'GetCalendarView' ? { CalendarId: { BaseFolderId: { Id: 'private-folder' } }, RangeStart: '2026-09-08', RangeEnd: '2026-09-09' } : { EventIds: [{ Id: 'private-item' }], ItemShape: {} }; const body = JSON.stringify({ __type: `${action}JsonRequest:#Exchange`, Header: { __type: 'JsonRequestHeaders:#Exchange' }, Body: { __type: `${action}Request:#Exchange`, ...Body } }); if (action === 'GetCalendarView') captured.request.headers.push({ name: 'x-owa-urlpostdata', value: encodeURIComponent(body) }); else captured.request.postData = { mimeType: 'application/json', text: body }; return captured; } test('observed OWA calendar read RPCs retain only captured header/body payloads and classify response envelopes', () => { for (const action of ['GetCalendarView', 'GetCalendarEvent']) { const captured = calendarRpc(action), report = analyzeHar(har([captured])).candidates[0], request = getReplayRequest(har([captured]), 0); assert.equal(report.method, 'POST'); assert.equal(report.kind, 'calendar'); assert.equal(report.itemCount, 1); assert.equal(report.replayable, true); assert.doesNotMatch(JSON.stringify(report), /Private|private-item|private-folder|private-session|private-change|signature/); assert.equal(request.method, 'POST'); assert.equal(request.headers.action, action); assert.equal(request.headers.Origin, 'https://outlook.office.com'); assert.equal(request.headers.Referer, 'https://outlook.office.com/calendar/'); assert.equal(request.headers['x-owa-sessionid'], 'private-session'); assert.equal(request.headers.prefer, 'outlook.timezone="UTC"'); if (action === 'GetCalendarView') { assert.equal(request.body, undefined); assert.equal(request.headers['x-owa-urlpostdata'], captured.request.headers.find(header => header.name === 'x-owa-urlpostdata').value); } else assert.equal(request.body, captured.request.postData.text); } }); test('OWA RPC authorization is limited to exact action, route, method, payload type and successful calendar structure', () => { const variants = []; const modify = fn => { const value = calendarRpc(); fn(value); variants.push(value); }; modify(value => { value.request.url = 'https://outlook.office.com/owa/service.svc?action=DeleteItem'; value.request.headers.find(header => header.name === 'action').value = 'DeleteItem'; }); modify(value => { value.request.headers.find(header => header.name === 'action').value = 'GetCalendarEvent'; }); modify(value => { value.request.headers.push({ name: 'Action', value: 'GetCalendarView' }); }); modify(value => { value.request.url += '&action=GetCalendarEvent'; }); modify(value => { value.request.url = value.request.url.replace('?action=', '?Action='); }); modify(value => { value.request.url = value.request.url.replace('outlook.office.com', 'outlook.office365.com'); }); modify(value => { value.request.url = value.request.url.replace('service.svc', 'other.svc'); }); modify(value => { value.request.method = 'PUT'; }); for (const value of variants) { assert.equal(analyzeHar(har([value])).candidates.length, 0); assert.throws(() => getReplayRequest(har([value]), 0), /白名单/); } const missing = calendarRpc(); missing.request.headers = missing.request.headers.filter(header => header.name !== 'x-owa-urlpostdata'); assert.throws(() => getReplayRequest(har([missing]), 0), /原始负载/); const wrongType = calendarRpc(); const header = wrongType.request.headers.find(header => header.name === 'x-owa-urlpostdata'); const body = JSON.parse(decodeURIComponent(header.value)); body.__type = 'DeleteItemJsonRequest:#Exchange'; header.value = encodeURIComponent(JSON.stringify(body)); assert.throws(() => getReplayRequest(har([wrongType]), 0), /动作类型不一致/); const failed = calendarRpc(); const response = JSON.parse(failed.response.content.text); response.Body.ResponseCode = 'ErrorAccessDenied'; failed.response.content.text = JSON.stringify(response); assert.equal(analyzeHar(har([failed])).candidates[0].kind, 'unknown'); const notCalendar = calendarRpc(); notCalendar.response.content.text = JSON.stringify({ Body: { Items: [{ Subject: 'unknown' }], ResponseCode: 'NoError', ResponseClass: 'Success' } }); assert.equal(analyzeHar(har([notCalendar])).candidates[0].kind, 'unknown'); const long = calendarRpc(); long.request.headers.find(header => header.name === 'x-owa-urlpostdata').value = 'x'.repeat(65537); assert.throws(() => getReplayRequest(har([long]), 0), /长度上限/); }); test('host, protocol, userinfo, port, fragment, OAuth and non-GET boundaries are enforced', () => { const urls = ['https://evil.example/messages', 'https://teams.microsoft.com.evil.example/messages', 'http://teams.microsoft.com/messages', 'https://user:secret@teams.microsoft.com/messages', 'https://teams.microsoft.com:8443/messages', 'https://teams.microsoft.com/messages#secret', 'https://login.microsoftonline.com/token', 'https://teams.cloud.microsoft/oauth2/token', 'https://teams.cloud.microsoft/api/%74oken', 'wss://region.msg.skype.com/messages', 'https://outlook.office.com.evil.example/messages', 'https://graph.microsoft.com/v1.0/chats']; const captured = urls.map(url => { const item = entry(); item.request.url = url; return item; }); const post = entry(); post.request.method = 'POST'; captured.push(post); const socket = entry(); socket._resourceType = 'websocket'; captured.push(socket); assert.equal(analyzeHar(har(captured)).candidates.length, 0); captured.forEach((_, index) => assert.throws(() => getReplayRequest(har(captured), index), /白名单/)); for (const host of ['teams.microsoft.com', 'api.teams.microsoft.com', 'teams.cloud.microsoft', 'api.teams.cloud.microsoft', 'emea.ng.msg.skype.com', 'outlook.office.com', 'outlook.office365.com']) { const item = entry(); item.request.url = `https://${host}/api/messages`; assert.equal(analyzeHar(har([item])).candidates[0].replayable, true, host); } }); test('write-like GET actions, unsuccessful responses, request bodies and missing auth cannot replay', () => { for (const suffix of ['/markRead', '/deleteMessage', '/send', '/messages%2FmarkRead', '/messages?action=sendMessage', '/messages?mark_read=true']) { const item = entry(); item.request.url = `https://teams.cloud.microsoft${suffix}`; assert.equal(analyzeHar(har([item])).candidates[0].replayable, false); assert.throws(() => getReplayRequest(har([item]), 0), /改变远端数据/); } const failed = entry(); failed.response.status = 302; const unauthenticated = entry(); unauthenticated.request.headers = [{ name: 'Accept', value: 'application/json' }]; const body = entry(); body.request.postData = { text: 'write-request' }; assert.throws(() => getReplayRequest(har([failed]), 0), /2xx/); assert.throws(() => getReplayRequest(har([unauthenticated]), 0), /HAR 可能已脱敏/); assert.throws(() => getReplayRequest(har([body]), 0), /请求体/); }); test('large raw and base64 bodies are bounded and unsafe header values are rejected', () => { const huge = entry({ value: [{ ...message, body: { content: 'x'.repeat(2 * 1024 * 1024) } }] }); const encoded = structuredClone(huge); encoded.response.content.text = Buffer.from(encoded.response.content.text).toString('base64'); encoded.response.content.encoding = 'base64'; assert.ok(analyzeHar(har([huge, encoded])).candidates.every(item => !item.replayable && /2 MiB/.test(item.reason))); const bad = entry(); bad.request.headers[0].value = 'Bearer secret\r\nInjected: true'; assert.throws(() => getReplayRequest(har([bad]), 0), /控制字符/); const external = entry(); external.request.headers.push({ name: 'Referer', value: 'https://evil.example/private' }, { name: 'Origin', value: 'https://outlook.office.com/' }); const replay = getReplayRequest(har([external]), 0); assert.equal(replay.headers.Origin, undefined); assert.equal(replay.headers.Referer, undefined); }); test('invalid HARs and selectors fail with fixed errors that do not contain request data', () => { assert.throws(() => analyzeHar({}), /HAR 格式无效/); assert.throws(() => getReplayRequest(har([entry()]), '0'), /请求编号无效/); assert.throws(() => getReplayRequest(har([entry()]), 1), /请求编号无效/); });