import { describe, expect, it, vi } from "vitest"; import { WEB_PUSH_PROTOCOLS, webPushSuccess, type PushAuthoritySnapshot, } from "../../src/contracts/web-push.ts"; import { createPushAssociationFenceStore } from "../../src/adapters/web-push/push-association-fence-store.ts"; import { createWebPushSubscriptionAdapter, type WindowPushSubscriptionFacade, } from "../../src/adapters/web-push/push-subscription-adapter.ts"; import type { WebPushRegistrationGateway } from "../../src/adapters/web-push/push-registration-gateway.ts"; import type { TimeoutScheduler } from "../../src/adapters/web-push/runtime-support.ts"; import { createFakePushControlStoreDependencies, } from "../helpers/fake-push-control-repository.ts"; const now = Date.parse("2026-07-28T00:00:00.000Z"); const authority = Object.freeze({ fenceGeneration: "fence_01", sessionBindingEpoch: "session_01", releaseEpoch: "release_01", }); const nextAuthority = Object.freeze({ fenceGeneration: "fence_02", sessionBindingEpoch: "session_02", releaseEpoch: "release_01", }); function bytes(length: number, first?: number): Uint8Array { const value = new Uint8Array(new ArrayBuffer(length)); value.fill(7); if (first !== undefined) value[0] = first; return value; } const applicationServerKey = bytes(65, 4); const vapidPublicKey = Buffer.from(applicationServerKey).toString("base64url"); function subscription( unsubscribe = vi.fn(async () => true), ): WindowPushSubscriptionFacade { return { endpoint: "https://push.example.test/subscription/opaque", expirationTime: null, options: { applicationServerKey: applicationServerKey.slice().buffer, }, getKey(name) { return name === "p256dh" ? bytes(65).buffer : bytes(16).buffer; }, unsubscribe, }; } function gateway( overrides: Partial = {}, ): WebPushRegistrationGateway { return { register: async () => webPushSuccess({ associationEpoch: "association_01", sessionBindingEpoch: "session_01", }), reconcile: async () => webPushSuccess({ state: "ACTIVE", associationEpoch: "association_01", sessionBindingEpoch: "session_01", }), revoke: async () => webPushSuccess({ state: "REVOKED" }), ...overrides, }; } async function activeFenceStore() { const store = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const prepared = await store.prepare({ authority, updatedAt: "2026-07-28T00:00:00.000Z", }); if (!prepared.ok) throw new Error("expected prepared control"); const active = await store.activate({ expectedRevision: prepared.value.revision, authority, associationEpoch: "association_01", updatedAt: "2026-07-28T00:00:01.000Z", }); if (!active.ok) throw new Error("expected active control"); return store; } function manualScheduler(): Readonly<{ scheduler: TimeoutScheduler; expireAll(): void; }> { let sequence = 0; const callbacks = new Map void>(); return { scheduler: { setTimeout(callback) { sequence += 1; callbacks.set(sequence, callback); return sequence; }, clearTimeout(handle) { if (typeof handle === "number") callbacks.delete(handle); }, }, expireAll() { for (const callback of [...callbacks.values()]) callback(); }, }; } describe("Web Push window subscription adapter", () => { it("requests permission only from an explicit action, registers, fences, and inspects READY", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const native = subscription(); let current: WindowPushSubscriptionFacade | null = null; const subscribe = vi.fn(async (input) => { expect(input.userVisibleOnly).toBe(true); expect([...input.applicationServerKey]).toEqual([ ...applicationServerKey, ]); current = native; return native; }); let permission: "default" | "granted" = "default"; const requestPermission = vi.fn(async () => { permission = "granted"; return permission; }); const register = vi.fn(gateway().register); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => permission, requestPermission, }, registration: { active: true, pushManager: { getSubscription: async () => current, subscribe, }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ register }), vapidPublicKey, lockManager: navigator.locks, now: () => now, idempotencyKeyFactory: () => "idempotency_01", }); expect( await adapter.enable({ authority, signal: new AbortController().signal, }), ).toEqual({ ok: true, value: { state: "PUSH_READY" } }); expect(requestPermission).toHaveBeenCalledOnce(); expect(subscribe).toHaveBeenCalledOnce(); expect(register).toHaveBeenCalledOnce(); expect( await adapter.inspect({ authority }), ).toEqual({ ok: true, value: { state: "PUSH_READY" } }); const control = await fenceStore.read(); expect(control).toMatchObject({ ok: true, value: { control: { association: { state: "ACTIVE", associationEpoch: "association_01", }, }, }, }); }); it("keeps denied and absent-user-activation flows side-effect free", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const subscribe = vi.fn(async () => subscription()); const register = vi.fn(gateway().register); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => false, permission: { permission: () => "default", requestPermission: async () => "denied", }, registration: { active: true, pushManager: { getSubscription: async () => null, subscribe, }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ register }), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); expect( await adapter.enable({ authority, signal: new AbortController().signal, }), ).toMatchObject({ ok: false, error: { code: "PERMISSION_DENIED" }, }); expect(subscribe).not.toHaveBeenCalled(); expect(register).not.toHaveBeenCalled(); expect(await fenceStore.read()).toEqual({ ok: true, value: null }); }); // 06-02 (D-4). Only a subscription this call created is unsubscribed; an // existing one may belong to another tab's association. it.each([ { existing: true, unsubscribeCalls: 0 }, { existing: false, unsubscribeCalls: 1 }, ])("compensates a stale backend session binding without activating local authority (existing native: $existing)", async ({ existing, unsubscribeCalls }) => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const unsubscribe = vi.fn(async () => true); const native = subscription(unsubscribe); const revoke = vi.fn(gateway().revoke); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => (existing ? native : null), subscribe: async () => native, }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ register: async () => webPushSuccess({ associationEpoch: "association_stale", sessionBindingEpoch: "session_old", }), revoke, }), vapidPublicKey, lockManager: navigator.locks, now: () => now, idempotencyKeyFactory: () => "idempotency_01", }); expect( await adapter.enable({ authority, signal: new AbortController().signal, }), ).toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "SESSION_AUTHORITY_CHANGED", }, }); expect(revoke).toHaveBeenCalledWith({ associationEpoch: "association_stale", signal: expect.any(AbortSignal), }); expect(unsubscribe).toHaveBeenCalledTimes(unsubscribeCalls); expect(await fenceStore.read()).toMatchObject({ ok: true, value: { control: { association: { state: "UNASSOCIATED" } }, }, }); }); it("commits the logout fence first, then revokes backend/native state and closes owned notifications", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const prepared = await fenceStore.prepare({ authority, updatedAt: "2026-07-28T00:00:00.000Z", }); if (!prepared.ok) throw new Error("expected prepared control"); await fenceStore.activate({ expectedRevision: prepared.value.revision, authority, associationEpoch: "association_01", updatedAt: "2026-07-28T00:00:01.000Z", }); const unsubscribe = vi.fn(async () => true); const native = subscription(unsubscribe); const notificationClose = vi.fn(); const revoke = vi.fn(async () => { const control = await fenceStore.read(); expect(control).toMatchObject({ ok: true, value: { control: { fenceGeneration: "fence_02", association: { state: "REVOKED" }, }, }, }); return webPushSuccess({ state: "REVOKED" as const }); }); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => native, subscribe: async () => native, }, getNotifications: async () => [ { data: { protocol: WEB_PUSH_PROTOCOLS.click, notificationId: "notification_01", routeIntent: "OPEN_INBOX", associationEpoch: "association_01", releaseEpoch: "release_01", expiresAt: "2026-07-28T01:00:00.000Z", }, close: notificationClose, }, ], }, fenceStore, gateway: gateway({ revoke }), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); expect( await adapter.revoke({ previousAuthority: authority, nextAuthority, }), ).toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "REVOKED" }, }); expect(revoke).toHaveBeenCalledWith({ associationEpoch: "association_01", signal: expect.any(AbortSignal), }); expect(unsubscribe).toHaveBeenCalledOnce(); expect(notificationClose).toHaveBeenCalledOnce(); }); it("does not clean the current native subscription for a stale revoke authority", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const prepared = await fenceStore.prepare({ authority: nextAuthority, updatedAt: "2026-07-28T00:00:00.000Z", }); if (!prepared.ok) throw new Error("expected prepared control"); const activated = await fenceStore.activate({ expectedRevision: prepared.value.revision, authority: nextAuthority, associationEpoch: "association_new", updatedAt: "2026-07-28T00:00:01.000Z", }); if (!activated.ok) throw new Error("expected active control"); const unsubscribe = vi.fn(async () => true); const getSubscription = vi.fn(async () => subscription(unsubscribe), ); const notificationClose = vi.fn(); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription, subscribe: async () => subscription(unsubscribe), }, getNotifications: async () => [ { data: { protocol: WEB_PUSH_PROTOCOLS.click, notificationId: "notification_new", routeIntent: "OPEN_INBOX", associationEpoch: "association_new", releaseEpoch: "release_01", expiresAt: "2026-07-28T01:00:00.000Z", }, close: notificationClose, }, ], }, fenceStore, gateway: gateway(), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); await expect( adapter.revoke({ previousAuthority: authority, nextAuthority, }), ).resolves.toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "LOCAL_FENCE_UNSAFE", }, }); expect(getSubscription).not.toHaveBeenCalled(); expect(unsubscribe).not.toHaveBeenCalled(); expect(notificationClose).not.toHaveBeenCalled(); }); it("does not clean a captured old subscription after a newer association commits", async () => { const fenceStore = await activeFenceStore(); const unsubscribe = vi.fn(async () => true); const native = subscription(unsubscribe); const notificationClose = vi.fn(); const revoke = vi.fn(async () => { const current = await fenceStore.read(); if (!current.ok || !current.value) { throw new Error("expected rotated control"); } const activated = await fenceStore.activate({ expectedRevision: current.value.revision, authority: nextAuthority, associationEpoch: "association_new", updatedAt: "2026-07-28T00:00:02.000Z", }); if (!activated.ok) throw new Error("expected new association"); return webPushSuccess({ state: "REVOKED" as const }); }); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => native, subscribe: async () => native, }, getNotifications: async () => [ { data: { protocol: WEB_PUSH_PROTOCOLS.click, notificationId: "notification_old", routeIntent: "OPEN_INBOX", associationEpoch: "association_01", releaseEpoch: "release_01", expiresAt: "2026-07-28T01:00:00.000Z", }, close: notificationClose, }, ], }, fenceStore, gateway: gateway({ revoke }), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); await expect( adapter.revoke({ previousAuthority: authority, nextAuthority, }), ).resolves.toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS", }, }); expect(unsubscribe).not.toHaveBeenCalled(); expect(notificationClose).not.toHaveBeenCalled(); await expect(fenceStore.read()).resolves.toMatchObject({ ok: true, value: { control: { association: { state: "ACTIVE", associationEpoch: "association_new", }, }, }, }); }); it("fences an ACTIVE association when notification permission drifts", async () => { const fenceStore = await activeFenceStore(); const unsubscribe = vi.fn(async () => true); const notificationClose = vi.fn(); const revoke = vi.fn(async () => webPushSuccess({ state: "REVOKED" as const }), ); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => false, permission: { permission: () => "denied", requestPermission: async () => "denied", }, registration: { active: true, pushManager: { getSubscription: async () => subscription(unsubscribe), subscribe: async () => subscription(unsubscribe), }, getNotifications: async () => [ { data: { protocol: WEB_PUSH_PROTOCOLS.click, notificationId: "notification_expired", routeIntent: "OPEN_INBOX", associationEpoch: "association_01", releaseEpoch: "release_01", expiresAt: "2026-07-27T00:00:00.000Z", }, close: notificationClose, }, ], }, fenceStore, gateway: gateway({ revoke }), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); expect(await adapter.reconcile({ authority })).toEqual({ ok: true, value: { state: "PUSH_DENIED" }, }); expect(await fenceStore.read()).toMatchObject({ ok: true, value: { control: { association: { state: "REVOKED", associationEpoch: "association_01", }, }, }, }); expect(revoke).toHaveBeenCalledOnce(); expect(unsubscribe).toHaveBeenCalledOnce(); expect(notificationClose).toHaveBeenCalledOnce(); }); it("revokes local, backend, and native state on VAPID key drift", async () => { const fenceStore = await activeFenceStore(); const unsubscribe = vi.fn(async () => true); const native = subscription(unsubscribe); const wrongApplicationServerKey = applicationServerKey.slice(); wrongApplicationServerKey[1] = 99; const mismatched: WindowPushSubscriptionFacade = { ...native, options: { applicationServerKey: wrongApplicationServerKey.buffer, }, }; const revoke = vi.fn(async () => webPushSuccess({ state: "REVOKED" as const }), ); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => mismatched, subscribe: async () => mismatched, }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ revoke }), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); expect(await adapter.reconcile({ authority })).toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "SUBSCRIPTION_KEY_MISMATCH", }, }); expect(await fenceStore.read()).toMatchObject({ ok: true, value: { control: { association: { state: "REVOKED", associationEpoch: "association_01", }, }, }, }); expect(revoke).toHaveBeenCalledOnce(); expect(unsubscribe).toHaveBeenCalledOnce(); }); it("bounds a non-cooperative native subscription inspection", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const clock = manualScheduler(); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: () => new Promise(() => {}), subscribe: async () => subscription(), }, getNotifications: async () => [], }, fenceStore, gateway: gateway(), vapidPublicKey, lockManager: navigator.locks, nativeOperationDeadlineMs: 1, scheduler: clock.scheduler, }); const inspection = adapter.inspect({ authority }); await Promise.resolve(); clock.expireAll(); expect(await inspection).toMatchObject({ ok: false, error: { code: "DEADLINE_EXCEEDED" }, }); }); it("aborts a non-cooperative native operation on dispose", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: () => new Promise(() => {}), subscribe: async () => subscription(), }, getNotifications: async () => [], }, fenceStore, gateway: gateway(), vapidPublicKey, lockManager: navigator.locks, }); const inspection = adapter.inspect({ authority }); await Promise.resolve(); adapter.dispose(); expect(await inspection).toMatchObject({ ok: false, error: { code: "ABORTED" }, }); }); it("maps a throwing browser facade and releases the exclusive lease", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission() { throw new Error("permission provider unavailable"); }, requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => null, subscribe: async () => subscription(), }, getNotifications: async () => [], }, fenceStore, gateway: gateway(), vapidPublicKey, lockManager: navigator.locks, }); for (let attempt = 0; attempt < 2; attempt += 1) { await expect( adapter.inspect({ authority }), ).resolves.toMatchObject({ ok: false, error: { code: "NATIVE_FAILURE", operation: "SUBSCRIPTION_INSPECT", }, }); } }); it("bounds a non-cooperative backend register and revokes its late commit", async () => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const clock = manualScheduler(); let signalRegisterStarted: (() => void) | undefined; const registerStarted = new Promise((resolve) => { signalRegisterStarted = resolve; }); let finishRegister: | (( result: Awaited< ReturnType >, ) => void) | undefined; const lateRegister = new Promise< Awaited> >((resolve) => { finishRegister = resolve; }); const revoke = vi.fn(async () => webPushSuccess({ state: "REVOKED" as const }), ); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => subscription(), subscribe: async () => subscription(), }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ register: async () => { signalRegisterStarted?.(); return await lateRegister; }, revoke, }), vapidPublicKey, lockManager: navigator.locks, backendOperationDeadlineMs: 1, scheduler: clock.scheduler, idempotencyKeyFactory: () => "idempotency_01", }); const enabling = adapter.enable({ authority, signal: new AbortController().signal, }); await registerStarted; clock.expireAll(); expect(await enabling).toMatchObject({ ok: false, error: { code: "DEADLINE_EXCEEDED" }, }); finishRegister?.( webPushSuccess({ associationEpoch: "association_late", sessionBindingEpoch: "session_01", }), ); for (let turn = 0; turn < 8; turn += 1) { await Promise.resolve(); } expect(revoke).toHaveBeenCalledWith({ associationEpoch: "association_late", signal: expect.any(AbortSignal), }); expect(await fenceStore.read()).toMatchObject({ ok: true, value: { control: { association: { state: "UNASSOCIATED" } }, }, }); }); }); /** * R-6.7. A server ABSENT answer is re-registered only when this browser's * local association was ACTIVE (the server lost it). A REVOKED or * UNASSOCIATED fence with a leftover native subscription must not sign the * current account up without its own opt-in. */ describe("Web Push reconcile with a server ABSENT association (R-6.7)", () => { function reconcileAdapter( fenceStore: ReturnType, native: WindowPushSubscriptionFacade, register: WebPushRegistrationGateway["register"], ) { return createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => false, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => native, subscribe: async () => native, }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ register, reconcile: async () => webPushSuccess({ state: "ABSENT" as const }), }), vapidPublicKey, lockManager: navigator.locks, now: () => now, idempotencyKeyFactory: () => "idempotency_02", }); } it("re-registers when the local association is ACTIVE (crash recovery)", async () => { const fenceStore = await activeFenceStore(); const unsubscribe = vi.fn(async () => true); const register = vi.fn(async () => webPushSuccess({ associationEpoch: "association_02", sessionBindingEpoch: "session_01", }), ); const adapter = reconcileAdapter( fenceStore, subscription(unsubscribe), register, ); expect(await adapter.reconcile({ authority })).toEqual({ ok: true, value: { state: "PUSH_READY" }, }); expect(register).toHaveBeenCalledOnce(); expect(unsubscribe).not.toHaveBeenCalled(); }); /** Logout rotated the fence to the next account, but unsubscribe failed. */ async function revokedForNextAccount() { const fenceStore = await activeFenceStore(); const current = await fenceStore.read(); if (!current.ok || !current.value) throw new Error("expected control"); const revoked = await fenceStore.rotateAndRevoke({ expectedRevision: current.value.revision, previousAuthority: authority, nextAuthority, updatedAt: "2026-07-28T00:00:02.000Z", }); if (!revoked.ok) throw new Error("expected revoked control"); return fenceStore; } it.each([ { state: "REVOKED", fenceStore: revokedForNextAccount }, { state: "UNASSOCIATED", fenceStore: async () => createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ), }, ])( "unsubscribes instead of registering when the local association is $state", async ({ fenceStore }) => { const unsubscribe = vi.fn(async () => true); // The backend would accept the next account's registration. const register = vi.fn(async () => webPushSuccess({ associationEpoch: "association_02", sessionBindingEpoch: nextAuthority.sessionBindingEpoch, }), ); const adapter = reconcileAdapter( await fenceStore(), subscription(unsubscribe), register, ); expect(await adapter.reconcile({ authority: nextAuthority })).toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "BACKEND_ASSOCIATION_MISSING", }, }); expect(register).not.toHaveBeenCalled(); expect(unsubscribe).toHaveBeenCalledOnce(); }, ); }); /** * 06-02 (D-4). The native subscription is one per service worker registration * and the fence record one per origin, so every tab shares both. enable, * reconcile and revoke hold the origin-wide `web-push-control` Web Lock * (Node's `navigator.locks` here, shared by both adapters like two tabs), and * a compensation unsubscribes only a subscription its own call created. */ describe("06-02 two tabs share one native subscription and one fence", () => { function sharedTabs( reconcileAnswer: ( serverAssociation: string | null, ) => Promise<"WAIT_FOR_REGISTER" | "NOW">, lockManager: Pick | null = navigator.locks, ) { const dependencies = createFakePushControlStoreDependencies(); const unsubscribe = vi.fn(async () => { current = null; return true; }); const native = subscription(unsubscribe); let current: WindowPushSubscriptionFacade | null = null; const server: { association: string | null } = { association: null }; let releaseRegister!: () => void; const registerGate = new Promise((resolve) => { releaseRegister = resolve; }); let registerReached!: () => void; const registerStarted = new Promise((resolve) => { registerReached = resolve; }); const shared: WebPushRegistrationGateway = { async register() { registerReached(); await registerGate; server.association = "association_01"; return webPushSuccess({ associationEpoch: "association_01", sessionBindingEpoch: "session_01", }); }, async reconcile() { if ((await reconcileAnswer(server.association)) === "WAIT_FOR_REGISTER") { await registerGate; } return webPushSuccess( server.association ? { state: "ACTIVE" as const, associationEpoch: server.association, sessionBindingEpoch: "session_01", } : { state: "ABSENT" as const }, ); }, async revoke(input) { if (server.association === input.associationEpoch) { server.association = null; } return webPushSuccess({ state: "REVOKED" as const }); }, }; function tab(activation: boolean) { return createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => activation, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => current, subscribe: async () => { current = native; return native; }, }, getNotifications: async () => [], }, fenceStore: createPushAssociationFenceStore(dependencies), gateway: shared, vapidPublicKey, now: () => now, ...(lockManager ? { lockManager } : {}), }); } return { tab, server, unsubscribe, registerStarted, releaseRegister: () => releaseRegister(), nativeAlive: () => current === native, fence: async () => await createPushAssociationFenceStore(dependencies).read(), }; } async function raceEnableWithReconcile( tabs: ReturnType, ) { const tab1 = tabs.tab(true); const tab2 = tabs.tab(false); const enabling = tab1.enable({ authority, signal: new AbortController().signal, }); // Tab 1 prepared the fence, subscribed and is waiting on register. await tabs.registerStarted; const reconciling = tab2.reconcile({ authority }); await new Promise((resolve) => setTimeout(resolve, 0)); tabs.releaseRegister(); return await Promise.all([enabling, reconciling]); } function expectReadyTabsStillReceive( tabs: ReturnType, results: readonly unknown[], ) { const ready = { ok: true, value: { state: "PUSH_READY" } }; expect(results).toContainEqual(ready); expect(tabs.unsubscribe).not.toHaveBeenCalled(); expect(tabs.nativeAlive()).toBe(true); expect(tabs.server.association).toBe("association_01"); } it("keeps the shared state when the reconciling tab would win the fence CAS", async () => { // Order 1: the server commits tab 1's register, tab 2 sees it first. const tabs = sharedTabs(async () => "WAIT_FOR_REGISTER"); const results = await raceEnableWithReconcile(tabs); expect(results).toEqual([ { ok: true, value: { state: "PUSH_READY" } }, { ok: true, value: { state: "PUSH_READY" } }, ]); expectReadyTabsStillReceive(tabs, results); expect(await tabs.fence()).toMatchObject({ ok: true, value: { control: { association: { state: "ACTIVE", associationEpoch: "association_01", }, }, }, }); }); it("keeps the shared state when a tab reconciles during another tab's unfinished opt-in", async () => { // Order 2: the server still answers ABSENT while tab 1's register runs. const tabs = sharedTabs(async () => "NOW"); const results = await raceEnableWithReconcile(tabs); expect(results[0]).toEqual({ ok: true, value: { state: "PUSH_READY" } }); expectReadyTabsStillReceive(tabs, results); }); it("aborts a tab that is still waiting for another tab's lock", async () => { const tabs = sharedTabs(async () => "NOW"); const enabling = tabs.tab(true).enable({ authority, signal: new AbortController().signal, }); await tabs.registerStarted; const waiting = new AbortController(); const reconciling = tabs.tab(false).reconcile({ authority, signal: waiting.signal, }); await new Promise((resolve) => setTimeout(resolve, 0)); waiting.abort(); expect(await reconciling).toMatchObject({ ok: false, error: { code: "ABORTED", operation: "SUBSCRIPTION_RECONCILE" }, }); tabs.releaseRegister(); expect(await enabling).toEqual({ ok: true, value: { state: "PUSH_READY" }, }); expect(tabs.unsubscribe).not.toHaveBeenCalled(); }); it("reports PUSH_UNSUPPORTED without side effects when Web Locks are missing", async () => { const tabs = sharedTabs(async () => "NOW", null); expect( await tabs.tab(true).enable({ authority, signal: new AbortController().signal, }), ).toEqual({ ok: true, value: { state: "PUSH_UNSUPPORTED" } }); expect(tabs.nativeAlive()).toBe(false); expect(await tabs.fence()).toEqual({ ok: true, value: null }); }); }); /** * 06-06. The session changed from A to B without `revoke` (expiry, cleared * cookies, a crash during logout). B cannot name A's stored authority, so * `revokeForeign` rotates a fence another fence generation holds. A fence B * already holds, for example because another tab of B opted in, is left alone. */ describe("06-06 account switch without logout", () => { async function fenceFor(owner: PushAuthoritySnapshot, associationEpoch: string) { const store = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); const prepared = await store.prepare({ authority: owner, updatedAt: "2026-07-28T00:00:00.000Z", }); if (!prepared.ok) throw new Error("expected prepared control"); const active = await store.activate({ expectedRevision: prepared.value.revision, authority: owner, associationEpoch, updatedAt: "2026-07-28T00:00:01.000Z", }); if (!active.ok) throw new Error("expected active control"); return store; } function adapterOver( fenceStore: ReturnType, ) { const unsubscribe = vi.fn(async () => { current = null; return true; }); let current: WindowPushSubscriptionFacade | null = subscription(unsubscribe); const revoke = vi.fn(gateway().revoke); const register = vi.fn(async () => webPushSuccess({ associationEpoch: "association_02", sessionBindingEpoch: nextAuthority.sessionBindingEpoch, }), ); const adapter = createWebPushSubscriptionAdapter({ secureContext: true, userActivationIsActive: () => true, permission: { permission: () => "granted", requestPermission: async () => "granted", }, registration: { active: true, pushManager: { getSubscription: async () => current, subscribe: async () => { current = subscription(); return current; }, }, getNotifications: async () => [], }, fenceStore, gateway: gateway({ register, revoke }), vapidPublicKey, lockManager: navigator.locks, now: () => now, }); return { adapter, unsubscribe, revoke, register }; } it("lets B take over A's ACTIVE fence in one call and opt in again", async () => { const fenceStore = await fenceFor(authority, "association_01"); const tab = adapterOver(fenceStore); // Without it B is stuck: the fence still belongs to A. expect( await tab.adapter.enable({ authority: nextAuthority, signal: new AbortController().signal, }), ).toMatchObject({ ok: false, error: { code: "STALE_AUTHORITY" } }); expect( await tab.adapter.revokeForeign({ nextAuthority }), ).toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "REVOKED" }, }); expect(tab.revoke.mock.calls).toEqual([ [{ associationEpoch: "association_01", signal: expect.any(AbortSignal) }], ]); expect(tab.unsubscribe).toHaveBeenCalledOnce(); expect(await fenceStore.read()).toMatchObject({ ok: true, value: { control: { ...nextAuthority, association: { state: "REVOKED", associationEpoch: "association_01" }, }, }, }); expect( await tab.adapter.enable({ authority: nextAuthority, signal: new AbortController().signal, }), ).toEqual({ ok: true, value: { state: "PUSH_READY" } }); }); it("leaves a fence B already holds alone and reports it like inspect", async () => { const fenceStore = await fenceFor(nextAuthority, "association_02"); const before = await fenceStore.read(); const tab = adapterOver(fenceStore); expect(await tab.adapter.revokeForeign({ nextAuthority })).toEqual({ ok: true, value: { state: "PUSH_READY" }, }); expect(tab.revoke).not.toHaveBeenCalled(); expect(tab.unsubscribe).not.toHaveBeenCalled(); expect(await fenceStore.read()).toEqual(before); }); it("does not treat a new release of the same session as another account", async () => { const fenceStore = await fenceFor(authority, "association_01"); const before = await fenceStore.read(); const tab = adapterOver(fenceStore); expect( await tab.adapter.revokeForeign({ nextAuthority: { ...authority, releaseEpoch: "release_02" }, }), ).toEqual({ ok: true, value: { state: "PUSH_UNAVAILABLE", reason: "SESSION_AUTHORITY_CHANGED" }, }); expect(tab.revoke).not.toHaveBeenCalled(); expect(tab.unsubscribe).not.toHaveBeenCalled(); expect(await fenceStore.read()).toEqual(before); }); });