import test from 'node:test'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { createStore } from '../src/store.js'; import { createNetworkHistory, validateHistoryCursor } from '../src/network-history.js'; import { normalizeMessages } from '../src/teams-network-records.js'; import { abortableDelay } from '../src/request-pacing.js'; const accountId = 'web-api:11111111-1111-1111-1111-111111111111:22222222-2222-2222-2222-222222222222'; const chatId = '19:fictional-history@thread.v2'; const prefix = 'https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/conversations/'; const view = 'msnp24Equivalent|supportsMessageProperties'; const token = `fake.${Buffer.from(JSON.stringify({ tid: '11111111-1111-1111-1111-111111111111', oid: '22222222-2222-2222-2222-222222222222' })).toString('base64url')}.signature`; function url({ chat = chatId, cursor, start = '0', size = 2 } = {}) { const result = new URL(`${prefix}${encodeURIComponent(chat)}/messages`); result.searchParams.set('view', view); result.searchParams.set('pageSize', String(size)); result.searchParams.set('startTime', start); if (cursor) result.searchParams.set('syncState', cursor); return result.href; } function message(id, overrides = {}) { return { id, conversationid: chatId, conversationLink: `${prefix}${encodeURIComponent(chatId)}`, type: 'Message', messagetype: 'RichText/Html', contenttype: 'text', content: `
Fictional ${id}
`, imdisplayname: 'Fictional author', composetime: '2023-11-14T22:13:20Z', originalarrivaltime: '2023-11-14T22:13:20Z', version: '1700000000000', ...overrides }; } function page(messages, { backward, boundary = 0, sync = url({ cursor: 'incremental-secret' }) } = {}) { return { messages, tenantId: 'fictional-tenant', _metadata: { lastCompleteSegmentStartTime: boundary, lastCompleteSegmentEndTime: 1800000000000, syncState: sync, ...(backward ? { backwardLink: backward } : {}) } }; } const json = (payload, status = 200) => new Response(JSON.stringify(payload), { status, headers: { 'content-type': 'application/json' } }); function har() { return { log: { entries: [{ request: { method: 'GET', url: url({ start: '1700000000000', size: 200 }), headers: [{ name: 'Authorization', value: `Bearer ${token}` }] }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(page([message('captured')], { boundary: 1700000000000 })) } }, }] } }; } function setup(fetch, options = {}) { const store = createStore(':memory:'), writes = [], originalSet = store.setState.bind(store); store.setState = (key, value) => { writes.push({ key, value: structuredClone(value) }); return originalSet(key, value); }; let milliseconds = Date.parse('2026-09-08T00:00:00Z'); const timing = { random: () => 0.5, clock: () => milliseconds, now: () => new Date(milliseconds).toISOString(), sleep: async (delay, { signal } = {}) => { if (signal?.aborted) throw new Error('cancelled'); milliseconds += delay; } }; const history = createNetworkHistory({ har: har(), store, fetch, pageSize: 2, ...timing, ...options }); return { store, history, writes, timing, advance: delay => { milliseconds += delay; }, close: () => store.close() }; } test('history shares validated committed message pages for optional conversation names without making metadata failures fatal', async () => { const observed = []; const payload = page([message('history-name-link')]); const f = setup(async () => json(payload), { onMessages: (scope, body) => { assert.equal(f.store.stats().total, 1, 'record must be committed before discovery'); assert.equal(f.history.coverage().complete, 1, 'history must already be committed'); observed.push({ scope, body }); throw new Error('Optional metadata failed with private details'); } }); try { const result = await f.history.runOnce(); assert.equal(result.complete, true); assert.equal(result.successful, 1); assert.deepEqual(result.errors, []); assert.equal(observed.length, 1); assert.deepEqual(observed[0].body, payload); assert.equal(observed[0].scope.accountId, accountId); assert.equal(observed[0].scope.chatId, chatId); assert.equal(observed[0].scope.requestUrl, url()); assert.equal(observed[0].scope.headers.Authorization, `Bearer ${token}`); await f.history.runOnce(); assert.equal(observed.length, 1, 'completed history must not be rescanned'); assert.doesNotMatch(JSON.stringify(result), /private details|Bearer|signature/); } finally { f.close(); } }); test('rejected or cancelled history responses never supply optional conversation-name evidence', async () => { for (const scenario of ['wrong-chat', 'invalid-cursor', 'invalid-boundary', 'cancelled']) { let observations = 0; const controller = new AbortController(); const f = setup(async () => { if (scenario === 'cancelled') controller.abort(); const payload = page([message('rejected', scenario === 'wrong-chat' ? { conversationid: 'other-chat' } : {})], scenario === 'invalid-cursor' ? { backward: 'https://untrusted.example/messages' } : {}); if (scenario === 'invalid-boundary') delete payload._metadata.lastCompleteSegmentStartTime; return json(payload); }, { onMessages: () => { observations++; } }); try { const result = await f.history.runOnce({ signal: controller.signal }); assert.equal(observations, 0, scenario); assert.equal(f.store.stats().total, 0, scenario); assert.ok(result.cancelled || result.errors.length > 0, scenario); } finally { f.close(); } } }); test('history starts at zero, follows only backwardLink, and completes only with an explicit zero boundary', async () => { const calls = []; const f = setup(async (request, options) => { calls.push({ request, options }); return json(calls.length === 1 ? page([message('newer')], { backward: url({ cursor: 'older-secret' }), boundary: 100 }) : page([message('older')])); }); try { const result = await f.history.runOnce(); assert.equal(result.complete, true); assert.equal(result.coverage.complete, 1); assert.equal(result.coverage.pages, 2); assert.equal(new URL(calls[0].request).searchParams.get('startTime'), '0'); assert.equal(new URL(calls[0].request).searchParams.has('syncState'), false); assert.equal(new URL(calls[1].request).searchParams.get('syncState'), 'older-secret'); assert.ok(calls.every(call => call.options.method === 'GET' && call.options.redirect === 'manual')); assert.equal(f.store.stats().total, 2); assert.ok(f.writes.every(write => write.key.startsWith('web-api:history:'))); assert.doesNotMatch(JSON.stringify(f.writes.map(write => write.value)), /Authorization|signature|Bearer/); assert.doesNotMatch(JSON.stringify(result), /older-secret|incremental-secret|fictional-history/); await f.history.runOnce(); assert.equal(calls.length, 2); } finally { f.close(); } }); test('captured draftVersion is omitted from the history seed without widening backward-link validation or resetting progress', async () => { const captured = har(), recent = new URL(captured.log.entries[0].request.url); recent.searchParams.set('draftVersion', 'fictional-private-draft'); recent.searchParams.set('syncState', 'recent-secret'); captured.log.entries[0].request.url = recent.href; const calls = []; const f = setup(async request => { calls.push(new URL(request)); return json(page([message('archived')], calls.length === 1 ? { backward: url({ cursor: 'older-secret' }), boundary: 100 } : {})); }, { har: captured }); try { const result = await f.history.runOnce(); assert.equal(result.complete, true); assert.equal(calls.length, 2); assert.equal(calls[0].searchParams.get('startTime'), '0'); assert.ok(calls.every(request => !request.searchParams.has('draftVersion'))); assert.equal(calls[0].searchParams.has('syncState'), false); assert.equal(calls[1].searchParams.get('syncState'), 'older-secret'); assert.equal(new URL(captured.log.entries[0].request.url).searchParams.get('draftVersion'), 'fictional-private-draft'); assert.doesNotMatch(JSON.stringify(f.writes), /fictional-private-draft/); const resumed = createNetworkHistory({ har: captured, store: f.store, pageSize: 2, ...f.timing, fetch: async () => { throw new Error('Completed history must not fetch again'); } }); assert.equal((await resumed.runOnce()).coverage.pages, 2); const untrusted = new URL(url({ cursor: 'older-secret' })); untrusted.searchParams.set('draftVersion', 'unapproved'); assert.throws(() => validateHistoryCursor(untrusted.href, recent.href), { code: 'invalid_history_cursor' }); } finally { f.close(); } }); test('history derives only chat metadata from the peer and uses its current title on later pages despite a stale catalogue', async () => { const self='22222222-2222-2222-2222-222222222222', peer='33333333-3333-3333-3333-333333333333'; let calls=0; const sender=id=>`https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${id}`)}`; const f=setup(async()=>json(++calls===1 ?page([message('peer-author',{from:sender(peer),imdisplayname:'Fictional peer'})],{backward:url({cursor:'older-page'}),boundary:1}) :page([message('self-author',{from:sender(self),imdisplayname:'Fictional self'})]))); try { f.store.upsertRecord({source:'web-api',accountId,kind:'chat',externalId:chatId,title:'聊天',raw:{isOneOnOne:true,titleSource:'placeholder'}}); const catalogueKey='web-api:chats:'+createHash('sha256').update(accountId+'https://teams.cloud.microsoft'+'/api/chatsvc/apac/v1/users/ME/conversations/').digest('hex').slice(0,24); f.store.setState(catalogueKey,{chats:[{id:chatId,title:'聊天'}]});f.history.refreshChats(); const result=await f.history.runOnce();assert.equal(result.complete,true);assert.equal(calls,2); const named=f.store.getRecordByIdentity({source:'web-api',accountId,kind:'chat',externalId:chatId}); assert.equal(named.title,'Fictional peer');assert.equal(named.raw.titleSource,'message-author'); const messages=f.store.listRecords({kind:'message'}).items; assert.equal(messages.find(record=>record.raw.messageId==='self-author').title,'Fictional peer'); assert.equal(messages.find(record=>record.raw.messageId==='self-author').raw.author,'Fictional self'); const messageChanges=f.store.readRows("SELECT c.ingestion FROM change_log c JOIN records r ON c.recordId=r.id WHERE r.kind='message'"); assert.ok(messageChanges.every(row=>row.ingestion==='history')); const versions=f.store.stats().versions;f.history.refreshChats();await f.history.runOnce(); assert.equal(calls,2);assert.equal(f.store.stats().versions,versions); } finally {f.close();} }); test('request-budget exhaustion persists an independent checkpoint and a fresh instance resumes its next page', async () => { let calls = 0; const fetch = async request => { calls++; return json(new URL(request).searchParams.has('syncState') ? page([message('old')]) : page([message('new')], { backward: url({ cursor: 'next-history-secret' }), boundary: 100 })); }; const f = setup(fetch, { maxRequests: 1 }); try { f.store.setState('web-api:cursor:watch-owned', { url: 'watch-private-cursor' }); const first = await f.history.runOnce(); assert.equal(first.complete, false); assert.equal(first.budgetExhausted, true); assert.equal(first.coverage.pending, 1); const next = createNetworkHistory({ har: har(), store: f.store, fetch, maxRequests: 1, pageSize: 2, ...f.timing }); const second = await next.runOnce(); assert.equal(second.complete, true); assert.equal(calls, 2); assert.deepEqual(f.store.getState('web-api:cursor:watch-owned'), { url: 'watch-private-cursor' }); assert.equal(f.store.stats().total, 2); } finally { f.close(); } }); test('an empty incremental-looking response or a missing backwardLink above zero is explicitly incomplete', async () => { for (const messages of [[], [message('recent')]]) { const f = setup(async () => json(page(messages, { boundary: 1700000000000 }))); try { const result = await f.history.runOnce(); assert.equal(result.complete, false); assert.equal(result.coverage.truncated, 1); assert.equal(result.coverage.stopReasons['unproven-start'], 1); } finally { f.close(); } } }); test('control-only pages still advance history instead of treating zero normalized records as completion', async () => { let calls = 0; const f = setup(async () => json(++calls === 1 ? page([message('control', { messagetype: 'ThreadActivity/MemberJoined' })], { boundary: 100, backward: url({ cursor: 'next' }) }) : page([message('user')]))); try { const result = await f.history.runOnce(); assert.equal(calls, 2); assert.equal(result.complete, true); assert.equal(result.skippedItems, 1); assert.equal(f.store.stats().total, 1); } finally { f.close(); } }); test('invalid cross-chat and cross-origin cursors cannot advance a checkpoint or commit a page', async () => { for (const backward of [url({ chat: '19:other-chat', cursor: 'private-marker' }), url({ cursor: 'private-marker' }).replace('teams.cloud.microsoft', 'untrusted.example')]) { const f = setup(async () => json(page([message('unsafe')], { backward, boundary: 100 }))); try { const result = await f.history.runOnce(); assert.equal(result.successful, 0); assert.equal(result.errors.length, 1); assert.equal(f.store.stats().total, 0); assert.equal(result.coverage.errors, 1); assert.equal(f.writes.at(-1).value.pages, 0); assert.equal(new URL(f.writes.at(-1).value.nextUrl).searchParams.has('syncState'), false); assert.doesNotMatch(JSON.stringify(result), /private-marker|untrusted|other-chat/); } finally { f.close(); } } }); test('cursor validation accepts path encoding differences but rejects duplicate or unsupported query parameters', () => { const original = url(); const compatible = url({ cursor: 'safe' }).replace(encodeURIComponent(chatId), chatId); assert.equal(new URL(validateHistoryCursor(compatible, original)).origin, 'https://teams.cloud.microsoft'); for (const candidate of [`${url({ cursor: 'safe' })}&startTime=0`, `${url()}&endTime=1`, `${url()}&token=secret`, url().replace('pageSize=2', 'pageSize=500')]) { assert.throws(() => validateHistoryCursor(candidate, original), { code: 'invalid_history_cursor' }); } }); test('message and checkpoint commits roll back together and the same page is retryable after storage recovers', async () => { const f = setup(async () => json(page([message('transactional')]))); const originalSet = f.store.setState; try { f.store.setState = () => { throw new Error('fictional database error private-marker'); }; const failed = await f.history.runOnce(); assert.equal(failed.successful, 0); assert.equal(f.store.stats().total, 0); assert.equal(f.history.coverage().pages, 0); assert.doesNotMatch(JSON.stringify(failed), /private-marker/); f.store.setState = originalSet; const recovered = await f.history.runOnce(); assert.equal(recovered.complete, true); assert.equal(f.store.stats().total, 1); } finally { f.close(); } }); test('repeated cursors and per-conversation page limits stop explicitly rather than claiming completion', async () => { const f = setup(async () => json(page([message('loop')], { backward: url(), boundary: 100 }))); try { const result = await f.history.runOnce(); assert.equal(result.requests, 1); assert.equal(result.complete, false); assert.equal(result.coverage.stopReasons['repeated-cursor'], 1); } finally { f.close(); } const g = setup(async () => json(page([message('bounded')], { backward: url({ cursor: 'next' }), boundary: 100 })), { maxPages: 1 }); try { const result = await g.history.runOnce(); assert.equal(result.coverage.stopReasons['page-limit'], 1); assert.equal(result.complete, false); const resumed = createNetworkHistory({ har: har(), store: g.store, pageSize: 2, maxPages: 2, fetch: async () => json(page([message('last')])), ...g.timing }); assert.equal((await resumed.runOnce()).complete, true); } finally { g.close(); } }); test('authentication pauses until a renewed collector; 429 and 5xx defer rounds until cooldown expires', async () => { for (const status of [429, 503]) { let calls = 0; const f = setup(async () => ++calls === 1 ? json({}, status) : json(page([message('retry')]))); try { assert.equal((await f.history.runOnce()).ok, false); const deferred = await f.history.runOnce(); assert.equal(deferred.deferred, true); assert.equal(deferred.requests, 0); assert.equal(calls, 1); f.advance(30_000); assert.equal((await f.history.runOnce()).complete, true); assert.equal(calls, 2); } finally { f.close(); } } let authCalls = 0; const f = setup(async () => { authCalls++; return json({}, 401); }); try { assert.equal((await f.history.runOnce()).authRequired, true); await f.history.runOnce(); assert.equal(authCalls, 1); const renewed = createNetworkHistory({ har: har(), store: f.store, fetch: async () => json(page([message('renewed')])), pageSize: 2, ...f.timing }); assert.equal((await renewed.runOnce()).complete, true); } finally { f.close(); } }); test('refreshChats reads new persisted chat records without requiring mutable watch cursors or duplicate targets', () => { const f = setup(async () => json(page([]))); try { f.store.upsertRecord({ source: 'web-api', accountId, kind: 'chat', externalId: '19:later-discovered', title: 'Fictional later chat', text: '' }); assert.equal(f.history.coverage().conversations, 1); assert.equal(f.history.refreshChats().conversations, 2); assert.equal(f.history.refreshChats().conversations, 2); assert.equal(f.writes.length, 0); const empty = createNetworkHistory({ har: { log: { entries: [] } }, store: f.store, ...f.timing }); assert.equal(empty.coverage().conversations, 0); } finally { f.close(); } }); test('older history never overwrites a newer real-time record when both versions have valid timestamps', async () => { const f = setup(async () => json(page([message('same-id')]))); try { const newer = normalizeMessages(page([message('same-id', { content: 'New live version
', version: '1800000000000' })]), { accountId, chatId }).records[0]; f.store.upsertRecord(newer); const result = await f.history.runOnce(); assert.equal(result.complete, true); assert.equal(result.skippedOlderRecords, 1); assert.equal(f.store.getRecordByIdentity(newer).text, 'New live version'); assert.equal(f.store.stats().versions, 1); } finally { f.close(); } }); test('concurrent calls share one pass and cancellation does not commit an in-flight response', async () => { let release, calls = 0; const f = setup(async () => { calls++; return new Promise(resolve => { release = resolve; }); }); const controller = new AbortController(); try { const first = f.history.runOnce({ signal: controller.signal }); while (!release) await new Promise(resolve => setImmediate(resolve)); const duplicate = f.history.runOnce({ signal: controller.signal }); controller.abort(); release(json(page([message('cancelled')]))); const result = await first; await duplicate; assert.equal(calls, 1); assert.equal(result.cancelled, true); assert.equal(f.store.stats().total, 0); assert.equal(f.writes.length, 0); } finally { f.close(); } }); test('backward pagination accepts the observed property-capability reduction only', async () => { const backward = new URL(url({ cursor: 'older' })); backward.searchParams.set('view', 'msnp24Equivalent'); assert.equal(validateHistoryCursor(backward.href, url()), backward.href); const unknown = new URL(backward); unknown.searchParams.set('view', 'unobserved-mode'); assert.throws(() => validateHistoryCursor(unknown.href, url())); let calls = 0; const f = setup(async () => json(++calls === 1 ? page([message('new')], { backward: backward.href, boundary: 1 }) : page([message('old')]))); try { assert.equal((await f.history.runOnce()).complete, true); assert.equal(calls, 2); } finally { f.close(); } }); test('history restores the same authenticated catalogue as monitoring and excludes activity service streams', () => { const f = setup(async () => json(page([]))); try { const key = 'web-api:chats:' + createHash('sha256').update(accountId + 'https://teams.cloud.microsoft' + '/api/chatsvc/apac/v1/users/ME/conversations/').digest('hex').slice(0, 24); f.store.setState(key, { chats: [{ id: chatId }, { id: '19:captured-earlier@thread.v2' }, { id: '48:activity' }, { id: 'bad\nidentity' }] }); const before = structuredClone(f.store.getState(key)); const coverage = f.history.refreshChats(); assert.equal(coverage.conversations, 2); assert.equal(coverage.skipped.activityConversation, 1); assert.equal(coverage.skipped.invalidCatalogueChat, 1); f.history.refreshChats(); assert.equal(f.history.coverage().conversations, 2); assert.deepEqual(f.store.getState(key), before); } finally { f.close(); } }); test('completed legacy checkpoints rescan once for newly supported Text without duplicating existing records', async () => { const f = setup(async () => json(page([message('existing')]))); try { await f.history.runOnce(); const saved = f.writes.at(-1), legacy = { ...saved.value }; delete legacy.adapterVersion; f.store.setState(saved.key, legacy); let calls = 0; const fetch = async () => { calls++; return json(page([message('existing'), message('plain', { messagetype: 'Text', content: '