@mccaskie-labs/workbench-accounts 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/limits.js ADDED
@@ -0,0 +1,38 @@
1
+ // The sign-in limits: Workers rate limiting per IP and per address, keyed by
2
+ // hashes so the counter store never holds an address or an IP (authentication
3
+ // standard §9). Past a limit the person is asked to wait a minute: never a lockout.
4
+ /**
5
+ * The IP as the limiter counts it: IPv4 whole, IPv6 by its /64, since one
6
+ * connection usually holds a whole /64 and could otherwise pick a new key per try.
7
+ */
8
+ export function ipKey(ip) {
9
+ if (!ip.includes(":"))
10
+ return ip;
11
+ const [head = "", tail = ""] = ip.toLowerCase().split("::");
12
+ const h = head ? head.split(":") : [];
13
+ const t = tail ? tail.split(":") : [];
14
+ const groups = ip.includes("::") ? [...h, ...Array(Math.max(0, 8 - h.length - t.length)).fill("0"), ...t] : h;
15
+ return `${groups.slice(0, 4).map((g) => g.replace(/^0+(?=.)/, "")).join(":")}::/64`;
16
+ }
17
+ /** Outside development both limiters must be bound: sign-in refuses rather than run without them. */
18
+ export function missingLimits(limits, environment) {
19
+ if (limits.ip && limits.email)
20
+ return false;
21
+ if (environment === "development")
22
+ return false;
23
+ console.error("SIGN_IN_IP_LIMIT or SIGN_IN_EMAIL_LIMIT isn't bound: sign-in is off");
24
+ return true;
25
+ }
26
+ /** True when this IP or this address (whichever are given) has tried too often in the last minute. */
27
+ export async function overLimit(limits, sessions, { ip, email }) {
28
+ const checks = [];
29
+ if (limits.ip && ip !== undefined)
30
+ checks.push(limits.ip.limit({ key: await sessions.limitKey("ip", ip) }));
31
+ if (limits.email && email !== undefined)
32
+ checks.push(limits.email.limit({ key: await sessions.limitKey("email", email.trim().toLowerCase()) }));
33
+ const results = await Promise.all(checks);
34
+ const over = results.some((r) => !r.success);
35
+ if (over)
36
+ console.warn(JSON.stringify({ event: "sign_in_limited" }));
37
+ return over;
38
+ }
@@ -0,0 +1,54 @@
1
+ import { type Result } from "@mccaskie-labs/workbench-forms";
2
+ import type { Words } from "./words.ts";
3
+ /** The paths the tool answers. */
4
+ export declare const PATHS: {
5
+ readonly signIn: "/sign-in";
6
+ readonly join: "/join";
7
+ readonly code: "/auth/code";
8
+ readonly joinCode: "/auth/join";
9
+ readonly resend: "/auth/resend";
10
+ readonly verify: "/auth/verify";
11
+ readonly signOut: "/auth/sign-out";
12
+ readonly account: "/account";
13
+ readonly name: "/account/name";
14
+ };
15
+ export interface Step {
16
+ title: string;
17
+ body: string;
18
+ script?: string;
19
+ /** The Turnstile site key when the step carries the check. */
20
+ turnstile?: string | null;
21
+ }
22
+ /** What every drawing needs: the words, the code's length and the Turnstile site key (null when off). */
23
+ export interface Draw {
24
+ w: (key: string, params?: Readonly<Record<string, string | number>>) => string;
25
+ t: Words;
26
+ codeLength: number;
27
+ check: string | null;
28
+ /** Where the Join page's privacy line links, when the project has a Privacy page. */
29
+ privacy?: string | null;
30
+ }
31
+ export declare const codeUrl: (next: string) => string;
32
+ /** Sign in, step 1: the email address. */
33
+ export declare function emailStep(d: Draw, next: string, email: string, error?: string, result?: Result): Step;
34
+ /** Join: email and name (and the 18-or-over tick when the project asks). */
35
+ export declare function joinStep(d: Draw, next: string, adult: boolean, o?: {
36
+ error?: string;
37
+ result?: Result;
38
+ input?: Record<string, unknown>;
39
+ }): Step;
40
+ /** Enter your code: one box per digit; paste fills them all. */
41
+ export declare function codeStep(d: Draw, next: string, pending: {
42
+ email: string;
43
+ sent: number;
44
+ }, error?: string, now?: number): Step;
45
+ /** Your account: who is signed in, their name, and sign out. */
46
+ export declare function accountStep(d: Draw, you: {
47
+ email: string;
48
+ name: string | null;
49
+ }, o?: {
50
+ saved?: boolean;
51
+ error?: string;
52
+ result?: Result;
53
+ input?: Record<string, unknown>;
54
+ }): Step;
package/dist/pages.js ADDED
@@ -0,0 +1,131 @@
1
+ // What the account pages draw. Every element the tool draws carries a
2
+ // `wb-accounts-<part>` class (ACCOUNTS_STYLES has each one's default rule);
3
+ // the page around it is workbench-ui's shell, as on every app page. The
4
+ // fields come from workbench-forms (renderForm, fieldsOnly), so they look and
5
+ // read like every other form in the app.
6
+ import { renderForm } from "@mccaskie-labs/workbench-forms";
7
+ import { FORM_CONTEXT, JOIN_ADULT_FORM, JOIN_FORM, NAME_FORM, SIGN_IN_FORM } from "./forms.js";
8
+ const ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
9
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ESC[c]);
10
+ /** The paths the tool answers. */
11
+ export const PATHS = {
12
+ signIn: "/sign-in",
13
+ join: "/join",
14
+ code: "/auth/code",
15
+ joinCode: "/auth/join",
16
+ resend: "/auth/resend",
17
+ verify: "/auth/verify",
18
+ signOut: "/auth/sign-out",
19
+ account: "/account",
20
+ name: "/account/name",
21
+ };
22
+ const withNext = (path, next) => (next === "/" ? path : `${path}${path.includes("?") ? "&" : "?"}next=${encodeURIComponent(next)}`);
23
+ export const codeUrl = (next) => withNext("/sign-in?step=code", next);
24
+ const hidden = (next) => `<input class="wb-accounts-next" type="hidden" name="next" value="${esc(next)}">`;
25
+ /** The Turnstile check inside a form: shown only when Cloudflare needs the person to click it. */
26
+ const widget = (siteKey) => siteKey ? `<div class="cf-turnstile wb-accounts-check" data-sitekey="${esc(siteKey)}" data-action="sign-in" data-appearance="interaction-only" data-theme="auto"></div>` : "";
27
+ const problem = (error) => (error ? `<p class="wb-ui-message wb-accounts-problem" data-tone="fail" role="alert" id="problem">${esc(error)}</p>` : "");
28
+ const note = (text) => (text ? `<p class="wb-ui-message wb-accounts-done" data-tone="pass" role="status">${esc(text)}</p>` : "");
29
+ const small = (inner) => `<p class="wb-ui-small wb-accounts-small">${inner}</p>`;
30
+ const button = (text, kind = "primary") => `<button class="wb-ui-button wb-accounts-button" data-kind="${kind}" type="submit">${esc(text)}</button>`;
31
+ const card = (inner) => `<div class="wb-ui-card wb-accounts-card"><div class="wb-ui-body wb-accounts-body">${inner}</div></div>`;
32
+ const fields = (d, form, action, o = {}) => renderForm(form, FORM_CONTEXT, { action, t: d.t, submit: "ui.wbaccounts.sign_in.send", fieldsOnly: true, ...o });
33
+ /** Puts autofocus on the form's first input, which renderForm leaves to the page. */
34
+ const focusFirst = (html) => html.replace(/<input(?= )/, "<input autofocus");
35
+ /** Sign in, step 1: the email address. */
36
+ export function emailStep(d, next, email, error, result) {
37
+ const values = email ? { email } : undefined;
38
+ return {
39
+ title: d.w("ui.wbaccounts.sign_in.title"),
40
+ body: card(`
41
+ <p class="wb-accounts-intro">${esc(d.w("ui.wbaccounts.sign_in.intro"))}</p>${problem(error)}
42
+ <form class="wb-accounts-form" method="post" action="${PATHS.code}" novalidate>${hidden(next)}
43
+ ${focusFirst(fields(d, SIGN_IN_FORM, PATHS.code, { ...(result ? { result } : {}), ...(values ? { values } : {}) }))}
44
+ ${widget(d.check)}<p class="wb-accounts-actions">${button(d.w("ui.wbaccounts.sign_in.send"))}</p>
45
+ </form>
46
+ ${small(esc(d.w("ui.wbaccounts.sign_in.forgot")))}
47
+ ${small(`<a class="wb-accounts-link" href="${esc(withNext(PATHS.join, next))}">${esc(d.w("ui.wbaccounts.sign_in.join"))}</a>`)}
48
+ `),
49
+ turnstile: d.check,
50
+ };
51
+ }
52
+ /** Join: email and name (and the 18-or-over tick when the project asks). */
53
+ export function joinStep(d, next, adult, o = {}) {
54
+ const form = adult ? JOIN_ADULT_FORM : JOIN_FORM;
55
+ const privacy = d.privacy ? small(`<a class="wb-accounts-link" href="${esc(d.privacy)}">${esc(d.w("ui.wbaccounts.join.privacy"))}</a>`) : "";
56
+ return {
57
+ title: d.w("ui.wbaccounts.join.title"),
58
+ body: card(`
59
+ <p class="wb-accounts-intro">${esc(d.w("ui.wbaccounts.join.intro"))}</p>${problem(o.error)}
60
+ <form class="wb-accounts-form" method="post" action="${PATHS.joinCode}" novalidate>${hidden(next)}
61
+ ${focusFirst(fields(d, form, PATHS.joinCode, { ...(o.result ? { result: o.result } : {}), ...(o.input ? { input: o.input } : {}) }))}
62
+ ${widget(d.check)}<p class="wb-accounts-actions">${button(d.w("ui.wbaccounts.join.send"))}</p>
63
+ </form>
64
+ ${privacy}${small(`<a class="wb-accounts-link" href="${esc(withNext(PATHS.signIn, next))}">${esc(d.w("ui.wbaccounts.join.have"))}</a>`)}
65
+ `),
66
+ turnstile: d.check,
67
+ };
68
+ }
69
+ /** Enter your code: one box per digit; paste fills them all. */
70
+ export function codeStep(d, next, pending, error, now = Date.now()) {
71
+ const ago = Math.max(0, Math.round((now / 1000 - pending.sent) / 60));
72
+ const key = ago < 1 ? "ui.wbaccounts.code.sent_now" : ago === 1 ? "ui.wbaccounts.code.sent_minute" : "ui.wbaccounts.code.sent_minutes";
73
+ const sent = d.w(key, { digits: d.codeLength, email: pending.email, minutes: ago });
74
+ const digits = Array.from({ length: d.codeLength }, (_, i) => {
75
+ const n = i + 1;
76
+ const a = [
77
+ ["class", "wb-ui-input wb-accounts-digit"],
78
+ ["id", `d${n}`],
79
+ ["name", `d${n}`],
80
+ ["aria-label", d.w("ui.wbaccounts.code.digit", { n, of: d.codeLength })],
81
+ ["inputmode", "numeric"],
82
+ ["pattern", "[0-9]"],
83
+ ["maxlength", "1"],
84
+ ["size", "1"],
85
+ ["autocomplete", n === 1 ? "one-time-code" : "off"],
86
+ ...(error ? [["aria-describedby", "problem"]] : []),
87
+ ];
88
+ return `<input${a.map(([k, v]) => ` ${k}="${esc(v)}"`).join("")} required${n === 1 ? " autofocus" : ""}>`;
89
+ }).join("");
90
+ return {
91
+ title: d.w("ui.wbaccounts.code.title"),
92
+ body: card(`
93
+ <p class="wb-accounts-intro">${esc(sent)}</p>${problem(error)}
94
+ <form class="wb-accounts-form" method="post" action="${PATHS.verify}">${hidden(next)}
95
+ <fieldset class="wb-accounts-code"><legend class="wb-accounts-code-label">${esc(d.w("ui.wbaccounts.code.label"))}</legend><div class="wb-accounts-digits">${digits}</div></fieldset>
96
+ <label class="wb-ui-check wb-accounts-keep"><input class="wb-ui-check-box wb-accounts-keep-box" type="checkbox" name="keep" value="yes" checked> <span class="wb-ui-check-text wb-accounts-keep-text">${esc(d.w("ui.wbaccounts.code.keep"))}</span></label>${small(esc(d.w("ui.wbaccounts.code.keep_hint")))}
97
+ <p class="wb-accounts-actions">${button(d.w("ui.wbaccounts.code.sign_in"))}</p>
98
+ </form>
99
+ <form class="wb-accounts-form" method="post" action="${PATHS.resend}">${hidden(next)}${widget(d.check)}${small(`${esc(d.w("ui.wbaccounts.code.none"))} ${button(d.w("ui.wbaccounts.code.resend"), "link")}`)}</form>
100
+ ${small(`<a class="wb-accounts-link" href="${esc(withNext(PATHS.signIn, next))}">${esc(d.w("ui.wbaccounts.code.other"))}</a>`)}
101
+ `),
102
+ script: DIGITS_SCRIPT,
103
+ turnstile: d.check,
104
+ };
105
+ }
106
+ /** Your account: who is signed in, their name, and sign out. */
107
+ export function accountStep(d, you, o = {}) {
108
+ const values = you.name ? { name: you.name } : undefined;
109
+ return {
110
+ title: d.w("ui.wbaccounts.account.title"),
111
+ body: card(`
112
+ <h2 class="wb-accounts-heading">${esc(d.w("ui.wbaccounts.account.you"))}</h2>
113
+ <p class="wb-accounts-intro">${esc(d.w("ui.wbaccounts.account.signed_in", { email: you.email }))}</p>${o.saved ? note(d.w("ui.wbaccounts.account.name_saved")) : ""}${problem(o.error)}
114
+ <form class="wb-accounts-form" method="post" action="${PATHS.name}" novalidate>
115
+ ${fields(d, NAME_FORM, PATHS.name, { ...(o.result ? { result: o.result } : {}), ...(o.input ? { input: o.input } : {}), ...(values && !o.result ? { values } : {}) })}
116
+ <p class="wb-accounts-actions">${button(d.w("ui.wbaccounts.account.save_name"))}</p>
117
+ </form>
118
+ <form class="wb-accounts-form wb-accounts-sign-out" method="post" action="${PATHS.signOut}"><p class="wb-accounts-actions">${button(d.w("ui.wbaccounts.account.sign_out"))}</p></form>
119
+ `),
120
+ };
121
+ }
122
+ /** Paste fills every box; typing a digit moves on; Backspace in an empty box moves back. The form works without it. */
123
+ const DIGITS_SCRIPT = `(() => {
124
+ const boxes = [...document.querySelectorAll(".wb-accounts-digits input")];
125
+ const fill = (from, text) => { const d = text.replace(/\\D/g, ""); if (!d) return; for (let i = 0; i < d.length && from + i < boxes.length; i++) boxes[from + i].value = d[i]; boxes[Math.min(from + d.length, boxes.length - 1)].focus(); };
126
+ boxes.forEach((b, i) => {
127
+ b.addEventListener("paste", (e) => { e.preventDefault(); fill(i, e.clipboardData.getData("text")); });
128
+ b.addEventListener("input", () => { if (b.value.length > 1) { fill(i, b.value); return; } b.value = b.value.replace(/\\D/g, ""); if (b.value && boxes[i + 1]) boxes[i + 1].focus(); });
129
+ b.addEventListener("keydown", (e) => { if (e.key === "Backspace" && !b.value && boxes[i - 1]) boxes[i - 1].focus(); });
130
+ });
131
+ })();`;
@@ -0,0 +1,14 @@
1
+ /** Every sample of one tool (workbench-ui's ToolSamples). */
2
+ export interface ToolSamples {
3
+ format: 1;
4
+ package: string;
5
+ title: string;
6
+ prefix: string;
7
+ samples: readonly {
8
+ id: string;
9
+ title: string;
10
+ layout?: string;
11
+ html: () => string;
12
+ }[];
13
+ }
14
+ export declare const ACCOUNTS_SAMPLES: ToolSamples;
@@ -0,0 +1,38 @@
1
+ // The account pages' samples (docs/look-studio.md §5.1): every part the tool
2
+ // draws, with a made-up person, for the project's style guide, the look
3
+ // previewer and the visual check. Drawn by the pages' own drawers, so a
4
+ // sample can't drift from the real page.
5
+ import { validate } from "@mccaskie-labs/workbench-forms";
6
+ import { FORM_CONTEXT, NAME_FORM } from "./forms.js";
7
+ import { accountStep, codeStep, emailStep, joinStep } from "./pages.js";
8
+ import { ACCOUNTS_STYLES } from "./styles.js";
9
+ import { wordsWith } from "./words.js";
10
+ const t = wordsWith();
11
+ const d = { w: (k, p) => t(k, p) ?? k, t, codeLength: 6, check: null, privacy: "/privacy" };
12
+ /** With the bot check's place drawn (Cloudflare's always-passes test key; the style guide loads no Turnstile script). */
13
+ const checked = { ...d, check: "1x00000000000000000000AA" };
14
+ const AT = 1_764_000_000;
15
+ export const ACCOUNTS_SAMPLES = {
16
+ format: 1,
17
+ package: ACCOUNTS_STYLES.package,
18
+ title: ACCOUNTS_STYLES.title,
19
+ prefix: ACCOUNTS_STYLES.prefix,
20
+ samples: [
21
+ { id: "sign-in", title: "Sign in", html: () => emailStep(checked, "/", "").body },
22
+ { id: "sign-in-problem", title: "Sign in, after too many tries", html: () => emailStep(d, "/", "maria@example.com", t("ui.wbaccounts.problem.too_many")).body },
23
+ { id: "join", title: "Make an account", html: () => joinStep(d, "/", false).body },
24
+ { id: "join-age", title: "Make an account, with the 18 or over tick", html: () => joinStep(d, "/", true).body },
25
+ { id: "code", title: "Enter your code", html: () => codeStep(d, "/", { email: "maria@example.com", sent: AT }, undefined, AT * 1000).body },
26
+ { id: "code-wrong", title: "Enter your code, after a wrong one", html: () => codeStep(d, "/", { email: "maria@example.com", sent: AT }, t("ui.wbaccounts.problem.wrong_code"), (AT + 180) * 1000).body },
27
+ { id: "account", title: "Your account", html: () => accountStep(d, { email: "maria@example.com", name: "Maria Santos" }).body },
28
+ { id: "account-saved", title: "Your account, name saved", html: () => accountStep(d, { email: "maria@example.com", name: "Maria Santos" }, { saved: true }).body },
29
+ {
30
+ id: "account-problem",
31
+ title: "Your account, with an empty name",
32
+ html: () => {
33
+ const input = { name: "" };
34
+ return accountStep(d, { email: "maria@example.com", name: null }, { result: validate(NAME_FORM, input, FORM_CONTEXT), input }).body;
35
+ },
36
+ },
37
+ ],
38
+ };
@@ -0,0 +1,3 @@
1
+ import type { ToolStyles } from "@mccaskie-labs/workbench-forms";
2
+ /** The style hooks of the account pages: Sign in, Join, Enter your code and Your account. */
3
+ export declare const ACCOUNTS_STYLES: ToolStyles;
package/dist/styles.js ADDED
@@ -0,0 +1,65 @@
1
+ // The look the account pages start with (docs/capabilities-manifest.md §10).
2
+ // Every element the tool draws carries one of these classes, and every class
3
+ // has a default rule here, so the pages look finished out of the box and a
4
+ // project restyles them from its own project.css by the same names. `npx
5
+ // workbench-ui styles` writes these into the project's
6
+ // public/styles/workbench.css. The names are public: renaming one is a
7
+ // breaking change. The fields inside the forms are workbench-forms' own
8
+ // (`wb-form-*`), and the page around them is workbench-ui's (`wb-ui-*`).
9
+ //
10
+ // Colours, fonts and corners default to the shared theme tokens
11
+ // (`--wb-accent`, `--wb-text`: docs/theming.md), each with a plain fallback.
12
+ const v = (name) => `var(--wb-accounts-${name})`;
13
+ const focus = { selector: ":focus-visible", about: "Has focus", css: `outline:none;box-shadow:0 0 0 3px ${v("focus")}` };
14
+ /** The style hooks of the account pages: Sign in, Join, Enter your code and Your account. */
15
+ export const ACCOUNTS_STYLES = {
16
+ format: 1,
17
+ tool: "accounts",
18
+ package: "@mccaskie-labs/workbench-accounts",
19
+ title: "Accounts",
20
+ prefix: "wb-accounts-",
21
+ variables: [
22
+ { name: "--wb-accounts-text", value: "var(--wb-text, #1d1d22)", about: "Text" },
23
+ { name: "--wb-accounts-muted", value: "var(--wb-muted, #5d5d68)", about: "Quieter text: the small print under a form" },
24
+ { name: "--wb-accounts-surface", value: "var(--wb-surface, #ffffff)", about: "Background of the card and the code boxes" },
25
+ { name: "--wb-accounts-line", value: "var(--wb-line, #dcdce2)", about: "Borders of the card and the code boxes" },
26
+ { name: "--wb-accounts-accent", value: "var(--wb-accent, #1b66d6)", about: "Links and the code box with focus" },
27
+ { name: "--wb-accounts-success", value: "var(--wb-success, #1f7a3d)", about: "The saved notice" },
28
+ { name: "--wb-accounts-danger", value: "var(--wb-danger, #b3261e)", about: "What went wrong" },
29
+ { name: "--wb-accounts-focus", value: "var(--wb-focus, rgba(27,102,214,.35))", about: "The ring round a control with focus" },
30
+ { name: "--wb-accounts-font", value: "var(--wb-font, system-ui, sans-serif)", about: "The pages' text" },
31
+ { name: "--wb-accounts-font-heading", value: "var(--wb-font-heading, var(--wb-accounts-font))", about: "The headings" },
32
+ { name: "--wb-accounts-radius", value: "var(--wb-radius, 8px)", about: "Corner rounding of the card" },
33
+ { name: "--wb-accounts-radius-small", value: "var(--wb-radius-small, 6px)", about: "Corner rounding of the code boxes" },
34
+ { name: "--wb-accounts-width", value: "28rem", about: "The card's widest" },
35
+ ],
36
+ classes: [
37
+ { name: "wb-accounts-card", element: "div", about: "The card each page sits in (also wb-ui-card)", css: `box-sizing:border-box;max-width:${v("width")};color:${v("text")};font-family:${v("font")}` },
38
+ { name: "wb-accounts-body", element: "div", about: "Inside the card", css: "display:grid;gap:.75rem" },
39
+ { name: "wb-accounts-heading", element: "h2", about: "A heading on Your account: \"You\"", css: `margin:0;font-family:${v("font-heading")};font-size:1.25rem;line-height:1.3` },
40
+ { name: "wb-accounts-intro", element: "p", about: "What the page is for: \"Enter your email address and we'll send you a code\"", css: "margin:0" },
41
+ { name: "wb-accounts-problem", element: "p", about: "What went wrong: \"That code isn't right or has expired\"", css: `margin:0;padding:.5rem .75rem;border-left:4px solid ${v("danger")}` },
42
+ { name: "wb-accounts-done", element: "p", about: "What just worked: \"Your name is saved\"", css: `margin:0;padding:.5rem .75rem;border-left:4px solid ${v("success")}` },
43
+ { name: "wb-accounts-form", element: "form", about: "A form: the address, the code, the name, sign out", css: "display:grid;gap:.75rem;margin:0" },
44
+ { name: "wb-accounts-next", element: "input", about: "Where to go after signing in (hidden)", css: "display:none" },
45
+ { name: "wb-accounts-check", element: "div", about: "The bot check, shown only when Cloudflare needs a click (also cf-turnstile)", css: "min-height:0" },
46
+ { name: "wb-accounts-actions", element: "p", about: "A form's button", css: "margin:0" },
47
+ { name: "wb-accounts-button", element: "button", about: "A button (also wb-ui-button): Send me a code, Sign in, Save your name, Sign out", css: "font:inherit", states: [focus] },
48
+ { name: "wb-accounts-small", element: "p", about: "Small print under a form: \"No code? Check your spam folder\"", css: `margin:0;color:${v("muted")};font-size:.9375rem` },
49
+ { name: "wb-accounts-link", element: "a", about: "A link to another account page: \"Use a different email address\"", css: `color:${v("accent")}`, states: [focus] },
50
+ { name: "wb-accounts-code", element: "fieldset", about: "The code's boxes and their label", css: "border:0;padding:0;margin:0 0 1rem" },
51
+ { name: "wb-accounts-code-label", element: "legend", about: "\"Code\"", css: "margin-bottom:.5rem" },
52
+ { name: "wb-accounts-digits", element: "div", about: "The row of code boxes", css: "display:flex;gap:.5rem" },
53
+ {
54
+ name: "wb-accounts-digit",
55
+ element: "input",
56
+ about: "One box per digit; pasting fills them all (also wb-ui-input)",
57
+ css: `box-sizing:border-box;width:2.5rem;padding:.45rem 0;font-size:1.5rem;text-align:center;font-variant-numeric:tabular-nums;border-radius:${v("radius-small")}`,
58
+ states: [focus, { selector: '[aria-describedby="problem"]', about: "The code was wrong", css: `border-color:${v("danger")}` }],
59
+ },
60
+ { name: "wb-accounts-keep", element: "label", about: "\"Keep me signed in on this device\" (also wb-ui-check)", css: "display:flex;gap:.5rem;align-items:flex-start" },
61
+ { name: "wb-accounts-keep-box", element: "input", about: "Its tick box", css: "margin-top:.2rem", states: [focus] },
62
+ { name: "wb-accounts-keep-text", element: "span", about: "Its words", css: "flex:1" },
63
+ { name: "wb-accounts-sign-out", element: "form", about: "The sign-out form on Your account (also wb-accounts-form)", css: `padding-top:.75rem;border-top:1px solid ${v("line")}` },
64
+ ],
65
+ };
@@ -0,0 +1,39 @@
1
+ export declare const TURNSTILE_ACTION = "sign-in";
2
+ export declare const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
3
+ export type TurnstileSetup =
4
+ /** Show the check, and verify it before sending a code. */
5
+ {
6
+ state: "on";
7
+ siteKey: string;
8
+ secret: string;
9
+ strict: boolean;
10
+ }
11
+ /** Development with no keys: no check. */
12
+ | {
13
+ state: "off";
14
+ }
15
+ /** A key is missing outside development: sign-in refuses to send codes. */
16
+ | {
17
+ state: "missing";
18
+ };
19
+ /** The app's Turnstile keys and environment, as its config holds them. */
20
+ export interface TurnstileKeys {
21
+ WORKBENCH_ENV: string;
22
+ TURNSTILE_SITE_KEY?: string | undefined;
23
+ TURNSTILE_SECRET_KEY?: string | undefined;
24
+ }
25
+ export declare function turnstileSetup(c: TurnstileKeys): TurnstileSetup;
26
+ export type TurnstileResult = {
27
+ ok: true;
28
+ } | {
29
+ ok: false;
30
+ reason: "no_token" | "rejected" | "unavailable";
31
+ };
32
+ /**
33
+ * Checks the token the form posted. Passes only when Siteverify says success
34
+ * for this hostname and the sign-in action. A token is single use, so a replay
35
+ * fails. Siteverify down or slow is "unavailable": the person is asked to try
36
+ * again, and no code is sent. Not strict (development only), the hostname and
37
+ * action aren't compared, since Cloudflare's test keys answer for example.com.
38
+ */
39
+ export declare function verifyTurnstile(secret: string, token: unknown, request: Request, strict?: boolean): Promise<TurnstileResult>;
@@ -0,0 +1,70 @@
1
+ // Cloudflare Turnstile on the forms that send a code, so a bot can't make the
2
+ // app mail codes to people who didn't ask (Robert chose "Yes, Turnstile before
3
+ // go-live", 11 November 2026). Moved here from the project template's
4
+ // src/lib/turnstile.ts, unchanged in what it does.
5
+ //
6
+ // Control makes one widget per hostname (cf_turnstile_widget_create) and writes
7
+ // its keys onto the Worker (cf_worker_secret_put sources turnstile_sitekey and
8
+ // turnstile_secret). The page shows the check; the Worker sends the token to
9
+ // Siteverify with the secret and accepts it only for this hostname and the
10
+ // sign-in action. The secret never reaches the browser.
11
+ //
12
+ // Outside development both keys must be set: sign-in refuses to send codes
13
+ // rather than run without the check. In development with no keys, there is no
14
+ // check (Cloudflare's test keys work in .dev.vars to try it).
15
+ export const TURNSTILE_ACTION = "sign-in";
16
+ export const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
17
+ const SITEVERIFY = `${TURNSTILE_ORIGIN}/turnstile/v0/siteverify`;
18
+ /** Cloudflare's tokens are at most 2048 characters. */
19
+ const MAX_TOKEN = 2048;
20
+ export function turnstileSetup(c) {
21
+ if (c.TURNSTILE_SITE_KEY && c.TURNSTILE_SECRET_KEY)
22
+ return { state: "on", siteKey: c.TURNSTILE_SITE_KEY, secret: c.TURNSTILE_SECRET_KEY, strict: c.WORKBENCH_ENV !== "development" };
23
+ if (c.WORKBENCH_ENV === "development" && !c.TURNSTILE_SITE_KEY && !c.TURNSTILE_SECRET_KEY)
24
+ return { state: "off" };
25
+ console.error("TURNSTILE_SITE_KEY or TURNSTILE_SECRET_KEY is not set: sign-in won't send codes");
26
+ return { state: "missing" };
27
+ }
28
+ /**
29
+ * Checks the token the form posted. Passes only when Siteverify says success
30
+ * for this hostname and the sign-in action. A token is single use, so a replay
31
+ * fails. Siteverify down or slow is "unavailable": the person is asked to try
32
+ * again, and no code is sent. Not strict (development only), the hostname and
33
+ * action aren't compared, since Cloudflare's test keys answer for example.com.
34
+ */
35
+ export async function verifyTurnstile(secret, token, request, strict = true) {
36
+ if (typeof token !== "string" || token.length === 0 || token.length > MAX_TOKEN)
37
+ return { ok: false, reason: "no_token" };
38
+ const body = new FormData();
39
+ body.set("secret", secret);
40
+ body.set("response", token);
41
+ const ip = request.headers.get("cf-connecting-ip");
42
+ if (ip)
43
+ body.set("remoteip", ip);
44
+ let res;
45
+ try {
46
+ res = await fetch(SITEVERIFY, { method: "POST", body, signal: AbortSignal.timeout(5000) });
47
+ }
48
+ catch {
49
+ return { ok: false, reason: "unavailable" };
50
+ }
51
+ if (!res.ok)
52
+ return { ok: false, reason: "unavailable" };
53
+ let out;
54
+ try {
55
+ out = (await res.json());
56
+ }
57
+ catch {
58
+ return { ok: false, reason: "unavailable" };
59
+ }
60
+ const codes = Array.isArray(out["error-codes"]) ? out["error-codes"].map(String) : [];
61
+ if (codes.includes("internal-error"))
62
+ return { ok: false, reason: "unavailable" };
63
+ const host = new URL(request.url).hostname;
64
+ if (out.success !== true || (strict && (out.hostname !== host || out.action !== TURNSTILE_ACTION))) {
65
+ // The codes say which check failed (expired, duplicate, bad secret); they never hold the token or the address.
66
+ console.warn(JSON.stringify({ event: "turnstile_rejected", codes: codes.slice(0, 5), host_ok: out.hostname === host, action_ok: out.action === TURNSTILE_ACTION }));
67
+ return { ok: false, reason: "rejected" };
68
+ }
69
+ return { ok: true };
70
+ }
@@ -0,0 +1,60 @@
1
+ /** A project's word lookup: the words for a key, or undefined when it has none. */
2
+ export type Words = (key: string, params?: Readonly<Record<string, string | number>>) => string | undefined;
3
+ export declare const ACCOUNTS_WORDS: {
4
+ readonly "ui.wbaccounts.sign_in.title": "Sign in";
5
+ readonly "ui.wbaccounts.sign_in.intro": "Enter your email address and we'll send you a code to sign in. New here? The same code makes your account.";
6
+ readonly "ui.wbaccounts.sign_in.send": "Send me a code";
7
+ readonly "ui.wbaccounts.sign_in.forgot": "Forgotten your password? You don't need one: sign in with a code.";
8
+ readonly "ui.wbaccounts.sign_in.join": "New here? Make an account";
9
+ readonly "ui.wbaccounts.join.title": "Make an account";
10
+ readonly "ui.wbaccounts.join.intro": "Tell us your email address and your name. We'll email you a code to make your account.";
11
+ readonly "ui.wbaccounts.join.send": "Send me a code";
12
+ readonly "ui.wbaccounts.join.have": "Already have an account? Sign in";
13
+ readonly "ui.wbaccounts.join.privacy": "How we look after your details";
14
+ readonly "ui.wbaccounts.code.title": "Enter your code";
15
+ readonly "ui.wbaccounts.code.sent_now": "We sent a {digits}-digit code to {email} just now. It works for an hour.";
16
+ readonly "ui.wbaccounts.code.sent_minute": "We sent a {digits}-digit code to {email} a minute ago. It works for an hour.";
17
+ readonly "ui.wbaccounts.code.sent_minutes": "We sent a {digits}-digit code to {email} {minutes} minutes ago. It works for an hour.";
18
+ readonly "ui.wbaccounts.code.label": "Code";
19
+ readonly "ui.wbaccounts.code.digit": "Digit {n} of {of}";
20
+ readonly "ui.wbaccounts.code.keep": "Keep me signed in on this device";
21
+ readonly "ui.wbaccounts.code.keep_hint": "Untick this on a shared or borrowed device: you'll be signed out after 30 minutes without use.";
22
+ readonly "ui.wbaccounts.code.sign_in": "Sign in";
23
+ readonly "ui.wbaccounts.code.none": "No code? Check your spam folder, or";
24
+ readonly "ui.wbaccounts.code.resend": "send another code";
25
+ readonly "ui.wbaccounts.code.other": "Use a different email address";
26
+ readonly "ui.wbaccounts.account.title": "Your account";
27
+ readonly "ui.wbaccounts.account.you": "You";
28
+ readonly "ui.wbaccounts.account.signed_in": "Signed in as {email}.";
29
+ readonly "ui.wbaccounts.account.name": "Your name";
30
+ readonly "ui.wbaccounts.account.save_name": "Save your name";
31
+ readonly "ui.wbaccounts.account.name_saved": "Your name is saved.";
32
+ readonly "ui.wbaccounts.account.sign_out": "Sign out";
33
+ readonly "question.wbform.accounts_sign_in.email": "Email address";
34
+ readonly "question.wbform.accounts_join.email": "Email address";
35
+ readonly "question.wbform.accounts_join.name": "Your name";
36
+ readonly "question.accounts_join.name.hint": "The name we'll use for you. You can change it later.";
37
+ readonly "question.wbform.accounts_join.adult": "I am 18 or over";
38
+ readonly "question.wbform.accounts_name.name": "Your name";
39
+ readonly "ui.wbaccounts.problem.bad_email": "Check the email address and try again.";
40
+ readonly "ui.wbaccounts.problem.bad_code": "Enter the code from the email: numbers only.";
41
+ readonly "ui.wbaccounts.problem.wrong_code": "That code isn't right or has expired. Check it, or send another code.";
42
+ readonly "ui.wbaccounts.problem.too_many": "Too many tries. Wait a minute, then try again.";
43
+ readonly "ui.wbaccounts.problem.bot_check": "We couldn't check that this came from a person. Try again, and tick the box if one appears.";
44
+ readonly "ui.wbaccounts.problem.start_again": "That sign-in has expired. Enter your email address to get a new code.";
45
+ readonly "ui.wbaccounts.problem.down": "Signing in isn't working right now. Try again in a few minutes.";
46
+ readonly "ui.wbaccounts.problem.cross_site": "This has to be sent from this site's own pages.";
47
+ readonly "ui.wbaccounts.problem.not_set_up": "Sign-in isn't set up on this site yet.";
48
+ readonly "ui.wbaccounts.problem.save_failed": "That didn't save. Try again in a few minutes.";
49
+ readonly "validation.accounts_sign_in.email.required": "Enter your email address";
50
+ readonly "validation.accounts_join.email.required": "Enter your email address";
51
+ readonly "validation.accounts_join.name.required": "Enter your name";
52
+ readonly "validation.accounts_join.adult.required": "Tick the box to confirm you are 18 or over";
53
+ readonly "validation.accounts_name.name.required": "Enter your name";
54
+ readonly "ui.form.optional": "(optional)";
55
+ };
56
+ export type AccountsWordKey = keyof typeof ACCOUNTS_WORDS;
57
+ /** Fills {name} placeholders. */
58
+ export declare function fill(text: string, params?: Readonly<Record<string, string | number>>): string;
59
+ /** The project's words first, then the tool's English. */
60
+ export declare function wordsWith(t?: Words): Words;
package/dist/words.js ADDED
@@ -0,0 +1,84 @@
1
+ // The words on the account pages, in English (en-AU), keyed as the project's
2
+ // strings catalogue keys them. A project passes its own `t` (workbench-strings)
3
+ // to change any of them or to add a language; a key its catalogue lacks falls
4
+ // back to the words here. Auth copy is the highest-stakes copy in the app
5
+ // (authentication standard §17): say what went wrong and what to do, never
6
+ // which check failed, and never whether an account exists.
7
+ //
8
+ // The sign-in words are the template's src/lib/sign-in-words.ts, unchanged.
9
+ export const ACCOUNTS_WORDS = {
10
+ // Sign in
11
+ "ui.wbaccounts.sign_in.title": "Sign in",
12
+ "ui.wbaccounts.sign_in.intro": "Enter your email address and we'll send you a code to sign in. New here? The same code makes your account.",
13
+ "ui.wbaccounts.sign_in.send": "Send me a code",
14
+ "ui.wbaccounts.sign_in.forgot": "Forgotten your password? You don't need one: sign in with a code.",
15
+ "ui.wbaccounts.sign_in.join": "New here? Make an account",
16
+ // Join
17
+ "ui.wbaccounts.join.title": "Make an account",
18
+ "ui.wbaccounts.join.intro": "Tell us your email address and your name. We'll email you a code to make your account.",
19
+ "ui.wbaccounts.join.send": "Send me a code",
20
+ "ui.wbaccounts.join.have": "Already have an account? Sign in",
21
+ "ui.wbaccounts.join.privacy": "How we look after your details",
22
+ // Enter your code
23
+ "ui.wbaccounts.code.title": "Enter your code",
24
+ "ui.wbaccounts.code.sent_now": "We sent a {digits}-digit code to {email} just now. It works for an hour.",
25
+ "ui.wbaccounts.code.sent_minute": "We sent a {digits}-digit code to {email} a minute ago. It works for an hour.",
26
+ "ui.wbaccounts.code.sent_minutes": "We sent a {digits}-digit code to {email} {minutes} minutes ago. It works for an hour.",
27
+ "ui.wbaccounts.code.label": "Code",
28
+ "ui.wbaccounts.code.digit": "Digit {n} of {of}",
29
+ "ui.wbaccounts.code.keep": "Keep me signed in on this device",
30
+ "ui.wbaccounts.code.keep_hint": "Untick this on a shared or borrowed device: you'll be signed out after 30 minutes without use.",
31
+ "ui.wbaccounts.code.sign_in": "Sign in",
32
+ "ui.wbaccounts.code.none": "No code? Check your spam folder, or",
33
+ "ui.wbaccounts.code.resend": "send another code",
34
+ "ui.wbaccounts.code.other": "Use a different email address",
35
+ // Your account
36
+ "ui.wbaccounts.account.title": "Your account",
37
+ "ui.wbaccounts.account.you": "You",
38
+ "ui.wbaccounts.account.signed_in": "Signed in as {email}.",
39
+ "ui.wbaccounts.account.name": "Your name",
40
+ "ui.wbaccounts.account.save_name": "Save your name",
41
+ "ui.wbaccounts.account.name_saved": "Your name is saved.",
42
+ "ui.wbaccounts.account.sign_out": "Sign out",
43
+ // The form's questions (workbench-forms labelKeys)
44
+ "question.wbform.accounts_sign_in.email": "Email address",
45
+ "question.wbform.accounts_join.email": "Email address",
46
+ "question.wbform.accounts_join.name": "Your name",
47
+ "question.accounts_join.name.hint": "The name we'll use for you. You can change it later.",
48
+ "question.wbform.accounts_join.adult": "I am 18 or over",
49
+ "question.wbform.accounts_name.name": "Your name",
50
+ // Problems
51
+ "ui.wbaccounts.problem.bad_email": "Check the email address and try again.",
52
+ "ui.wbaccounts.problem.bad_code": "Enter the code from the email: numbers only.",
53
+ "ui.wbaccounts.problem.wrong_code": "That code isn't right or has expired. Check it, or send another code.",
54
+ "ui.wbaccounts.problem.too_many": "Too many tries. Wait a minute, then try again.",
55
+ "ui.wbaccounts.problem.bot_check": "We couldn't check that this came from a person. Try again, and tick the box if one appears.",
56
+ "ui.wbaccounts.problem.start_again": "That sign-in has expired. Enter your email address to get a new code.",
57
+ "ui.wbaccounts.problem.down": "Signing in isn't working right now. Try again in a few minutes.",
58
+ "ui.wbaccounts.problem.cross_site": "This has to be sent from this site's own pages.",
59
+ "ui.wbaccounts.problem.not_set_up": "Sign-in isn't set up on this site yet.",
60
+ "ui.wbaccounts.problem.save_failed": "That didn't save. Try again in a few minutes.",
61
+ // What each account form's problems say (workbench-forms shows these beside the field; a project's own catalogue wins).
62
+ "validation.accounts_sign_in.email.required": "Enter your email address",
63
+ "validation.accounts_join.email.required": "Enter your email address",
64
+ "validation.accounts_join.name.required": "Enter your name",
65
+ "validation.accounts_join.adult.required": "Tick the box to confirm you are 18 or over",
66
+ "validation.accounts_name.name.required": "Enter your name",
67
+ "ui.form.optional": "(optional)",
68
+ };
69
+ /** Fills {name} placeholders. */
70
+ export function fill(text, params) {
71
+ if (!params)
72
+ return text;
73
+ return text.replace(/\{(\w+)\}/g, (all, k) => (Object.hasOwn(params, k) ? String(params[k]) : all));
74
+ }
75
+ /** The project's words first, then the tool's English. */
76
+ export function wordsWith(t) {
77
+ return (key, params) => {
78
+ const own = t?.(key, params);
79
+ if (own !== undefined)
80
+ return own;
81
+ const base = Object.hasOwn(ACCOUNTS_WORDS, key) ? ACCOUNTS_WORDS[key] : undefined;
82
+ return base === undefined ? undefined : fill(base, params);
83
+ };
84
+ }