import test from 'node:test'; import assert from 'node:assert/strict'; import { normalizeChats, normalizeMessages, normalizeCalendar } from '../src/teams-network-records.js'; import { classifyMessage } from '../src/message-signals.js'; // All data below is fictional; only the field names/types follow the supplied HAR. const chatId = '19:fictional-meeting@thread.v2'; const options = { accountId: 'local-fictional-account', chatId, chatTitle: 'Fictional project' }; const link = id => `https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/conversations/${encodeURIComponent(id)}`; function message(overrides = {}) { return { sequenceId: 1, conversationid: chatId, conversationLink: link(chatId), contenttype: 'text', type: 'Message', amsreferences: [], s2spartnername: 'fictional-partner', id: '1700000000123', clientmessageid: 'fictional-client-message', version: '1700000001123', messagetype: 'RichText/Html', content: '
Hello fictional team & friends.
Next line.
', from: 'fictional-author-id', imdisplayname: 'Fictional author', composetime: '2023-11-14T22:13:20.000Z', originalarrivaltime: '2023-11-14T22:13:20.123Z', properties: { atp: 'fictional-unneeded-metadata' }, ...overrides }; } test('normalizes observed message schema with caller identity, text, scoped ID, and allowlisted provenance', () => { const input = message({ accountId: 'wrong-account', authorization: 'secret-marker', fromDisplayNameInToken: 'token-derived-name', properties: { files: 'attachment-marker', authorization: 'nested-secret' } }); const result = normalizeMessages({ messages: [input], tenantId: 'unneeded-tenant-id' }, options); assert.deepEqual(result, { records: [{ source: 'web-api', accountId: options.accountId, kind: 'message', externalId: `${encodeURIComponent(chatId)}:1700000000123`, parentId: chatId, title: 'Fictional project', text: 'Hello fictional team & friends.\nNext line.', occurredAt: '2023-11-14T22:13:20.123Z', updatedAt: '2023-11-14T22:13:21.123Z', webUrl: null, deleted: false, raw: { messageId: '1700000000123', messageType: 'RichText/Html', author: 'Fictional author', senderId: null, mentions: null, composedAt: '2023-11-14T22:13:20.000Z', arrivedAt: '2023-11-14T22:13:20.123Z', version: '1700000001123' }, }], pagination: {} }); assert.doesNotMatch(JSON.stringify(result), /secret-marker|nested-secret|attachment-marker|token-derived-name|unneeded-tenant-id|fictional-author-id|fictional-client-message/); }); test('encodes both identity components so equal message IDs in different chats do not collide', () => { const one = '19:fictional-a@thread.v2', two = '19:fictional-b@thread.v2'; const build = id => normalizeMessages({ messages: [message({ id: 'id:/%:same', conversationid: id, conversationLink: link(id) })] }, { ...options, chatId: id }).records[0]; assert.notEqual(build(one).externalId, build(two).externalId); assert.equal(build(one).externalId, `${encodeURIComponent(one)}:${encodeURIComponent('id:/%:same')}`); }); test('retains only structured sender and mention evidence for downstream notifications', () => { const tenant = '33333333-3333-4333-8333-333333333333'; const self = '11111111-1111-4111-8111-111111111111'; const other = '22222222-2222-4222-8222-222222222222'; const accountId = `web-api:${tenant}:${self}`; const input = message({ from: `https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${other}`)}`, properties: { mentions: JSON.stringify([{ '@type': 'mention', itemid: 0, mri: `8:orgid:${self}`, mentionType: 'person', displayName: 'unused-mention-name' }]), files: 'unneeded-attachment', authorization: 'nested-secret-marker' } }); const record = normalizeMessages({ messages: [input] }, { ...options, accountId }).records[0]; assert.equal(record.raw.senderId, other); assert.equal(record.raw.selfUserId, self); assert.deepEqual(record.raw.mentions, [{ id: self, type: 'user' }]); assert.equal(classifyMessage(record).mentionsSelf, true); assert.equal(classifyMessage(record).isFromSelf, false); assert.doesNotMatch(JSON.stringify(record.raw), /https:|unused-mention-name|unneeded-attachment|nested-secret-marker/); const missing = normalizeMessages({ messages: [message({ properties: {} })] }, { ...options, accountId }).records[0]; const empty = normalizeMessages({ messages: [message({ properties: { mentions: '[]' } })] }, { ...options, accountId }).records[0]; assert.equal(classifyMessage(missing).mentionsSelf, null); assert.equal(classifyMessage(empty).mentionsSelf, false); }); test('rejects the entire mixed-chat response even if the mismatched item is a skipped control message', () => { const other = '19:fictional-other@thread.v2'; for (const override of [ { conversationid: other }, { conversationLink: link(other) }, { conversationid: other, conversationLink: link(other), messagetype: 'ThreadActivity/MemberJoined' }, ]) { assert.throws(() => normalizeMessages({ messages: [message(), message({ id: 'other-message', ...override })] }, options), { code: 'conversation_mismatch' }); } }); test('requires observed conversation identity fields and rejects malformed or foreign links without logging them', () => { for (const override of [ { conversationid: undefined }, { conversationLink: undefined }, { conversationLink: 'https://untrusted.example/api/chatsvc/apac/v1/users/ME/conversations/secret-marker' }, { conversationLink: `${link(chatId)}?token=secret-marker` }, { conversationLink: `${link(chatId)}#secret-marker` }, { conversationLink: 'https://teams.cloud.microsoft/other-route/secret-marker' }, ]) { assert.throws(() => normalizeMessages({ messages: [message(override)] }, options), error => { assert.doesNotMatch(error.message, /secret-marker|https:\/\//); return true; }); } }); test('skips observed system/control/media types and never infers message deletion', () => { const types = ['Event/Call', 'ThreadActivity/AddCustomApp', 'ThreadActivity/TopicUpdate', 'ThreadActivity/MemberJoined', 'ThreadActivity/MemberLeft', 'RichText/Media_CallRecording', 'RichText/Media_CallTranscript']; const result = normalizeMessages({ messages: [ ...types.map((type, index) => message({ id: `control-${index}`, messagetype: type, content: '<safe> 😀
second
ζΆε°δΊ
Discuss the fictional plan.
' }, start: { dateTime: '2026-09-08T01:00:00.0000000', timeZone: 'UTC' }, end: { dateTime: '2026-09-08T02:00:00.0000000', timeZone: 'UTC' }, createdDateTime: '2026-09-01T09:00:00Z', lastModifiedDateTime: '2026-09-07T09:00:00Z', isCancelled: false, isAllDay: false, ...overrides }; } test('normalizes observed REST calendar details with explicit UTC and narrowly retained provenance', () => { const { records, coverage } = normalizeCalendar({ value: [restEvent({ attendees: [{ emailAddress: { address: 'private-email-marker' } }], recurrence: { range: { private: 'private-recurrence-marker' } }, onlineMeeting: { joinUrl: 'https://example.invalid/private-join-marker' }, authorization: 'private-token-marker', })] }, options); assert.deepEqual(coverage, { received: 1, recorded: 1, skippedIncomplete: 0, unresolvedTimezones: 0, schema: 'rest-events' }); assert.equal(records[0].source, 'web-api'); assert.equal(records[0].accountId, options.accountId); assert.equal(records[0].externalId, `rest-events:${encodeURIComponent('fictional-calendar-event/+A')}`); assert.equal(records[0].text, 'Discuss the fictional plan.'); assert.equal(records[0].occurredAt, '2026-09-08T01:00:00.000Z'); assert.equal(records[0].raw.detailLevel, 'detail'); assert.doesNotMatch(JSON.stringify(records), /private-email-marker|private-recurrence-marker|private-join-marker|private-token-marker/); }); test('titled calendar views omit unknown body text for caller-side merging with previous details', () => { const complete = normalizeCalendar({ value: [restEvent()] }, options).records[0]; const summary = normalizeCalendar({ value: [restEvent({ body: undefined })] }, options).records[0]; assert.equal(summary.externalId, complete.externalId); assert.equal(summary.title, complete.title); assert.equal(summary.text, undefined); assert.equal(summary.raw.detailLevel, 'summary'); assert.equal(normalizeCalendar({ value: [restEvent({ body: { contentType: 'text', content: '' } })] }, options).records[0].raw.detailLevel, 'detail'); }); test('calendar lookups with only id and times are skipped rather than overwriting titled events', () => { const result = normalizeCalendar({ value: [restEvent({ subject: undefined, body: undefined })] }, options); assert.equal(result.records.length, 0); assert.equal(result.coverage.skippedIncomplete, 1); }); test('calendar wall-clock times with unknown timezones are retained without inventing an instant', () => { for (const timeZone of ['', 'Pacific Standard Time', 'Asia/Singapore']) { const result = normalizeCalendar({ value: [restEvent({ start: { dateTime: '2026-09-08T09:00:00', timeZone } })] }, options); assert.equal(result.records[0].occurredAt, null); assert.equal(result.records[0].raw.start.dateTime, '2026-09-08T09:00:00'); assert.equal(result.coverage.unresolvedTimezones, 1); } const offset = normalizeCalendar({ value: [restEvent({ start: { dateTime: '2026-09-08T09:00:00+08:00', timeZone: 'Asia/Singapore' } })] }, options); assert.equal(offset.records[0].occurredAt, '2026-09-08T01:00:00.000Z'); }); test('cancelled calendar events retain actual cancellation without becoming deletion tombstones', () => { const result = normalizeCalendar({ value: [restEvent({ isCancelled: true, '@removed': {}, deletedDateTime: '2026-09-08T01:00:00Z' })] }, options); assert.equal(result.records[0].deleted, false); assert.equal(result.records[0].raw.isCancelled, true); assert.equal(result.records[0].text, 'Discuss the fictional plan.'); assert.throws(() => normalizeCalendar({ Header: {}, Body: { TimeZones: [] } }, options), { code: 'invalid_calendar_payload' }); }); function owaEvent(overrides = {}) { return { __type: 'CalendarItem:#Exchange', ItemId: { __type: 'ItemId:#Exchange', ChangeKey: 'fictional-change-key', Id: 'fictional-calendar-event/+A' }, ParentFolderId: { Id: 'fictional-calendar-folder', ChangeKey: 'fictional-folder-change-key' }, UID: 'fictional-event-uid', Subject: 'Fictional OWA meeting', Start: '2026-09-08T09:00:00+08:00', End: '2026-09-08T10:00:00+08:00', StartTimeZoneId: 'Singapore Standard Time', EndTimeZoneId: 'Singapore Standard Time', IsCancelled: false, IsAllDayEvent: false, Preview: 'short private-preview-marker', CalendarItemType: 'Single', IsRecurring: false, Organizer: { Mailbox: { Name: 'Fictional organizer', EmailAddress: 'private-organizer-marker' } }, Location: { DisplayName: 'Fictional location' }, ...overrides }; } test('normalizes observed OWA CalendarView and StartupData summaries without treating Preview as full body', () => { const view = { Body: { ResponseCode: 'NoError', ResponseClass: 'Success', Items: [owaEvent()] } }; for (const payload of [view, { getCalendarView: view }]) { const { records, coverage } = normalizeCalendar(payload, options); assert.equal(coverage.schema, 'owa-calendar'); assert.equal(coverage.recorded, 1); assert.equal(records[0].externalId, `owa-calendar:${encodeURIComponent('fictional-calendar-event/+A')}`); assert.equal(records[0].title, 'Fictional OWA meeting'); assert.equal(records[0].text, undefined); assert.equal(records[0].occurredAt, '2026-09-08T01:00:00.000Z'); assert.equal(records[0].raw.detailLevel, 'summary'); assert.doesNotMatch(JSON.stringify(records), /private-preview-marker|private-organizer-marker|fictional-calendar-folder|fictional-change-key/); } }); test('OWA detail responses use the same native event ID as views and remain distinct from REST IDs', () => { const item = owaEvent({ Body: { BodyType: 'HTML', Value: 'Full fictional description.
' }, DateTimeCreated: '2026-09-01T09:00:00Z', LastModifiedTime: '2026-09-07T09:00:00Z', RequiredAttendees: [{ Mailbox: { EmailAddress: 'private-attendee-marker' } }], OnlineMeetingJoinUrl: 'https://example.invalid/private-link-marker', }); const result = normalizeCalendar({ Body: { ResponseMessages: { Items: [ { ResponseCode: 'NoError', ResponseClass: 'Success', Items: [item] }, ] } } }, options); const detail = result.records[0]; const summary = normalizeCalendar({ Body: { Items: [owaEvent()] } }, options).records[0]; const rest = normalizeCalendar({ value: [restEvent()] }, options).records[0]; assert.equal(detail.externalId, summary.externalId); assert.notEqual(detail.externalId, rest.externalId); assert.equal(detail.text, 'Full fictional description.'); assert.equal(detail.raw.detailLevel, 'detail'); assert.equal(detail.updatedAt, '2026-09-07T09:00:00.000Z'); assert.doesNotMatch(JSON.stringify(result), /private-attendee-marker|private-link-marker/); }); test('OWA cancellation remains an explicit observation and response failures cannot masquerade as an empty calendar', () => { const cancelled = normalizeCalendar({ Body: { Items: [owaEvent({ IsCancelled: true })] } }, options).records[0]; assert.equal(cancelled.deleted, false); assert.equal(cancelled.raw.isCancelled, true); for (const payload of [ { Body: { ResponseClass: 'Error', ResponseCode: 'ErrorAccessDenied', Items: [] } }, { Body: { ResponseMessages: { Items: [{ ResponseCode: 'ErrorItemNotFound', ResponseClass: 'Error' }] } } }, ]) assert.throws(() => normalizeCalendar(payload, options), { code: 'calendar_response_error' }); });