Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223import assert from "node:assert/strict";import { existsSync } from "node:fs";import { resolve, delimiter } from "node:path";import { pathToFileURL } from "node:url";import { test } from "node:test";import vm from "node:vm";
// Run with npm exec --yes --package=lakebed@0.0.33 -- node scripts/test-notifications.mjsconst packageRoot = process.env.PATH.split(delimiter).map((p) => resolve(p, "../lakebed")) .find((p) => existsSync(resolve(p, "dist/runtime.js")));assert.ok(packageRoot, "Run this script via npm exec --package=lakebed");const load = (path) => import(pathToFileURL(resolve(packageRoot, path)).href);const { buildCapsule } = await load("dist/cli/build.js");const { StateCell, LogBuffer } = await load("dist/runtime.js");const { createGuestAuth } = await load("dist/auth.js");const { runQuery, runMutation, createContext } = await load("dist/cli/dev/runners.js");const { app } = await buildCapsule({ capsuleDir: process.cwd(), capsuleId: "notification-tests" });const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);const publicKey = Buffer.from(await crypto.subtle.exportKey("raw", keys.publicKey)).toString("base64url");const env = { PUSH_VAPID_PUBLIC_KEY: publicKey, PUSH_VAPID_PRIVATE_JWK: JSON.stringify(await crypto.subtle.exportKey("jwk", keys.privateKey)), PUSH_VAPID_SUBJECT: "https://lunchtime.example",};const realFetch = globalThis.fetch;
async function fixture() { const stateCell = new StateCell(app.schema); const logs = new LogBuffer(); const options = (user) => ({ app, stateCell, logs, env, auth: createGuestAuth(user) }); const query = (user, name) => runQuery({ ...options(user), name }); const mutate = async (user, name, ...args) => (await runMutation({ ...options(user), name, args })).result; const { shareToken } = await mutate("cook", "createEvent", { title: "Test lunch", description: "", date: "2026-09-20", maxParticipants: 20 }); const [event] = await query("cook", "myEvents"); const join = (user, notifyOnClose, partySize = 1) => mutate(user, "joinEvent", { shareToken, name: user, email: "", partySize, notifyOnClose }); const close = (price = 4.25) => mutate("cook", "closeEvent", { eventId: event.id, totalGroceries: 0, splitCount: 1, finalPricePerPerson: price }); return { stateCell, options, query, mutate, event, join, close };}
test("opt-in is explicit; close alerts are private, contain final party totals, and repeated closes are idempotent", async () => { const f = await fixture(); await f.join("alice", true, 3); await f.join("bob", false); await f.join("legacy-client", undefined); await Promise.all([f.close(), f.close(99)]); const [alert] = await f.query("alice", "myNotifications"); assert.equal(alert.pricePerPerson, "4.25"); assert.equal(alert.partySize, "3"); assert.equal(alert.read, false); assert.equal((await f.query("alice", "myNotifications")).length, 1); for (const user of ["bob", "cook", "legacy-client", "stranger"]) assert.deepEqual(await f.query(user, "myNotifications"), []); assert.equal((await f.mutate("bob", "markNotificationRead", alert.id)).error, "Forbidden"); await f.mutate("alice", "markNotificationRead", alert.id); assert.equal((await f.query("alice", "myNotifications"))[0].read, true); await f.mutate("cook", "reopenEvent", f.event.id); await f.close(5); assert.equal((await f.query("alice", "myNotifications")).length, 2); await f.mutate("alice", "markAllNotificationsRead"); assert.ok((await f.query("alice", "myNotifications")).every((n) => n.read));});
test("only a registration's owner can opt in or out; only the cook can close or retry delivery", async () => { const f = await fixture(); await f.join("alice", false); const [registration] = await f.query("alice", "myRegistrations"); assert.deepEqual(await f.query("bob", "myRegistrations"), []); assert.equal((await f.mutate("bob", "setCloseNotification", { registrationId: registration.id, enabled: true })).error, "Forbidden"); await f.mutate("alice", "setCloseNotification", { registrationId: registration.id, enabled: true }); assert.equal((await f.query("alice", "myRegistrations"))[0].notifyOnClose, true); await f.mutate("alice", "setCloseNotification", { registrationId: registration.id, enabled: false }); assert.equal((await f.mutate("alice", "closeEvent", { eventId: f.event.id })).error, "Forbidden"); assert.equal((await f.mutate("alice", "retryEventPush", f.event.id)).error, "Forbidden"); await f.close(); assert.deepEqual(await f.query("alice", "myNotifications"), []); assert.ok((await f.mutate("alice", "setCloseNotification", { registrationId: registration.id, enabled: true })).error);});
test("failed registrations do not create notification preferences; public reads do not expose ownership", async () => { const f = await fixture(); await f.close(); assert.ok((await f.join("alice", true)).error); assert.deepEqual(await f.query("alice", "myRegistrations"), []); await f.mutate("cook", "reopenEvent", f.event.id); await f.join("alice", true); const [participant] = await f.query("stranger", "allParticipants"); assert.equal(participant.userId, undefined); assert.equal(participant.notifyOnClose, undefined);});
test("push uses valid signed VAPID requests, only for opted-in registrations", async () => { const f = await fixture(); await f.join("alice", true); await f.join("bob", false); await f.mutate("alice", "savePushSubscription", "https://fcm.googleapis.com/fcm/send/alice"); await f.mutate("bob", "savePushSubscription", "https://fcm.googleapis.com/fcm/send/bob"); const requests = []; globalThis.fetch = async (endpoint, init) => { requests.push({ endpoint, init }); return new Response(null, { status: 201 }); }; try { await f.close(); assert.equal(requests.length, 1); assert.match(requests[0].endpoint, /alice$/); const { init } = requests[0]; assert.equal(init.method, "POST"); assert.equal(init.redirect, "error"); assert.equal(init.body, undefined); const [, jwt, key] = init.headers.Authorization.match(/^vapid t=(.+), k=(.+)$/); assert.equal(key, publicKey); const [header, payload, signature] = jwt.split("."); const claims = JSON.parse(Buffer.from(payload, "base64url")); assert.equal(claims.aud, "https://fcm.googleapis.com"); assert.equal(claims.sub, env.PUSH_VAPID_SUBJECT); assert.ok(claims.exp > Date.now() / 1000 && claims.exp < Date.now() / 1000 + 86400); assert.ok(await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, keys.publicKey, Buffer.from(signature, "base64url"), new TextEncoder().encode(`${header}.${payload}`))); await f.close(); assert.equal(requests.length, 1); } finally { globalThis.fetch = realFetch; }});
test("food-ready alerts use the opted-in recipients and do not prevent the later close alert", async () => { const f = await fixture(); await f.join("alice", true); await f.join("bob", false); await f.mutate("alice", "savePushSubscription", "https://fcm.googleapis.com/fcm/send/alice"); const requests = []; globalThis.fetch = async (endpoint) => { requests.push(endpoint); return new Response(null, { status: 201 }); }; try { const ready = await f.mutate("cook", "sendFoodReady", f.event.id); assert.deepEqual(ready, { success: true, notified: 1, pushFailed: 0 }); assert.deepEqual(requests, ["https://fcm.googleapis.com/fcm/send/alice"]); assert.equal((await f.query("alice", "myNotifications"))[0].kind, "foodReady"); assert.deepEqual(await f.query("bob", "myNotifications"), []);
await f.close(); assert.equal(requests.length, 2); assert.deepEqual((await f.query("alice", "myNotifications")).map((notification) => notification.kind).sort(), ["closed", "foodReady"]); } finally { globalThis.fetch = realFetch; }});
test("push failures preserve event closing and the inbox, can be retried, and expired devices are removed", async () => { const f = await fixture(); await f.join("alice", true); await f.mutate("alice", "savePushSubscription", "https://fcm.googleapis.com/fcm/send/alice"); globalThis.fetch = async () => { throw new Error("offline"); }; try { assert.equal((await f.close()).pushFailed, 1); assert.equal((await f.query("cook", "myEvents"))[0].closed, true); assert.equal((await f.query("alice", "myNotifications")).length, 1); assert.deepEqual(await f.query("cook", "pendingEventPush"), [f.event.id]); globalThis.fetch = async () => new Response(null, { status: 410 }); assert.equal((await f.mutate("cook", "retryEventPush", f.event.id)).pushFailed, 0); assert.deepEqual(await f.query("alice", "myPushSubscriptions"), []); assert.deepEqual(await f.query("cook", "pendingEventPush"), []); } finally { globalThis.fetch = realFetch; }});
test("push subscriptions are private and reject arbitrary URLs or another user's device", async () => { const f = await fixture(); for (const endpoint of ["http://localhost/test", "https://example.com/test", "https://fcm.googleapis.com.evil.test/test", "https://user:pass@fcm.googleapis.com/test", "https://fcm.googleapis.com:444/test"]) { assert.ok((await f.mutate("alice", "savePushSubscription", endpoint)).error); } const endpoint = "https://fcm.googleapis.com/fcm/send/alice"; await f.mutate("alice", "savePushSubscription", endpoint); assert.deepEqual(await f.query("bob", "myPushSubscriptions"), []); assert.ok((await f.mutate("bob", "savePushSubscription", endpoint)).error); await f.mutate("bob", "removePushSubscription", endpoint); assert.equal((await f.query("alice", "myPushSubscriptions")).length, 1); await f.mutate("alice", "removePushSubscription", endpoint); assert.deepEqual(await f.query("alice", "myPushSubscriptions"), []);});
test("removing a participant or deleting an event cleans up alerts and preferences", async () => { const f = await fixture(); await f.join("alice", true); await f.join("bob", true); await f.close(); const [registration] = await f.query("alice", "myRegistrations"); await f.mutate("cook", "removeParticipant", { eventId: f.event.id, participantId: registration.participantId }); assert.deepEqual(await f.query("alice", "myRegistrations"), []); assert.deepEqual(await f.query("alice", "myNotifications"), []); assert.equal((await f.query("bob", "myNotifications")).length, 1); await f.mutate("cook", "deleteEvent", f.event.id); assert.deepEqual(await f.query("bob", "myRegistrations"), []); assert.deepEqual(await f.query("bob", "myNotifications"), []);});
test("Google guest upgrade carries private registrations, alerts and devices to the signed-in identity", async () => { const f = await fixture(); await f.join("alice", true); await f.mutate("alice", "savePushSubscription", "https://fcm.googleapis.com/fcm/send/alice"); globalThis.fetch = async () => new Response(null, { status: 201 }); try { await f.close(); } finally { globalThis.fetch = realFetch; } await f.stateCell.transaction((db) => app.auth.onGuestUpgrade(createContext({ ...f.options("alice"), db }), { guestUserId: createGuestAuth("alice").userId, userId: createGuestAuth("signed-in-alice").userId, })); for (const query of ["myRegistrations", "myNotifications", "myPushSubscriptions"]) { assert.equal((await f.query("signed-in-alice", query)).length, 1); assert.deepEqual(await f.query("alice", query), []); }});
test("service worker handles empty pushes and opens the notification inbox without an existing tab", async () => { const response = await app.endpoints.pushWorker.handler(); assert.equal(response.headers["content-type"], "application/javascript"); const handlers = {}; const shown = []; const opened = []; vm.runInNewContext(response.body, { URL, self: { addEventListener: (name, handler) => { handlers[name] = handler; }, registration: { showNotification: async (...args) => shown.push(args) }, location: { origin: "https://lunchtime.example" }, clients: { matchAll: async () => [], openWindow: async (url) => opened.push(url) }, } }); let pending; handlers.push({ waitUntil: (promise) => { pending = promise; } }); await pending; assert.equal(shown[0][0], "Lunchtime update"); assert.equal(shown[0][1].tag, undefined); handlers.notificationclick({ notification: { close() {} }, waitUntil: (promise) => { pending = promise; } }); await pending; assert.deepEqual(opened, ["https://lunchtime.example/#notifications"]);});