| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import fs from 'node:fs';
- import { JSDOM } from 'jsdom';
- import { collectVisible, visibleText, safePageUrl } from '../extension/parser.js';
- import { DEFAULT_CONFIG, validateConfig, publicConfig, isTeamsSender, isTrustedPage, validateCapture, deliverWithRetry } from '../extension/config.js';
- import { DeliveryQueue } from '../extension/queue.js';
- function fixture(html) { return new JSDOM(html, { url: 'https://teams.microsoft.com/v2/' }).window.document; }
- const chat = `<nav><div data-message-id="sidebar">Sidebar must not be a message</div></nav>
- <header data-tid="chat-header-title">项目组</header><main data-conversation-id="thread-123"><div role="log">
- <article data-message-id="170000000001"><div data-tid="message-wrapper"><span data-tid="message-author-name">王明</span><time datetime="2026-09-08T09:00:00+08:00">09:00</time><div data-tid="message-body"><p>今天确认需求。</p><p>请查看方案。</p><span hidden>hidden secret</span><input value="password secret"><textarea>draft secret</textarea><div contenteditable="true">composer secret</div><button>Reply</button></div></div></article>
- <article data-message-id="170000000002"><time>昨天 10:30</time><div data-tid="message-body">第二条消息</div></article>
- <article data-message-id="hidden" aria-hidden="true">Hidden message</article></div></main>`;
- test('Teams chat fixture extracts visible message bodies, author and explicit dates; excludes inputs/navigation/nested duplicates', () => {
- const document = fixture(chat);
- for (const input of document.querySelectorAll('input,textarea')) Object.defineProperty(input, 'value', { get() { throw new Error('Input value must never be read'); } });
- const result = collectVisible(document);
- assert.equal(result.records.length, 2);
- assert.deepEqual(result.counts, { message: 2, event: 0, activity: 0 });
- assert.equal(result.records[0].text, '今天确认需求。\n\n请查看方案。');
- assert.equal(result.records[0].raw.author, '王明');
- assert.equal(result.records[0].parentId, 'thread-123');
- assert.equal(result.records[0].occurredAt, '2026-09-08T01:00:00.000Z');
- assert.equal(result.records[1].occurredAt, null);
- assert.equal(result.records[1].raw.timeText, '昨天 10:30');
- assert.equal(result.records[1].raw.timestampResolution, 'unresolved');
- assert.equal(result.page.signedIn, true);
- assert.doesNotMatch(JSON.stringify(result), /secret|Sidebar|Reply|Hidden/);
- });
- test('hidden ancestors and CSS-hidden nodes are excluded while offscreen loaded content remains eligible', () => {
- const document = fixture(`<main><div style="display:none"><article data-message-id="1">A</article></div><article style="visibility:hidden" data-message-id="2">B</article><div aria-hidden="true"><article data-message-id="3">C</article></div><article data-message-id="4" style="opacity:0">D</article><article data-message-id="5" style="position:absolute;top:3000px">Loaded item</article></main>`);
- assert.deepEqual(collectVisible(document).records.map(record => record.text), ['Loaded item']);
- });
- test('message body images preserve inline and standalone emoji without reading source URLs or nearby avatars', () => {
- const document = fixture(`<main data-conversation-id="fictional-chat">
- <article data-message-id="mixed"><img alt="Avatar excluded"><div data-tid="message-body">好<img alt="👍" src="https://example.invalid/private">呀<span role="img" aria-label="微笑"></span><button><img alt="reaction excluded"></button><img hidden alt="hidden excluded"></div></article>
- <article data-message-id="only"><div data-tid="message-body"><img alt="😊"><img title="爱心"></div></article>
- <article data-message-id="unlabelled"><div data-tid="message-body"><img src="https://example.invalid/private"></div></article>
- </main>`);
- for (const img of document.querySelectorAll('img')) Object.defineProperty(img, 'src', { get() { throw new Error('Media URLs must never be read'); } });
- const result = collectVisible(document);
- assert.deepEqual(result.records.map(record => record.text), ['好👍呀微笑', '😊爱心', '[图片]']);
- assert.equal(new Set(result.records.map(record => record.externalId)).size, 3);
- assert.doesNotMatch(JSON.stringify(result), /private|Avatar excluded|reaction excluded|hidden excluded/);
- });
- test('calendar fixture captures event title and unresolved time without guessing a date', () => {
- const document = fixture(`<main><div data-tid="calendar-header">日历</div><div role="grid"><div role="gridcell"><button data-event-id="event-42"><span data-tid="event-title">设计评审</span><span data-tid="event-time">星期二 14:00 – 15:00</span></button><button data-event-id="event-43" aria-label="Planning meeting, 16:00"></button></div></div></main>`);
- const result = collectVisible(document);
- assert.equal(result.records.length, 2);
- assert.equal(result.records[0].kind, 'event');
- assert.equal(result.records[0].title, '设计评审');
- assert.equal(result.records[0].occurredAt, null);
- assert.equal(result.records[0].raw.timeText, '星期二 14:00 – 15:00');
- assert.equal(result.records[1].text, 'Planning meeting, 16:00');
- });
- test('no arbitrary page or draft collection, including unsafe custom container selectors', () => {
- const document = fixture('<div id="app"><header>Private login screen</header><main><input value="secret"><div contenteditable="true">unsent draft</div><p>Unrelated text</p></main></div>');
- assert.equal(collectVisible(document).records.length, 0);
- const unsafe = collectVisible(document, { selectors: { message: 'body, main, #app' } });
- assert.equal(unsafe.records.length, 0);
- assert.equal(unsafe.errors.length, 1);
- assert.equal(visibleText(document.querySelector('[contenteditable]')), '');
- });
- test('custom selectors work; invalid CSS is reported without blocking other record kinds', () => {
- const document = fixture('<main><div class="my-message">Custom message</div><div data-event-id="event-1">Calendar item</div></main>');
- const valid = collectVisible(document, { selectors: { message: '.my-message' } });
- assert.equal(valid.records.length, 2);
- const invalid = collectVisible(document, { selectors: { message: '[broken' } });
- assert.equal(invalid.errors.length, 1);
- assert.equal(invalid.records[0].kind, 'event');
- });
- test('stable DOM IDs preserve edits and prevent cross-conversation collisions; fallback IDs are content based', () => {
- const document = fixture(chat);
- const original = collectVisible(document).records[0];
- document.querySelector('[data-tid="message-body"] p').textContent = '已修改需求。';
- const updated = collectVisible(document).records[0];
- assert.equal(original.externalId, updated.externalId);
- assert.notEqual(original.text, updated.text);
- document.querySelector('main').setAttribute('data-conversation-id', 'another-chat');
- assert.notEqual(collectVisible(document).records[0].externalId, updated.externalId);
- const noId = fixture('<div data-tid="chat-header-title">Chat A</div><div data-tid="message-wrapper">Hello</div>');
- const first = collectVisible(noId).records[0];
- assert.equal(first.raw.identityStrategy, 'content-context-hash');
- assert.equal(first.externalId, collectVisible(noId).records[0].externalId);
- noId.querySelector('[data-tid="message-wrapper"]').textContent = 'Changed';
- assert.notEqual(first.externalId, collectVisible(noId).records[0].externalId);
- });
- test('activity is explicitly opt-in and request record limits are bounded', () => {
- const document = fixture('<div data-tid="activity-feed-item">Mention from colleague</div>' + Array.from({ length: 220 }, (_, index) => `<article data-message-id="${index}">Message ${index}</article>`).join(''));
- assert.equal(collectVisible(document).records.length, 200);
- assert.equal(collectVisible(document).records.some(record => record.kind === 'activity'), false);
- assert.equal(collectVisible(fixture('<div data-tid="activity-feed-item">Mention</div>'), { includeActivity: true }).records[0].kind, 'activity');
- });
- test('page provenance strips query/fragment credentials and rejects other origins', () => {
- assert.equal(safePageUrl('https://teams.microsoft.com/v2/?access_token=secret#token=more'), 'https://teams.microsoft.com/v2/');
- assert.equal(safePageUrl('https://evil.example/'), '');
- assert.equal(safePageUrl('http://teams.microsoft.com/v2/'), '');
- });
- test('configuration uses fixed loopback host, explicit account isolation, disabled defaults and no secret in public config', () => {
- assert.equal(DEFAULT_CONFIG.enabled, false);
- const config = validateConfig({ ...DEFAULT_CONFIG, enabled: true, accountId: ' company-work ', token: 'local-token', port: 4318 });
- assert.equal(config.accountId, 'company-work');
- assert.equal(publicConfig(config).token, undefined);
- assert.throws(() => validateConfig({ ...config, accountId: '' }), /账号标签/);
- assert.throws(() => validateConfig({ ...config, port: 'https://evil.example' }), /端口/);
- assert.throws(() => validateConfig({ ...config, port: 65536 }), /端口/);
- const message = { accountId: config.accountId, records: [{ kind: 'message', externalId: 'id', text: 'hello' }], page: { url: 'https://teams.microsoft.com/v2/' } };
- assert.equal(JSON.parse(validateCapture(message, config)).accountId, 'company-work');
- assert.throws(() => validateCapture({ ...message, accountId: 'someone-else' }, config), /账号/);
- assert.throws(() => validateCapture(message, { ...config, enabled: false }), /暂停/);
- assert.throws(() => validateCapture({ ...message, records: Array(201).fill(message.records[0]) }, config), /数量/);
- });
- test('runtime sender gates require own top-frame Teams tab or exact trusted extension page', () => {
- const sender = { id: 'my-extension', frameId: 0, url: 'https://teams.microsoft.com/v2/', tab: { id: 7, url: 'https://teams.microsoft.com/v2/' } };
- assert.equal(isTeamsSender(sender, 'my-extension'), true);
- assert.equal(isTeamsSender({ ...sender, frameId: 1 }, 'my-extension'), false);
- assert.equal(isTeamsSender({ ...sender, id: 'another-extension' }, 'my-extension'), false);
- assert.equal(isTeamsSender({ ...sender, url: 'https://teams.microsoft.com.evil.test/' }, 'my-extension'), false);
- assert.equal(isTrustedPage({ id: 'my-extension', url: 'chrome-extension://my-extension/options.html' }, 'my-extension', 'chrome-extension://my-extension/'), true);
- assert.equal(isTrustedPage(sender, 'my-extension', 'chrome-extension://my-extension/'), false);
- });
- test('failed deliveries retry a bounded number and keep queued data until successful ACK', async () => {
- const queue = new DeliveryQueue(); const record = { externalId: 'id', text: 'hello' }; queue.add(record);
- let calls = 0; const waits = [];
- await assert.rejects(deliverWithRetry(async () => { calls++; throw new Error('offline'); }, { sleep: async ms => waits.push(ms) }), /offline/);
- assert.equal(calls, 3); assert.deepEqual(waits, [300, 1000]); assert.equal(queue.size, 1);
- const batch = queue.batch();
- await deliverWithRetry(async () => ({ ok: true })); queue.acknowledge(batch);
- assert.equal(queue.size, 0); queue.add(record); assert.equal(queue.size, 0);
- let permanentCalls = 0;
- await assert.rejects(deliverWithRetry(async () => { permanentCalls++; throw Object.assign(new Error('invalid token'), { permanent: true }); }), /invalid token/);
- assert.equal(permanentCalls, 1);
- });
- test('queue preserves concurrent edits, enforces capacity and clears on account switches', () => {
- const queue = new DeliveryQueue({ capacity: 2 });
- queue.add({ externalId: 'id', text: 'version 1' }); const oldBatch = queue.batch();
- queue.add({ externalId: 'id', text: 'version 2' }); queue.acknowledge(oldBatch);
- assert.equal(queue.batch()[0][1].record.text, 'version 2');
- queue.add({ externalId: 'second', text: 'other' }); queue.add({ externalId: 'third', text: 'overflow' });
- assert.equal(queue.size, 2); assert.equal(queue.overflow, true);
- queue.reset(); assert.equal(queue.size, 0); assert.equal(queue.delivered.size, 0);
- });
- test('batch byte limit splits large Unicode messages without discarding unsent records', () => {
- const queue = new DeliveryQueue();
- for (let index = 0; index < 40; index++) queue.add({ externalId: `message-${index}`, text: '本地记录'.repeat(4000) });
- const first = queue.batch();
- assert.ok(first.length > 0 && first.length < 40);
- assert.ok(new TextEncoder().encode(JSON.stringify(first.map(([, item]) => item.record))).length < 751000);
- queue.acknowledge(first);
- assert.equal(queue.size, 40 - first.length);
- });
- test('extension manifest restricts hosts and does not request cookie, debugger, or network interception permissions', () => {
- const manifest = JSON.parse(fs.readFileSync(new URL('../extension/manifest.json', import.meta.url), 'utf8'));
- assert.equal(manifest.manifest_version, 3);
- assert.deepEqual(manifest.permissions, ['storage', 'scripting']);
- assert.deepEqual(manifest.host_permissions, ['https://teams.microsoft.com/*', 'https://teams.cloud.microsoft/*', 'http://127.0.0.1/*']);
- assert.equal(manifest.externally_connectable, undefined);
- assert.equal(manifest.content_scripts[0].all_frames, false);
- });
|