|
| 1 | +// A fire-and-forget notify() must not sit in the operator's "needs you" queue. |
| 2 | +// |
| 3 | +// These boot the real routers against a throwaway libsql file database. They |
| 4 | +// skip cleanly when the PWA dependencies are not installed (a fresh repo clone |
| 5 | +// only has the root CLI deps), so the root `npm test` stays green either way. |
| 6 | +// Run `npm install` in apps/pwa to enable them. |
| 7 | +import assert from "node:assert/strict"; |
| 8 | +import { mkdtempSync } from "node:fs"; |
| 9 | +import { tmpdir } from "node:os"; |
| 10 | +import path from "node:path"; |
| 11 | +import { createRequire } from "node:module"; |
| 12 | +import test from "node:test"; |
| 13 | + |
| 14 | +const require = createRequire(import.meta.url); |
| 15 | +let deps = null; |
| 16 | +try { |
| 17 | + deps = { express: require("express"), cookieParser: require("cookie-parser") }; |
| 18 | +} catch { |
| 19 | + deps = null; // pwa dependencies not installed — tests below skip |
| 20 | +} |
| 21 | + |
| 22 | +// Point the app at a throwaway database BEFORE importing its modules (config |
| 23 | +// reads the environment once, at import time). |
| 24 | +const workdir = mkdtempSync(path.join(tmpdir(), "moshcode-pwa-notify-test-")); |
| 25 | +process.env.DATABASE_URL = `file:${path.join(workdir, "test.db")}`; |
| 26 | +process.env.SESSION_SECRET = "test-secret"; |
| 27 | + |
| 28 | +async function boot() { |
| 29 | + const { migrate } = await import("../src/migrate.mjs"); |
| 30 | + await migrate(); |
| 31 | + const { run, all, get } = await import("../src/db.mjs"); |
| 32 | + const { sessionMiddleware, csrfGuard } = await import("../src/lib/session.mjs"); |
| 33 | + const { approvalsRouter } = await import("../src/routes/approvals.mjs"); |
| 34 | + const { pagesRouter } = await import("../src/routes/pages.mjs"); |
| 35 | + const { createApiKey } = await import("../src/lib/apikey.mjs"); |
| 36 | + const { id, token } = await import("../src/lib/crypto.mjs"); |
| 37 | + |
| 38 | + const app = deps.express(); |
| 39 | + app.use(deps.express.json({ verify: (req, _res, buf) => { req.rawBody = buf.toString("utf8"); } })); |
| 40 | + app.use(deps.express.urlencoded({ extended: false })); |
| 41 | + app.use(deps.cookieParser()); |
| 42 | + app.use(sessionMiddleware); |
| 43 | + app.use(csrfGuard); |
| 44 | + app.use(approvalsRouter); |
| 45 | + app.use(pagesRouter); |
| 46 | + const server = await new Promise((resolve) => { |
| 47 | + const s = app.listen(0, "127.0.0.1", () => resolve(s)); |
| 48 | + }); |
| 49 | + const base = `http://127.0.0.1:${server.address().port}`; |
| 50 | + |
| 51 | + // A user with push enabled (free, and on by default for real signups), plus |
| 52 | + // the API key the CLI sends and a browser session for the dashboard. |
| 53 | + const seedUser = async (userId) => { |
| 54 | + await run(`INSERT INTO users (id, email, display_name, created_at) VALUES (?,?,?,?)`, |
| 55 | + [userId, `${userId}@b.c`, "demo", Date.now()]); |
| 56 | + await run(`INSERT INTO channels (id,user_id,kind,target,enabled,created_at) VALUES (?,?,?,?,?,?)`, |
| 57 | + [id(), userId, "push", null, 1, Date.now()]); |
| 58 | + const { plaintext } = await createApiKey(userId, "cli"); |
| 59 | + const sess = token(); |
| 60 | + await run(`INSERT INTO sessions (token,user_id,created_at,expires_at) VALUES (?,?,?,?)`, |
| 61 | + [sess, userId, Date.now(), Date.now() + 3600e3]); |
| 62 | + return { key: plaintext, sess }; |
| 63 | + }; |
| 64 | + |
| 65 | + // What the CLI does: POST /api/approvals with kind ask | notify. |
| 66 | + const ingest = async (key, kind, message) => { |
| 67 | + const res = await fetch(`${base}/api/approvals`, { |
| 68 | + method: "POST", |
| 69 | + headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, |
| 70 | + body: JSON.stringify({ message, kind, script: "ship.mosh" }), |
| 71 | + }); |
| 72 | + return { status: res.status, body: await res.json() }; |
| 73 | + }; |
| 74 | + |
| 75 | + const dashboard = (sess) => fetch(`${base}/dashboard`, { headers: { cookie: `mc_sess=${sess}` } }).then((r) => r.text()); |
| 76 | + const approvePage = (id, cap) => fetch(`${base}/approve/${id}?t=${cap}`).then((r) => r.text()); |
| 77 | + |
| 78 | + return { base, server, run, all, get, seedUser, ingest, dashboard, approvePage }; |
| 79 | +} |
| 80 | + |
| 81 | +// The dashboard's "needs you" column links each pending approval; "moshed" |
| 82 | +// history renders the message in a <b> instead. |
| 83 | +const waitingBanner = (html) => Number(/(\d+) waiting on you/.exec(html)?.[1]); |
| 84 | +const needsYou = (html) => |
| 85 | + [...html.matchAll(/href="\/approve\/[^"]*"[\s\S]{0,400}?font-weight:700">([^<]*)</g)].map((m) => m[1]); |
| 86 | +const moshed = (html) => [...html.matchAll(/<b style="color:var\(--text\)">([^<]*)</g)].map((m) => m[1]); |
| 87 | + |
| 88 | +test("a notify() is filed as already sent, not pending", { skip: !deps && "pwa deps not installed" }, async () => { |
| 89 | + const { server, get, seedUser, ingest } = await boot(); |
| 90 | + try { |
| 91 | + const { key } = await seedUser("u-notify-status"); |
| 92 | + const { status, body } = await ingest(key, "notify", "deployed to prod"); |
| 93 | + assert.equal(status, 201); |
| 94 | + assert.equal(body.status, "sent"); |
| 95 | + |
| 96 | + const row = await get(`SELECT status, submitted_at FROM approvals WHERE id = ?`, [body.id]); |
| 97 | + assert.equal(row.status, "sent"); |
| 98 | + assert.ok(row.submitted_at, "a sent notify is resolved, so it needs a submitted_at to sort history by"); |
| 99 | + } finally { server.close(); } |
| 100 | +}); |
| 101 | + |
| 102 | +test("an ask() still waits on a human", { skip: !deps && "pwa deps not installed" }, async () => { |
| 103 | + const { server, get, seedUser, ingest } = await boot(); |
| 104 | + try { |
| 105 | + const { key } = await seedUser("u-ask-status"); |
| 106 | + const { body } = await ingest(key, "ask", "promote to stable?"); |
| 107 | + assert.equal(body.status, "pending"); |
| 108 | + |
| 109 | + const row = await get(`SELECT status, submitted_at FROM approvals WHERE id = ?`, [body.id]); |
| 110 | + assert.equal(row.status, "pending"); |
| 111 | + assert.equal(row.submitted_at, null); |
| 112 | + } finally { server.close(); } |
| 113 | +}); |
| 114 | + |
| 115 | +test("the dashboard counts only what is actually waiting", { skip: !deps && "pwa deps not installed" }, async () => { |
| 116 | + const { server, seedUser, ingest, dashboard } = await boot(); |
| 117 | + try { |
| 118 | + const { key, sess } = await seedUser("u-dash"); |
| 119 | + // a typical script run: chatter along the way, one real gate at the end |
| 120 | + for (const m of ["build started", "tests green", "deployed to prod"]) await ingest(key, "notify", m); |
| 121 | + await ingest(key, "ask", "promote to stable?"); |
| 122 | + |
| 123 | + const html = await dashboard(sess); |
| 124 | + assert.equal(waitingBanner(html), 1, "only the ask() is waiting on the operator"); |
| 125 | + assert.deepEqual(needsYou(html), ["promote to stable?"]); |
| 126 | + // the notifications are history, not a queue |
| 127 | + assert.deepEqual(moshed(html).sort(), ["build started", "deployed to prod", "tests green"]); |
| 128 | + } finally { server.close(); } |
| 129 | +}); |
| 130 | + |
| 131 | +test("a notify() cannot be answered — it stays sent and records no reply", |
| 132 | + { skip: !deps && "pwa deps not installed" }, async () => { |
| 133 | + const { base, server, get, seedUser, ingest } = await boot(); |
| 134 | + try { |
| 135 | + const { key } = await seedUser("u-notify-resolve"); |
| 136 | + const { body } = await ingest(key, "notify", "deployed to prod"); |
| 137 | + const cap = (await get(`SELECT cap_token FROM approvals WHERE id = ?`, [body.id])).cap_token; |
| 138 | + |
| 139 | + // the page issues the double-submit CSRF cookie the form posts back |
| 140 | + const pageRes = await fetch(`${base}/approve/${body.id}?t=${cap}`); |
| 141 | + await pageRes.text(); |
| 142 | + const csrf = /mc_csrf=([^;]+)/.exec(pageRes.headers.getSetCookie().join("; "))[1]; |
| 143 | + |
| 144 | + const res = await fetch(`${base}/approve/${body.id}?t=${cap}`, { |
| 145 | + method: "POST", |
| 146 | + headers: { "content-type": "application/x-www-form-urlencoded", cookie: `mc_csrf=${csrf}` }, |
| 147 | + body: new URLSearchParams({ response: "sure, go ahead", _csrf: csrf }), |
| 148 | + redirect: "manual", |
| 149 | + }); |
| 150 | + assert.equal(res.status, 302); |
| 151 | + |
| 152 | + const row = await get(`SELECT status, response FROM approvals WHERE id = ?`, [body.id]); |
| 153 | + assert.equal(row.status, "sent"); |
| 154 | + assert.equal(row.response, null); |
| 155 | + } finally { server.close(); } |
| 156 | +}); |
| 157 | + |
| 158 | +test("the notify page says there is nothing to respond to", { skip: !deps && "pwa deps not installed" }, async () => { |
| 159 | + const { server, get, seedUser, ingest, approvePage } = await boot(); |
| 160 | + try { |
| 161 | + const { key } = await seedUser("u-notify-page"); |
| 162 | + const { body } = await ingest(key, "notify", "deployed to prod"); |
| 163 | + const cap = (await get(`SELECT cap_token FROM approvals WHERE id = ?`, [body.id])).cap_token; |
| 164 | + |
| 165 | + const html = await approvePage(body.id, cap); |
| 166 | + assert.match(html, /nothing to respond to/); |
| 167 | + assert.doesNotMatch(html, /You replied/); |
| 168 | + assert.doesNotMatch(html, /Kill the loop/, "a notification has no loop to kill"); |
| 169 | + } finally { server.close(); } |
| 170 | +}); |
0 commit comments