import test from 'node:test'; import assert from 'node:assert/strict'; import { mkdtemp, mkdir, writeFile, readFile, rm, readdir } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { resolve, join, sep } from 'node:path'; import { createStore } from '../src/store.js'; import { createInstanceManager, capturedAccounts } from '../src/instance-manager.js'; import { createNetworkService } from '../src/network-service.js'; import { createNetworkSynchronizer } from '../src/network-sync.js'; import { createNetworkHistory } from '../src/network-history.js'; import { classifyPresenceCapture, createNetworkPresence } from '../src/network-presence.js'; const tenant = '11111111-1111-1111-1111-111111111111'; const alice = '22222222-2222-2222-2222-222222222222', bob = '33333333-3333-3333-3333-333333333333'; const app = '44444444-4444-4444-4444-444444444444'; const tick = () => new Promise(done => setImmediate(done)); const scope = (person = alice, tid = tenant) => ({ source: 'web-api', accountId: `web-api:${tid}:${person}` }); const token = (person = alice, tid = tenant) => 'Bearer fixture.' + Buffer.from(JSON.stringify({ tid, oid: person, appid: app, aud: 'https://graph.microsoft.com', scp: 'Presence.Read Presence.ReadWrite', exp: 2200000000 })).toString('base64url') + '.fictional-signature'; const url = chat => `https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/conversations/${encodeURIComponent(chat)}/messages?pageSize=200`; const payload = (chat = '19:fictional-chat', ids = ['fixture-message']) => ({ messages: ids.map(id => ({ id, conversationid: chat, conversationLink: url(chat).split('/messages')[0], type: 'Message', messagetype: 'RichText/Html', content: '
Fictional message
', version: '1788850000000', originalarrivaltime: '2026-09-08T01:00:00Z', imdisplayname: 'Fictional author' })), _metadata: { lastCompleteSegmentStartTime: 0, lastCompleteSegmentEndTime: 1788850000000 } }); const messageEntry = (person = alice, tid = tenant, chat = '19:fictional-chat') => ({ request: { method: 'GET', url: url(chat), headers: [{ name: 'Authorization', value: token(person, tid) }] }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(payload(chat)) } } }); const har = (...entries) => ({ log: { version: '1.2', entries } }); const session = (person = alice) => har(messageEntry(person)); function presenceEntries(person = alice) { const headers = [{ name: 'Authorization', value: token(person) }]; return [ { request: { method: 'GET', url: 'https://graph.microsoft.com/v1.0/me/presence', headers }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify({ id: person, availability: 'Available', activity: 'Available' }) } } }, { request: { method: 'POST', url: `https://graph.microsoft.com/v1.0/users/${person}/presence/setPresence`, headers, postData: { mimeType: 'application/json', text: JSON.stringify({ sessionId: app, availability: 'Available', activity: 'Available', expirationDuration: 'PT5M' }) } }, response: { status: 200, content: { text: '' } } } ]; } const record = (person = alice, text = 'Fictional message') => ({ ...scope(person), kind: 'message', externalId: 'same-message-id', parentId: 'same-chat-id', title: 'Fixture', text, occurredAt: '2026-09-08T01:00:00Z', raw: {} }); async function fixture(t, options = {}) { const directory = await mkdtemp(join(tmpdir(), 'teams-instance-manager-test-')); const store = createStore(':memory:'), sessions = new Map(), candidates = new Map(), logins = new Map(), services = new Map(); const timers = [], calls = [], seenStores = new Map(), presenceCalls = []; const idAt = dataDir => resolve(dataDir) === resolve(directory) ? 'default' : dataDir.split(/[\\/]/).at(-1); const loginFactory = ({ dataDir, validateSession }) => { const id = idAt(dataDir); let state = 'idle'; const login = { dataDir, validateSession, status: () => ({ state }), start: async () => { state = 'waiting'; calls.push(`login:${id}`); return login.status(); }, finish: async () => { const input = candidates.get(id); await validateSession(input); await mkdir(dataDir, { recursive: true }); await writeFile(join(dataDir, 'network-session.har'), JSON.stringify(input)); sessions.set(id, input); state = 'complete'; return { ok: true }; }, stop: async () => { state = 'cancelled'; calls.push(`cancel:${id}`); return login.status(); } }; logins.set(id, login); return login; }; const serviceOptions = { schedule: (fn, ms) => { const timer = { fn, ms }; timers.push(timer); return timer; }, unschedule: timer => { timer.cancelled = true; }, syncFactory: ({ har: input, store: scoped }) => { const account = capturedAccounts(input)[0]; seenStores.set(account.accountId, scoped); return { runOnce: async () => { calls.push(`sync:${account.accountId}`); scoped.setState('web-api:cursor:shared-test-key', { accountId: account.accountId }); scoped.upsertRecord({ ...record(), ...account }); return { ok: true, authRequired: false, noUsableRequests: false }; } }; }, historyFactory: () => ({ refreshChats: () => {}, runOnce: async () => ({ ok: true, coverage: { conversations: 1 } }) }), presenceFactory: () => { let running = false; return { status: () => ({ running, state: running ? 'running' : 'disabled' }), start: async () => { running = true; presenceCalls.push('start'); }, stop: async () => { running = false; presenceCalls.push('stop'); }, shutdown: async () => { running = false; presenceCalls.push('shutdown'); } }; }, ...options.serviceOptions }; const manager = createInstanceManager({ store, config: { dataDir: directory, pollIntervalMs: 30000, historyRequestMinDelayMs: 0, historyRequestMaxDelayMs: 0, ...options.config }, loginFactory, serviceOptions, serviceFactory: input => { const service = createNetworkService(input); services.set(idAt(input.config.dataDir), { input, service }); return service; }, ...(options.diskSessions ? {} : { readSession: async ({ id }) => { if (!sessions.has(id)) throw new Error('No fictional session'); return sessions.get(id); } }) }); t.after(async () => { await manager.shutdown(); store.close(); const target = resolve(directory), allowed = resolve(tmpdir()) + sep; assert.ok(target.startsWith(allowed) && target.slice(allowed.length).startsWith('teams-instance-manager-test-')); await rm(target, { recursive: true, force: true }); }); return { directory, store, manager, sessions, candidates, logins, services, timers, calls, seenStores, presenceCalls, saveSession: async (id, input) => { const path = join(id === 'default' ? directory : join(directory, 'instances', id), 'network-session.har'); await mkdir(resolve(path, '..'), { recursive: true }); await writeFile(path, JSON.stringify(input)); sessions.set(id, input); return path; }, saveCapture: async (name, input) => { await mkdir(join(directory, 'captures'), { recursive: true }); await writeFile(join(directory, 'captures', name), JSON.stringify(input)); } }; } test('creating instances is inert and two login flows use distinct instance directories', async t => { const f = await fixture(t), first = f.manager.create({ name: 'First' }), second = f.manager.create({ name: 'Second' }); assert.notEqual(first.id, second.id); assert.equal(first.keepOnline, false); assert.equal(first.runtime.running, false); assert.equal(first.runtime.sessionAvailable, false); assert.deepEqual(first.accounts, []); assert.deepEqual(f.calls, []); await Promise.all([f.manager.beginLogin(first.id), f.manager.beginLogin(second.id)]); assert.notEqual(f.logins.get(first.id).dataDir, f.logins.get(second.id).dataDir); assert.equal(f.logins.get(first.id).dataDir, join(f.directory, 'instances', first.id)); assert.equal(f.manager.status(first.id).login.state, 'waiting'); await f.manager.cancelLogin(first.id); assert.equal(f.manager.status(first.id).login.state, 'cancelled'); assert.equal(f.manager.status(second.id).login.state, 'waiting'); assert.ok(f.manager.listInstances().every(value => value.runtime && value.id && typeof value.keepOnline === 'boolean')); }); test('two accounts collect concurrently with separate state and stopping one preserves the other worker', async t => { const f = await fixture(t), second = f.manager.create({ name: 'Second' }); f.sessions.set('default', session(alice)); f.sessions.set(second.id, session(bob)); await Promise.all([f.manager.start(), f.manager.start(second.id)]); await tick(); assert.equal(f.manager.status().running, true); assert.equal(f.manager.status(second.id).running, true); assert.deepEqual(f.store.getState('web-api:cursor:shared-test-key'), { accountId: scope(alice).accountId }); assert.deepEqual(f.store.getState(`instance:${second.id}:web-api:cursor:shared-test-key`), { accountId: scope(bob).accountId }); const ownStore = f.seenStores.get(scope(alice).accountId); assert.throws(() => ownStore.upsertRecord(record(bob)), /不属于/); assert.throws(() => ownStore.getRecordByIdentity(record(bob)), /不属于/); assert.equal(ownStore.listRecords({}).total, 1); await f.manager.update(second.id, { keepOnline: true }); assert.equal(f.manager.status(second.id).presence.running, true); await f.manager.stop(); assert.equal(f.manager.status().running, false); assert.equal(f.manager.status(second.id).running, true); assert.equal(f.manager.status(second.id).presence.running, true); const before = f.calls.filter(value => value === `sync:${scope(bob).accountId}`).length; for (const timer of [...f.timers]) if (!timer.cancelled) { await timer.fn(); await tick(); } assert.equal(f.calls.filter(value => value === `sync:${scope(bob).accountId}`).length, before + 1); assert.equal(f.store.getState('web-api:service').enabled, false); assert.equal(f.store.getState(`instance:${second.id}:web-api:service`).enabled, true); }); test('default resumes legacy state without rewriting its history checkpoint while new instances remain disabled', async t => { let seen; const checkpoint = { adapterVersion: 4, status: 'complete', pages: 7, records: 81 }; const f = await fixture(t, { serviceOptions: { historyFactory: ({ store }) => { seen = store.getState('web-api:history:legacy'); return { runOnce: async () => ({ ok: true }) }; } } }); f.sessions.set('default', session()); f.store.setState('web-api:history:legacy', checkpoint); f.store.setState('web-api:service', { enabled: true }); const other = f.manager.create({ name: 'Not started' }); await f.manager.resume(); await tick(); assert.deepEqual(seen, checkpoint); assert.deepEqual(f.store.getState('web-api:history:legacy'), checkpoint); assert.equal(f.manager.status().running, true); assert.equal(f.manager.status(other.id).running, false); assert.equal(f.services.get('default').input.config.dataDir, f.directory); assert.equal(f.store.getState(`instance:${other.id}:web-api:service`), null); }); test('only the default instance can use an external legacy HAR fallback', async t => { const f = await fixture(t, { diskSessions: true }); const external = join(f.directory, 'legacy-external.har'); await writeFile(external, JSON.stringify(session())); // The configuration object passed to the real service remains local to this fixture. f.manager.status(); f.services.get('default').input.config.networkHarPath = external; const other = f.manager.create({ name: 'No fallback' }); assert.equal(f.services.get(other.id).input.allowExternalSessionPath, false); assert.equal(f.services.get(other.id).input.config.networkHarPath, ''); await f.manager.start(); await f.manager.start(other.id); await tick(); assert.equal(f.manager.status().running, true); assert.equal(f.manager.status(other.id).running, false); assert.equal(f.manager.status(other.id).sessionAvailable, false); assert.deepEqual(f.store.getInstance(other.id).accounts, []); }); test('duplicate account login and changing a bound account fail before replacing any session', async t => { const f = await fixture(t), second = f.manager.create({ name: 'Second' }); f.candidates.set('default', session(alice)); await f.manager.beginLogin(); await f.manager.finishLogin(); await tick(); const path = join(f.directory, 'network-session.har'), before = await readFile(path, 'utf8'); f.candidates.set(second.id, session(alice)); await f.manager.beginLogin(second.id); await assert.rejects(f.manager.finishLogin(second.id), error => error.code === 'instance_account_conflict'); assert.deepEqual(f.store.getInstance(second.id).accounts, []); assert.equal(f.manager.status(second.id).sessionAvailable, false); f.candidates.set('default', session(bob)); await f.manager.beginLogin(); await assert.rejects(f.manager.finishLogin(), error => error.code === 'instance_identity_mismatch'); assert.equal(await readFile(path, 'utf8'), before); assert.equal(f.manager.status().running, true); assert.deepEqual(f.store.getInstance('default').accounts, [scope(alice)]); assert.doesNotMatch(JSON.stringify(f.manager.listInstances()), /fictional-signature|Fictional message|Authorization/); }); test('bindings come from captured requests, allow a previously captured tenant subset, and reject opaque identities', async t => { const f = await fixture(t), otherTenant = '55555555-5555-5555-5555-555555555555'; f.store.upsertRecord(record(bob)); const validate = f.logins.get('default') || (f.manager.status(), f.logins.get('default')); validate.validateSession(har(messageEntry(alice), messageEntry(alice, otherTenant))); assert.equal(f.store.getInstance('default').accounts.length, 2); assert.ok(f.store.getInstance('default').accounts.every(value => value.accountId !== scope(bob).accountId)); assert.doesNotThrow(() => validate.validateSession(har(messageEntry(alice, otherTenant)))); assert.throws(() => validate.validateSession(session(bob)), error => error.code === 'instance_identity_mismatch'); const opaque = session(); opaque.log.entries[0].request.headers[0].value = 'Bearer opaque-fixture'; assert.throws(() => capturedAccounts(opaque), error => error.code === 'instance_account_unidentified'); }); test('deletion validates exact scope and confirmation, clears only its instance checkpoints, and leaves other collection running', async t => { const f = await fixture(t), second = f.manager.create({ name: 'Second' }); f.sessions.set('default', session(alice)); f.sessions.set(second.id, session(bob)); await Promise.all([f.manager.start(), f.manager.start(second.id)]); await tick(); f.store.upsertRecord({ ...record(alice), source: 'browser' }); f.store.setState('web-api:history:legacy', { complete: true }); f.store.setState('web-api:chat-metadata:legacy', { nextCheckAt: 2000000000000 }); f.store.setState(`instance:${second.id}:web-api:chat-metadata:other`, { nextCheckAt: 2000000000000 }); f.store.setState(`instance:${second.id}:web-api:history:other`, { complete: true }); f.store.setState('graph:cursor:keep', { keep: true }); await f.manager.update('default', { keepOnline: true }); await f.manager.beginLogin(); await assert.rejects(f.manager.deleteRecords('default', { ...scope(bob), confirmation: scope(bob).accountId }), /不属于/); await assert.rejects(f.manager.deleteRecords('default', { ...scope(alice), confirmation: 'wrong' }), /输入/); assert.equal(f.manager.status().running, true); const result = await f.manager.deleteRecords('default', { ...scope(alice), confirmation: scope(alice).accountId }); assert.equal(result.instanceId, 'default'); assert.equal(f.store.listRecords(scope(alice)).total, 0); assert.equal(f.store.listRecords(scope(bob)).total, 1); assert.equal(f.store.listRecords({ source: 'browser' }).total, 1); assert.equal(f.manager.status().running, false); assert.equal(f.manager.status().login.state, 'cancelled'); assert.equal(f.manager.status().presence.running, false); assert.equal(f.manager.status(second.id).running, true); assert.equal(f.store.getState('web-api:history:legacy'), null); assert.equal(f.store.getState('web-api:cursor:shared-test-key'), null); assert.equal(f.store.getState('web-api:chat-metadata:legacy'), null); assert.deepEqual(f.store.getState(`instance:${second.id}:web-api:chat-metadata:other`), { nextCheckAt: 2000000000000 }); assert.deepEqual(f.store.getState(`instance:${second.id}:web-api:history:other`), { complete: true }); assert.deepEqual(f.store.getState('graph:cursor:keep'), { keep: true }); assert.deepEqual(f.store.getInstance('default').accounts, [scope(alice)]); assert.equal(f.store.getState('web-api:service').enabled, false); }); test('presence import validates first, then stops only its instance and atomically preserves message templates', async t => { const f = await fixture(t), second = f.manager.create({ name: 'Second' }); const path = await f.saveSession('default', session(alice)); f.sessions.set(second.id, session(bob)); await Promise.all([f.manager.start(), f.manager.start(second.id)]); await tick(); await f.manager.beginLogin(); const entries = presenceEntries(alice), unrelated = { request: { method: 'POST', url: 'https://login.microsoftonline.com/token', postData: { text: 'not-to-import' } }, response: { status: 200 } }; await f.saveCapture('presence.har', har(...entries, unrelated)); const result = await f.manager.importPresence('default', { fileName: 'presence.har' }); const saved = JSON.parse(await readFile(path, 'utf8')); assert.equal(result.ok, true); assert.equal(result.imported, 2); assert.equal(saved.log.entries.length, 3); assert.deepEqual(saved.log.entries[0], messageEntry(alice)); assert.equal(saved.log.entries.filter(classifyPresenceCapture).length, 2); assert.doesNotMatch(JSON.stringify(saved), /not-to-import|login.microsoftonline/); assert.equal(f.manager.status().running, false); assert.equal(f.manager.status().login.state, 'cancelled'); assert.equal(f.manager.status(second.id).running, true); assert.equal(f.store.getState('web-api:service').enabled, false); assert.equal((await readdir(f.directory)).some(name => name.endsWith('.tmp')), false); const offline = createNetworkPresence({ har: saved, fetch: () => assert.fail('Import must not request presence') }); assert.equal(offline.status().configured, true); await offline.shutdown(); }); test('foreign, incomplete and escaped presence captures cannot stop a worker or change its session', async t => { const f = await fixture(t), path = await f.saveSession('default', session()); await f.manager.start(); await tick(); const before = await readFile(path, 'utf8'); await f.saveCapture('foreign.har', har(...presenceEntries(bob))); await f.saveCapture('read-only.har', har(presenceEntries(alice)[0])); for (const fileName of ['foreign.har', 'read-only.har', '../outside.har', '..\\outside.har', 'C:\\outside.har', 'presence.har:stream', 'nested/file.har']) { await assert.rejects(f.manager.importPresence('default', { fileName })); assert.equal(await readFile(path, 'utf8'), before); assert.equal(f.manager.status().running, true); } assert.equal(f.store.getState('web-api:service').enabled, true); }); test('the real synchronizer and history execute through the scoped store using only a fictional fetch', async t => { const requests = []; const fetch = async raw => { requests.push(raw); return Response.json(payload()); }; const f = await fixture(t, { serviceOptions: { syncFactory: options => createNetworkSynchronizer({ ...options, fetch }), historyFactory: options => createNetworkHistory({ ...options, fetch, requestMinDelayMs: 0, requestMaxDelayMs: 0 }) } }); f.sessions.set('default', session()); await f.manager.start(); for (let attempt = 0; attempt < 100 && !f.manager.status().history?.coverage; attempt++) await tick(); const current = f.manager.status(); assert.equal(current.sync?.ok, true, JSON.stringify(current.sync)); assert.equal(current.history?.ok, true, JSON.stringify(current.history)); assert.equal(current.error, null); assert.equal(requests.length, 2); assert.equal(f.store.listRecords({ ...scope(alice), kind: 'message' }).total, 1); assert.equal(current.history.coverage.conversations, 1); assert.equal(current.history.coverage.complete, 1); });