network-presence.test.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { createNetworkPresence, classifyPresenceCapture, sanitizePresenceCapture, extractPresenceEntries, isPresenceCaptureRequest } from '../src/network-presence.js';
  4. const self='11111111-1111-1111-1111-111111111111', tenant='22222222-2222-2222-2222-222222222222', app='33333333-3333-3333-3333-333333333333';
  5. const other='44444444-4444-4444-4444-444444444444';
  6. const time=Date.parse('2026-09-08T10:00:00Z');
  7. const value=(availability='Available',activity=availability)=>({id:self,availability,activity});
  8. const bearer=overrides=>'Bearer fake.'+Buffer.from(JSON.stringify({oid:self,tid:tenant,appid:app,aud:'https://graph.microsoft.com',scp:'Presence.Read Presence.ReadWrite',exp:Math.floor(time/1000)+3600,...overrides})).toString('base64url')+'.private-signature';
  9. function capture({claims,writeBody,readPath='/v1.0/me/presence',writePath=`/v1.0/users/${self}/presence/setPresence`}={}) {
  10. const headers=[{name:'Authorization',value:bearer(claims)}];
  11. return {log:{entries:[
  12. {request:{method:'GET',url:'https://graph.microsoft.com'+readPath,headers},response:{status:200,content:{mimeType:'application/json',text:JSON.stringify(value())}}},
  13. {request:{method:'POST',url:'https://graph.microsoft.com'+writePath,headers,postData:{mimeType:'application/json',text:JSON.stringify(writeBody||{sessionId:app,availability:'Available',activity:'Available',expirationDuration:'PT5M'})}},response:{status:200,content:{text:''}}},
  14. ]}};
  15. }
  16. function fixture(options={}) {
  17. const calls=[],timers=[];let milliseconds=time;
  18. const presence=createNetworkPresence({har:capture(),now:()=>milliseconds,
  19. schedule:(fn,delay)=>{const timer={fn,delay};timers.push(timer);return timer;},unschedule:timer=>{timer.cancelled=true;},
  20. fetch:async(url,request)=>{calls.push({url,request});return request.method==='GET'?Response.json(value()):new Response('',{status:200});},...options});
  21. return {presence,calls,timers,advance:delta=>{milliseconds+=delta;}};
  22. }
  23. test('default is disabled and missing or unsupported captures block without sending any request',async()=>{
  24. for(const har of [undefined,{log:{entries:[]}},{log:{entries:[{request:{method:'POST',url:'https://teams.cloud.microsoft/unobserved-presence'},response:{status:200}}]}}]) {
  25. let calls=0;const p=createNetworkPresence({har,fetch:async()=>{calls++;throw new Error('Must not send');}});
  26. assert.equal(p.status().state,'disabled');assert.equal(p.status().running,false);
  27. assert.equal((await p.start()).state,'blocked');assert.equal(calls,0);
  28. }
  29. });
  30. test('an enabled verified template reads self before renewing only the captured Available session',async()=>{
  31. const f=fixture();
  32. try {
  33. assert.equal(f.calls.length,0);
  34. const result=await f.presence.start();
  35. assert.equal(result.state,'running');assert.equal(result.configured,true);assert.equal(result.lastRenewedAt,new Date(time).toISOString());
  36. assert.deepEqual(f.calls.map(call=>call.request.method),['GET','POST']);
  37. assert.deepEqual(JSON.parse(f.calls[1].request.body),{sessionId:app,availability:'Available',activity:'Available',expirationDuration:'PT5M'});
  38. assert.ok(f.calls.every(call=>call.request.redirect==='manual'&&call.request.credentials==='omit'));
  39. assert.equal(f.timers[0].delay,120000);
  40. assert.doesNotMatch(JSON.stringify(result),/private-signature|11111111|22222222|33333333|https:/);
  41. } finally {await f.presence.shutdown();}
  42. });
  43. test('busy, DND, meetings, out-of-office and explicit offline states are never overwritten',async()=>{
  44. for(const [availability,activity,extra] of [['Busy','Busy'],['DoNotDisturb','DoNotDisturb'],['Busy','InAMeeting'],['DoNotDisturb','Presenting'],['Offline','OffWork'],['Available','Available',{outOfOfficeSettings:{isOutOfOffice:true}}]]) {
  45. const calls=[];const f=fixture({fetch:async(_url,request)=>{calls.push(request.method);return Response.json({...value(availability,activity),...extra});}});
  46. try {assert.equal((await f.presence.start()).state,'paused');assert.deepEqual(calls,['GET']);assert.equal(f.presence.status().lastRenewedAt,null);}
  47. finally {await f.presence.shutdown();}
  48. }
  49. });
  50. test('wrong-user writes, preferred-presence overrides, mismatched sessions and ambiguous identities stay blocked',async()=>{
  51. const unsupported=[capture({writePath:`/v1.0/users/${other}/presence/setPresence`}),capture({writePath:`/v1.0/users/${self}/presence/setUserPreferredPresence`}),
  52. capture({writeBody:{sessionId:other,availability:'Available',activity:'Available'}}),capture({claims:{scp:'Presence.Read'}}),
  53. capture({writeBody:{sessionId:app,availability:'Busy',activity:'InACall'}})];
  54. const mixed=capture();mixed.log.entries.push(...capture({claims:{appid:other},writeBody:{sessionId:other,availability:'Available',activity:'Available'}}).log.entries);unsupported.push(mixed);
  55. for(const har of unsupported) {
  56. const f=fixture({har,fetch:async()=>assert.fail('Unverified write must not be requested')});
  57. assert.equal((await f.presence.start()).state,'blocked');
  58. }
  59. const f=fixture({fetch:async()=>Response.json({...value(),id:other})});
  60. assert.equal((await f.presence.start()).state,'blocked');assert.equal(f.presence.status().lastRenewedAt,null);
  61. });
  62. test('401 and 403 stop the worker, and expired credentials never make a request',async()=>{
  63. for(const code of [401,403]) {
  64. const f=fixture({fetch:async()=>new Response('private receiver text',{status:code})});
  65. assert.equal((await f.presence.start()).state,'auth-required');assert.equal(f.presence.status().running,false);assert.equal(f.timers.length,0);
  66. }
  67. const f=fixture({har:capture({claims:{exp:Math.floor(time/1000)-1}}),fetch:async()=>assert.fail('Expired token must not be sent')});
  68. assert.equal((await f.presence.start()).state,'auth-required');
  69. });
  70. test('rate limits stop renewal and manual restart cannot bypass Retry-After',async()=>{
  71. let requests=0;const f=fixture({fetch:async()=>{requests++;return new Response('',{status:429,headers:{'retry-after':'180'}});}});
  72. assert.equal((await f.presence.start()).state,'rate-limited');assert.equal(f.presence.status().running,false);assert.equal(f.timers.length,0);
  73. assert.equal(f.presence.status().retryAfterAt,new Date(time+180000).toISOString());
  74. await f.presence.start();assert.equal(requests,1);f.advance(180000);await f.presence.start();assert.equal(requests,2);
  75. });
  76. test('redirects, malformed responses and oversized responses never cause an Available write',async()=>{
  77. for(const response of [()=>new Response('',{status:302,headers:{location:'https://example.invalid/foreign'}}),()=>Response.json({unexpected:'private-response'}),
  78. ()=>new Response('x'.repeat(64001),{headers:{'content-type':'application/json'}})]) {
  79. let requests=0;const f=fixture({fetch:async()=>{requests++;return response();}});
  80. const result=await f.presence.start();assert.equal(result.running,false);assert.equal(requests,1);assert.equal(result.lastRenewedAt,null);
  81. assert.doesNotMatch(JSON.stringify(result),/private-response|foreign/);
  82. }
  83. });
  84. test('stop during a pending self read prevents the subsequent write; shutdown rejects future starts',async()=>{
  85. let release;const calls=[];const f=fixture({fetch:async(_url,request)=>{calls.push(request.method);return new Promise(resolve=>{release=resolve;});}});
  86. const first=f.presence.start();await Promise.resolve();const stopped=f.presence.stop();release(Response.json(value()));
  87. await Promise.all([first,stopped]);assert.deepEqual(calls,['GET']);assert.equal(f.presence.status().state,'disabled');assert.equal(f.timers.length,0);
  88. await f.presence.shutdown();assert.equal((await f.presence.start()).state,'closed');assert.equal(calls.length,1);
  89. });
  90. test('two instances have independent lifecycle and concurrent starts share a single read/write cycle',async()=>{
  91. const first=fixture(),second=fixture();
  92. try {
  93. await Promise.all([first.presence.start(),first.presence.start()]);assert.equal(first.calls.length,2);assert.equal(second.calls.length,0);
  94. await second.presence.start();await first.presence.stop();assert.equal(first.presence.status().running,false);assert.equal(second.presence.status().running,true);
  95. }finally{await first.presence.shutdown();await second.presence.shutdown();}
  96. });
  97. const endpoint = '55555555-5555-5555-5555-555555555555';
  98. const teamsValue = (availability='Available', activity=availability, extra={}) => [{ mri:`8:orgid:${self}`, presence:{ availability, activity, calendarData:{isOutOfOffice:false}, ...extra } }];
  99. function teamsCapture({claims={}, endpointBody={}, readBody, sample=teamsValue()}={}) {
  100. const headers=[{name:'Authorization',value:bearer({aud:'https://presence.example.invalid',...claims})},{name:'x-ms-object-id',value:''},
  101. {name:'x-ms-endpoint-id',value:endpoint},{name:'Cookie',value:'unnecessary-private-cookie'}, {name:'Referer',value:'https://example.invalid/private-page'}];
  102. return {log:{entries:[
  103. {request:{method:'POST',url:'https://teams.cloud.microsoft/ups/apac/v1/presence/getpresence/',headers:headers.filter(h=>h.name!=='x-ms-endpoint-id'),
  104. postData:{text:JSON.stringify(readBody||[{mri:`8:orgid:${self}`,source:'fixture-source'}])}},response:{status:200,content:{text:JSON.stringify(sample)}}},
  105. {request:{method:'PUT',url:'https://teams.cloud.microsoft/ups/apac/v1/me/endpoints/',headers,
  106. postData:{text:JSON.stringify({id:endpoint,availability:'Available',activity:'Available',activityReporting:'fixture-reporting',deviceType:'Web',...endpointBody})}},response:{status:201,content:{text:''}}},
  107. ]}};
  108. }
  109. test('Teams capture recognizes only observed own read and Available endpoint templates and strips unrelated data',()=>{
  110. const har=teamsCapture({sample:teamsValue('Available','Available',{note:{private:'message text'},capabilities:['unneeded'],forcedAvailability:{availability:'Available',activity:'Available',expiry:new Date(time+50000).toISOString(),publishTime:'unneeded'}})});
  111. const entries=extractPresenceEntries(har);
  112. assert.equal(entries.length,2);
  113. assert.deepEqual(entries.map(classifyPresenceCapture),[{kind:'presence',operation:'read',accountId:`web-api:${tenant}:${self}`},{kind:'presence',operation:'session',accountId:`web-api:${tenant}:${self}`}]);
  114. assert.ok(entries.every(entry=>isPresenceCaptureRequest(entry.request.url,entry.request.method)));
  115. assert.doesNotMatch(JSON.stringify(entries),/private-cookie|private-page|message text|unneeded|publishTime/);
  116. assert.equal(createNetworkPresence({har:{log:{entries}}}).status().adapter,'captured-teams-endpoint');
  117. for(const [method,url] of [['PUT','https://teams.cloud.microsoft/ups/apac/v1/me/forceavailability/'],['PUT','https://teams.cloud.microsoft/ups/other/v1/me/endpoints/'],['PUT','https://example.invalid/ups/apac/v1/me/endpoints/'],['PUT','https://teams.cloud.microsoft/ups/apac/v1/me/endpoints/?target=other']]) {
  118. assert.equal(isPresenceCaptureRequest(url,method),false);
  119. const bad=structuredClone(har.log.entries[1]);bad.request.url=url;bad.request.method=method;assert.equal(sanitizePresenceCapture(bad),null);
  120. }
  121. });
  122. test('Teams worker reads self then repeats the observed Available endpoint independently without preferred overrides',async()=>{
  123. const har=teamsCapture(), calls=[];
  124. const f=fixture({har,fetch:async(url,request)=>{calls.push({url,request});return request.method==='POST'?Response.json(teamsValue('Away')):new Response(null,{status:201});}});
  125. try {
  126. assert.equal(f.presence.status().state,'disabled');assert.equal(calls.length,0);
  127. const result=await f.presence.start();assert.equal(result.state,'running');assert.equal(result.adapter,'captured-teams-endpoint');
  128. assert.deepEqual(calls.map(c=>c.request.method),['POST','PUT']);
  129. assert.deepEqual(JSON.parse(calls[1].request.body),JSON.parse(har.log.entries[1].request.postData.text));
  130. assert.equal(calls[1].request.headers['x-ms-endpoint-id'],endpoint);assert.equal(calls[1].request.headers.Cookie,undefined);
  131. f.advance(120000);f.timers[0].fn();await new Promise(resolve=>setImmediate(resolve));
  132. assert.deepEqual(calls.map(c=>c.request.method),['POST','PUT','POST','PUT']);assert.equal(f.timers.length,2);
  133. assert.ok(calls.every(c=>!c.url.includes('forceavailability')));assert.doesNotMatch(JSON.stringify(f.presence.status()),/private-signature|11111111|55555555/);
  134. } finally {await f.presence.shutdown();}
  135. });
  136. test('Teams protects calendar and user-preferred states, including explicit offline captured in the panel',async()=>{
  137. for(const state of [teamsValue('Busy'),teamsValue('DoNotDisturb'),teamsValue('Busy','InAMeeting'),teamsValue('Offline','OffWork'),
  138. teamsValue('Available','Available',{calendarData:{isOutOfOffice:true}}),
  139. teamsValue('Available','Available',{forcedAvailability:{availability:'Offline',activity:'OffWork',expiry:new Date(time+500000).toISOString()}}),
  140. teamsValue('Available','Available',{forcedAvailability:{availability:'Busy',expiry:'unknown'}}),
  141. teamsValue('Available','Available',{forcedAvailability:{availability:'Available',activity:'InAMeeting',expiry:new Date(time+500000).toISOString()}})]) {
  142. let calls=0;const f=fixture({har:teamsCapture(),fetch:async()=>{calls++;return Response.json(state);}});
  143. try {assert.equal((await f.presence.start()).state,'paused');assert.equal(calls,1);assert.equal(f.presence.status().lastRenewedAt,null);}
  144. finally{await f.presence.shutdown();}
  145. }
  146. });
  147. test('Teams wrong-user, endpoint mismatch, extra body, non-Available, and mixed-token captures block before requests',async()=>{
  148. const invalid=[teamsCapture({readBody:[{mri:`8:orgid:${other}`,source:'fixture'}]}),teamsCapture({sample:[{mri:`8:orgid:${other}`,presence:{availability:'Available',activity:'Available'}}]}),
  149. teamsCapture({endpointBody:{id:other}}),teamsCapture({endpointBody:{availability:'Busy'}}),teamsCapture({endpointBody:{arbitrary:'private'}})];
  150. const mismatch=teamsCapture();mismatch.log.entries[1].request.headers[0]={name:'Authorization',value:bearer({aud:'different-service'})};invalid.push(mismatch);
  151. const foreign=teamsCapture();foreign.log.entries[1].request.headers.find(h=>h.name==='x-ms-object-id').value=other;invalid.push(foreign);
  152. const multiple=teamsCapture(), second=structuredClone(multiple.log.entries[1]);second.request.headers.find(h=>h.name==='x-ms-endpoint-id').value=other;
  153. const body=JSON.parse(second.request.postData.text);body.id=other;second.request.postData.text=JSON.stringify(body);multiple.log.entries.push(second);invalid.push(multiple);
  154. for(const [index,har] of invalid.entries()) {
  155. const f=fixture({har,fetch:async()=>assert.fail('Unverified Teams template must not send')});assert.equal((await f.presence.start()).state,'blocked',`invalid fixture ${index}`);
  156. }
  157. const f=fixture({har:teamsCapture(),fetch:async()=>Response.json([{mri:`8:orgid:${other}`,presence:{availability:'Available',activity:'Available'}}])});
  158. assert.equal((await f.presence.start()).state,'blocked');
  159. });
  160. test('Teams write rejection stops renewal without claiming success or leaking response content',async()=>{
  161. for(const code of [401,403,429,500]) {
  162. let requests=0;const f=fixture({har:teamsCapture(),fetch:async()=>++requests===1?Response.json(teamsValue()):new Response('private backend message',{status:code,headers:{'retry-after':'300'}})});
  163. const result=await f.presence.start();assert.equal(requests,2);assert.equal(result.running,false);assert.equal(result.lastRenewedAt,null);
  164. assert.equal(result.state,code===429?'rate-limited':code===500?'error':'auth-required');assert.doesNotMatch(JSON.stringify(result),/private backend/);assert.equal(f.timers.length,0);
  165. if(code===429){await f.presence.start();assert.equal(requests,2);assert.equal(f.presence.status().retryAfterAt,new Date(time+300000).toISOString());}
  166. }
  167. });
  168. test('Teams token expiring during the read cannot authorize a later endpoint write',async()=>{
  169. let requests=0;const f=fixture({har:teamsCapture({claims:{exp:Math.floor(time/1000)+10}}),fetch:async()=>{requests++;f.advance(6000);return Response.json(teamsValue());}});
  170. assert.equal((await f.presence.start()).state,'auth-required');assert.equal(requests,1);
  171. });
  172. test('stopping Teams during a pending read never proceeds to the endpoint request',async()=>{
  173. let release;let calls=0;const f=fixture({har:teamsCapture(),fetch:async()=>{calls++;return new Promise(resolve=>{release=resolve;});}});
  174. const started=f.presence.start();await Promise.resolve();const stopped=f.presence.stop();release(Response.json(teamsValue()));
  175. await Promise.all([started,stopped]);assert.equal(calls,1);assert.equal(f.presence.status().state,'disabled');assert.equal(f.timers.length,0);
  176. });
  177. test('Teams natural Offline can create a session, while an active manual Offline preference is protected',async()=>{
  178. for(const forcedAvailability of [undefined,{}, {availability:'Offline',activity:'OffWork',expiry:new Date(time-1).toISOString()}]) {
  179. const calls=[];const f=fixture({har:teamsCapture(),fetch:async(_url,request)=>{calls.push(request.method);return request.method==='POST'
  180. ?Response.json(teamsValue('Offline','Offline',forcedAvailability===undefined?{}:{forcedAvailability})):new Response(null,{status:200});}});
  181. try{assert.equal((await f.presence.start()).state,'running');assert.deepEqual(calls,['POST','PUT']);}
  182. finally{await f.presence.shutdown();}
  183. }
  184. for(const forcedAvailability of [{availability:'Offline',activity:'OffWork',expiry:new Date(time+60000).toISOString()},
  185. {availability:'DoNotDisturb',activity:'DoNotDisturb',expiry:new Date(time+60000).toISOString()}, {availability:'Offline',activity:'OffWork'}]) {
  186. let calls=0;const f=fixture({har:teamsCapture(),fetch:async()=>{calls++;return Response.json(teamsValue('Offline','Offline',{forcedAvailability}));}});
  187. try{const result=await f.presence.start();assert.equal(result.state,'paused');assert.equal(calls,1);assert.match(result.message,/请先在 Teams 设为可用/);}
  188. finally{await f.presence.shutdown();}
  189. }
  190. });
  191. test('Teams checks current preferences each cycle and never treats the HAR sample as a lasting preference',async()=>{
  192. const forcedAvailability={availability:'Offline',activity:'OffWork',expiry:new Date(time+600000).toISOString()};
  193. const har=teamsCapture({sample:teamsValue('Offline','OffWork',{forcedAvailability})});
  194. let calls=0,manual=false;const f=fixture({har,fetch:async(_url,request)=>{calls++;return request.method==='POST'
  195. ?Response.json(manual?teamsValue('Offline','OffWork',{forcedAvailability}):teamsValue('Offline','Offline')):new Response(null,{status:200});}});
  196. try {
  197. assert.equal((await f.presence.start()).state,'running');assert.equal(calls,2);
  198. manual=true;f.advance(120000);f.timers[0].fn();await new Promise(resolve=>setImmediate(resolve));
  199. assert.equal(f.presence.status().state,'paused');assert.equal(calls,3);assert.match(f.presence.status().message,/请先在 Teams 设为可用/);
  200. }finally{await f.presence.shutdown();}
  201. });