Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

408 lines · 25.8 KBRaw History
1// End-to-end early access (lib/early-access.ts, web/early-access.tsx) on a real `wrangler dev` Worker:
2// the home page, 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
13import "./fresh-connections.mjs";
14import { spawn, execFileSync } from "node:child_process";
15import { createHash, randomBytes } from "node:crypto";
16import { mkdtempSync, rmSync } from "node:fs";
17import { tmpdir } from "node:os";
18import { join, dirname, resolve } from "node:path";
19import { fileURLToPath } from "node:url";
20import { request as httpRequest } from "node:http";
21import { test, after } from "node:test";
22import assert from "node:assert/strict";
23import { migratedState } from "./d1-state.mjs";
24import { freePort } from "./ports.mjs";
25
26const APP = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
27const work = mkdtempSync(join(tmpdir(), "diffinery-early-access-e2e-"));
28const running = [];
29
30const hash = (s) => createHash("sha256").update(s).digest("hex");
31const 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 */
37function 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
60function stopWorker(dev) {
61 try {
62 process.kill(-dev.pid, "SIGTERM");
63 } catch {}
64}
65
66after(() => {
67 for (const dev of running) stopWorker(dev);
68 if (process.env.E2E_KEEP !== "1") rmSync(work, { recursive: true, force: true });
69});
70
71const T = { root: `dfy_root_${randomBytes(12).toString("hex")}`, ann: `dfy_ann_${randomBytes(12).toString("hex")}` };
72const 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). */
74const VISITOR = "visitor.example";
75
76let w;
77async 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 &#39;; 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(/&#39;/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. */
170const same = (html, address) => html.replace(address, "ADDRESS").replace(/nonce="[^"]*"/g, "");
171const request = (email, over = {}) => ({ email, name: "", company: "", use_case: "", hosting: "", website: "", ...over });
172const byEmail = async (api, address) => (await api("GET", `/diffinery/admin/early-access?q=${encodeURIComponent(address)}`, undefined, T.root)).json.find((r) => r.email === address);
173let nextIp = 1;
174/** A fresh address for the Worker to see each request from, so the daily limit per network doesn't mix tests. */
175const ip = () => `198.51.100.${nextIp++}`;
176
177test("early access: the home page, 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 assert.match(home, /href="\/early-access"[^>]*>\s*Request early access/);
181 assert.match(await (await page("/login")).text(), /href="\/early-access">request early access</);
182 const signup = await page("/signup");
183 assert.equal(signup.status, 302);
184 assert.equal(signup.headers.get("location"), "/early-access");
185 const form = await page("/early-access");
186 assert.equal(form.status, 200);
187 const html = await form.text();
188 assert.match(html, /Request early access to Diffinery/);
189 for (const name of ["email", "name", "company", "use_case", "hosting", "website", "stamp"]) assert.match(html, new RegExp(`name="${name}"`), name);
190 assert.doesNotMatch(html, /<select|type="checkbox"/, "Kumo controls only");
191 assert.match(html, /href="\/early-access\/remove"/);
192 // Signed in, the form isn't needed.
193 const annForm = await page("/early-access", "ann");
194 assert.equal(annForm.status, 302);
195 assert.equal(annForm.headers.get("location"), "/");
196 // Search engines find the form, not the confirmation pages.
197 const robots = await (await page("/robots.txt")).text();
198 assert.match(robots, /Disallow: \/early-access\/confirm/);
199 assert.match(robots, /Disallow: \/early-access\/remove/);
200 assert.match(await (await page("/sitemap.xml")).text(), /\/early-access<\/loc>/);
201});
202
203test("early access: a request is confirmed with the link from its email, then waits for site administrators", async () => {
204 const { page, api, post, email, linkIn, ready } = await worker();
205 const f = await ready();
206 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" };
207 const sent = await post("/early-access", f, request("Ada@Example.net", hostile), undefined, ip());
208 assert.equal(sent.status, 200, sent.html.slice(0, 600));
209 assert.match(sent.html, /Check your inbox/);
210 assert.match(sent.html, /ada@example\.net/);
211 const m = await email("the confirmation", (e) => e.kind === "early_access_confirm" && e.to_addr === "ada@example.net");
212 assert.equal(m.subject, "[Diffinery] Confirm your early access request");
213 assert.doesNotMatch(JSON.stringify(m.dev_copy), /Ada|Acme|onerror|Move 40/, "nothing typed in the form goes into the email");
214 const token = linkIn(m, "/early-access/confirm");
215
216 // Unconfirmed: not waiting yet.
217 const before = await byEmail(api, "ada@example.net");
218 assert.equal(before.state, "unconfirmed");
219 assert.doesNotMatch(await (await page("/settings/admin/early-access", "root")).text(), /ada@example\.net/);
220
221 const confirmPage = await page("/early-access/confirm");
222 assert.equal(confirmPage.status, 200);
223 const cf = { ...(await w.formOf("/early-access/confirm")), stamp: "" };
224 const wrong = await post("/early-access/confirm", cf, { token: "x".repeat(40) });
225 assert.equal(wrong.status, 410);
226 assert.match(wrong.html, /This link doesn't work any more/);
227 const ok = await post("/early-access/confirm", cf, { token });
228 assert.equal(ok.status, 200, ok.html.slice(0, 600));
229 assert.match(ok.html, /You're on the list/);
230 assert.ok(ok.html.includes("Ada &lt;script&gt;alert(1)&lt;/script&gt;"), "the name is escaped");
231 assert.equal((await post("/early-access/confirm", cf, { token })).status, 410, "a link works once");
232
233 const after = await byEmail(api, "ada@example.net");
234 assert.equal(after.state, "confirmed");
235 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" });
236 assert.ok(!("confirm_hash" in after));
237 const admin = await (await page("/settings/admin/early-access", "root")).text();
238 assert.match(admin, /ada@example\.net/);
239 assert.ok(!admin.includes("<script>alert(1)") && !admin.includes("<img src=x"), "everything is escaped");
240 assert.match(admin, /Early access\s*<span class="badge blue"[^>]*>\s*1\s*</, "the sidebar counts what waits");
241 const detail = await (await page(`/settings/admin/early-access/${after.id}`, "root")).text();
242 assert.ok(detail.includes("Move 40 repos.\n&lt;img src=x onerror=alert(1)&gt;"), "the use is plain text");
243 assert.match(await (await page("/notifications", "root")).text(), /New early access requests are waiting for you/);
244 assert.match(await (await page("/settings/admin", "root")).text(), /1 confirmed early access request is waiting/);
245});
246
247test("early access: the same answer for an address that already asked or has an account; only its inbox learns which", async () => {
248 const { api, post, email, emails, ready } = await worker();
249 const f = await ready();
250 const again = await post("/early-access", f, request("ada@example.net", { name: "Mallory" }), undefined, ip());
251 assert.equal(again.status, 200);
252 assert.match(again.html, /Check your inbox/);
253 const known = await email("already asked", (e) => e.kind === "early_access_known" && e.to_addr === "ada@example.net");
254 assert.equal(known.subject, "[Diffinery] We already have your early access request");
255 assert.equal((await byEmail(api, "ada@example.net")).name, "Ada <script>alert(1)</script>", "a confirmed request isn't changed");
256 const account = await post("/early-access", f, request("ANN@example.com"), undefined, ip());
257 assert.equal(account.status, 200);
258 assert.equal(same(account.html, /ann@example\.com/gi), same(again.html, /ada@example\.net/g), "the page is the same either way");
259 const note = await email("already an account", (e) => e.kind === "early_access_known" && e.to_addr === "ann@example.com");
260 assert.equal(note.subject, "[Diffinery] You already have a Diffinery account");
261 assert.equal(await byEmail(api, "ann@example.com"), undefined);
262 assert.ok((await emails()).every((e) => e.kind !== "early_access_confirm" || e.to_addr !== "ann@example.com"));
263});
264
265test("early access: bots, bad input and big bodies get nowhere", async () => {
266 const { api, post, emails, formOf, ready } = await worker();
267 const fresh = await formOf("/early-access");
268 // Too fast after the page was shown, a filled honeypot, or a forged stamp: the usual page, nothing kept or sent.
269 const fast = await post("/early-access", fresh, request("bot1@example.net"), undefined, ip());
270 assert.equal(fast.status, 200);
271 assert.match(fast.html, /Check your inbox/);
272 const f = await ready();
273 const honey = await post("/early-access", f, request("bot2@example.net", { website: "https://spam.example" }), undefined, ip());
274 assert.match(honey.html, /Check your inbox/);
275 const forged = await post("/early-access", { ...f, stamp: `${Date.now() - 10_000}.${"A".repeat(43)}` }, request("bot3@example.net"), undefined, ip());
276 assert.match(forged.html, /Check your inbox/);
277 const missing = await post("/early-access", { ...f, stamp: "" }, request("bot4@example.net"), undefined, ip());
278 assert.match(missing.html, /Check your inbox/);
279 for (const a of ["bot1@example.net", "bot2@example.net", "bot3@example.net", "bot4@example.net"]) assert.equal(await byEmail(api, a), undefined, a);
280
281 // Bad input is refused with the reason, keeping what was typed.
282 const long = await post("/early-access", f, request("long@example.net", { use_case: "x".repeat(1001), name: "Keep me" }), undefined, ip());
283 assert.equal(long.status, 422);
284 assert.match(long.html, /Keep what you'd use Diffinery for to 1,000 characters/);
285 assert.match(long.html, /value="Keep me"/);
286 const bad = await post("/early-access", f, request("not-an-address"), undefined, ip());
287 assert.equal(bad.status, 422);
288 assert.match(bad.html, /Enter a valid email address/);
289 const hosting = await post("/early-access", f, request("h@example.net", { hosting: "<script>" }), undefined, ip());
290 assert.equal(hosting.status, 422);
291 assert.ok(!hosting.html.includes('value="<script>"'));
292 const huge = await post("/early-access", f, request("huge@example.net", { use_case: "y".repeat(40_000) }), undefined, ip());
293 assert.equal(huge.status, 413);
294 await sleep(1500);
295 const tried = new Set(["bot1", "bot2", "bot3", "bot4", "long", "h", "huge"].map((n) => `${n}@example.net`));
296 assert.deepEqual((await emails()).filter((e) => tried.has(e.to_addr)), [], "nothing was emailed");
297});
298
299test("early access: only site administrators see requests (404 for anyone else)", async () => {
300 const { page, api, post, formOf } = await worker();
301 const ada = await byEmail(api, "ada@example.net");
302 assert.ok(ada, "the request from the tests above");
303 for (const path of ["/settings/admin/early-access", `/settings/admin/early-access/${ada.id}`]) {
304 assert.equal((await page(path, "ann")).status, 404, `${path} for a person who isn't a site administrator`);
305 const anon = await page(path);
306 assert.equal(anon.status, 302, `${path} sends a visitor to sign in`);
307 assert.match(anon.headers.get("location") ?? "", /^\/login\?next=/);
308 }
309 const annForm = await formOf("/settings", "ann");
310 for (const action of ["invite", "decline", "delete"]) assert.equal((await post(`/settings/admin/early-access/${ada.id}/${action}`, annForm, {}, "ann")).status, 404, action);
311 assert.equal((await api("GET", "/diffinery/admin/early-access", undefined, T.ann)).status, 404);
312 assert.equal((await api("GET", `/diffinery/admin/early-access/${ada.id}`, undefined, T.ann)).status, 404);
313 assert.equal((await api("POST", `/diffinery/admin/early-access/${ada.id}/invite`, undefined, T.ann)).status, 404);
314 assert.equal((await api("PATCH", `/diffinery/admin/early-access/${ada.id}`, { state: "declined" }, T.ann)).status, 404);
315 assert.equal((await api("DELETE", `/diffinery/admin/early-access/${ada.id}`, undefined, T.ann)).status, 404);
316 assert.equal((await api("GET", "/diffinery/admin/early-access")).status, 401);
317 assert.doesNotMatch(await (await page("/settings", "ann")).text(), /href="\/settings\/admin\/early-access"/);
318 assert.equal((await byEmail(api, "ada@example.net")).state, "confirmed", "nothing changed");
319});
320
321test("early access: invite, decline, put back and delete, on the web and through the API, audited", async () => {
322 const { page, api, post, formOf, email, emails, linkIn, ready } = await worker();
323 const ada = await byEmail(api, "ada@example.net");
324 // Invite from the web: the instance invitation goes to the address.
325 const adminForm = await formOf("/settings/admin/early-access", "root");
326 const invited = await post(`/settings/admin/early-access/${ada.id}/invite`, adminForm, { back: "/settings/admin/early-access" }, "root");
327 assert.equal(invited.status, 303);
328 assert.equal(invited.location, "/settings/admin/early-access");
329 const now = await byEmail(api, "ada@example.net");
330 assert.equal(now.state, "invited");
331 assert.equal(now.decided_by, "root");
332 assert.ok(now.invite_id);
333 const inv = await email("the invitation", (e) => e.kind === "invite" && e.to_addr === "ada@example.net");
334 assert.match(inv.subject, /invited you to Diffinery/);
335 assert.equal((await api("POST", `/diffinery/admin/early-access/${ada.id}/invite`, undefined, T.root)).status, 422, "not twice");
336 assert.match(await (await page("/settings/admin/early-access?state=invited", "root")).text(), /invited by root/);
337 // Asking again now says so.
338 const f = await ready();
339 await post("/early-access", f, request("ada@example.net"), undefined, ip());
340 const already = await email("already invited", (e) => e.kind === "early_access_known" && e.to_addr === "ada@example.net" && /already invited/.test(e.subject));
341 assert.equal(already.subject, "[Diffinery] You're already invited");
342
343 // A second request: decline and put back through the API (no email), then delete on the web.
344 await post("/early-access", f, request("bob@example.net", { use_case: "secret plans" }), undefined, ip());
345 const token = linkIn(await email("bob's confirmation", (e) => e.kind === "early_access_confirm" && e.to_addr === "bob@example.net"), "/early-access/confirm");
346 await post("/early-access/confirm", { ...(await formOf("/early-access/confirm")), stamp: "" }, { token });
347 const bob = await byEmail(api, "bob@example.net");
348 assert.equal(bob.state, "confirmed");
349 const sent = (await emails()).length;
350 const declined = await api("PATCH", `/diffinery/admin/early-access/${bob.id}`, { state: "declined" }, T.root);
351 assert.equal(declined.status, 200, JSON.stringify(declined.json));
352 assert.equal(declined.json.state, "declined");
353 assert.equal((await api("PATCH", `/diffinery/admin/early-access/${bob.id}`, { state: "invited" }, T.root)).status, 422);
354 assert.equal((await api("PATCH", `/diffinery/admin/early-access/${bob.id}`, { state: "confirmed" }, T.root)).json.state, "confirmed");
355 await sleep(1500);
356 assert.equal((await emails()).length, sent, "declining emails nobody");
357 const del = await post(`/settings/admin/early-access/${bob.id}/delete`, await formOf(`/settings/admin/early-access/${bob.id}`, "root"), {}, "root");
358 assert.equal(del.status, 303);
359 assert.equal(del.location, "/settings/admin/early-access");
360 assert.equal((await api("GET", `/diffinery/admin/early-access/${bob.id}`, undefined, T.root)).status, 404);
361
362 const audit = await (await page("/settings/audit", "root")).text();
363 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`);
364 assert.ok(!audit.includes("secret plans") && !audit.includes("onerror"), "the audit log holds no request content");
365});
366
367test("early access: people remove their own request with an emailed link", async () => {
368 const { api, post, formOf, email, emails, linkIn, ready } = await worker();
369 const f = await ready();
370 await post("/early-access", f, request("carol@example.net"), undefined, ip());
371 await email("carol's confirmation", (e) => e.kind === "early_access_confirm" && e.to_addr === "carol@example.net");
372 assert.ok(await byEmail(api, "carol@example.net"));
373 const rf = await ready("/early-access/remove");
374 const none = await post("/early-access/remove", rf, { email: "nobody@example.net", website: "" }, undefined, ip());
375 assert.equal(none.status, 200);
376 assert.match(none.html, /If there's an early access request for <b>nobody@example\.net<\/b>/);
377 const asked = await post("/early-access/remove", rf, { email: "Carol@Example.net", website: "" }, undefined, ip());
378 assert.equal(same(asked.html, /carol@example\.net/gi), same(none.html, /nobody@example\.net/g), "the same page either way");
379 const m = await email("the removal link", (e) => e.kind === "early_access_remove" && e.to_addr === "carol@example.net");
380 assert.equal(m.subject, "[Diffinery] Remove your early access request");
381 assert.ok((await emails()).every((e) => e.to_addr !== "nobody@example.net"), "no request, no email");
382 const token = linkIn(m, "/early-access/remove/confirm");
383 const cf = { ...(await formOf("/early-access/remove/confirm")), stamp: "" };
384 const gone = await post("/early-access/remove/confirm", cf, { token });
385 assert.equal(gone.status, 200);
386 assert.match(gone.html, /Your request is removed/);
387 assert.equal(await byEmail(api, "carol@example.net"), undefined);
388 assert.equal((await post("/early-access/remove/confirm", cf, { token })).status, 410);
389});
390
391test("early access: daily limits per network and per address", async () => {
392 const { api, post, emails, ready } = await worker();
393 const f = await ready();
394 // One address: three emails a day, then the page stays the same and nothing more is sent.
395 const flood = "flood@example.net";
396 for (let i = 0; i < 4; i++) assert.equal((await post("/early-access", f, request(flood), undefined, ip())).status, 200);
397 await sleep(1500);
398 assert.equal((await emails()).filter((e) => e.to_addr === flood).length, 3);
399 // One network: ten submissions a day, then a visible refusal.
400 const net = "203.0.113.77";
401 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}`);
402 const over = await post("/early-access", f, request("n10@example.net"), undefined, net);
403 assert.equal(over.status, 429);
404 assert.match(over.html, /Too many requests from your network today/);
405 assert.equal(await byEmail(api, "n10@example.net"), undefined);
406 // Another network still gets through.
407 assert.equal((await post("/early-access", f, request("other@example.net"), undefined, ip())).status, 200);
408});