| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221 |
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import { createNetworkPresence, classifyPresenceCapture, sanitizePresenceCapture, extractPresenceEntries, isPresenceCaptureRequest } from '../src/network-presence.js';
- const self='11111111-1111-1111-1111-111111111111', tenant='22222222-2222-2222-2222-222222222222', app='33333333-3333-3333-3333-333333333333';
- const other='44444444-4444-4444-4444-444444444444';
- const time=Date.parse('2026-09-08T10:00:00Z');
- const value=(availability='Available',activity=availability)=>({id:self,availability,activity});
- 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';
- function capture({claims,writeBody,readPath='/v1.0/me/presence',writePath=`/v1.0/users/${self}/presence/setPresence`}={}) {
- const headers=[{name:'Authorization',value:bearer(claims)}];
- return {log:{entries:[
- {request:{method:'GET',url:'https://graph.microsoft.com'+readPath,headers},response:{status:200,content:{mimeType:'application/json',text:JSON.stringify(value())}}},
- {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:''}}},
- ]}};
- }
- function fixture(options={}) {
- const calls=[],timers=[];let milliseconds=time;
- const presence=createNetworkPresence({har:capture(),now:()=>milliseconds,
- schedule:(fn,delay)=>{const timer={fn,delay};timers.push(timer);return timer;},unschedule:timer=>{timer.cancelled=true;},
- fetch:async(url,request)=>{calls.push({url,request});return request.method==='GET'?Response.json(value()):new Response('',{status:200});},...options});
- return {presence,calls,timers,advance:delta=>{milliseconds+=delta;}};
- }
- test('default is disabled and missing or unsupported captures block without sending any request',async()=>{
- for(const har of [undefined,{log:{entries:[]}},{log:{entries:[{request:{method:'POST',url:'https://teams.cloud.microsoft/unobserved-presence'},response:{status:200}}]}}]) {
- let calls=0;const p=createNetworkPresence({har,fetch:async()=>{calls++;throw new Error('Must not send');}});
- assert.equal(p.status().state,'disabled');assert.equal(p.status().running,false);
- assert.equal((await p.start()).state,'blocked');assert.equal(calls,0);
- }
- });
- test('an enabled verified template reads self before renewing only the captured Available session',async()=>{
- const f=fixture();
- try {
- assert.equal(f.calls.length,0);
- const result=await f.presence.start();
- assert.equal(result.state,'running');assert.equal(result.configured,true);assert.equal(result.lastRenewedAt,new Date(time).toISOString());
- assert.deepEqual(f.calls.map(call=>call.request.method),['GET','POST']);
- assert.deepEqual(JSON.parse(f.calls[1].request.body),{sessionId:app,availability:'Available',activity:'Available',expirationDuration:'PT5M'});
- assert.ok(f.calls.every(call=>call.request.redirect==='manual'&&call.request.credentials==='omit'));
- assert.equal(f.timers[0].delay,120000);
- assert.doesNotMatch(JSON.stringify(result),/private-signature|11111111|22222222|33333333|https:/);
- } finally {await f.presence.shutdown();}
- });
- test('busy, DND, meetings, out-of-office and explicit offline states are never overwritten',async()=>{
- for(const [availability,activity,extra] of [['Busy','Busy'],['DoNotDisturb','DoNotDisturb'],['Busy','InAMeeting'],['DoNotDisturb','Presenting'],['Offline','OffWork'],['Available','Available',{outOfOfficeSettings:{isOutOfOffice:true}}]]) {
- const calls=[];const f=fixture({fetch:async(_url,request)=>{calls.push(request.method);return Response.json({...value(availability,activity),...extra});}});
- try {assert.equal((await f.presence.start()).state,'paused');assert.deepEqual(calls,['GET']);assert.equal(f.presence.status().lastRenewedAt,null);}
- finally {await f.presence.shutdown();}
- }
- });
- test('wrong-user writes, preferred-presence overrides, mismatched sessions and ambiguous identities stay blocked',async()=>{
- const unsupported=[capture({writePath:`/v1.0/users/${other}/presence/setPresence`}),capture({writePath:`/v1.0/users/${self}/presence/setUserPreferredPresence`}),
- capture({writeBody:{sessionId:other,availability:'Available',activity:'Available'}}),capture({claims:{scp:'Presence.Read'}}),
- capture({writeBody:{sessionId:app,availability:'Busy',activity:'InACall'}})];
- const mixed=capture();mixed.log.entries.push(...capture({claims:{appid:other},writeBody:{sessionId:other,availability:'Available',activity:'Available'}}).log.entries);unsupported.push(mixed);
- for(const har of unsupported) {
- const f=fixture({har,fetch:async()=>assert.fail('Unverified write must not be requested')});
- assert.equal((await f.presence.start()).state,'blocked');
- }
- const f=fixture({fetch:async()=>Response.json({...value(),id:other})});
- assert.equal((await f.presence.start()).state,'blocked');assert.equal(f.presence.status().lastRenewedAt,null);
- });
- test('401 and 403 stop the worker, and expired credentials never make a request',async()=>{
- for(const code of [401,403]) {
- const f=fixture({fetch:async()=>new Response('private receiver text',{status:code})});
- assert.equal((await f.presence.start()).state,'auth-required');assert.equal(f.presence.status().running,false);assert.equal(f.timers.length,0);
- }
- const f=fixture({har:capture({claims:{exp:Math.floor(time/1000)-1}}),fetch:async()=>assert.fail('Expired token must not be sent')});
- assert.equal((await f.presence.start()).state,'auth-required');
- });
- test('rate limits stop renewal and manual restart cannot bypass Retry-After',async()=>{
- let requests=0;const f=fixture({fetch:async()=>{requests++;return new Response('',{status:429,headers:{'retry-after':'180'}});}});
- assert.equal((await f.presence.start()).state,'rate-limited');assert.equal(f.presence.status().running,false);assert.equal(f.timers.length,0);
- assert.equal(f.presence.status().retryAfterAt,new Date(time+180000).toISOString());
- await f.presence.start();assert.equal(requests,1);f.advance(180000);await f.presence.start();assert.equal(requests,2);
- });
- test('redirects, malformed responses and oversized responses never cause an Available write',async()=>{
- for(const response of [()=>new Response('',{status:302,headers:{location:'https://example.invalid/foreign'}}),()=>Response.json({unexpected:'private-response'}),
- ()=>new Response('x'.repeat(64001),{headers:{'content-type':'application/json'}})]) {
- let requests=0;const f=fixture({fetch:async()=>{requests++;return response();}});
- const result=await f.presence.start();assert.equal(result.running,false);assert.equal(requests,1);assert.equal(result.lastRenewedAt,null);
- assert.doesNotMatch(JSON.stringify(result),/private-response|foreign/);
- }
- });
- test('stop during a pending self read prevents the subsequent write; shutdown rejects future starts',async()=>{
- let release;const calls=[];const f=fixture({fetch:async(_url,request)=>{calls.push(request.method);return new Promise(resolve=>{release=resolve;});}});
- const first=f.presence.start();await Promise.resolve();const stopped=f.presence.stop();release(Response.json(value()));
- await Promise.all([first,stopped]);assert.deepEqual(calls,['GET']);assert.equal(f.presence.status().state,'disabled');assert.equal(f.timers.length,0);
- await f.presence.shutdown();assert.equal((await f.presence.start()).state,'closed');assert.equal(calls.length,1);
- });
- test('two instances have independent lifecycle and concurrent starts share a single read/write cycle',async()=>{
- const first=fixture(),second=fixture();
- try {
- await Promise.all([first.presence.start(),first.presence.start()]);assert.equal(first.calls.length,2);assert.equal(second.calls.length,0);
- await second.presence.start();await first.presence.stop();assert.equal(first.presence.status().running,false);assert.equal(second.presence.status().running,true);
- }finally{await first.presence.shutdown();await second.presence.shutdown();}
- });
- const endpoint = '55555555-5555-5555-5555-555555555555';
- const teamsValue = (availability='Available', activity=availability, extra={}) => [{ mri:`8:orgid:${self}`, presence:{ availability, activity, calendarData:{isOutOfOffice:false}, ...extra } }];
- function teamsCapture({claims={}, endpointBody={}, readBody, sample=teamsValue()}={}) {
- const headers=[{name:'Authorization',value:bearer({aud:'https://presence.example.invalid',...claims})},{name:'x-ms-object-id',value:''},
- {name:'x-ms-endpoint-id',value:endpoint},{name:'Cookie',value:'unnecessary-private-cookie'}, {name:'Referer',value:'https://example.invalid/private-page'}];
- return {log:{entries:[
- {request:{method:'POST',url:'https://teams.cloud.microsoft/ups/apac/v1/presence/getpresence/',headers:headers.filter(h=>h.name!=='x-ms-endpoint-id'),
- postData:{text:JSON.stringify(readBody||[{mri:`8:orgid:${self}`,source:'fixture-source'}])}},response:{status:200,content:{text:JSON.stringify(sample)}}},
- {request:{method:'PUT',url:'https://teams.cloud.microsoft/ups/apac/v1/me/endpoints/',headers,
- postData:{text:JSON.stringify({id:endpoint,availability:'Available',activity:'Available',activityReporting:'fixture-reporting',deviceType:'Web',...endpointBody})}},response:{status:201,content:{text:''}}},
- ]}};
- }
- test('Teams capture recognizes only observed own read and Available endpoint templates and strips unrelated data',()=>{
- 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'}})});
- const entries=extractPresenceEntries(har);
- assert.equal(entries.length,2);
- assert.deepEqual(entries.map(classifyPresenceCapture),[{kind:'presence',operation:'read',accountId:`web-api:${tenant}:${self}`},{kind:'presence',operation:'session',accountId:`web-api:${tenant}:${self}`}]);
- assert.ok(entries.every(entry=>isPresenceCaptureRequest(entry.request.url,entry.request.method)));
- assert.doesNotMatch(JSON.stringify(entries),/private-cookie|private-page|message text|unneeded|publishTime/);
- assert.equal(createNetworkPresence({har:{log:{entries}}}).status().adapter,'captured-teams-endpoint');
- 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']]) {
- assert.equal(isPresenceCaptureRequest(url,method),false);
- const bad=structuredClone(har.log.entries[1]);bad.request.url=url;bad.request.method=method;assert.equal(sanitizePresenceCapture(bad),null);
- }
- });
- test('Teams worker reads self then repeats the observed Available endpoint independently without preferred overrides',async()=>{
- const har=teamsCapture(), calls=[];
- 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});}});
- try {
- assert.equal(f.presence.status().state,'disabled');assert.equal(calls.length,0);
- const result=await f.presence.start();assert.equal(result.state,'running');assert.equal(result.adapter,'captured-teams-endpoint');
- assert.deepEqual(calls.map(c=>c.request.method),['POST','PUT']);
- assert.deepEqual(JSON.parse(calls[1].request.body),JSON.parse(har.log.entries[1].request.postData.text));
- assert.equal(calls[1].request.headers['x-ms-endpoint-id'],endpoint);assert.equal(calls[1].request.headers.Cookie,undefined);
- f.advance(120000);f.timers[0].fn();await new Promise(resolve=>setImmediate(resolve));
- assert.deepEqual(calls.map(c=>c.request.method),['POST','PUT','POST','PUT']);assert.equal(f.timers.length,2);
- assert.ok(calls.every(c=>!c.url.includes('forceavailability')));assert.doesNotMatch(JSON.stringify(f.presence.status()),/private-signature|11111111|55555555/);
- } finally {await f.presence.shutdown();}
- });
- test('Teams protects calendar and user-preferred states, including explicit offline captured in the panel',async()=>{
- for(const state of [teamsValue('Busy'),teamsValue('DoNotDisturb'),teamsValue('Busy','InAMeeting'),teamsValue('Offline','OffWork'),
- teamsValue('Available','Available',{calendarData:{isOutOfOffice:true}}),
- teamsValue('Available','Available',{forcedAvailability:{availability:'Offline',activity:'OffWork',expiry:new Date(time+500000).toISOString()}}),
- teamsValue('Available','Available',{forcedAvailability:{availability:'Busy',expiry:'unknown'}}),
- teamsValue('Available','Available',{forcedAvailability:{availability:'Available',activity:'InAMeeting',expiry:new Date(time+500000).toISOString()}})]) {
- let calls=0;const f=fixture({har:teamsCapture(),fetch:async()=>{calls++;return Response.json(state);}});
- try {assert.equal((await f.presence.start()).state,'paused');assert.equal(calls,1);assert.equal(f.presence.status().lastRenewedAt,null);}
- finally{await f.presence.shutdown();}
- }
- });
- test('Teams wrong-user, endpoint mismatch, extra body, non-Available, and mixed-token captures block before requests',async()=>{
- const invalid=[teamsCapture({readBody:[{mri:`8:orgid:${other}`,source:'fixture'}]}),teamsCapture({sample:[{mri:`8:orgid:${other}`,presence:{availability:'Available',activity:'Available'}}]}),
- teamsCapture({endpointBody:{id:other}}),teamsCapture({endpointBody:{availability:'Busy'}}),teamsCapture({endpointBody:{arbitrary:'private'}})];
- const mismatch=teamsCapture();mismatch.log.entries[1].request.headers[0]={name:'Authorization',value:bearer({aud:'different-service'})};invalid.push(mismatch);
- const foreign=teamsCapture();foreign.log.entries[1].request.headers.find(h=>h.name==='x-ms-object-id').value=other;invalid.push(foreign);
- const multiple=teamsCapture(), second=structuredClone(multiple.log.entries[1]);second.request.headers.find(h=>h.name==='x-ms-endpoint-id').value=other;
- 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);
- for(const [index,har] of invalid.entries()) {
- 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}`);
- }
- const f=fixture({har:teamsCapture(),fetch:async()=>Response.json([{mri:`8:orgid:${other}`,presence:{availability:'Available',activity:'Available'}}])});
- assert.equal((await f.presence.start()).state,'blocked');
- });
- test('Teams write rejection stops renewal without claiming success or leaking response content',async()=>{
- for(const code of [401,403,429,500]) {
- 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'}})});
- const result=await f.presence.start();assert.equal(requests,2);assert.equal(result.running,false);assert.equal(result.lastRenewedAt,null);
- 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);
- if(code===429){await f.presence.start();assert.equal(requests,2);assert.equal(f.presence.status().retryAfterAt,new Date(time+300000).toISOString());}
- }
- });
- test('Teams token expiring during the read cannot authorize a later endpoint write',async()=>{
- 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());}});
- assert.equal((await f.presence.start()).state,'auth-required');assert.equal(requests,1);
- });
- test('stopping Teams during a pending read never proceeds to the endpoint request',async()=>{
- let release;let calls=0;const f=fixture({har:teamsCapture(),fetch:async()=>{calls++;return new Promise(resolve=>{release=resolve;});}});
- const started=f.presence.start();await Promise.resolve();const stopped=f.presence.stop();release(Response.json(teamsValue()));
- await Promise.all([started,stopped]);assert.equal(calls,1);assert.equal(f.presence.status().state,'disabled');assert.equal(f.timers.length,0);
- });
- test('Teams natural Offline can create a session, while an active manual Offline preference is protected',async()=>{
- for(const forcedAvailability of [undefined,{}, {availability:'Offline',activity:'OffWork',expiry:new Date(time-1).toISOString()}]) {
- const calls=[];const f=fixture({har:teamsCapture(),fetch:async(_url,request)=>{calls.push(request.method);return request.method==='POST'
- ?Response.json(teamsValue('Offline','Offline',forcedAvailability===undefined?{}:{forcedAvailability})):new Response(null,{status:200});}});
- try{assert.equal((await f.presence.start()).state,'running');assert.deepEqual(calls,['POST','PUT']);}
- finally{await f.presence.shutdown();}
- }
- for(const forcedAvailability of [{availability:'Offline',activity:'OffWork',expiry:new Date(time+60000).toISOString()},
- {availability:'DoNotDisturb',activity:'DoNotDisturb',expiry:new Date(time+60000).toISOString()}, {availability:'Offline',activity:'OffWork'}]) {
- let calls=0;const f=fixture({har:teamsCapture(),fetch:async()=>{calls++;return Response.json(teamsValue('Offline','Offline',{forcedAvailability}));}});
- try{const result=await f.presence.start();assert.equal(result.state,'paused');assert.equal(calls,1);assert.match(result.message,/请先在 Teams 设为可用/);}
- finally{await f.presence.shutdown();}
- }
- });
- test('Teams checks current preferences each cycle and never treats the HAR sample as a lasting preference',async()=>{
- const forcedAvailability={availability:'Offline',activity:'OffWork',expiry:new Date(time+600000).toISOString()};
- const har=teamsCapture({sample:teamsValue('Offline','OffWork',{forcedAvailability})});
- let calls=0,manual=false;const f=fixture({har,fetch:async(_url,request)=>{calls++;return request.method==='POST'
- ?Response.json(manual?teamsValue('Offline','OffWork',{forcedAvailability}):teamsValue('Offline','Offline')):new Response(null,{status:200});}});
- try {
- assert.equal((await f.presence.start()).state,'running');assert.equal(calls,2);
- manual=true;f.advance(120000);f.timers[0].fn();await new Promise(resolve=>setImmediate(resolve));
- assert.equal(f.presence.status().state,'paused');assert.equal(calls,3);assert.match(f.presence.status().message,/请先在 Teams 设为可用/);
- }finally{await f.presence.shutdown();}
- });
|