| 1 | // End-to-end early access (lib/early-access.ts, web/early-access.tsx) on a real `wrangler dev` Worker: |
| 2 | // the sign-in page and closed sign-up lead to /early-access; a request is confirmed with |
| 3 | // the link from its email (double opt-in); the form answers the same for known addresses and accounts; |
| 4 | // bots, bursts, oversized and hostile input get nowhere; only site administrators see requests, on the |
| 5 | // web and through the API; inviting sends the instance invitation; declining, putting back, deleting and |
| 6 | // removing your own request work and are audited without the request's content. |
| 7 | // |
| 8 | // The Worker keeps env.dev's DEV_AUTH so it keeps whole copies of the emails it sends (for reading the |
| 9 | // links). Visitors who aren't signed in are requests with another Host header: local development's fixed |
| 10 | // identity only applies to requests addressed to this machine. |
| 11 | // |
| 12 | // pnpm --filter @diffinery/app exec node --test test/e2e/early-access.test.mjs |
| 13 | import "./fresh-connections.mjs"; |
| 14 | import { spawn, execFileSync } from "node:child_process"; |
| 15 | import { createHash, randomBytes } from "node:crypto"; |
| 16 | import { mkdtempSync, rmSync } from "node:fs"; |
| 17 | import { tmpdir } from "node:os"; |
| 18 | import { join, dirname, resolve } from "node:path"; |
| 19 | import { fileURLToPath } from "node:url"; |
| 20 | import { request as httpRequest } from "node:http"; |
| 21 | import { test, after } from "node:test"; |
| 22 | import assert from "node:assert/strict"; |
| 23 | import { migratedState } from "./d1-state.mjs"; |
| 24 | import { freePort } from "./ports.mjs"; |
| 25 | |
| 26 | const APP = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); |
| 27 | const work = mkdtempSync(join(tmpdir(), "diffinery-early-access-e2e-")); |
| 28 | const running = []; |
| 29 | |
| 30 | const hash = (s) => createHash("sha256").update(s).digest("hex"); |
| 31 | const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); |
| 32 | |
| 33 | /** |
| 34 | * A fetch-like request over node:http, which (unlike fetch) sends the Host header it is given: the |
| 35 | * Worker sees a visitor's requests addressed to VISITOR. Redirects are never followed. |
| 36 | */ |
| 37 | function send(url, { method = "GET", headers = {}, body } = {}) { |
| 38 | const data = body === undefined ? undefined : Buffer.from(typeof body === "string" ? body : body.toString()); |
| 39 | return new Promise((res, rej) => { |
| 40 | const r = httpRequest(url, { method, headers: { ...headers, ...(data ? { "content-length": String(data.length) } : {}) } }, (resp) => { |
| 41 | const chunks = []; |
| 42 | resp.on("data", (c) => chunks.push(c)); |
| 43 | resp.on("end", () => { |
| 44 | const text = Buffer.concat(chunks).toString("utf8"); |
| 45 | const h = resp.headers; |
| 46 | res({ |
| 47 | status: resp.statusCode, |
| 48 | headers: { get: (k) => (Array.isArray(h[k.toLowerCase()]) ? h[k.toLowerCase()].join(", ") : (h[k.toLowerCase()] ?? null)) }, |
| 49 | text: async () => text, |
| 50 | json: async () => JSON.parse(text), |
| 51 | }); |
| 52 | }); |
| 53 | }); |
| 54 | r.on("error", rej); |
| 55 | if (data) r.write(data); |
| 56 | r.end(); |
| 57 | }); |
| 58 | } |
| 59 | |
| 60 | function stopWorker(dev) { |
| 61 | try { |
| 62 | process.kill(-dev.pid, "SIGTERM"); |
| 63 | } catch {} |
| 64 | } |
| 65 | |
| 66 | after(() => { |
| 67 | for (const dev of running) stopWorker(dev); |
| 68 | if (process.env.E2E_KEEP !== "1") rmSync(work, { recursive: true, force: true }); |
| 69 | }); |
| 70 | |
| 71 | const T = { root: `dfy_root_${randomBytes(12).toString("hex")}`, ann: `dfy_ann_${randomBytes(12).toString("hex")}` }; |
| 72 | const S = { root: `root-session-${randomBytes(12).toString("hex")}`, ann: `ann-session-${randomBytes(12).toString("hex")}` }; |
| 73 | /** The Host a visitor who isn't signed in uses (see the header comment). */ |
| 74 | const VISITOR = "visitor.example"; |
| 75 | |
| 76 | let w; |
| 77 | async function worker() { |
| 78 | if (w) return w; |
| 79 | const port = await freePort(); |
| 80 | const base = `http://127.0.0.1:${port}`; |
| 81 | const persist = join(work, "state"); |
| 82 | const at = new Date().toISOString(); |
| 83 | const later = new Date(Date.now() + 30 * 86400_000).toISOString(); |
| 84 | const person = (id, login, email, admin) => `INSERT INTO accounts (id, login, kind, name, email, status, site_admin, created_at) VALUES ('${id}', '${login}', 'user', '${login}', '${email}', 'active', ${admin}, '${at}')`; |
| 85 | const token = (id, account, t) => `INSERT INTO tokens (id, account_id, name, token_hash, prefix, scopes, expires_at, created_at) VALUES ('${id}', '${account}', 'e2e', '${hash(t)}', '${t.slice(0, 10)}', '["admin"]', '${later}', '${at}')`; |
| 86 | const session = (account, cookie) => `INSERT INTO sessions (id, account_id, method, created_at, last_seen_at, expires_at) VALUES ('${hash(cookie)}', '${account}', 'passkey', '${at}', '${at}', '${later}')`; |
| 87 | const seed = [person("u-root", "root", "root@example.com", 1), person("u-ann", "ann", "ann@example.com", 0), token("t-root", "u-root", T.root), token("t-ann", "u-ann", T.ann), session("u-root", S.root), session("u-ann", S.ann)]; |
| 88 | const wrangler = (...args) => execFileSync("pnpm", ["exec", "wrangler", ...args], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } }); |
| 89 | migratedState(APP, persist); |
| 90 | wrangler("d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist, "--command", seed.join("; ")); |
| 91 | const args = ["exec", "wrangler", "dev", "-e", "dev", "--ip", "127.0.0.1", "--port", String(port), "--inspector-port", String(await freePort()), "--persist-to", persist, "--var", `PUBLIC_URL:${base}`, "--show-interactive-dev-session=false"]; |
| 92 | const dev = spawn("pnpm", args, { cwd: APP, env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false" }, stdio: ["ignore", "pipe", "pipe"], detached: true }); |
| 93 | let log = ""; |
| 94 | dev.stdout.on("data", (d) => (log += d)); |
| 95 | dev.stderr.on("data", (d) => (log += d)); |
| 96 | running.push(dev); |
| 97 | const end = Date.now() + 120_000; |
| 98 | while (Date.now() < end) { |
| 99 | try { |
| 100 | if ((await fetch(`${base}/healthz`)).ok) break; |
| 101 | } catch {} |
| 102 | await sleep(500); |
| 103 | } |
| 104 | assert.ok((await fetch(`${base}/healthz`).catch(() => ({ ok: false }))).ok, `wrangler dev did not start\n${log.slice(-4000)}`); |
| 105 | |
| 106 | /** Headers for a visitor (no `who`), or a signed-in person's browser. */ |
| 107 | const headers = (who, extra = {}) => ({ ...(who ? { cookie: `__Host-dfy_session=${S[who]}` } : { host: VISITOR }), ...extra }); |
| 108 | const page = (path, who) => send(`${base}${path}`, { headers: headers(who) }); |
| 109 | const api = async (method, path, body, tok) => { |
| 110 | const r = await send(`${base}/api/v3${path}`, { method, headers: { "content-type": "application/json", ...(tok ? { authorization: `Bearer ${tok}` } : { host: VISITOR }) }, body: body === undefined ? undefined : JSON.stringify(body) }); |
| 111 | const text = await r.text(); |
| 112 | let json = null; |
| 113 | try { |
| 114 | json = text ? JSON.parse(text) : null; |
| 115 | } catch { |
| 116 | json = text; |
| 117 | } |
| 118 | return { status: r.status, json }; |
| 119 | }; |
| 120 | /** A form's CSRF pair and timing stamp, read from `path` the way a browser does. */ |
| 121 | const formOf = async (path, who) => { |
| 122 | const res = await page(path, who); |
| 123 | assert.equal(res.status, 200, `GET ${path} -> ${res.status}`); |
| 124 | const html = await res.text(); |
| 125 | const csrf = /name="_csrf" value="([^"]+)"/.exec(html)?.[1]; |
| 126 | const pair = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1]; |
| 127 | assert.ok(csrf && pair, `no CSRF pair on ${path}`); |
| 128 | return { csrf, pair, stamp: /name="stamp" value="([^"]*)"/.exec(html)?.[1] ?? "", html }; |
| 129 | }; |
| 130 | /** POST a form; `form` is from formOf. `ip` sets the address the Worker sees. */ |
| 131 | const post = async (action, form, fields, who, ip) => { |
| 132 | const body = new URLSearchParams({ _csrf: form.csrf, ...(form.stamp ? { stamp: form.stamp } : {}), ...fields }); |
| 133 | const cookie = [who ? `__Host-dfy_session=${S[who]}` : "", `dfy_csrf=${form.pair}`].filter(Boolean).join("; "); |
| 134 | const r = await send(`${base}${action}`, { method: "POST", body, headers: { ...headers(who), cookie, "content-type": "application/x-www-form-urlencoded", "sec-fetch-site": "same-origin", ...(ip ? { "cf-connecting-ip": ip } : {}) } }); |
| 135 | // Apostrophes come back as '; nothing else is unescaped, so the escaping checks still hold. |
| 136 | return { status: r.status, location: r.headers.get("location"), html: (await r.text()).replace(/'/g, "'") }; |
| 137 | }; |
| 138 | /** Every email the Worker sent, newest first, with the whole message (DEV_AUTH keeps it). */ |
| 139 | const emails = async () => { |
| 140 | const r = await api("GET", "/diffinery/emails?all=1&per_page=200", undefined, T.root); |
| 141 | assert.equal(r.status, 200, JSON.stringify(r.json)); |
| 142 | return r.json; |
| 143 | }; |
| 144 | const email = async (what, pred) => { |
| 145 | const end = Date.now() + 60_000; |
| 146 | while (Date.now() < end) { |
| 147 | const m = (await emails()).find(pred); |
| 148 | if (m) return m; |
| 149 | await sleep(500); |
| 150 | } |
| 151 | assert.fail(`timed out waiting for the email: ${what}\n${log.slice(-3000)}`); |
| 152 | }; |
| 153 | const linkIn = (m, path) => { |
| 154 | const text = m.dev_copy?.text ?? ""; |
| 155 | const found = new RegExp(`${base.replace(/[.]/g, "\\.")}${path}#([A-Za-z0-9_-]{20,100})`).exec(text); |
| 156 | assert.ok(found, `no ${path} link in:\n${text}`); |
| 157 | return found[1]; |
| 158 | }; |
| 159 | /** A form whose stamp is old enough to count as a person's (3 seconds). */ |
| 160 | const ready = async (path = "/early-access", who) => { |
| 161 | const f = await formOf(path, who); |
| 162 | await sleep(3200); |
| 163 | return f; |
| 164 | }; |
| 165 | w = { base, page, api, formOf, post, emails, email, linkIn, ready, log: () => log }; |
| 166 | return w; |
| 167 | } |
| 168 | |
| 169 | /** A page with the address typed and the per-page nonce taken out, to compare two answers. */ |
| 170 | const same = (html, address) => html.replace(address, "ADDRESS").replace(/nonce="[^"]*"/g, ""); |
| 171 | const request = (email, over = {}) => ({ email, name: "", company: "", use_case: "", hosting: "", website: "", ...over }); |
| 172 | const byEmail = async (api, address) => (await api("GET", `/diffinery/admin/early-access?q=${encodeURIComponent(address)}`, undefined, T.root)).json.find((r) => r.email === address); |
| 173 | let nextIp = 1; |
| 174 | /** A fresh address for the Worker to see each request from, so the daily limit per network doesn't mix tests. */ |
| 175 | const ip = () => `198.51.100.${nextIp++}`; |
| 176 | |
| 177 | test("early access: the sign-in page and closed sign-up lead to the form", async () => { |
| 178 | const { page } = await worker(); |
| 179 | const home = await (await page("/")).text(); |
| 180 | // The home page is about running Diffinery yourself, not about asking for access to this instance. |
| 181 | assert.doesNotMatch(home, /href="\/early-access"/); |
| 182 | assert.match(await (await page("/login")).text(), /href="\/early-access">request early access</); |
| 183 | const signup = await page("/signup"); |
| 184 | assert.equal(signup.status, 302); |
| 185 | assert.equal(signup.headers.get("location"), "/early-access"); |
| 186 | const form = await page("/early-access"); |
| 187 | assert.equal(form.status, 200); |
| 188 | const html = await form.text(); |
| 189 | assert.match(html, /Request early access to Diffinery/); |
| 190 | for (const name of ["email", "name", "company", "use_case", "hosting", "website", "stamp"]) assert.match(html, new RegExp(`name="${name}"`), name); |
| 191 | assert.doesNotMatch(html, /<select|type="checkbox"/, "Kumo controls only"); |
| 192 | assert.match(html, /href="\/early-access\/remove"/); |
| 193 | // Signed in, the form isn't needed. |
| 194 | const annForm = await page("/early-access", "ann"); |
| 195 | assert.equal(annForm.status, 302); |
| 196 | assert.equal(annForm.headers.get("location"), "/"); |
| 197 | // Search engines are kept away from the confirmation pages, and the form isn't in the sitemap. |
| 198 | const robots = await (await page("/robots.txt")).text(); |
| 199 | assert.match(robots, /Disallow: \/early-access\/confirm/); |
| 200 | assert.match(robots, /Disallow: \/early-access\/remove/); |
| 201 | assert.doesNotMatch(await (await page("/sitemap.xml")).text(), /:\d+\/early-access<\/loc>/); |
| 202 | }); |
| 203 | |
| 204 | test("early access: a request is confirmed with the link from its email, then waits for site administrators", async () => { |
| 205 | const { page, api, post, email, linkIn, ready } = await worker(); |
| 206 | const f = await ready(); |
| 207 | const hostile = { name: `Ada <script>alert(1)</script>`, company: "Acme & Co", use_case: "Move 40 repos.\n<img src=x onerror=alert(1)>", hosting: "github" }; |
| 208 | const sent = await post("/early-access", f, request("Ada@Example.net", hostile), undefined, ip()); |
| 209 | assert.equal(sent.status, 200, sent.html.slice(0, 600)); |
| 210 | assert.match(sent.html, /Check your inbox/); |
| 211 | assert.match(sent.html, /ada@example\.net/); |
| 212 | const m = await email("the confirmation", (e) => e.kind === "early_access_confirm" && e.to_addr === "ada@example.net"); |
| 213 | assert.equal(m.subject, "[Diffinery] Confirm your early access request"); |
| 214 | assert.doesNotMatch(JSON.stringify(m.dev_copy), /Ada|Acme|onerror|Move 40/, "nothing typed in the form goes into the email"); |
| 215 | const token = linkIn(m, "/early-access/confirm"); |
| 216 | |
| 217 | // Unconfirmed: not waiting yet. |
| 218 | const before = await byEmail(api, "ada@example.net"); |
| 219 | assert.equal(before.state, "unconfirmed"); |
| 220 | assert.doesNotMatch(await (await page("/settings/admin/early-access", "root")).text(), /ada@example\.net/); |
| 221 | |
| 222 | const confirmPage = await page("/early-access/confirm"); |
| 223 | assert.equal(confirmPage.status, 200); |
| 224 | const cf = { ...(await w.formOf("/early-access/confirm")), stamp: "" }; |
| 225 | const wrong = await post("/early-access/confirm", cf, { token: "x".repeat(40) }); |
| 226 | assert.equal(wrong.status, 410); |
| 227 | assert.match(wrong.html, /This link doesn't work any more/); |
| 228 | const ok = await post("/early-access/confirm", cf, { token }); |
| 229 | assert.equal(ok.status, 200, ok.html.slice(0, 600)); |
| 230 | assert.match(ok.html, /You're on the list/); |
| 231 | assert.ok(ok.html.includes("Ada <script>alert(1)</script>"), "the name is escaped"); |
| 232 | assert.equal((await post("/early-access/confirm", cf, { token })).status, 410, "a link works once"); |
| 233 | |
| 234 | const after = await byEmail(api, "ada@example.net"); |
| 235 | assert.equal(after.state, "confirmed"); |
| 236 | assert.deepEqual({ name: after.name, company: after.company, use_case: after.use_case, hosting: after.hosting }, { name: hostile.name, company: hostile.company, use_case: hostile.use_case, hosting: "github" }); |
| 237 | assert.ok(!("confirm_hash" in after)); |
| 238 | const admin = await (await page("/settings/admin/early-access", "root")).text(); |
| 239 | assert.match(admin, /ada@example\.net/); |
| 240 | assert.ok(!admin.includes("<script>alert(1)") && !admin.includes("<img src=x"), "everything is escaped"); |
| 241 | assert.match(admin, /Early access\s*<span class="badge blue"[^>]*>\s*1\s*</, "the sidebar counts what waits"); |
| 242 | const detail = await (await page(`/settings/admin/early-access/${after.id}`, "root")).text(); |
| 243 | assert.ok(detail.includes("Move 40 repos.\n<img src=x onerror=alert(1)>"), "the use is plain text"); |
| 244 | assert.match(await (await page("/notifications", "root")).text(), /New early access requests are waiting for you/); |
| 245 | assert.match(await (await page("/settings/admin", "root")).text(), /1 confirmed early access request is waiting/); |
| 246 | }); |
| 247 | |
| 248 | test("early access: the same answer for an address that already asked or has an account; only its inbox learns which", async () => { |
| 249 | const { api, post, email, emails, ready } = await worker(); |
| 250 | const f = await ready(); |
| 251 | const again = await post("/early-access", f, request("ada@example.net", { name: "Mallory" }), undefined, ip()); |
| 252 | assert.equal(again.status, 200); |
| 253 | assert.match(again.html, /Check your inbox/); |
| 254 | const known = await email("already asked", (e) => e.kind === "early_access_known" && e.to_addr === "ada@example.net"); |
| 255 | assert.equal(known.subject, "[Diffinery] We already have your early access request"); |
| 256 | assert.equal((await byEmail(api, "ada@example.net")).name, "Ada <script>alert(1)</script>", "a confirmed request isn't changed"); |
| 257 | const account = await post("/early-access", f, request("ANN@example.com"), undefined, ip()); |
| 258 | assert.equal(account.status, 200); |
| 259 | assert.equal(same(account.html, /ann@example\.com/gi), same(again.html, /ada@example\.net/g), "the page is the same either way"); |
| 260 | const note = await email("already an account", (e) => e.kind === "early_access_known" && e.to_addr === "ann@example.com"); |
| 261 | assert.equal(note.subject, "[Diffinery] You already have a Diffinery account"); |
| 262 | assert.equal(await byEmail(api, "ann@example.com"), undefined); |
| 263 | assert.ok((await emails()).every((e) => e.kind !== "early_access_confirm" || e.to_addr !== "ann@example.com")); |
| 264 | }); |
| 265 | |
| 266 | test("early access: bots, bad input and big bodies get nowhere", async () => { |
| 267 | const { api, post, emails, formOf, ready } = await worker(); |
| 268 | const fresh = await formOf("/early-access"); |
| 269 | // Too fast after the page was shown, a filled honeypot, or a forged stamp: the usual page, nothing kept or sent. |
| 270 | const fast = await post("/early-access", fresh, request("bot1@example.net"), undefined, ip()); |
| 271 | assert.equal(fast.status, 200); |
| 272 | assert.match(fast.html, /Check your inbox/); |
| 273 | const f = await ready(); |
| 274 | const honey = await post("/early-access", f, request("bot2@example.net", { website: "https://spam.example" }), undefined, ip()); |
| 275 | assert.match(honey.html, /Check your inbox/); |
| 276 | const forged = await post("/early-access", { ...f, stamp: `${Date.now() - 10_000}.${"A".repeat(43)}` }, request("bot3@example.net"), undefined, ip()); |
| 277 | assert.match(forged.html, /Check your inbox/); |
| 278 | const missing = await post("/early-access", { ...f, stamp: "" }, request("bot4@example.net"), undefined, ip()); |
| 279 | assert.match(missing.html, /Check your inbox/); |
| 280 | for (const a of ["bot1@example.net", "bot2@example.net", "bot3@example.net", "bot4@example.net"]) assert.equal(await byEmail(api, a), undefined, a); |
| 281 | |
| 282 | // Bad input is refused with the reason, keeping what was typed. |
| 283 | const long = await post("/early-access", f, request("long@example.net", { use_case: "x".repeat(1001), name: "Keep me" }), undefined, ip()); |
| 284 | assert.equal(long.status, 422); |
| 285 | assert.match(long.html, /Keep what you'd use Diffinery for to 1,000 characters/); |
| 286 | assert.match(long.html, /value="Keep me"/); |
| 287 | const bad = await post("/early-access", f, request("not-an-address"), undefined, ip()); |
| 288 | assert.equal(bad.status, 422); |
| 289 | assert.match(bad.html, /Enter a valid email address/); |
| 290 | const hosting = await post("/early-access", f, request("h@example.net", { hosting: "<script>" }), undefined, ip()); |
| 291 | assert.equal(hosting.status, 422); |
| 292 | assert.ok(!hosting.html.includes('value="<script>"')); |
| 293 | const huge = await post("/early-access", f, request("huge@example.net", { use_case: "y".repeat(40_000) }), undefined, ip()); |
| 294 | assert.equal(huge.status, 413); |
| 295 | await sleep(1500); |
| 296 | const tried = new Set(["bot1", "bot2", "bot3", "bot4", "long", "h", "huge"].map((n) => `${n}@example.net`)); |
| 297 | assert.deepEqual((await emails()).filter((e) => tried.has(e.to_addr)), [], "nothing was emailed"); |
| 298 | }); |
| 299 | |
| 300 | test("early access: only site administrators see requests (404 for anyone else)", async () => { |
| 301 | const { page, api, post, formOf } = await worker(); |
| 302 | const ada = await byEmail(api, "ada@example.net"); |
| 303 | assert.ok(ada, "the request from the tests above"); |
| 304 | for (const path of ["/settings/admin/early-access", `/settings/admin/early-access/${ada.id}`]) { |
| 305 | assert.equal((await page(path, "ann")).status, 404, `${path} for a person who isn't a site administrator`); |
| 306 | const anon = await page(path); |
| 307 | assert.equal(anon.status, 302, `${path} sends a visitor to sign in`); |
| 308 | assert.match(anon.headers.get("location") ?? "", /^\/login\?next=/); |
| 309 | } |
| 310 | const annForm = await formOf("/settings", "ann"); |
| 311 | for (const action of ["invite", "decline", "delete"]) assert.equal((await post(`/settings/admin/early-access/${ada.id}/${action}`, annForm, {}, "ann")).status, 404, action); |
| 312 | assert.equal((await api("GET", "/diffinery/admin/early-access", undefined, T.ann)).status, 404); |
| 313 | assert.equal((await api("GET", `/diffinery/admin/early-access/${ada.id}`, undefined, T.ann)).status, 404); |
| 314 | assert.equal((await api("POST", `/diffinery/admin/early-access/${ada.id}/invite`, undefined, T.ann)).status, 404); |
| 315 | assert.equal((await api("PATCH", `/diffinery/admin/early-access/${ada.id}`, { state: "declined" }, T.ann)).status, 404); |
| 316 | assert.equal((await api("DELETE", `/diffinery/admin/early-access/${ada.id}`, undefined, T.ann)).status, 404); |
| 317 | assert.equal((await api("GET", "/diffinery/admin/early-access")).status, 401); |
| 318 | assert.doesNotMatch(await (await page("/settings", "ann")).text(), /href="\/settings\/admin\/early-access"/); |
| 319 | assert.equal((await byEmail(api, "ada@example.net")).state, "confirmed", "nothing changed"); |
| 320 | }); |
| 321 | |
| 322 | test("early access: invite, decline, put back and delete, on the web and through the API, audited", async () => { |
| 323 | const { page, api, post, formOf, email, emails, linkIn, ready } = await worker(); |
| 324 | const ada = await byEmail(api, "ada@example.net"); |
| 325 | // Invite from the web: the instance invitation goes to the address. |
| 326 | const adminForm = await formOf("/settings/admin/early-access", "root"); |
| 327 | const invited = await post(`/settings/admin/early-access/${ada.id}/invite`, adminForm, { back: "/settings/admin/early-access" }, "root"); |
| 328 | assert.equal(invited.status, 303); |
| 329 | assert.equal(invited.location, "/settings/admin/early-access"); |
| 330 | const now = await byEmail(api, "ada@example.net"); |
| 331 | assert.equal(now.state, "invited"); |
| 332 | assert.equal(now.decided_by, "root"); |
| 333 | assert.ok(now.invite_id); |
| 334 | const inv = await email("the invitation", (e) => e.kind === "invite" && e.to_addr === "ada@example.net"); |
| 335 | assert.match(inv.subject, /invited you to Diffinery/); |
| 336 | assert.equal((await api("POST", `/diffinery/admin/early-access/${ada.id}/invite`, undefined, T.root)).status, 422, "not twice"); |
| 337 | assert.match(await (await page("/settings/admin/early-access?state=invited", "root")).text(), /invited by root/); |
| 338 | // Asking again now says so. |
| 339 | const f = await ready(); |
| 340 | await post("/early-access", f, request("ada@example.net"), undefined, ip()); |
| 341 | const already = await email("already invited", (e) => e.kind === "early_access_known" && e.to_addr === "ada@example.net" && /already invited/.test(e.subject)); |
| 342 | assert.equal(already.subject, "[Diffinery] You're already invited"); |
| 343 | |
| 344 | // A second request: decline and put back through the API (no email), then delete on the web. |
| 345 | await post("/early-access", f, request("bob@example.net", { use_case: "secret plans" }), undefined, ip()); |
| 346 | const token = linkIn(await email("bob's confirmation", (e) => e.kind === "early_access_confirm" && e.to_addr === "bob@example.net"), "/early-access/confirm"); |
| 347 | await post("/early-access/confirm", { ...(await formOf("/early-access/confirm")), stamp: "" }, { token }); |
| 348 | const bob = await byEmail(api, "bob@example.net"); |
| 349 | assert.equal(bob.state, "confirmed"); |
| 350 | const sent = (await emails()).length; |
| 351 | const declined = await api("PATCH", `/diffinery/admin/early-access/${bob.id}`, { state: "declined" }, T.root); |
| 352 | assert.equal(declined.status, 200, JSON.stringify(declined.json)); |
| 353 | assert.equal(declined.json.state, "declined"); |
| 354 | assert.equal((await api("PATCH", `/diffinery/admin/early-access/${bob.id}`, { state: "invited" }, T.root)).status, 422); |
| 355 | assert.equal((await api("PATCH", `/diffinery/admin/early-access/${bob.id}`, { state: "confirmed" }, T.root)).json.state, "confirmed"); |
| 356 | await sleep(1500); |
| 357 | assert.equal((await emails()).length, sent, "declining emails nobody"); |
| 358 | const del = await post(`/settings/admin/early-access/${bob.id}/delete`, await formOf(`/settings/admin/early-access/${bob.id}`, "root"), {}, "root"); |
| 359 | assert.equal(del.status, 303); |
| 360 | assert.equal(del.location, "/settings/admin/early-access"); |
| 361 | assert.equal((await api("GET", `/diffinery/admin/early-access/${bob.id}`, undefined, T.root)).status, 404); |
| 362 | |
| 363 | const audit = await (await page("/settings/audit", "root")).text(); |
| 364 | for (const action of ["early_access.confirm", "early_access.invite", "early_access.decline", "early_access.restore", "early_access.delete", "invite.create"]) assert.ok(audit.includes(action), `${action} is audited`); |
| 365 | assert.ok(!audit.includes("secret plans") && !audit.includes("onerror"), "the audit log holds no request content"); |
| 366 | }); |
| 367 | |
| 368 | test("early access: people remove their own request with an emailed link", async () => { |
| 369 | const { api, post, formOf, email, emails, linkIn, ready } = await worker(); |
| 370 | const f = await ready(); |
| 371 | await post("/early-access", f, request("carol@example.net"), undefined, ip()); |
| 372 | await email("carol's confirmation", (e) => e.kind === "early_access_confirm" && e.to_addr === "carol@example.net"); |
| 373 | assert.ok(await byEmail(api, "carol@example.net")); |
| 374 | const rf = await ready("/early-access/remove"); |
| 375 | const none = await post("/early-access/remove", rf, { email: "nobody@example.net", website: "" }, undefined, ip()); |
| 376 | assert.equal(none.status, 200); |
| 377 | assert.match(none.html, /If there's an early access request for <b>nobody@example\.net<\/b>/); |
| 378 | const asked = await post("/early-access/remove", rf, { email: "Carol@Example.net", website: "" }, undefined, ip()); |
| 379 | assert.equal(same(asked.html, /carol@example\.net/gi), same(none.html, /nobody@example\.net/g), "the same page either way"); |
| 380 | const m = await email("the removal link", (e) => e.kind === "early_access_remove" && e.to_addr === "carol@example.net"); |
| 381 | assert.equal(m.subject, "[Diffinery] Remove your early access request"); |
| 382 | assert.ok((await emails()).every((e) => e.to_addr !== "nobody@example.net"), "no request, no email"); |
| 383 | const token = linkIn(m, "/early-access/remove/confirm"); |
| 384 | const cf = { ...(await formOf("/early-access/remove/confirm")), stamp: "" }; |
| 385 | const gone = await post("/early-access/remove/confirm", cf, { token }); |
| 386 | assert.equal(gone.status, 200); |
| 387 | assert.match(gone.html, /Your request is removed/); |
| 388 | assert.equal(await byEmail(api, "carol@example.net"), undefined); |
| 389 | assert.equal((await post("/early-access/remove/confirm", cf, { token })).status, 410); |
| 390 | }); |
| 391 | |
| 392 | test("early access: daily limits per network and per address", async () => { |
| 393 | const { api, post, emails, ready } = await worker(); |
| 394 | const f = await ready(); |
| 395 | // One address: three emails a day, then the page stays the same and nothing more is sent. |
| 396 | const flood = "flood@example.net"; |
| 397 | for (let i = 0; i < 4; i++) assert.equal((await post("/early-access", f, request(flood), undefined, ip())).status, 200); |
| 398 | await sleep(1500); |
| 399 | assert.equal((await emails()).filter((e) => e.to_addr === flood).length, 3); |
| 400 | // One network: ten submissions a day, then a visible refusal. |
| 401 | const net = "203.0.113.77"; |
| 402 | for (let i = 0; i < 10; i++) assert.equal((await post("/early-access", f, request(`n${i}@example.net`), undefined, net)).status, 200, `submission ${i + 1}`); |
| 403 | const over = await post("/early-access", f, request("n10@example.net"), undefined, net); |
| 404 | assert.equal(over.status, 429); |
| 405 | assert.match(over.html, /Too many requests from your network today/); |
| 406 | assert.equal(await byEmail(api, "n10@example.net"), undefined); |
| 407 | // Another network still gets through. |
| 408 | assert.equal((await post("/early-access", f, request("other@example.net"), undefined, ip())).status, 200); |
| 409 | }); |