server.test.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { test } from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { once } from 'node:events';
  4. import http from 'node:http';
  5. import { createStore } from '../src/store.js';
  6. import { createServer } from '../src/server.js';
  7. async function fixture(fn, network, extras = {}) {
  8. const store = createStore(':memory:');
  9. const config = { port: 0, localToken: 'local-test', pairingToken: 'extension-test', mcpToken:'mcp-test', dataDir: 'temp-test', rotatePairing() { return this.pairingToken = 'new-token'; } };
  10. const graph = { status: () => ({ configured: false }), beginLogin: async () => ({ url: 'https://login.microsoftonline.com/' }), sync: async () => ({ ok: true }), completeLogin: async () => { throw Error(); } };
  11. const server = createServer({ store, config, graph, network, ...extras }); server.listen(0, '127.0.0.1'); await once(server, 'listening'); config.port = server.address().port;
  12. const base = `http://127.0.0.1:${config.port}`;
  13. try { await fn({ store, config, base }); } finally { await new Promise(resolve => server.close(resolve)); store.close(); }
  14. }
  15. const payload = { accountId: 'work@example.com', records: [{ kind: 'message', externalId: 'm1', title: 'test', text: '<img src=x onerror=alert(1)>', raw: { provenance: 'dom' } }], page: { url: 'https://teams.microsoft.com/v2/', signedIn: true, view: 'chat', coverage: '已加载内容' } };
  16. const post = (base, path, token, body, extra = {}) => fetch(base + path, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, ...extra }, body: JSON.stringify(body) });
  17. test('local image download requires the operation token and serves local bytes with safe headers', async () => {
  18. const id = '11111111-1111-4111-8111-111111111111', calls = [], image = Buffer.from('local-test-image');
  19. await fixture(async ({ base }) => {
  20. assert.equal((await post(base, `/api/images/${id}/download`, '', {})).status, 403);
  21. assert.equal((await post(base, `/api/images/${id}/download`, '', {}, { 'X-Local-Token': 'local-test' })).status, 200);
  22. assert.deepEqual(calls, [{ id }]);
  23. const result = await fetch(base + `/api/images/${id}/content?download=1`);
  24. assert.equal(result.status, 200); assert.deepEqual(Buffer.from(await result.arrayBuffer()), image);
  25. assert.equal(result.headers.get('content-type'), 'image/png');
  26. assert.equal(result.headers.get('x-content-type-options'), 'nosniff');
  27. assert.match(result.headers.get('content-disposition'), /^attachment/);
  28. assert.equal((await fetch(base + `/api/images/${id}/content`, { headers: { Origin: 'https://evil.invalid' } })).status, 403);
  29. }, undefined, { media: {
  30. downloadImage: args => { calls.push(args); return { id, status: 'saved' }; },
  31. readImage: async () => ({ bytes: image, mimeType: 'image/png', fileName: `${id}.png` })
  32. } });
  33. });
  34. test('historical image controls require local authorization, valid instance and boolean settings', async () => {
  35. const calls = [], network = { status: () => ({}), listInstances: () => [] };
  36. await fixture(async ({ base, store }) => {
  37. store.createInstance({ id: 'default', name: 'Images' });
  38. const headers = { 'X-Local-Token': 'local-test' }, route = '/api/instances/default/images/backfill';
  39. assert.equal((await post(base, route, '', { enabled: true })).status, 403);
  40. assert.equal((await post(base, route, '', { enabled: 'true' }, headers)).status, 400);
  41. assert.equal((await post(base, route, '', { enabled: true, retryFailed: 'true' }, headers)).status, 400);
  42. assert.equal((await post(base, '/api/instances/11111111-1111-4111-8111-111111111111/images/backfill', '', { enabled: true }, headers)).status, 404);
  43. assert.equal(calls.length, 0);
  44. assert.equal((await post(base, route, '', { enabled: true, retryFailed: true }, headers)).status, 200);
  45. assert.deepEqual(calls[0], { instanceId: 'default', enabled: true, retryFailed: true });
  46. assert.equal((await post(base, route, '', { enabled: false }, headers)).status, 200);
  47. assert.deepEqual(calls[1], { instanceId: 'default', enabled: false, retryFailed: false });
  48. }, network, { media: { configureHistoryDownloads: args => { calls.push(args); return { enabled: args.enabled }; } } });
  49. });
  50. test('demo and browser accounts can be previewed and purged without an instance, preserving other scopes', async () => {
  51. const order = [], headers = { 'X-Local-Token': 'local-test' };
  52. await fixture(async ({ base, store }) => {
  53. await post(base, '/api/demo', '', {}, headers);
  54. const initialDemo = await post(base, '/api/local-records/preview', '', { source: 'demo', accountId: 'demo' }, headers);
  55. assert.equal(initialDemo.status, 200); assert.equal((await initialDemo.json()).counts.records, 2);
  56. await post(base, '/api/extension/events', 'extension-test', payload);
  57. const edited = { ...payload, records: [{ ...payload.records[0], text: 'Fictional edit' }] };
  58. await post(base, '/api/extension/events', 'extension-test', edited);
  59. const scope = { source: 'browser', accountId: `browser:${payload.accountId}` };
  60. store.upsertRecord({ ...scope, source: 'demo', kind: 'message', externalId: 'same-account-other-source', text: 'Preserve other source' });
  61. store.upsertRecord({ ...scope, accountId: 'browser:other', kind: 'event', externalId: 'other-browser', text: 'Preserve other account' });
  62. store.createInstance({ id: 'default', name: 'Existing API instance' });
  63. store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: scope.accountId }]);
  64. store.upsertRecord({ ...scope, source: 'web-api', kind: 'message', externalId: 'api-message', text: 'Preserve API account' });
  65. store.setState('web-api:service', { enabled: true });
  66. const before = store.listRecords().items.filter(row => !(row.source === scope.source && row.accountId === scope.accountId));
  67. const accounts = await (await fetch(base + '/api/local-records/accounts')).json();
  68. assert.deepEqual(accounts.items, [
  69. { source: 'browser', accountId: scope.accountId, records: 1 },
  70. { source: 'browser', accountId: 'browser:other', records: 1 },
  71. { source: 'demo', accountId: scope.accountId, records: 1 },
  72. { source: 'demo', accountId: 'demo', records: 2 },
  73. ].sort((a, b) => a.source.localeCompare(b.source) || a.accountId.localeCompare(b.accountId)));
  74. const preview = await post(base, '/api/local-records/preview', '', scope, headers);
  75. assert.equal(preview.status, 200);
  76. assert.deepEqual((await preview.json()).counts, { records: 1, versions: 2, changes: 2, liveObservations: 0, webhookDeliveries: 0, images: 0 });
  77. assert.equal(store.listRecords(scope).total, 1);
  78. const result = await post(base, '/api/local-records/delete', '', { ...scope, confirmation: scope.accountId }, headers);
  79. assert.equal(result.status, 200); assert.equal((await result.json()).deleted, true);
  80. assert.deepEqual(store.listRecords().items, before);
  81. assert.equal(store.getState('web-api:service').enabled, true);
  82. assert.equal(store.previewAccountDeletion(scope).counts.versions, 0);
  83. assert.deepEqual(order, ['pause', 'resume']);
  84. const updated = await (await fetch(base + '/api/local-records/accounts')).json();
  85. assert.equal(updated.items.some(a => a.source === scope.source && a.accountId === scope.accountId), false);
  86. const demo = await post(base, '/api/local-records/delete', '', { source: 'demo', accountId: 'demo', confirmation: 'demo' }, headers);
  87. assert.equal(demo.status, 200); assert.equal((await demo.json()).counts.records, 2);
  88. assert.equal(store.listRecords({ source: 'demo', accountId: scope.accountId }).total, 1);
  89. }, undefined, { webhooks: { status: () => ({ running: true }), stop: async () => { order.push('pause'); }, start: () => { order.push('resume'); } } });
  90. });
  91. test('local record deletion rejects unauthorized, malformed, unsupported and instance-bound scopes', async () => fixture(async ({ base, store }) => {
  92. const headers = { 'X-Local-Token': 'local-test' }, scope = { source: 'demo', accountId: 'demo' };
  93. store.upsertRecord({ ...scope, kind: 'message', externalId: 'keep', text: 'Fictional' });
  94. for (const path of ['/api/local-records/preview', '/api/local-records/delete']) {
  95. assert.equal((await post(base, path, '', scope)).status, 403);
  96. assert.equal((await post(base, path, '', scope, { ...headers, Origin: 'https://untrusted.example' })).status, 403);
  97. for (const invalid of [{}, { source: 'web-api', accountId: 'demo' }, { source: 'graph', accountId: 'demo' }, { source: 'demo', accountId: '' }, { source: 'demo', accountId: 'demo\u0000' }])
  98. assert.equal((await post(base, path, '', { ...invalid, confirmation: invalid.accountId }, headers)).status, 400);
  99. }
  100. assert.equal((await post(base, '/api/local-records/delete', '', scope, headers)).status, 400);
  101. assert.equal((await post(base, '/api/local-records/delete', '', { ...scope, confirmation: 'other' }, headers)).status, 400);
  102. store.createInstance({ id: 'default', name: 'Bound' }); store.bindInstanceAccounts('default', [scope]);
  103. assert.deepEqual((await (await fetch(base + '/api/local-records/accounts')).json()).items, []);
  104. assert.equal((await post(base, '/api/local-records/preview', '', scope, headers)).status, 400);
  105. assert.equal((await post(base, '/api/local-records/delete', '', { ...scope, confirmation: 'demo' }, headers)).status, 400);
  106. assert.equal(store.listRecords(scope).total, 1);
  107. }));
  108. test('local deletion rechecks ownership after awaiting the notification dispatcher', async () => {
  109. const scope = { source: 'browser', accountId: 'browser:late-bound' }; let bind, resumed = 0;
  110. await fixture(async ({ base, store }) => {
  111. store.createInstance({ id: 'default', name: 'Late binding' });
  112. store.upsertRecord({ ...scope, kind: 'message', externalId: 'keep', text: 'Fictional' });
  113. bind = () => store.bindInstanceAccounts('default', [scope]);
  114. const response = await post(base, '/api/local-records/delete', '', { ...scope, confirmation: scope.accountId }, { 'X-Local-Token': 'local-test' });
  115. assert.equal(response.status, 400); assert.equal(resumed, 1);
  116. assert.equal(store.listRecords(scope).total, 1);
  117. }, undefined, { webhooks: { status: () => ({ running: true }), stop: async () => { bind(); }, start: () => { resumed++; } } });
  118. });
  119. test('instance mutation routes validate local authorization and account membership before dispatch', async () => {
  120. const calls = [], deliveryOrder = [], network = { status: () => ({}), listInstances: () => [],
  121. start: async id => { calls.push(['start', id]); return { running: true }; },
  122. update: async (id, settings) => { calls.push(['settings', id, settings]); return {}; },
  123. deleteRecords: async (id, scope) => { calls.push(['delete', id, scope]); deliveryOrder.push('delete'); return { deleted: true }; },
  124. importPresence: async () => { throw new Error('secret-auth-capture-path'); } };
  125. await fixture(async ({ base, store }) => {
  126. store.createInstance({ id: 'default', name: 'Fictional instance' });
  127. store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: 'account-a' }]);
  128. const headers = { 'X-Local-Token': 'local-test' };
  129. assert.equal((await post(base, '/api/instances/default/start', '', {})).status, 403);
  130. assert.equal((await post(base, '/api/instances/default/start', '', {}, headers)).status, 200);
  131. assert.deepEqual(calls[0], ['start', 'default']);
  132. assert.equal((await post(base, '/api/instances/default/settings', '', { keepOnline: 'true' }, headers)).status, 400);
  133. assert.equal((await post(base, '/api/instances/default/settings', '', { keepOnline: true }, headers)).status, 200);
  134. const scope = { source: 'web-api', accountId: 'account-a' };
  135. assert.equal((await post(base, '/api/instances/default/records/preview', '', scope, headers)).status, 200);
  136. assert.equal((await post(base, '/api/instances/default/records/delete', '', scope, headers)).status, 400);
  137. assert.equal((await post(base, '/api/instances/default/records/delete', '', { ...scope, accountId: 'account-b', confirmation: 'account-b' }, headers)).status, 400);
  138. assert.equal(calls.length, 2);
  139. assert.equal((await post(base, '/api/instances/default/records/delete', '', { ...scope, confirmation: 'account-a' }, headers)).status, 200);
  140. assert.equal(calls[2][0], 'delete'); assert.equal(calls[2][1], 'default');
  141. assert.deepEqual(deliveryOrder, ['stop', 'delete', 'start']);
  142. const rejected = await post(base, '/api/instances/default/presence/import', '', { fileName: '../wrong.har' }, headers);
  143. assert.equal(rejected.status, 400); assert.doesNotMatch(await rejected.text(), /secret-auth/);
  144. }, network, { webhooks: { status: () => ({ running: true }), stop: async () => { deliveryOrder.push('stop'); }, start: () => { deliveryOrder.push('start'); } } });
  145. });
  146. test('REST and export combine instance and exclusive time range; invalid or unknown filters fail closed', async () => fixture(async ({ base, store }) => {
  147. store.createInstance({ id: 'default', name: 'Fictional instance' }); store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: 'account-a' }]);
  148. for (const [id, accountId, occurredAt] of [['first','account-a','2026-09-08T00:00:00Z'],['end','account-a','2026-09-08T01:00:00Z'],['other','account-b','2026-09-08T00:00:00Z']])
  149. store.upsertRecord({ source:'web-api',accountId,kind:'message',externalId:id,text:id,occurredAt });
  150. const filters = new URLSearchParams({ instanceId:'default',from:'2026-09-08T08:00:00+08:00',to:'2026-09-08T09:00:00+08:00' });
  151. const response = await (await fetch(base+'/api/records?'+filters)).json(); assert.equal(response.total,1); assert.equal(response.items[0].externalId,'first');
  152. const exported = await (await fetch(base+'/api/export?'+filters)).text(); assert.equal(exported.trim().split('\n').length,1);
  153. for (const filter of ['instanceId=unknown','instanceId=11111111-1111-1111-1111-111111111111','from=2026-09-08T00:00:00','from=2026-02-30T00:00:00Z','from=2026-09-09T00:00:00Z&to=2026-09-08T00:00:00Z'])
  154. assert.equal((await fetch(base+'/api/records?'+filter)).status,400);
  155. }));
  156. test('MCP HTTP requires its own Bearer token and same-origin loopback access before parsing protocol messages',async()=>{
  157. const calls=[];
  158. const mcpHandler=async(req,res,body)=>{calls.push(body);res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify({jsonrpc:'2.0',id:body.id,result:{ok:true}}));};
  159. await fixture(async({base})=>{
  160. const message={jsonrpc:'2.0',id:1,method:'tools/list'};
  161. assert.equal((await post(base,'/mcp','wrong',message)).status,401);
  162. assert.equal((await post(base,'/mcp','mcp-test',message,{Origin:'https://untrusted.example'})).status,403);
  163. assert.equal((await post(base,'/mcp','mcp-test',message)).status,200);assert.equal(calls.length,1);
  164. assert.equal((await post(base,'/mcp','mcp-test',{data:'x'.repeat(1024*1024)})).status,413);
  165. const status=await(await fetch(base+'/api/status')).json();assert.equal(status.mcp.available,true);assert.equal(status.mcpToken,undefined);
  166. },undefined,{mcpHandler});
  167. });
  168. test('API worker controls require local authorization and never expose internal login exceptions', async () => {
  169. const calls = [];
  170. const network = { status: () => ({ running: true, login: { state: 'waiting' } }),
  171. beginLogin: async () => { calls.push('login'); return { state: 'opening' }; },
  172. finishLogin: async () => { throw new Error('Bearer secret-browser-request'); },
  173. stop: async () => { calls.push('stop'); return { running: false }; } };
  174. await fixture(async ({ base }) => {
  175. assert.equal((await post(base, '/api/network/login', '', {})).status, 403);
  176. assert.equal((await post(base, '/api/network/login', '', {}, { 'X-Local-Token': 'local-test', Origin: 'https://evil.example' })).status, 403);
  177. const response = await post(base, '/api/network/login', '', {}, { 'X-Local-Token': 'local-test' });
  178. assert.equal(response.status, 200); assert.deepEqual(calls, ['login']);
  179. const status = await (await fetch(base + '/api/status')).json(); assert.equal(status.network.running, true);
  180. const denied = await post(base, '/api/network/login/finish', '', {}, { 'X-Local-Token': 'local-test' });
  181. assert.equal(denied.status, 400); assert.doesNotMatch(await denied.text(), /secret-browser-request|Bearer/);
  182. }, network);
  183. });
  184. test('扩展配对、批量入库、幂等上传、历史和导出完整闭环', async () => fixture(async ({ base, store }) => {
  185. const ping = await post(base, '/api/extension/ping', 'extension-test', {}); assert.equal(ping.status, 200);
  186. const first = await post(base, '/api/extension/events', 'extension-test', payload); assert.equal(first.status, 200); assert.equal((await first.json()).changed, 1);
  187. const again = await post(base, '/api/extension/events', 'extension-test', payload); assert.equal((await again.json()).changed, 0);
  188. const result = await (await fetch(base + '/api/records?kind=message')).json(); assert.equal(result.total, 1);
  189. assert.equal(result.items[0].accountId, 'browser:work@example.com'); assert.equal(result.items[0].source, 'browser');
  190. assert.equal(result.items[0].text, payload.records[0].text);
  191. const edited = structuredClone(payload); edited.records[0].text = 'updated';
  192. await post(base, '/api/extension/events', 'extension-test', edited);
  193. const detail = await (await fetch(base + '/api/records/' + result.items[0].id)).json(); assert.equal(detail.versions.length, 2);
  194. const exported = await fetch(base + '/api/export?kind=message'); assert.match(exported.headers.get('content-disposition'), /attachment/); assert.equal(JSON.parse((await exported.text()).trim()).text, 'updated');
  195. assert.equal(store.getState('browser:lastHeartbeat').signedIn, true);
  196. }));
  197. test('跨站、错误令牌、DNS rebinding 与越权写入被拒绝', async () => fixture(async ({ base, config }) => {
  198. assert.equal((await post(base, '/api/extension/events', 'wrong', payload)).status, 401);
  199. assert.equal((await post(base, '/api/extension/events', 'extension-test', payload, { Origin: 'https://evil.example' })).status, 403);
  200. assert.equal((await fetch(base + '/api/status', { headers: { Origin: 'https://evil.example' } })).status, 403);
  201. assert.equal((await fetch(base + '/api/status', { headers: { 'Sec-Fetch-Site': 'cross-site' } })).status, 403);
  202. // Native fetch normalizes Host, so use raw HTTP to exercise DNS rebinding protection.
  203. const hostStatus = await new Promise((resolve, reject) => http.get(base + '/api/status', { headers: { Host: `evil.example:${config.port}` } }, res => { res.resume(); resolve(res.statusCode); }).on('error', reject));
  204. assert.equal(hostStatus, 403);
  205. assert.equal((await post(base, '/api/demo', 'extension-test', {})).status, 403);
  206. assert.equal((await post(base, '/api/demo', '', {}, { 'X-Local-Token': 'local-test' })).status, 200);
  207. const status = await (await fetch(base + '/api/status')).json(); assert.equal(status.localToken, 'local-test');
  208. }));
  209. test('无效批次不会部分写入;大请求拒绝,浏览器不能伪造 source', async () => fixture(async ({ base, store }) => {
  210. const invalid = structuredClone(payload); invalid.records.push({ kind: 'invalid' });
  211. assert.equal((await post(base, '/api/extension/events', 'extension-test', invalid)).status, 400); assert.equal(store.stats().total, 0);
  212. const excessive = structuredClone(payload); excessive.records = Array.from({ length: 201 }, () => payload.records[0]);
  213. assert.equal((await post(base, '/api/extension/events', 'extension-test', excessive)).status, 400);
  214. const huge = await post(base, '/api/extension/events', 'extension-test', { data: 'x'.repeat(1024 * 1024) }); assert.equal(huge.status, 413);
  215. const forged = structuredClone(payload); forged.records[0].source = 'graph'; forged.records[0].accountId = 'victim';
  216. assert.equal((await post(base, '/api/extension/events', 'extension-test', forged)).status, 200);
  217. assert.equal(store.listRecords().items[0].source, 'browser');
  218. }));
  219. test('扩展预检允许准确的扩展来源;旋转后旧配对密钥失效', async () => fixture(async ({ base }) => {
  220. const origin = 'chrome-extension://' + 'a'.repeat(32);
  221. const options = await fetch(base + '/api/extension/events', { method: 'OPTIONS', headers: { Origin: origin } });
  222. assert.equal(options.status, 204); assert.equal(options.headers.get('Access-Control-Allow-Origin'), origin);
  223. await post(base, '/api/extension/ping', 'extension-test', { accountId: 'work' });
  224. await post(base, '/api/extension/events', 'extension-test', payload);
  225. assert.equal((await post(base, '/api/pairing/rotate', '', {}, { 'X-Local-Token': 'local-test' })).status, 200);
  226. const reset = await (await fetch(base + '/api/status')).json();
  227. assert.equal(reset.pairing, null); assert.equal(reset.browser, null); assert.equal(reset.extension, null);
  228. assert.equal(reset.stats.total, 1);
  229. assert.equal((await post(base, '/api/extension/ping', 'extension-test', {})).status, 401);
  230. assert.equal((await post(base, '/api/extension/ping', 'new-token', {})).status, 200);
  231. }));
  232. test('静态页面强制 CSP,路径遍历无法获取数据文件,OAuth 失败跳回本地页面', async () => fixture(async ({ base }) => {
  233. const page = await fetch(base + '/'); assert.equal(page.status, 200); assert.match(page.headers.get('Content-Security-Policy'), /frame-ancestors 'none'/);
  234. assert.equal((await fetch(base + '/data/pairing.json')).status, 404);
  235. for (const query of ['limit=1.5', 'offset=Infinity', 'offset=0.5']) assert.equal((await fetch(base + '/api/records?' + query)).status, 400);
  236. const login = await fetch(base + '/auth/callback?code=untrusted', { redirect: 'manual' }); assert.equal(login.status, 303); assert.equal(login.headers.get('Location'), '/?login=failed');
  237. }));
  238. test('配对状态与页面心跳分开,诊断指出已开启但未注入,零条采集仍更新心跳', async () => fixture(async ({ base }) => {
  239. await post(base, '/api/extension/ping', 'extension-test', { accountId: 'work' });
  240. let status = await (await fetch(base + '/api/status')).json();
  241. assert.ok(status.pairing.at); assert.equal(status.browser, null);
  242. const diagnostic = { accountId: 'work', version: '0.1.1', enabled: true, teamsTabCount: 1, readyTabCount: 0, error: '页面脚本未连接' };
  243. const sent = await post(base, '/api/extension/status', 'extension-test', diagnostic); assert.equal(sent.status, 200);
  244. status = await (await fetch(base + '/api/status')).json();
  245. assert.equal(status.extension.error, '页面脚本未连接'); assert.equal(status.extension.enabled, true); assert.equal(status.browser, null);
  246. assert.equal((await post(base, '/api/extension/status', 'wrong', diagnostic)).status, 401);
  247. assert.equal((await post(base, '/api/extension/status', 'extension-test', { ...diagnostic, readyTabCount: 2 })).status, 400);
  248. assert.equal((await post(base, '/api/extension/status', 'extension-test', { ...diagnostic, teamsTabCount: '1' })).status, 400);
  249. const zero = { ...payload, records: [] };
  250. assert.equal((await post(base, '/api/extension/events', 'extension-test', zero)).status, 200);
  251. status = await (await fetch(base + '/api/status')).json(); assert.ok(status.browser.at); assert.equal(status.browser.received, 0);
  252. }));