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: 'not a user message', deleted: true })), message({ properties: { deletetime: '2023-11-14T22:13:20.000Z' }, deletedDateTime: '2023-11-14T22:13:20.000Z', '@removed': {} }), ] }, options); assert.equal(result.records.length, 1); assert.equal(result.records[0].deleted, false); assert.equal(normalizeMessages({ messages: [] }, options).records.length, 0); }); test('extracts only the observed metadata fields without putting the continuation cursor in record data', () => { const syncState = `${link(chatId)}/messages?syncState=fictional-cursor`; const result = normalizeMessages({ messages: [message()], _metadata: { lastCompleteSegmentStartTime: 0, lastCompleteSegmentEndTime: 1700000000000, syncState, nextLink: 'not-observed', authorization: 'private-marker', } }, options); assert.deepEqual(result.pagination, { lastCompleteSegmentStartTime: 0, lastCompleteSegmentEndTime: 1700000000000, syncState }); assert.doesNotMatch(JSON.stringify(result.records), /fictional-cursor|private-marker/); assert.equal(Object.hasOwn(result.pagination, 'nextLink'), false); assert.throws(() => normalizeMessages({ messages: [], _metadata: { lastCompleteSegmentStartTime: -1 } }, options), { code: 'invalid_metadata' }); }); test('dates are valid normalized ISO timestamps and invalid or timezone-free dates remain unknown', () => { const first = normalizeMessages({ messages: [message({ originalarrivaltime: '2026-09-08T10:30:00.1234567+08:00' })] }, options).records[0]; assert.equal(first.occurredAt, '2026-09-08T02:30:00.123Z'); for (const originalarrivaltime of ['2026-02-30T12:00:00Z', '2026-09-08T12:00:00', '2026-13-01T12:00:00Z', '2026-09-08T24:00:00Z', 'not a date']) { const result = normalizeMessages({ messages: [message({ originalarrivaltime, composetime: 'invalid', version: 'invalid' })] }, options).records[0]; assert.equal(result.occurredAt, null); assert.equal(result.updatedAt, null); assert.equal(Object.hasOwn(result.raw, 'arrivedAt'), false); } }); test('HTML is converted to plain text and empty user messages are skipped', () => { const result = normalizeMessages({ messages: [ message({ content: '

<safe> 😀
second

', imdisplayname: 'Fictional author' }), message({ id: 'empty', content: '


' }), ] }, { ...options, chatTitle: '' }); assert.equal(result.records.length, 1); assert.equal(result.records[0].text, ' πŸ˜€\nsecond'); assert.equal(result.records[0].title, '聊倩梈息'); assert.equal(result.records[0].raw.author, 'Fictional author'); }); test('image-backed inline and emoji-only messages are retained in order without treating reactions as body text', () => { const result = normalizeMessages({ messages: [ message({ id: 'inline-emoji', content: '

ζ”Άεˆ°πŸ˜€δΊ†πŸ‘πŸ½

', properties: { emotions: [{ key: 'reaction-marker', users: ['private-reactor'] }] } }), message({ id: 'only-emoji', content: '

👩🏽‍💻(laugh)

' }), message({ id: 'only-image', content: '' }), message({ id: 'reactions-only', content: '', properties: { emotions: [{ key: 'reaction-marker', users: ['private-reactor'] }] } }), ] }, options); assert.equal(result.records.length, 3); assert.deepEqual(result.records.map(record => record.text), ['ζ”Άεˆ°πŸ˜€δΊ†πŸ‘πŸ½', 'πŸ‘©πŸ½β€πŸ’»(laugh)', '[图片]']); assert.doesNotMatch(JSON.stringify(result.records), /private-emoji|private-image|reaction-marker|private-reactor/); }); test('observed ordinary Text retains literal text while 48 activity notifications stay out of chat records', () => { const result = normalizeMessages({ messages: [message({ messagetype: 'Text', content: ' & text' })] }, options); assert.equal(result.records.length, 1); assert.equal(result.records[0].text, ' & text'); const activity = '48:fictional-notifications'; const skipped = normalizeMessages({ messages: [message({ messagetype: 'Text', content: 'notification', conversationid: activity, conversationLink: link(activity), properties: { activity: '{}' } })] }, { ...options, chatId: activity }); assert.equal(skipped.records.length, 0); }); test('accepts the observed empty incremental chat response', () => { assert.deepEqual(normalizeChats({ chats: [], teams: [], users: [], metadata: { syncToken: 'fictional-cursor', forwardSyncToken: null, isPartialData: false, hasMoreChats: false } }, options), { records: [], chats: [] }); }); test('normalizes the newly observed nonempty chat schema while ignoring previews, credentials, and deletion flags', () => { const result = normalizeChats({ chats: [{ id: chatId, title: 'Fictional meeting', threadType: 'meeting', isOneOnOne: false, createdAt: '2023-11-14T22:13:20Z', version: 1700000001123, members: [{ friendlyName: 'Fictional member', mri: 'private-member-marker' }], lastMessage: { content: 'private-preview-marker', containerId: 'another-chat' }, tenantId: 'private-tenant-marker', isConversationDeleted: true, hidden: true, authorization: 'private-secret-marker', meetingInformation: { meetingJoinUrl: 'https://example.invalid/private-marker' }, }] }, options); assert.deepEqual(result.chats, [{ id: chatId, title: 'Fictional meeting' }]); assert.deepEqual(result.records, [{ source: 'web-api', accountId: options.accountId, kind: 'chat', externalId: chatId, title: 'Fictional meeting', text: '', occurredAt: '2023-11-14T22:13:20.000Z', updatedAt: '2023-11-14T22:13:21.123Z', webUrl: null, deleted: false, raw: { chatId, titleSource: 'explicit', members: [], membersComplete: false, threadType: 'meeting', isOneOnOne: false, createdAt: '2023-11-14T22:13:20.000Z', version: 1700000001123 }, }]); assert.doesNotMatch(JSON.stringify(result), /private-|another-chat/); const untitled = normalizeChats({ chats: [{ id: '19:fictional-direct', title: '', isOneOnOne: true, members: [{ friendlyName: 'Fictional person' }] }] }, options); assert.equal(untitled.chats[0].title, '聊倩'); }); test('rejects missing identities and unrelated response shapes instead of silently treating them as empty results', () => { for (const payload of [null, [], {}, { value: [] }, { messages: {} }]) assert.throws(() => normalizeMessages(payload, options), { code: 'invalid_message_payload' }); assert.throws(() => normalizeMessages({ messages: [] }, { ...options, accountId: '' }), { code: 'invalid_identity' }); assert.throws(() => normalizeMessages({ messages: [message({ id: '' })] }, options), { code: 'invalid_identity' }); assert.throws(() => normalizeChats({ value: [] }, options), { code: 'invalid_chat_payload' }); }); test('chat normalization names only the verified other member and records explicit-title provenance', () => { const tenant='11111111-1111-1111-1111-111111111111', self='22222222-2222-2222-2222-222222222222', peer='33333333-3333-3333-3333-333333333333'; const accountId=`web-api:${tenant}:${self}`; const input={id:chatId,title:'',isOneOnOne:true,members:[ {objectId:self,mri:`8:orgid:${self}`,friendlyName:'Fictional self'}, {objectId:peer,mri:`8:orgid:${peer}`,friendlyName:'Fictional peer'}, ]}; const named=normalizeChats({chats:[input]}, {accountId}).records[0]; assert.equal(named.title,'Fictional peer');assert.equal(named.raw.titleSource,'members');assert.equal(named.raw.peerId,peer); assert.equal(named.raw.membersComplete,true); const explicit=normalizeChats({chats:[{...input,title:'聊倩'}]}, {accountId}).records[0]; assert.equal(explicit.title,'聊倩');assert.equal(explicit.raw.titleSource,'explicit'); const unnamed=normalizeChats({chats:[{...input,members:input.members.map(({friendlyName,...member})=>member)}]}, {accountId}).records[0]; assert.equal(unnamed.title,'聊倩');assert.equal(unnamed.raw.titleSource,'placeholder');assert.equal(unnamed.raw.members.length,2); }); function restEvent(overrides = {}) { return { id: 'fictional-calendar-event/+A', subject: 'Fictional planning meeting', body: { contentType: 'html', content: '

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' }); });