feat(agent): add opt-in push notifications
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import vm from "node:vm";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
const workerSource = await readFile(new URL("../public/sw.js", import.meta.url), "utf8");
|
||||
const sourceId = "4599d348-e053-4937-987d-1392746fb2ce", otherSource = "550caef2-b4bc-482c-bd9f-58045ed0a8a8";
|
||||
const payload = (cursor = "5", extra = {}) => ({ version: 1, kind: "message", sourceId, messageId: `outbound:${cursor}`, cursor,
|
||||
title: "Sybil Agent", body: "You have a new message.", url: "/?agent=root", tag: `sybil-agent:${sourceId}`, ...extra });
|
||||
function idb(records) {
|
||||
const request = value => { const result = {}; queueMicrotask(() => { result.result = structuredClone(value); result.onsuccess?.(); }); return result; };
|
||||
return { open() {
|
||||
const opening = {};
|
||||
queueMicrotask(() => {
|
||||
opening.result = { close() {}, transaction() {
|
||||
const transaction = { objectStore: () => ({
|
||||
get: key => request(records.get(key)), getAll: () => request([...records.values()]),
|
||||
put: value => records.set(value.sourceId, structuredClone(value)), delete: key => records.delete(key),
|
||||
}) };
|
||||
setImmediate(() => transaction.oncomplete?.()); return transaction;
|
||||
} };
|
||||
opening.onsuccess?.();
|
||||
}); return opening;
|
||||
} };
|
||||
}
|
||||
function fixture(sharedRecords = new Map()) {
|
||||
const handlers = new Map(), shown = [], notifications = [], routes = [], messages = [], fetches = [];
|
||||
const normalClient = { id: "client", type: "window", url: "https://sybil.example.test/?chat=somewhere", postMessage: value => messages.push(value),
|
||||
navigate: async url => { routes.push(["navigate", url]); return normalClient; }, focus: async () => { routes.push(["focus"]); return normalClient; } };
|
||||
let windows = [normalClient];
|
||||
const makeNotification = value => {
|
||||
const notification = { tag: value.tag, data: value.data, closed: false, close() { notification.closed = true; } };
|
||||
notifications.push(notification); return notification;
|
||||
};
|
||||
const self = {
|
||||
addEventListener: (name, handler) => handlers.set(name, handler), skipWaiting() {}, location: { origin: "https://sybil.example.test" },
|
||||
clients: { claim: async () => undefined, matchAll: async () => windows,
|
||||
get: async id => windows.find(client => client.id === id), openWindow: async url => { routes.push(["open", url]); } },
|
||||
registration: {
|
||||
showNotification: async (title, options) => {
|
||||
shown.push({ title, ...structuredClone(options) });
|
||||
for (const notification of notifications) if (notification.tag === options.tag) notification.close();
|
||||
makeNotification(options);
|
||||
},
|
||||
getNotifications: async ({ tag } = {}) => notifications.filter(value => !value.closed && (!tag || value.tag === tag)),
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(workerSource, { self, indexedDB: idb(sharedRecords), URL, Date, Promise, BigInt,
|
||||
fetch: async request => { fetches.push(request); throw new Error("Network blocked in worker tests"); }, Request });
|
||||
const emit = async (type, properties = {}) => {
|
||||
const waits = []; handlers.get(type)?.({ ...properties, waitUntil: value => waits.push(value) }); await Promise.all(waits);
|
||||
};
|
||||
return { shown, notifications, routes, messages, fetches, records: sharedRecords, makeNotification,
|
||||
push: value => emit("push", { data: { text: () => typeof value === "string" ? value : JSON.stringify(value) } }),
|
||||
click: notification => emit("notificationclick", { notification }),
|
||||
message: (data, id = "client") => emit("message", { data, source: { id }, ports: [] }),
|
||||
emit, windows: value => { windows = value; }, normalClient,
|
||||
};
|
||||
}
|
||||
|
||||
test("actual worker push handler shows fixed generic notification and never fetches credentials", async () => {
|
||||
const f = fixture(); await f.push(payload());
|
||||
assert.equal(f.shown.length, 1); assert.equal(f.shown[0].title, "Sybil Agent"); assert.equal(f.shown[0].body, "You have a new message.");
|
||||
assert.deepEqual(f.shown[0].data, { version: 1, kind: "message", sourceId, messageId: "outbound:5", cursor: "5" });
|
||||
assert.equal(f.shown[0].tag, `sybil-agent:${sourceId}`); assert.equal(f.shown[0].renotify, false);
|
||||
assert.deepEqual(f.fetches, []); assert.ok(!JSON.stringify([...f.records]).includes("token"));
|
||||
});
|
||||
|
||||
test("every valid message push remains visible, including read or duplicate deliveries; stale payload never regresses identity", async () => {
|
||||
const records = new Map(), f = fixture(records);
|
||||
await f.message({ type: "sybil-agent-read", version: 1, sourceId, cursor: "10" });
|
||||
await f.push(payload("8")); await f.push(payload("8")); await f.push(payload("5"));
|
||||
assert.equal(f.shown.length, 3, "Safari visibility requirement is preserved");
|
||||
assert.ok(f.shown.every(notification => notification.data.cursor === "8"));
|
||||
const restarted = fixture(records); await restarted.push(payload("6"));
|
||||
assert.equal(restarted.shown[0].data.cursor, "8");
|
||||
assert.equal(records.get(sourceId).readCursor, "10");
|
||||
});
|
||||
|
||||
test("malformed/unexpected payloads cannot supply text, destinations, cross-source tags or silent read pushes", async () => {
|
||||
const f = fixture();
|
||||
for (const value of ["not-json", "x".repeat(5000), payload("1", { title: "sensitive text" }), payload("1", { body: "transcript" }),
|
||||
payload("1", { url: "https://evil.example/" }), payload("1", { tag: "some-other-app" }), payload("-1"), payload("9007199254740992"),
|
||||
payload("1", { sourceId: "../../bad" }), payload("1", { messageId: "<script>" }), { version: 1, kind: "read_state", sourceId, readCursor: "8" }]) await f.push(value);
|
||||
assert.equal(f.shown.length, 0); assert.equal(f.fetches.length, 0);
|
||||
});
|
||||
|
||||
test("authenticated page read sync closes only owned matching source at or below monotonic read cursor", async () => {
|
||||
const f = fixture();
|
||||
const older = f.makeNotification({ tag: `sybil-agent:${sourceId}`, data: payload("4") });
|
||||
const newer = f.makeNotification({ tag: `sybil-agent:${sourceId}`, data: payload("8") });
|
||||
const different = f.makeNotification({ tag: `sybil-agent:${otherSource}`, data: payload("1", { sourceId: otherSource }) });
|
||||
const unrelated = f.makeNotification({ tag: "calendar", data: payload("1") });
|
||||
const read = { type: "sybil-agent-read", version: 1, sourceId, cursor: "5" };
|
||||
await f.message(read, "unknown-client"); assert.equal(older.closed, false);
|
||||
f.windows([{ ...f.normalClient, id: "foreign", url: "https://evil.example/" }]);
|
||||
await f.message(read, "foreign"); assert.equal(older.closed, false);
|
||||
f.windows([f.normalClient]); await f.message(read); await f.message({ ...read, cursor: "2" });
|
||||
assert.equal(older.closed, true); assert.equal(newer.closed, false); assert.equal(different.closed, false); assert.equal(unrelated.closed, false);
|
||||
assert.equal(f.records.get(sourceId).readCursor, "5");
|
||||
await f.message({ ...read, cursor: "8" }); assert.equal(newer.closed, true);
|
||||
});
|
||||
|
||||
test("notification click closes and navigates a same-origin client using fixed root URL, without marking read", async () => {
|
||||
const f = fixture(); await f.push(payload());
|
||||
const notification = f.notifications[0]; notification.data.url = "https://evil.example/";
|
||||
await f.click(notification);
|
||||
assert.equal(notification.closed, true);
|
||||
assert.deepEqual(f.routes, [["navigate", "https://sybil.example.test/?agent=root"], ["focus"]]);
|
||||
assert.equal(f.records.get(sourceId).readCursor, undefined);
|
||||
f.windows([{ ...f.normalClient, url: "https://evil.example/" }]); await f.click(notification);
|
||||
assert.deepEqual(f.routes.at(-1), ["open", "https://sybil.example.test/?agent=root"]);
|
||||
});
|
||||
|
||||
test("logout closes only owned alerts and subscription change asks pages to re-register without network or secrets", async () => {
|
||||
const f = fixture(); await f.push(payload());
|
||||
const unrelated = f.makeNotification({ tag: "another-app", data: payload() });
|
||||
await f.message({ type: "sybil-agent-logout", version: 1 });
|
||||
assert.equal(f.notifications[0].closed, true); assert.equal(unrelated.closed, false);
|
||||
await f.emit("pushsubscriptionchange");
|
||||
assert.equal(f.messages.at(-1).type, "sybil-push-subscription-changed");
|
||||
assert.deepEqual(f.fetches, []);
|
||||
});
|
||||
|
||||
test("worker bounds durable source metadata", async () => {
|
||||
const f = fixture();
|
||||
for (let index = 0; index < 20; index++) await f.message({ type: "sybil-agent-read", version: 1, sourceId: `4599d348-e053-4937-987d-${String(index).padStart(12, "0")}`, cursor: "1" });
|
||||
assert.equal(f.records.size, 16);
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import assert from "node:assert/strict";
|
||||
// Fresh isolated Chromium only. All REST, sockets and PushManager provider calls
|
||||
// are mocked. The real /sw.js and browser IndexedDB/notification APIs execute.
|
||||
// PLAYWRIGHT_MODULE=/path/playwright-core/index.mjs CHROME_EXECUTABLE=/path/chrome
|
||||
// WEB_TEST_URL=http://127.0.0.1:5197 node tests/agent-push.browser.mjs
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core");
|
||||
const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/");
|
||||
assert.ok(target.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname));
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME_EXECUTABLE || undefined, headless: true,
|
||||
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1200, height: 900 }, permissions: ["notifications"] });
|
||||
const sourceId = "4599d348-e053-4937-987d-1392746fb2ce", requests = [], sockets = [], errors = [], blocked = [];
|
||||
const replacementSourceId = "22222222-2222-4222-8222-222222222222";
|
||||
const config = { version: 1, enabled: true, webPushAvailable: true, apnsAvailable: false, sourceId: null, quarantined: false,
|
||||
vapidPublicKey: "B".repeat(87), policy: { presenceHeartbeatMs: 15000, presenceLeaseMs: 60000 } };
|
||||
const idle = { state: "idle", isThinking: false, queued: 0, backgroundWorkers: 0, tools: [], queuedMessages: [] };
|
||||
let readCursor = "0", readSourceId = sourceId, failDelete = false;
|
||||
await context.addInitScript(() => {
|
||||
if (!localStorage.getItem("fixture-bootstrapped")) {
|
||||
localStorage.setItem("fixture-bootstrapped", "true"); localStorage.setItem("sybil_admin_token", "browser-fixture-token");
|
||||
}
|
||||
window.__pushCalls = [];
|
||||
window.__fixturePermission = localStorage.getItem("fixture-subscription") ? "granted" : "default";
|
||||
window.__fixtureDecision = "denied";
|
||||
Object.defineProperty(Notification, "permission", { configurable: true, get: () => window.__fixturePermission });
|
||||
Notification.requestPermission = () => {
|
||||
window.__pushCalls.push({ type: "permission", gesture: navigator.userActivation.isActive });
|
||||
window.__fixturePermission = window.__fixtureDecision; return Promise.resolve(window.__fixturePermission);
|
||||
};
|
||||
const subscription = () => ({
|
||||
toJSON: () => ({ endpoint: "https://fcm.googleapis.com/fcm/send/browser-fixture", expirationTime: null, keys: { p256dh: "B".repeat(87), auth: "A".repeat(22) } }),
|
||||
unsubscribe: async () => { window.__pushCalls.push({ type: "unsubscribe" }); localStorage.removeItem("fixture-subscription"); return true; },
|
||||
});
|
||||
PushManager.prototype.getSubscription = async () => localStorage.getItem("fixture-subscription") ? subscription() : null;
|
||||
PushManager.prototype.subscribe = async options => {
|
||||
window.__pushCalls.push({ type: "subscribe", visible: options.userVisibleOnly, keyLength: options.applicationServerKey.byteLength });
|
||||
localStorage.setItem("fixture-subscription", "true"); return subscription();
|
||||
};
|
||||
});
|
||||
await context.route("**/*", async route => {
|
||||
const request = route.request(), url = new URL(request.url());
|
||||
if (url.origin !== target.origin) { blocked.push(url.origin); await route.abort(); return; }
|
||||
if (!url.pathname.startsWith("/api/")) { await route.continue(); return; }
|
||||
const method = request.method(), path = url.pathname;
|
||||
const body = request.postData() ? request.postDataJSON() : undefined;
|
||||
requests.push({ path, method, body, authorization: request.headers().authorization });
|
||||
assert.ok(["Bearer browser-fixture-token", "Bearer browser-fixture-rotated-token"].includes(request.headers().authorization));
|
||||
let value;
|
||||
if (path.endsWith("/push/config")) value = config;
|
||||
else if (path.includes("/push/installations/")) {
|
||||
if (method === "DELETE") { await route.fulfill({ status: failDelete ? 503 : 204, ...(failDelete ? { json: { message: "offline" } } : {}) }); return; }
|
||||
value = { installationId: path.split("/").at(-1), transport: "web", enabled: true, version: 1 };
|
||||
} else if (path.includes("/presence/")) {
|
||||
if (method === "DELETE") { await route.fulfill({ status: 204 }); return; }
|
||||
value = { expiresAt: new Date(Date.now() + 60000).toISOString() };
|
||||
} else if (path.endsWith("/read-state")) {
|
||||
if (method === "PUT") readCursor = body.cursor;
|
||||
value = { cursor: readCursor, sourceId: readSourceId, updatedAt: null };
|
||||
} else if (path.endsWith("/agent/messages")) value = { conversationId: "1", messages: [], cursor: "0", beforeCursor: null, hasMore: false };
|
||||
else if (path.endsWith("/agent")) value = { id: "1", title: "Sybil Agent", activity: idle, protocol: "pi-room.v1", websocket: "/v1/agent/ws" };
|
||||
else if (path.includes("session")) value = { mode: "token", authenticated: true };
|
||||
else if (path.endsWith("/tools") || path.endsWith("/chat-tools")) value = { tools: [] };
|
||||
else if (path.endsWith("/models")) value = { models: [], providers: {} };
|
||||
else value = [];
|
||||
await route.fulfill({ json: value });
|
||||
});
|
||||
await context.routeWebSocket("**/api/v1/agent/ws", socket => {
|
||||
socket.onMessage(raw => {
|
||||
const frame = JSON.parse(String(raw));
|
||||
if (frame.type === "auth") { sockets.push({ socket, frame }); socket.send(JSON.stringify({ type: "ready", conversationId: "1" })); }
|
||||
});
|
||||
});
|
||||
const page = await context.newPage(); page.on("pageerror", error => errors.push(error.message));
|
||||
const expectEventually = async predicate => { for (let i = 0; i < 100; i++) { if (await predicate()) return; await new Promise(resolve => setTimeout(resolve, 50)); } assert.fail("Condition did not settle"); };
|
||||
try {
|
||||
await page.goto(target.href, { waitUntil: "networkidle" });
|
||||
await page.getByText("Agent notifications", { exact: true }).click();
|
||||
await page.getByText("Notifications are not configured on this server yet.", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: "Enable notifications", exact: true }).isDisabled(), true, "unknown source cannot opt in");
|
||||
assert.deepEqual(await page.evaluate(() => window.__pushCalls), []);
|
||||
config.sourceId = sourceId;
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled());
|
||||
assert.equal(requests.filter(request => request.path.includes("/push/installations/")).length, 0);
|
||||
await page.getByRole("button", { name: "Enable notifications", exact: true }).click();
|
||||
await page.getByText(/Notifications were not allowed/).waitFor();
|
||||
assert.equal(requests.filter(request => request.path.includes("/push/installations/")).length, 0);
|
||||
assert.deepEqual(await page.evaluate(() => window.__pushCalls), [{ type: "permission", gesture: true }]);
|
||||
await page.evaluate(() => { window.__fixturePermission = "default"; window.__fixtureDecision = "granted"; });
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled());
|
||||
await page.getByRole("button", { name: "Enable notifications", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor();
|
||||
const registrations = requests.filter(request => request.path.includes("/push/installations/") && request.method === "PUT");
|
||||
assert.equal(registrations.length, 1); assert.equal(registrations[0].body.transport, "web");
|
||||
assert.deepEqual(await page.evaluate(() => window.__pushCalls.filter(call => call.type === "subscribe")), [{ type: "subscribe", visible: true, keyLength: 65 }]);
|
||||
await expectEventually(() => sockets.length === 1);
|
||||
const firstSession = sockets[0].frame.presenceSessionId;
|
||||
assert.equal(sockets[0].frame.clientKind, "web");
|
||||
assert.ok(requests.some(request => request.path.endsWith(firstSession) && request.body?.visibility === "visible"));
|
||||
|
||||
// /search has no Agent pane or room socket but must still report attention.
|
||||
const second = await context.newPage(); second.on("pageerror", error => errors.push(error.message));
|
||||
await second.goto(new URL("/search", target).href, { waitUntil: "networkidle" });
|
||||
await second.bringToFront();
|
||||
await expectEventually(() => new Set(requests.filter(request => request.path.includes("/presence/")).map(request => request.path)).size >= 2);
|
||||
const sessionPaths = [...new Set(requests.filter(request => request.path.includes("/presence/")).map(request => request.path))];
|
||||
assert.equal(sessionPaths.length, 2);
|
||||
const secondPath = sessionPaths.find(path => !path.endsWith(firstSession));
|
||||
await expectEventually(() => requests.some(request => request.path === secondPath && request.body?.focused === true));
|
||||
await second.getByRole("textbox").first().click();
|
||||
await second.getByRole("textbox").first().pressSequentially("interaction");
|
||||
await expectEventually(() => requests.some(request => request.path === secondPath && request.body?.interacted === true));
|
||||
for (const path of sessionPaths) {
|
||||
const sequences = requests.filter(request => request.path === path && request.method === "PUT").map(request => request.body.sequence);
|
||||
assert.deepEqual(sequences, [...new Set(sequences)].sort((a, b) => a - b));
|
||||
}
|
||||
await page.bringToFront();
|
||||
const worker = context.serviceWorkers().find(worker => new URL(worker.url()).pathname === "/sw.js");
|
||||
assert.ok(worker, "actual service worker activated");
|
||||
const push = async cursor => worker.evaluate(async ({ cursor, sourceId }) => {
|
||||
const value = { version: 1, kind: "message", sourceId, cursor, messageId: `outbound:${cursor}`, title: "Sybil Agent", body: "You have a new message.", url: "/?agent=root", tag: `sybil-agent:${sourceId}` };
|
||||
const event = new Event("push"), waits = [];
|
||||
Object.defineProperties(event, { data: { value: { text: () => JSON.stringify(value) } }, waitUntil: { value: promise => waits.push(promise) } });
|
||||
self.dispatchEvent(event); await Promise.all(waits);
|
||||
return (await self.registration.getNotifications()).map(notification => ({ title: notification.title, body: notification.body, tag: notification.tag, data: notification.data }));
|
||||
}, { cursor, sourceId });
|
||||
const notification = await push("8");
|
||||
assert.equal(notification.length, 1); assert.equal(notification[0].title, "Sybil Agent"); assert.equal(notification[0].body, "You have a new message.");
|
||||
assert.equal(notification[0].data.cursor, "8");
|
||||
assert.equal(requests.filter(request => request.method === "PUT" && request.path.endsWith("/read-state")).length, 0, "push reception never marks read");
|
||||
readCursor = "7";
|
||||
sockets[0].socket.send(JSON.stringify({ type: "read_state", sourceId, cursor: readCursor, updatedAt: null }));
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
assert.equal(await worker.evaluate(async () => (await self.registration.getNotifications()).length), 1);
|
||||
readCursor = "8";
|
||||
sockets[0].socket.send(JSON.stringify({ type: "read_state", sourceId, cursor: readCursor, updatedAt: null }));
|
||||
await expectEventually(async () => await worker.evaluate(async () => (await self.registration.getNotifications()).length) === 0);
|
||||
const dbRows = await worker.evaluate(async () => {
|
||||
const db = await new Promise(resolve => { const request = indexedDB.open("sybil-agent-notifications-v1"); request.onsuccess = () => resolve(request.result); });
|
||||
const rows = await new Promise(resolve => { const request = db.transaction("sources").objectStore("sources").getAll(); request.onsuccess = () => resolve(request.result); });
|
||||
db.close(); return rows;
|
||||
});
|
||||
assert.equal(dbRows[0].readCursor, "8"); assert.doesNotMatch(JSON.stringify(dbRows), /browser-fixture-token|fcm.googleapis/);
|
||||
|
||||
// The rendered room belongs to source A. A B read frame must stop the room,
|
||||
// preserving A's cursor instead of relabeling old queued reads with B.
|
||||
await second.close();
|
||||
await page.locator('[data-testid="agent-sidebar-item"]').click();
|
||||
sockets[0].socket.send(JSON.stringify({ type: "read_state", sourceId: replacementSourceId, cursor: "0", updatedAt: null }));
|
||||
await page.getByText("Agent history changed. Reload the page before marking messages read.", { exact: true }).waitFor();
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
assert.equal(requests.filter(request => request.method === "PUT" && request.path.endsWith("/read-state")).length, 0, "source mismatch cannot produce relabeled writes or a write loop");
|
||||
|
||||
// Replacing the source at the same backend/token invalidates persisted push
|
||||
// consent. The new source requires another gesture and another installation.
|
||||
const oldConsent = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
const registrationCount = requests.filter(request => request.path.includes("/push/installations/") && request.method === "PUT").length;
|
||||
config.sourceId = replacementSourceId; readSourceId = replacementSourceId; readCursor = "0";
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled());
|
||||
const retiredConsent = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
assert.equal(retiredConsent.enabled, false); assert.equal(retiredConsent.sourceId, sourceId);
|
||||
assert.equal(requests.filter(request => request.path.includes("/push/installations/") && request.method === "PUT").length, registrationCount);
|
||||
assert.ok(requests.some(request => request.path.endsWith(oldConsent.installationId) && request.method === "DELETE"));
|
||||
await page.getByRole("button", { name: "Enable notifications", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor();
|
||||
const replacementConsent = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
assert.equal(replacementConsent.enabled, true); assert.equal(replacementConsent.sourceId, replacementSourceId);
|
||||
assert.equal(replacementConsent.scope, oldConsent.scope); assert.notEqual(replacementConsent.installationId, oldConsent.installationId);
|
||||
assert.ok((await page.evaluate(() => window.__pushCalls.filter(call => call.type === "permission"))).every(call => call.gesture === true));
|
||||
const socketCount = sockets.length;
|
||||
await page.getByRole("button", { name: "Retry", exact: true }).click();
|
||||
await expectEventually(() => sockets.length > socketCount);
|
||||
assert.equal(await page.getByText("Agent history changed. Reload the page before marking messages read.", { exact: true }).count(), 0, "explicit reload binds a fresh room to B");
|
||||
await page.getByText("Agent notifications", { exact: true }).click();
|
||||
await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor();
|
||||
|
||||
// Credential rotation is a new authority scope. The old UUID remains queued
|
||||
// locally even if this server would return204 for an unknown DELETE.
|
||||
const originalAuthority = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
await page.evaluate(() => localStorage.setItem("sybil_admin_token", "browser-fixture-rotated-token"));
|
||||
await page.reload({ waitUntil: "networkidle" });
|
||||
await page.getByText("Agent notifications", { exact: true }).click();
|
||||
await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled());
|
||||
const rotatedOff = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
assert.deepEqual(rotatedOff.pendingRevocations, [{ installationId: originalAuthority.installationId, scope: originalAuthority.scope }]);
|
||||
assert.ok(!requests.some(request => request.method === "DELETE" && request.path.endsWith(originalAuthority.installationId)
|
||||
&& request.authorization === "Bearer browser-fixture-rotated-token"), "rotated credentials cannot falsely acknowledge old-authority cleanup");
|
||||
await page.evaluate(() => { window.__fixtureDecision = "granted"; });
|
||||
await page.getByRole("button", { name: "Enable notifications", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor();
|
||||
const rotatedOn = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
assert.equal(rotatedOn.enabled, true); assert.notEqual(rotatedOn.scope, originalAuthority.scope);
|
||||
assert.notEqual(rotatedOn.installationId, originalAuthority.installationId); assert.deepEqual(rotatedOn.pendingRevocations, rotatedOff.pendingRevocations);
|
||||
await page.evaluate(() => localStorage.setItem("sybil_admin_token", "browser-fixture-token"));
|
||||
await page.reload({ waitUntil: "networkidle" });
|
||||
await page.getByText("Agent notifications", { exact: true }).click();
|
||||
await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled());
|
||||
const returned = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1")));
|
||||
assert.deepEqual(returned.pendingRevocations, [{ installationId: rotatedOn.installationId, scope: rotatedOn.scope }]);
|
||||
assert.ok(requests.some(request => request.method === "DELETE" && request.path.endsWith(originalAuthority.installationId)
|
||||
&& request.authorization === "Bearer browser-fixture-token"));
|
||||
await page.evaluate(() => { window.__fixtureDecision = "granted"; });
|
||||
await page.getByRole("button", { name: "Enable notifications", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor();
|
||||
|
||||
// Offline sign-out still removes the local subscription and leaves a tombstone.
|
||||
failDelete = true;
|
||||
await page.getByRole("button", { name: "Sign out", exact: true }).click();
|
||||
await page.getByRole("button", { name: /Sign in/i }).waitFor();
|
||||
const local = await page.evaluate(() => ({ token: localStorage.getItem("sybil_admin_token"), subscription: localStorage.getItem("fixture-subscription"), consent: JSON.parse(localStorage.getItem("sybil.agent.push.v1")) }));
|
||||
assert.equal(local.token, null); assert.equal(local.subscription, null); assert.equal(local.consent.enabled, false); assert.equal(local.consent.revocationPending, true);
|
||||
assert.ok(requests.some(request => request.method === "DELETE" && request.path.includes("/push/installations/") && request.authorization === "Bearer browser-fixture-token"));
|
||||
// Existing app fonts are blocked as well; nothing leaves the loopback fixture.
|
||||
assert.ok(blocked.every(origin => origin === "https://fonts.googleapis.com")); assert.deepEqual(errors, []);
|
||||
console.log("PASS real worker activation/showNotification/IndexedDB/read close; unknown-source/gesture denial/enable; two-tab + standalone search presence; auth-frame binding; source-replacement read quiescence and explicit re-opt-in/reload; authority-scoped cleanup/credential rotation/return retry; offline logout; no provider network");
|
||||
} finally { await context.close(); await browser.close(); }
|
||||
@@ -0,0 +1,467 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
AgentPushClient, agentPushAuthorityScope, agentPushCursor, createAgentPresenceReporter, createAgentPushController,
|
||||
MAX_AGENT_PUSH_REVOCATIONS, parseAgentPushConfig, parseAgentPushConsent,
|
||||
} from "../src/lib/agent-push.ts";
|
||||
import { agentAuthFrame, applyAgentEvent, createAgentRoomState, parseAgentRoomEvent } from "../src/lib/agent-room.ts";
|
||||
|
||||
const sourceId = "4599d348-e053-4937-987d-1392746fb2ce";
|
||||
const replacementSourceId = "22222222-2222-4222-8222-222222222222";
|
||||
const configuration = () => ({ version: 1, enabled: true, webPushAvailable: true, apnsAvailable: false, sourceId, quarantined: false,
|
||||
vapidPublicKey: "B".repeat(87), policy: { presenceHeartbeatMs: 15000, presenceLeaseMs: 60000 } });
|
||||
const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; };
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
function fixture(overrides = {}, shared = {}) {
|
||||
let record = shared.record || null, subscription = null, permission = "default", support = "supported", config = configuration();
|
||||
const calls = [], states = [];
|
||||
const api = {
|
||||
config: async () => config,
|
||||
register: async (id, value) => { calls.push(["register", id, value]); },
|
||||
revoke: async id => { calls.push(["revoke", id]); },
|
||||
...overrides.api,
|
||||
};
|
||||
const makeSubscription = (endpoint = "https://push.example.test/opaque") => ({
|
||||
toJSON: () => ({ endpoint, keys: { p256dh: "fixture-public", auth: "fixture-auth" } }),
|
||||
unsubscribe: async () => { calls.push(["unsubscribe"]); subscription = null; return true; },
|
||||
});
|
||||
const platform = {
|
||||
support: () => support, permission: () => permission,
|
||||
requestPermission: () => { calls.push(["permission"]); permission = "granted"; return Promise.resolve(permission); },
|
||||
subscription: async () => subscription,
|
||||
subscribe: async key => { calls.push(["subscribe", key]); return subscription = makeSubscription(); },
|
||||
clearNotifications: async () => { calls.push(["clear"]); },
|
||||
...overrides.platform,
|
||||
};
|
||||
const options = {
|
||||
api, platform, read: () => record, write: value => { record = structuredClone(value); }, uuid: randomUUID,
|
||||
scope: async () => "a".repeat(64),
|
||||
lock: async operation => operation(), changed: state => states.push(state), ...shared.options,
|
||||
};
|
||||
const controller = createAgentPushController(options);
|
||||
return { controller, options, calls, states, api, platform, makeSubscription, record: () => record,
|
||||
setConfig(value) { config = value; }, setPermission(value) { permission = value; }, setSupport(value) { support = value; }, setSubscription(value) { subscription = value; } };
|
||||
}
|
||||
|
||||
test("explicit gesture requests permission before yielding; permission alone never opts in", async () => {
|
||||
const f = fixture(); f.setPermission("granted");
|
||||
await f.controller.refresh();
|
||||
assert.equal(f.record(), null); assert.deepEqual(f.calls, []);
|
||||
const enabling = f.controller.enable();
|
||||
assert.deepEqual(f.calls, [["permission"]], "request runs directly inside the click stack");
|
||||
await enabling;
|
||||
assert.equal(f.record().enabled, true);
|
||||
assert.equal(f.record().sourceId, sourceId);
|
||||
assert.equal(f.record().revocationPending, false);
|
||||
assert.equal(f.calls.filter(([name]) => name === "register").length, 1);
|
||||
await f.controller.refresh(); await f.controller.refresh();
|
||||
assert.equal(f.calls.filter(([name]) => name === "register").length, 1, "heartbeat does not repeatedly register an unchanged subscription");
|
||||
});
|
||||
|
||||
test("denial, disabled config, unsupported browser and iOS installation guidance do not subscribe", async () => {
|
||||
for (const support of ["unsupported", "install"]) {
|
||||
const f = fixture(); f.setSupport(support); await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.controller.state().canEnable, false); assert.deepEqual(f.calls, []);
|
||||
assert.match(f.controller.state().message, support === "install" ? /Home Screen/ : /HTTPS/);
|
||||
}
|
||||
const disabled = fixture(); disabled.setConfig({ ...configuration(), enabled: false });
|
||||
await disabled.controller.refresh(); await disabled.controller.enable(); assert.deepEqual(disabled.calls, []);
|
||||
const denied = fixture({ platform: { requestPermission: async () => "denied" } });
|
||||
await denied.controller.refresh(); await denied.controller.enable();
|
||||
assert.equal(denied.record().enabled, false); assert.equal(denied.calls.length, 0);
|
||||
assert.match(denied.controller.state().error, /not allowed/);
|
||||
});
|
||||
|
||||
test("registration failure rolls back subscription, persists revoke intent and never echoes provider errors", async () => {
|
||||
const f = fixture({ api: { register: async () => { throw new Error("https://private-provider/token-secret"); }, revoke: async () => { throw new Error("offline"); } } });
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().revocationPending, true);
|
||||
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
|
||||
assert.doesNotMatch(JSON.stringify(f.states), /private-provider|token-secret/);
|
||||
assert.equal(f.controller.state().canEnable, false);
|
||||
});
|
||||
|
||||
test("offline logout writes tombstone synchronously, unsubscribes locally and retries before any enable", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const id = f.record().installationId;
|
||||
f.api.revoke = async () => { throw new Error("offline"); };
|
||||
const disabling = f.controller.disable();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().revocationPending, true);
|
||||
await disabling;
|
||||
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
|
||||
const count = f.calls.filter(([name]) => name === "register").length;
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.calls.filter(([name]) => name === "register").length, count);
|
||||
f.api.revoke = async revoked => { assert.equal(revoked, id); };
|
||||
await f.controller.refresh();
|
||||
assert.equal(f.record().revocationPending, false); assert.equal(f.record().enabled, false);
|
||||
});
|
||||
|
||||
test("storage failures during logout still revoke, unsubscribe and close notifications", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
f.options.write = () => { throw new Error("quota"); };
|
||||
let removed = false; f.options.remove = () => { removed = true; };
|
||||
await f.controller.disable();
|
||||
assert.ok(removed); assert.equal(f.controller.state().enabled, false);
|
||||
for (const name of ["revoke", "unsubscribe", "clear"]) assert.ok(f.calls.some(([action]) => action === name));
|
||||
await f.controller.refresh();
|
||||
assert.equal(f.controller.state().enabled, false);
|
||||
});
|
||||
|
||||
test("a stuck cross-tab lock cannot prevent server retirement or local logout cleanup", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
f.options.lock = async () => { throw new Error("lock acquisition expired"); };
|
||||
await f.controller.disable();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().revocationPending, false);
|
||||
for (const name of ["revoke", "unsubscribe", "clear"]) assert.ok(f.calls.some(([action]) => action === name));
|
||||
});
|
||||
|
||||
test("synchronous permission API failures remain a recoverable opt-in error", async () => {
|
||||
const f = fixture({ platform: { requestPermission: () => { throw new Error("user gesture rejected"); } } });
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.record().enabled, false); assert.match(f.controller.state().error, /could not be requested/);
|
||||
});
|
||||
|
||||
test("subscription rotation upserts the same installation; permission revocation removes it", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const id = f.record().installationId;
|
||||
f.setSubscription(f.makeSubscription("https://push.example.test/rotated"));
|
||||
await f.controller.refresh();
|
||||
const registrations = f.calls.filter(([name]) => name === "register");
|
||||
assert.equal(registrations.length, 2); assert.ok(registrations.every(([, installation]) => installation === id));
|
||||
f.setPermission("denied"); await f.controller.refresh();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().revocationPending, false);
|
||||
});
|
||||
|
||||
test("logout while permission prompt is open cancels the older opt-in", async () => {
|
||||
const prompt = deferred(), f = fixture({ platform: { requestPermission: () => prompt.promise } });
|
||||
await f.controller.refresh(); const enabling = f.controller.enable();
|
||||
await f.controller.disable(); prompt.resolve("granted"); await enabling;
|
||||
assert.equal(f.record().enabled, false);
|
||||
assert.ok(!f.calls.some(([name]) => name === "subscribe" || name === "register"));
|
||||
});
|
||||
|
||||
test("two-tab enable → disable → enable uses permanent server tombstones and a new installation UUID", async () => {
|
||||
let sharedRecord = null, queue = Promise.resolve(), currentRegistration = false;
|
||||
const calls = [], pendingRegister = deferred(), retired = new Set(); let first = true;
|
||||
const common = { options: {
|
||||
read: () => sharedRecord, write: value => { sharedRecord = structuredClone(value); },
|
||||
lock: operation => { const running = queue.then(operation); queue = running.catch(() => undefined); return running; },
|
||||
} };
|
||||
const api = {
|
||||
register: async id => { calls.push("register"); if (first) { first = false; await pendingRegister.promise; } assert.ok(!retired.has(id), "retired UUID must never be reused"); currentRegistration = true; },
|
||||
revoke: async id => { calls.push("revoke"); retired.add(id); currentRegistration = false; },
|
||||
};
|
||||
const a = fixture({ api }, common), b = fixture({ api }, common);
|
||||
await a.controller.refresh(); await b.controller.refresh();
|
||||
const enabling = a.controller.enable(); await settle();
|
||||
assert.deepEqual(calls, ["register"]);
|
||||
const disabling = b.controller.disable();
|
||||
assert.equal(sharedRecord.enabled, false); assert.equal(sharedRecord.revocationPending, true);
|
||||
pendingRegister.resolve(); await Promise.all([enabling, disabling]);
|
||||
assert.equal(currentRegistration, false);
|
||||
const id = sharedRecord.installationId;
|
||||
await b.controller.enable();
|
||||
assert.equal(currentRegistration, true); assert.equal(sharedRecord.enabled, true); assert.notEqual(sharedRecord.installationId, id);
|
||||
assert.ok(retired.has(id));
|
||||
assert.equal(calls.at(-1), "register");
|
||||
});
|
||||
|
||||
test("a timed-out old PUT completing after DELETE cannot revive the retired installation or affect a new opt-in", async () => {
|
||||
const retired = new Set(), active = new Set(), late = deferred(); let firstId, lateStatus, first = true;
|
||||
const f = fixture({ api: {
|
||||
register: async id => {
|
||||
if (first) {
|
||||
first = false; firstId = id;
|
||||
late.promise.then(() => { lateStatus = retired.has(id) ? 409 : 200; if (lateStatus === 200) active.add(id); });
|
||||
throw new Error("request timed out while server is still processing");
|
||||
}
|
||||
assert.ok(!retired.has(id)); active.add(id);
|
||||
},
|
||||
revoke: async id => { retired.add(id); active.delete(id); },
|
||||
} });
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().revocationPending, false); assert.ok(retired.has(firstId));
|
||||
await f.controller.enable(); const currentId = f.record().installationId;
|
||||
assert.notEqual(currentId, firstId); assert.ok(active.has(currentId));
|
||||
late.resolve(); await settle();
|
||||
assert.equal(lateStatus, 409); assert.deepEqual([...active], [currentId]);
|
||||
});
|
||||
|
||||
test("authority changes retain original-server cleanup without issuing a misleading DELETE to the new server", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const oldId = f.record().installationId, registrations = f.calls.filter(([name]) => name === "register").length;
|
||||
f.options.scope = async () => "b".repeat(64);
|
||||
await f.controller.refresh(); await f.controller.refresh();
|
||||
assert.equal(f.record().enabled, false);
|
||||
assert.equal(f.record().revocationPending, false, "local unsubscribe succeeded, but old server cleanup stays queued");
|
||||
assert.deepEqual(f.record().pendingRevocations, [{ installationId: oldId, scope: "a".repeat(64) }]);
|
||||
assert.ok(!f.calls.some(([name]) => name === "revoke"), "new server's unknown-ID DELETE/204 cannot retire the original server registration");
|
||||
assert.equal(f.calls.filter(([name]) => name === "register").length, registrations);
|
||||
await f.controller.enable();
|
||||
const newId = f.record().installationId;
|
||||
assert.notEqual(newId, oldId); assert.equal(f.record().scope, "b".repeat(64)); assert.equal(f.record().enabled, true);
|
||||
assert.deepEqual(f.record().pendingRevocations, [{ installationId: oldId, scope: "a".repeat(64) }]);
|
||||
const reloaded = createAgentPushController(f.options);
|
||||
await reloaded.refresh();
|
||||
assert.deepEqual(f.record().pendingRevocations, [{ installationId: oldId, scope: "a".repeat(64) }], "queue survives a reload on B");
|
||||
assert.ok(!f.calls.some(([name]) => name === "revoke"));
|
||||
f.options.scope = async () => "a".repeat(64);
|
||||
await reloaded.refresh();
|
||||
assert.deepEqual(f.calls.filter(([name]) => name === "revoke"), [["revoke", oldId]], "returning with A credentials retries only A's intent");
|
||||
assert.deepEqual(f.record().pendingRevocations, [{ installationId: newId, scope: "b".repeat(64) }]);
|
||||
assert.equal(f.record().enabled, false);
|
||||
await reloaded.enable();
|
||||
assert.equal(f.record().enabled, true); assert.equal(f.record().scope, "a".repeat(64));
|
||||
assert.notEqual(f.record().installationId, oldId);
|
||||
});
|
||||
|
||||
test("revoked old credentials do not prevent fresh opt-in after same-server credential rotation", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const oldId = f.record().installationId;
|
||||
f.api.revoke = async () => { throw new Error("old credentials revoked"); };
|
||||
await f.controller.disable();
|
||||
assert.equal(f.record().revocationPending, true);
|
||||
f.options.scope = async () => "c".repeat(64);
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.record().enabled, true); assert.equal(f.record().scope, "c".repeat(64));
|
||||
assert.notEqual(f.record().installationId, oldId);
|
||||
assert.deepEqual(f.record().pendingRevocations, [{ installationId: oldId, scope: "a".repeat(64) }]);
|
||||
assert.doesNotMatch(JSON.stringify(f.record()), /credentials|provider|opaque|fixture-auth/);
|
||||
});
|
||||
|
||||
test("failed old-authority retries retain intent while other queued authorities are never contacted", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable(); await f.controller.disable();
|
||||
const queue = [{ installationId: randomUUID(), scope: "a".repeat(64) }, { installationId: randomUUID(), scope: "b".repeat(64) }];
|
||||
f.options.write({ ...f.record(), pendingRevocations: queue });
|
||||
const attempted = []; f.api.revoke = async id => { attempted.push(id); throw new Error("offline"); };
|
||||
await f.controller.refresh();
|
||||
assert.deepEqual(attempted, [queue[0].installationId]); assert.deepEqual(f.record().pendingRevocations, queue);
|
||||
await f.controller.enable();
|
||||
assert.equal(f.record().enabled, true); assert.deepEqual(f.record().pendingRevocations, queue);
|
||||
});
|
||||
|
||||
test("bounded revocation queue never silently evicts cleanup and gives actionable opt-in recovery", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable(); await f.controller.disable();
|
||||
const queue = Array.from({ length: MAX_AGENT_PUSH_REVOCATIONS }, () => ({ installationId: randomUUID(), scope: "b".repeat(64) }));
|
||||
f.options.write({ ...f.record(), pendingRevocations: queue });
|
||||
await f.controller.refresh();
|
||||
assert.equal(f.controller.state().canEnable, false); assert.match(f.controller.state().message, /Sign in to a previous server/);
|
||||
const count = f.calls.filter(([name]) => name === "register").length;
|
||||
await f.controller.enable();
|
||||
assert.deepEqual(f.record().pendingRevocations, queue); assert.equal(f.calls.filter(([name]) => name === "register").length, count);
|
||||
assert.ok(parseAgentPushConsent(JSON.stringify(f.record())));
|
||||
assert.equal(parseAgentPushConsent(JSON.stringify({ ...f.record(), pendingRevocations: [...queue, queue[0]] })), null);
|
||||
assert.equal(parseAgentPushConsent(JSON.stringify({ ...f.record(), pendingRevocations: [{ installationId: queue[0].installationId, scope: "raw-token" }] })), null);
|
||||
f.options.scope = async () => "b".repeat(64);
|
||||
await f.controller.refresh();
|
||||
assert.deepEqual(f.record().pendingRevocations, []); assert.equal(f.controller.state().canEnable, true);
|
||||
});
|
||||
|
||||
test("in-flight cleanup cannot overwrite a newer tab's consent revision", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const entered = deferred(), release = deferred();
|
||||
let reads = 0;
|
||||
f.options.scope = async () => {
|
||||
if (++reads === 2) { entered.resolve(); await release.promise; }
|
||||
return "a".repeat(64);
|
||||
};
|
||||
const disabling = f.controller.disable(); await entered.promise;
|
||||
const newer = { ...f.record(), installationId: randomUUID(), revision: randomUUID(), enabled: true, revocationPending: false };
|
||||
f.options.write(newer); release.resolve(); await disabling;
|
||||
assert.deepEqual(f.record(), newer);
|
||||
});
|
||||
|
||||
test("principal scope changing while permission is pending prevents registration", async () => {
|
||||
const prompt = deferred(), f = fixture({ platform: { requestPermission: () => prompt.promise } });
|
||||
await f.controller.refresh(); const enabling = f.controller.enable();
|
||||
f.options.scope = async () => "b".repeat(64);
|
||||
prompt.resolve("granted"); await enabling;
|
||||
assert.equal(f.record().enabled, false); assert.ok(!f.calls.some(([name]) => name === "subscribe" || name === "register"));
|
||||
});
|
||||
|
||||
test("authority changing during config fetch cannot enable against a mixed identity snapshot", async () => {
|
||||
const f = fixture({ api: { config: async () => { f.options.scope = async () => "b".repeat(64); return configuration(); } } });
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.controller.state().canEnable, false); assert.equal(f.record(), null); assert.deepEqual(f.calls, []);
|
||||
});
|
||||
|
||||
test("same backend/token with a replaced source invalidates persisted consent on reload and requires a new opt-in", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const old = structuredClone(f.record());
|
||||
f.setConfig({ ...configuration(), sourceId: replacementSourceId });
|
||||
const reloaded = createAgentPushController(f.options);
|
||||
await reloaded.refresh(); await reloaded.refresh();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().sourceId, sourceId);
|
||||
assert.equal(f.calls.filter(([name]) => name === "register").length, 1, "source replacement cannot reuse old consent");
|
||||
assert.ok(f.calls.some(([name, id]) => name === "revoke" && id === old.installationId));
|
||||
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
|
||||
await reloaded.enable();
|
||||
assert.equal(f.record().enabled, true); assert.equal(f.record().sourceId, replacementSourceId);
|
||||
assert.equal(f.record().scope, old.scope); assert.notEqual(f.record().installationId, old.installationId);
|
||||
assert.equal(f.calls.filter(([name]) => name === "permission").length, 2, "replacement requires another explicit permission gesture");
|
||||
});
|
||||
|
||||
test("null or invalid source prevents new opt-in even when transport is configured", async () => {
|
||||
for (const unknown of [null, undefined, "not-a-source-uuid"]) {
|
||||
const f = fixture(); f.setConfig({ ...configuration(), sourceId: unknown });
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.controller.state().canEnable, false); assert.equal(f.record(), null);
|
||||
assert.deepEqual(f.calls, [], "unknown source must not request permission, subscribe or register");
|
||||
}
|
||||
});
|
||||
|
||||
test("losing a known source retires old consent and never resumes it automatically", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const oldId = f.record().installationId;
|
||||
f.setConfig({ ...configuration(), sourceId: null });
|
||||
await f.controller.refresh();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.controller.state().canEnable, false);
|
||||
assert.ok(f.calls.some(([name, id]) => name === "revoke" && id === oldId));
|
||||
f.setConfig(configuration()); await f.controller.refresh();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.calls.filter(([name]) => name === "register").length, 1);
|
||||
});
|
||||
|
||||
test("legacy or malformed source bindings retain installation identity for retirement, not re-enrollment", async () => {
|
||||
for (const invalid of [undefined, null, "invalid-source"]) {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const oldId = f.record().installationId;
|
||||
const stored = parseAgentPushConsent(JSON.stringify({ ...f.record(), sourceId: invalid }));
|
||||
assert.equal(stored.installationId, oldId); assert.equal(stored.sourceId, undefined);
|
||||
f.options.write(stored);
|
||||
await createAgentPushController(f.options).refresh();
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.calls.filter(([name]) => name === "register").length, 1);
|
||||
assert.ok(f.calls.some(([name, id]) => name === "revoke" && id === oldId));
|
||||
}
|
||||
});
|
||||
|
||||
test("source change while permission is pending prevents subscription and retires the incomplete intent", async () => {
|
||||
const prompt = deferred(), f = fixture({ platform: { requestPermission: () => prompt.promise } });
|
||||
await f.controller.refresh(); const enabling = f.controller.enable();
|
||||
const oldId = f.record().installationId;
|
||||
f.setConfig({ ...configuration(), sourceId: replacementSourceId });
|
||||
f.setPermission("granted"); prompt.resolve("granted"); await enabling;
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().sourceId, sourceId);
|
||||
assert.ok(!f.calls.some(([name]) => name === "subscribe" || name === "register"));
|
||||
assert.ok(f.calls.some(([name, id]) => name === "revoke" && id === oldId));
|
||||
});
|
||||
|
||||
test("source change while subscribe is pending unsubscribes without registering", async () => {
|
||||
const entered = deferred(), release = deferred();
|
||||
const f = fixture({ platform: { subscribe: async () => {
|
||||
entered.resolve(); await release.promise;
|
||||
const subscription = f.makeSubscription(); f.setSubscription(subscription); return subscription;
|
||||
} } });
|
||||
await f.controller.refresh(); const enabling = f.controller.enable(); await entered.promise;
|
||||
f.setConfig({ ...configuration(), sourceId: replacementSourceId }); release.resolve(); await enabling;
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.calls.filter(([name]) => name === "register").length, 0);
|
||||
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
|
||||
});
|
||||
|
||||
test("source change during initial registration rolls back instead of persisting enabled consent", async () => {
|
||||
const entered = deferred(), release = deferred(), registered = [], retired = [];
|
||||
const f = fixture({ api: {
|
||||
register: async id => { registered.push(id); entered.resolve(); await release.promise; },
|
||||
revoke: async id => { retired.push(id); },
|
||||
} });
|
||||
await f.controller.refresh(); const enabling = f.controller.enable(); await entered.promise;
|
||||
f.setConfig({ ...configuration(), sourceId: replacementSourceId }); release.resolve(); await enabling;
|
||||
assert.equal(f.record().enabled, false); assert.equal(f.record().sourceId, sourceId);
|
||||
assert.deepEqual(retired, registered); assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
|
||||
});
|
||||
|
||||
test("source change during automatic rotation registration retires the source-bound installation", async () => {
|
||||
const f = fixture(); await f.controller.refresh(); await f.controller.enable();
|
||||
const oldId = f.record().installationId, entered = deferred(), release = deferred();
|
||||
f.setSubscription(f.makeSubscription("https://push.example.test/rotated"));
|
||||
f.api.register = async id => { assert.equal(id, oldId); entered.resolve(); await release.promise; };
|
||||
const refreshing = f.controller.refresh(); await entered.promise;
|
||||
f.setConfig({ ...configuration(), sourceId: replacementSourceId }); release.resolve(); await refreshing;
|
||||
assert.equal(f.record().enabled, false); assert.ok(f.calls.some(([name, id]) => name === "revoke" && id === oldId));
|
||||
});
|
||||
|
||||
test("source verification failure after registration fails closed and rolls back", async () => {
|
||||
const f = fixture({ api: { register: async () => { f.api.config = async () => { throw new Error("source unavailable"); }; } } });
|
||||
await f.controller.refresh(); await f.controller.enable();
|
||||
assert.equal(f.record().enabled, false); assert.ok(f.calls.some(([name]) => name === "revoke"));
|
||||
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
|
||||
});
|
||||
|
||||
test("attention is per-tab, ordered, focused while idle, and recent input persists until acknowledged", async () => {
|
||||
const rows = [], failure = deferred(); let focus = true;
|
||||
const a = createAgentPresenceReporter({ snapshot: () => ({ visibility: "visible", focused: focus }), send: async value => { rows.push(["a", value]); } });
|
||||
const b = createAgentPresenceReporter({ snapshot: () => ({ visibility: "hidden", focused: true }), send: async value => { rows.push(["b", value]); } });
|
||||
await a.report(); await b.report();
|
||||
assert.equal(rows[0][1].focused, true); assert.equal(rows[0][1].interacted, false);
|
||||
assert.equal(rows[1][1].focused, false); assert.equal(rows[1][1].sequence, 1);
|
||||
a.interact(); focus = false; await a.report(); await a.report();
|
||||
assert.equal(rows[2][1].interacted, true); assert.equal(rows[2][1].focused, false);
|
||||
assert.equal(rows[3][1].interacted, false); assert.equal(rows[3][1].sequence, 3);
|
||||
let attempts = 0;
|
||||
const c = createAgentPresenceReporter({ snapshot: () => ({ visibility: "visible", focused: false }), send: async value => {
|
||||
assert.equal(value.interacted, true); if (++attempts === 1) return failure.promise;
|
||||
} });
|
||||
c.interact(); const report = c.report(); failure.reject(new Error("offline")); await assert.rejects(report); await c.report();
|
||||
const id = randomUUID(), frame = JSON.parse(agentAuthFrame("fixture-token", "2", id));
|
||||
assert.equal(frame.clientKind, "web"); assert.equal(frame.presenceSessionId, id);
|
||||
assert.equal(JSON.parse(agentAuthFrame(null, "0", "not-an-id")).clientKind, undefined);
|
||||
});
|
||||
|
||||
test("read frames validate source/cursor and preserve existing read semantics", () => {
|
||||
const event = parseAgentRoomEvent(JSON.stringify({ type: "read_state", cursor: "9", updatedAt: null, sourceId }));
|
||||
assert.equal(applyAgentEvent(createAgentRoomState(), event).readCursor, "9");
|
||||
for (const cursor of ["-1", "1e5", "9007199254740992", "1".repeat(200)]) {
|
||||
assert.equal(agentPushCursor(cursor), false);
|
||||
assert.throws(() => parseAgentRoomEvent(JSON.stringify({ type: "read_state", cursor, updatedAt: null, sourceId })));
|
||||
}
|
||||
assert.throws(() => parseAgentRoomEvent(JSON.stringify({ type: "read_state", cursor: "1", updatedAt: null, sourceId: "https://evil.test" })));
|
||||
assert.equal(parseAgentPushConsent('{"enabled":true}'), null);
|
||||
assert.throws(() => parseAgentPushConfig({ ...configuration(), policy: { presenceHeartbeatMs: 1, presenceLeaseMs: 60000 } }));
|
||||
});
|
||||
|
||||
test("API keeps credentials in headers, validates receipts, handles 204 and redacts provider bodies", async () => {
|
||||
const id = randomUUID(), requests = []; let mode = "config";
|
||||
const api = new AgentPushClient({ baseUrl: "/api", token: () => "fixture-bearer", fetch: async (url, init) => {
|
||||
requests.push({ url, init });
|
||||
if (mode === "revoke") return new Response(null, { status: 204 });
|
||||
if (mode === "fail") return new Response(JSON.stringify({ error: "private-token-and-endpoint" }), { status: 500 });
|
||||
if (mode === "register") return Response.json({ installationId: id, transport: "web", enabled: true, version: 1 });
|
||||
if (mode === "read") return Response.json({ cursor: "0008", sourceId });
|
||||
return Response.json(configuration());
|
||||
} });
|
||||
await api.config(); mode = "register"; await api.register(id, { endpoint: "https://provider.test/endpoint-secret" });
|
||||
mode = "read"; assert.deepEqual(await api.readState(), { sourceId, cursor: "8" });
|
||||
mode = "revoke"; await api.revoke(id);
|
||||
mode = "fail"; await assert.rejects(api.revoke(id), error => !/private-token/.test(error.message));
|
||||
for (const request of requests) {
|
||||
assert.equal(request.init.headers.Authorization, "Bearer fixture-bearer");
|
||||
assert.equal(request.init.cache, "no-store"); assert.equal(request.init.redirect, "error");
|
||||
assert.doesNotMatch(request.url, /fixture-bearer|endpoint-secret/);
|
||||
}
|
||||
await assert.rejects(api.revoke("../../bad"));
|
||||
const unauthenticated = new AgentPushClient({ baseUrl: "/api", token: () => null, fetch: () => { throw new Error("must not send"); } });
|
||||
await assert.rejects(unauthenticated.config(), /Sign in/);
|
||||
});
|
||||
|
||||
test("authority-guarded API refuses mismatched credentials and pins the captured bearer across async hashing", async () => {
|
||||
const id = randomUUID(), requests = [], baseUrl = "https://sybil.example.test/api/";
|
||||
const scope = await agentPushAuthorityScope(baseUrl, "original-fixture-token");
|
||||
assert.equal(scope, await agentPushAuthorityScope("/api", "original-fixture-token", "https://sybil.example.test/"));
|
||||
assert.match(scope, /^[a-f0-9]{64}$/); assert.equal(await agentPushAuthorityScope(baseUrl, null), null);
|
||||
let token = "rotated-fixture-token";
|
||||
const api = new AgentPushClient({ baseUrl, token: () => token, fetch: async (url, init) => {
|
||||
requests.push({ url, init });
|
||||
return init.method === "DELETE" ? new Response(null, { status: 204 }) : Response.json({ installationId: id, transport: "web", enabled: true, version: 1 });
|
||||
} });
|
||||
await assert.rejects(api.revoke(id, scope));
|
||||
await assert.rejects(api.register(id, { endpoint: "https://provider.test/fixture" }, scope));
|
||||
assert.deepEqual(requests, [], "wrong authority cannot send a mutation or falsely acknowledge cleanup");
|
||||
token = "original-fixture-token";
|
||||
const deleting = api.revoke(id, scope); token = "rotated-fixture-token"; await deleting;
|
||||
token = "original-fixture-token";
|
||||
const registering = api.register(id, { endpoint: "https://provider.test/fixture" }, scope); token = "rotated-fixture-token"; await registering;
|
||||
assert.equal(requests.length, 2);
|
||||
assert.ok(requests.every(({ init }) => init.headers.Authorization === "Bearer original-fixture-token"));
|
||||
assert.ok(requests.every(({ url }) => !url.includes("fixture-token")));
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
AgentRoomClient, advanceAgentCursor, agentAuthFrame, agentDisplayMessages, agentUnreadCount,
|
||||
applyAgentEvent, applyAgentPage, applyAgentReadState, createAgentReadWriter,
|
||||
AgentRoomClient, AgentReadSourceChangedError, advanceAgentCursor, agentAuthFrame, agentDisplayMessages, agentUnreadCount,
|
||||
applyAgentEvent, applyAgentPage, applyAgentReadState, createAgentReadSession, createAgentReadWriter,
|
||||
createAgentRoomState, mergeAgentMessages, normalizeAgentCursor, parseAgentRoomEvent, syncAgentHistory,
|
||||
} from "../src/lib/agent-room.ts";
|
||||
import { createAgentOptimisticOutbox } from "../src/lib/agent-optimistic-outbox.ts";
|
||||
@@ -16,6 +16,9 @@ const page = (cursor, messages = [], hasMore = false) => ({
|
||||
conversationId: "1", messages, cursor, beforeCursor: messages.length ? String(messages[0].metadata.entryId) : cursor, hasMore,
|
||||
});
|
||||
const activity = (queuedMessages = []) => ({ state: "idle", isThinking: false, queued: queuedMessages.length, backgroundWorkers: 0, tools: [], queuedMessages });
|
||||
const sourceA = "4599d348-e053-4937-987d-1392746fb2ce", sourceB = "22222222-2222-4222-8222-222222222222";
|
||||
const deferred = () => { let resolve; const promise = new Promise(yes => { resolve = yes; }); return { promise, resolve }; };
|
||||
const sourceRoom = () => applyAgentPage(applyAgentReadState(createAgentRoomState(), { sourceId: sourceA, cursor: "90", updatedAt: null }), page("100", [message(100)]));
|
||||
|
||||
test("tool starts and results merge across replay without downgrading completed cards", () => {
|
||||
const start = message(2, "tool", { id: "tool:1:call1", metadata: { kind: "tool_call", entryId: 2, status: "initiated", args: { query: "cookie" }, startedAt: "2026-10-14T10:00:00Z" } });
|
||||
@@ -113,6 +116,93 @@ test("read acknowledgments coalesce concurrent seen snapshots and reject unackno
|
||||
await assert.rejects(broken.request("2"), /did not acknowledge/);
|
||||
});
|
||||
|
||||
test("source replacement through GET or WS quiesces queued old-history reads without relabeling their cursor", async () => {
|
||||
for (const via of ["GET", "WS"]) {
|
||||
let room = sourceRoom(); const saved = [], invalidated = [];
|
||||
const session = createAgentReadSession({ initial: room,
|
||||
save: async (cursor, sourceId) => { saved.push({ cursor, sourceId }); throw new Error("temporarily offline"); },
|
||||
apply: read => { room = applyAgentReadState(room, read); }, invalidated: error => invalidated.push(error),
|
||||
});
|
||||
await assert.rejects(session.request("100", sourceA), /temporarily offline/);
|
||||
const replacement = { cursor: "0", sourceId: sourceB, updatedAt: null };
|
||||
const incoming = via === "WS" ? parseAgentRoomEvent(JSON.stringify({ type: "read_state", ...replacement })) : replacement;
|
||||
assert.throws(() => session.receive(incoming), AgentReadSourceChangedError);
|
||||
for (let i = 0; i < 3; i++) await session.flush();
|
||||
await assert.rejects(session.request("100", sourceA), AgentReadSourceChangedError);
|
||||
await assert.rejects(session.request("5", sourceB), AgentReadSourceChangedError);
|
||||
assert.deepEqual(saved, [{ cursor: "100", sourceId: sourceA }], `${via}: no write to B and no retry loop`);
|
||||
assert.equal(room.sourceId, sourceA); assert.equal(room.readCursor, "90"); assert.equal(room.cursor, "100");
|
||||
assert.equal(session.sourceId(), sourceA); assert.equal(invalidated.length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test("source replacement cancels an in-flight old read and prevents a coalesced larger write", async () => {
|
||||
let room = sourceRoom(); const gate = deferred(), saved = [];
|
||||
const session = createAgentReadSession({ initial: room,
|
||||
save: async (cursor, sourceId) => { saved.push({ cursor, sourceId }); return gate.promise; },
|
||||
apply: read => { room = applyAgentReadState(room, read); },
|
||||
});
|
||||
const first = session.request("100", sourceA), second = session.request("110", sourceA);
|
||||
assert.throws(() => session.receive({ cursor: "0", sourceId: sourceB, updatedAt: null }), AgentReadSourceChangedError);
|
||||
gate.resolve({ cursor: "100", sourceId: sourceA, updatedAt: null });
|
||||
await Promise.all([first, second]); await session.flush();
|
||||
assert.deepEqual(saved, [{ cursor: "100", sourceId: sourceA }]);
|
||||
assert.equal(room.sourceId, sourceA); assert.equal(room.readCursor, "90");
|
||||
});
|
||||
|
||||
test("mismatched acknowledgment and server409 stop retries without applying a read to new history", async () => {
|
||||
for (const mode of ["ack", "409"]) {
|
||||
let room = sourceRoom(), saves = 0, invalidated = 0;
|
||||
const session = createAgentReadSession({ initial: room,
|
||||
save: async () => { saves++; if (mode === "409") throw Object.assign(new Error("cursor not valid for this source"), { status: 409 });
|
||||
return { cursor: "100", sourceId: sourceB, updatedAt: null }; },
|
||||
apply: read => { room = applyAgentReadState(room, read); }, invalidated: () => invalidated++,
|
||||
});
|
||||
await assert.rejects(session.request("100", sourceA), AgentReadSourceChangedError);
|
||||
await session.flush(); await session.flush();
|
||||
await assert.rejects(session.request("101", sourceA), AgentReadSourceChangedError);
|
||||
assert.equal(saves, 1); assert.equal(invalidated, 1); assert.equal(room.readCursor, "90"); assert.equal(room.sourceId, sourceA);
|
||||
}
|
||||
});
|
||||
|
||||
test("read writer stops after an ignored acknowledgment instead of repeating the same PUT forever", async () => {
|
||||
let saves = 0;
|
||||
const writer = createAgentReadWriter({ current: () => "0", save: async cursor => { saves++; return { cursor, updatedAt: null }; }, apply: () => {} });
|
||||
await assert.rejects(writer.request("2"), /did not acknowledge/);
|
||||
await writer.flush(); await writer.request("3"); assert.equal(saves, 1);
|
||||
});
|
||||
|
||||
test("legacy source-absent sessions stay compatible but cannot adopt a source after rendering old history", async () => {
|
||||
let room = applyAgentPage(createAgentRoomState(), page("5", [message(5)])); const saved = [];
|
||||
const session = createAgentReadSession({ initial: room,
|
||||
save: async (cursor, sourceId) => { saved.push({ cursor, sourceId }); return { cursor, updatedAt: null }; },
|
||||
apply: read => { room = applyAgentReadState(room, read); },
|
||||
});
|
||||
session.receive({ cursor: "0", updatedAt: null });
|
||||
assert.equal(room.sourceId, null);
|
||||
await session.request("5", room.sourceId);
|
||||
assert.deepEqual(saved, [{ cursor: "5", sourceId: null }]); assert.equal(room.readCursor, "5");
|
||||
assert.throws(() => session.receive({ cursor: "0", sourceId: sourceB, updatedAt: null }), AgentReadSourceChangedError);
|
||||
await session.flush(); assert.equal(saved.length, 1);
|
||||
assert.throws(() => applyAgentReadState(applyAgentPage(createAgentRoomState(), page("5", [message(5)])), { cursor: "0", sourceId: sourceA, updatedAt: null }), AgentReadSourceChangedError);
|
||||
assert.throws(() => applyAgentReadState(sourceRoom(), { cursor: "0", updatedAt: null }), AgentReadSourceChangedError);
|
||||
});
|
||||
|
||||
test("rendered snapshot source must match the pinned session and new sessions cannot read before binding", async () => {
|
||||
for (const initial of [createAgentRoomState(), sourceRoom()]) {
|
||||
const session = createAgentReadSession({ initial, save: async () => assert.fail("must not send unbound or relabeled reads"), apply: () => {} });
|
||||
await assert.rejects(session.request("100", sourceB), AgentReadSourceChangedError); await session.flush();
|
||||
}
|
||||
let room = createAgentRoomState(); const saved = [];
|
||||
const session = createAgentReadSession({ initial: room,
|
||||
save: async (cursor, sourceId) => { saved.push({ cursor, sourceId }); return { cursor, sourceId, updatedAt: null }; },
|
||||
apply: read => { room = applyAgentReadState(room, read); },
|
||||
});
|
||||
session.receive({ cursor: "0", sourceId: sourceA, updatedAt: null });
|
||||
room = applyAgentPage(room, page("5", [message(5)])); await session.request(room.cursor, room.sourceId);
|
||||
assert.deepEqual(saved, [{ cursor: "5", sourceId: sourceA }]); assert.equal(room.readCursor, "5");
|
||||
});
|
||||
|
||||
test("failed persistence after acknowledgment retains the original receipt key across reload", async () => {
|
||||
let stored = [], writes = 0;
|
||||
const storage = { read: () => structuredClone(stored), write: rows => {
|
||||
@@ -168,6 +258,18 @@ test("client uses Sybil auth and routes while websocket credentials remain in th
|
||||
assert.deepEqual(JSON.parse(agentAuthFrame(token, "42")), { type: "auth", token, after: "42" });
|
||||
});
|
||||
|
||||
test("client sends the pinned source and exposes409 without requiring a JSON response body", async () => {
|
||||
for (const json of [true, false]) {
|
||||
let body;
|
||||
const client = new AgentRoomClient({ fetch: async (_url, init) => {
|
||||
body = JSON.parse(init.body);
|
||||
return json ? Response.json({ message: "Read source changed" }, { status: 409 }) : new Response(null, { status: 409 });
|
||||
} });
|
||||
await assert.rejects(client.markRead("100", undefined, sourceA), error => error.status === 409);
|
||||
assert.deepEqual(body, { cursor: "100", sourceId: sourceA });
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed successful receipts keep optimistic messages retryable under the original request ID", async () => {
|
||||
const requests = [];
|
||||
let response = {};
|
||||
|
||||
Reference in New Issue
Block a user