@mccaskie-labs/workbench-accounts 0.0.0-stage → 0.1.0
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/CHANGELOG.md +7 -0
- package/README.md +43 -2
- package/dist/accounts.d.ts +87 -0
- package/dist/accounts.js +353 -0
- package/dist/answers.d.ts +10 -0
- package/dist/answers.js +39 -0
- package/dist/forms.d.ts +22 -0
- package/dist/forms.js +21 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +15 -0
- package/dist/limits.d.ts +25 -0
- package/dist/limits.js +38 -0
- package/dist/pages.d.ts +54 -0
- package/dist/pages.js +131 -0
- package/dist/samples.d.ts +14 -0
- package/dist/samples.js +38 -0
- package/dist/styles.d.ts +3 -0
- package/dist/styles.js +65 -0
- package/dist/turnstile.d.ts +39 -0
- package/dist/turnstile.js +70 -0
- package/dist/words.d.ts +62 -0
- package/dist/words.js +86 -0
- package/package.json +51 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# @mccaskie-labs/workbench-accounts
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- First version (docs/accounts.md, step 1; needs workbench-supabase 0.6.0): the app's sign-in with an emailed six-digit code, moved out of the project template's `src/lib/sign-in.ts`, `session.ts` and `turnstile.ts` with no change to what its routes do (`createAccounts`, `requireUser`, `currentUser`, `sessionCookies`, `withCookies`, `turnstileSetup`, `verifyTurnstile`, `ipKey`). New: a Join page (`/join`: email and name, and an "I am 18 or over" tick when the project's answers ask for one, recorded with its time as a statement), and Your account (`/account`) with the person's name, changed at `/account/name`. The fields are workbench-forms forms; every element has a `wb-accounts-*` class (`ACCOUNTS_STYLES`) whose colours, fonts and corners default to the shared theme tokens; `fromAnswers` and `accountsProblems` make and check `workbench/accounts.json`; the words are in `ACCOUNTS_WORDS` (English) and a project's own catalogue wins.
|
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mccaskie-labs/workbench-accounts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The ways people sign in to a Workbench app and the account features that go with them, so no project builds its own. The design is `docs/accounts.md` in the Workbench repo; it follows Robert's authentication standard.
|
|
4
|
+
|
|
5
|
+
Built so far (step 1): an emailed six-digit code, which is on in every project, a Join page, and Your account with the person's name. Passwords, Google, changing an email address, two-step sign-in and the Members page come in later steps.
|
|
6
|
+
|
|
7
|
+
- The Worker makes every Supabase Auth call; the browser never does and never sees a token. The session is one sealed `__Host-session` cookie (workbench-supabase `createSessions`).
|
|
8
|
+
- Every POST must come from the site's own pages. Sending a code needs a passed Cloudflare Turnstile check and stays inside a per-IP and a per-address limit (Workers rate limiting, hashed keys). Past a limit the person waits a minute: never a lockout.
|
|
9
|
+
- Joining and signing in answer the same whether or not the address has an account.
|
|
10
|
+
|
|
11
|
+
## Use
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createAccounts, sessionCookies } from "@mccaskie-labs/workbench-accounts";
|
|
15
|
+
import { shell, STYLESHEETS, topBar } from "@mccaskie-labs/workbench-ui";
|
|
16
|
+
|
|
17
|
+
const accounts = createAccounts({
|
|
18
|
+
environment: c.WORKBENCH_ENV,
|
|
19
|
+
SUPABASE_URL: c.SUPABASE_URL,
|
|
20
|
+
SUPABASE_PUBLISHABLE_KEY: c.SUPABASE_PUBLISHABLE_KEY,
|
|
21
|
+
SESSION_SECRET: c.SESSION_SECRET,
|
|
22
|
+
TURNSTILE_SITE_KEY: c.TURNSTILE_SITE_KEY,
|
|
23
|
+
TURNSTILE_SECRET_KEY: c.TURNSTILE_SECRET_KEY,
|
|
24
|
+
limits: { ip: env.SIGN_IN_IP_LIMIT, email: env.SIGN_IN_EMAIL_LIMIT },
|
|
25
|
+
appName: brand.name,
|
|
26
|
+
answers, // workbench/accounts.json
|
|
27
|
+
shell, topBar, stylesheets: STYLESHEETS,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// In the Worker's fetch, before the app's own routes:
|
|
31
|
+
const r = await accounts.route(request, url);
|
|
32
|
+
if (r) return r;
|
|
33
|
+
|
|
34
|
+
// A page for signed-in people:
|
|
35
|
+
const s = await accounts.requireUser(request);
|
|
36
|
+
if (s instanceof Response) return s;
|
|
37
|
+
return s.finish(page);
|
|
38
|
+
|
|
39
|
+
// And on every response: sessionCookies(request, response).
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Routes: `GET /sign-in` (and `?step=code`), `GET /join`, `POST /auth/code`, `/auth/join`, `/auth/resend`, `/auth/verify`, `/auth/sign-out`, `GET /account`, `POST /account/name`.
|
|
43
|
+
|
|
44
|
+
Restyle the pages in the project's `public/styles/project.css` with the `wb-accounts-*` classes and `--wb-accounts-*` variables (`ACCOUNTS_STYLES`); the fields are workbench-forms' `wb-form-*`. Change any words in the project's strings catalogue by the keys in `ACCOUNTS_WORDS`.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { type Sessions, type SessionTimers, type SessionUser } from "@mccaskie-labs/workbench-supabase";
|
|
2
|
+
import { type Limits } from "./limits.ts";
|
|
3
|
+
import { type Words } from "./words.ts";
|
|
4
|
+
/** Every path the tool answers, so a Worker can route them before its own. */
|
|
5
|
+
export declare const ACCOUNTS_PATHS: readonly string[];
|
|
6
|
+
/** The project's answers file, workbench/accounts.json (the manifest's offer). */
|
|
7
|
+
export interface AccountsAnswers {
|
|
8
|
+
format: 1;
|
|
9
|
+
/** Ways to sign in. Only "code" is built so far; it is always on. */
|
|
10
|
+
methods?: readonly ("code" | "password" | "google")[];
|
|
11
|
+
/** Who may make an account. Only "anyone" is built so far. */
|
|
12
|
+
join?: "anyone" | "invited";
|
|
13
|
+
/** Ask for an "I am 18 or over" tick on Join. */
|
|
14
|
+
ask_age?: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface AccountsOptions {
|
|
17
|
+
/** WORKBENCH_ENV: development, staging or production. */
|
|
18
|
+
environment: string;
|
|
19
|
+
SUPABASE_URL: string;
|
|
20
|
+
SUPABASE_PUBLISHABLE_KEY: string;
|
|
21
|
+
/** SESSION_SECRET. Unset, sign-in answers 503 naming it. */
|
|
22
|
+
SESSION_SECRET?: string | undefined;
|
|
23
|
+
TURNSTILE_SITE_KEY?: string | undefined;
|
|
24
|
+
TURNSTILE_SECRET_KEY?: string | undefined;
|
|
25
|
+
/** The Workers rate limiting bindings SIGN_IN_IP_LIMIT and SIGN_IN_EMAIL_LIMIT. Outside development both must be bound. */
|
|
26
|
+
limits: Limits;
|
|
27
|
+
/** The app's name, for the top bar and the tab. */
|
|
28
|
+
appName: string;
|
|
29
|
+
/** The emailed code's length: Supabase's Email OTP Length (the vendor settings baseline holds it at 6). */
|
|
30
|
+
codeLength?: number;
|
|
31
|
+
/** The project's answers (workbench/accounts.json). */
|
|
32
|
+
answers?: AccountsAnswers | null;
|
|
33
|
+
/** The project's words (workbench-strings), in the visitor's language; the tool's English fills any gap. */
|
|
34
|
+
t?: Words;
|
|
35
|
+
/** The Privacy page's address, linked from Join, when the project has one. */
|
|
36
|
+
privacyPath?: string | null;
|
|
37
|
+
/** The page's stylesheets (workbench-ui's STYLESHEETS). */
|
|
38
|
+
stylesheets?: readonly string[];
|
|
39
|
+
/** Draws the page around a step: workbench-ui's shell. */
|
|
40
|
+
shell: (o: {
|
|
41
|
+
title: string;
|
|
42
|
+
site: string;
|
|
43
|
+
top: string;
|
|
44
|
+
stylesheets?: readonly string[];
|
|
45
|
+
head?: string;
|
|
46
|
+
body: string;
|
|
47
|
+
tail?: string;
|
|
48
|
+
}) => string;
|
|
49
|
+
/** The top bar: workbench-ui's topBar. */
|
|
50
|
+
topBar: (o: {
|
|
51
|
+
name: string;
|
|
52
|
+
href?: string;
|
|
53
|
+
}) => string;
|
|
54
|
+
/** Change a session dial. */
|
|
55
|
+
timers?: Partial<SessionTimers>;
|
|
56
|
+
/** For tests: a fake Supabase. */
|
|
57
|
+
fetch?: typeof fetch;
|
|
58
|
+
}
|
|
59
|
+
export interface SignedIn {
|
|
60
|
+
user: SessionUser;
|
|
61
|
+
/** Pass to dbAs(env, accessToken). Never send it to the browser. */
|
|
62
|
+
accessToken: string;
|
|
63
|
+
/** The code was typed in the last 15 minutes. */
|
|
64
|
+
fresh: boolean;
|
|
65
|
+
/** The response with the session's cookie (when it changed) and no caching. Wrap every response to this request. */
|
|
66
|
+
finish(res: Response): Response;
|
|
67
|
+
}
|
|
68
|
+
export interface Accounts {
|
|
69
|
+
/** The tool's routes, or null for any other path. */
|
|
70
|
+
route(request: Request, url?: URL): Promise<Response | null>;
|
|
71
|
+
/**
|
|
72
|
+
* The signed-in user, or the response to send instead: a redirect to
|
|
73
|
+
* /sign-in (or 401 JSON under /api/) when signed out, 403 for a write from
|
|
74
|
+
* another site, 503 when sign-in is down or not set up.
|
|
75
|
+
*/
|
|
76
|
+
requireUser(request: Request): Promise<SignedIn | Response>;
|
|
77
|
+
/** The signed-in user, or null (signed out, sign-in down or not set up). For pages that show either. Never guard a write with it. */
|
|
78
|
+
currentUser(request: Request): Promise<SignedIn | null>;
|
|
79
|
+
/** The sessions underneath (workbench-supabase createSessions), or null when SESSION_SECRET isn't set. */
|
|
80
|
+
sessions: Sessions | null;
|
|
81
|
+
}
|
|
82
|
+
/** The response with any session cookie this request still owes. A Worker calls it on every response it returns. */
|
|
83
|
+
export declare function sessionCookies(request: Request, res: Response): Response;
|
|
84
|
+
/** Adds Set-Cookie lines and keeps a signed-in page out of every cache. */
|
|
85
|
+
export declare function withCookies(res: Response, cookies: readonly string[]): Response;
|
|
86
|
+
/** The account pages and the signed-in check for one Worker env. Make it once per isolate. */
|
|
87
|
+
export declare function createAccounts(o: AccountsOptions): Accounts;
|
package/dist/accounts.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
// The account routes and the signed-in check: today's emailed-code sign-in,
|
|
2
|
+
// moved out of the project template (src/lib/sign-in.ts and session.ts) with
|
|
3
|
+
// no change to what the routes do, plus Join and the name on Your account.
|
|
4
|
+
// Codes only for now; passwords, Google and two-step come in later steps
|
|
5
|
+
// (docs/accounts.md §8).
|
|
6
|
+
//
|
|
7
|
+
// GET /sign-in step 1: the email address; step 2 (?step=code): the code
|
|
8
|
+
// GET /join make an account: email and name
|
|
9
|
+
// POST /auth/code send a code, then step 2
|
|
10
|
+
// POST /auth/join send a code for a new account (the name goes with it), then step 2
|
|
11
|
+
// POST /auth/resend send another code to the same address
|
|
12
|
+
// POST /auth/verify check the code, set the session, go back to ?next=
|
|
13
|
+
// POST /auth/sign-out clear the session, then tell Supabase
|
|
14
|
+
// GET /account Your account: who is signed in, their name, sign out
|
|
15
|
+
// POST /account/name change the name
|
|
16
|
+
//
|
|
17
|
+
// Supabase makes every code; the app's Send Email hook mails it through the
|
|
18
|
+
// Gateway in the app's own words. The browser never talks to Supabase Auth:
|
|
19
|
+
// the Worker makes every call. Every POST must come from the site's own pages
|
|
20
|
+
// (Origin). The ones that send a code are limited per IP and per address with
|
|
21
|
+
// Workers rate limiting, keyed by hashes so no address is stored, and carry a
|
|
22
|
+
// Turnstile check verified before Supabase is asked for a code. Past a limit,
|
|
23
|
+
// the person is asked to wait a minute: never a lockout.
|
|
24
|
+
import { readForm as readFields, validate } from "@mccaskie-labs/workbench-forms";
|
|
25
|
+
import { createSessions, plainAuthError, safeReturnPath, sameOrigin } from "@mccaskie-labs/workbench-supabase";
|
|
26
|
+
import { JOIN_ADULT_FORM, JOIN_FORM, NAME_FORM, FORM_CONTEXT, NAME_MAX } from "./forms.js";
|
|
27
|
+
import { ipKey, missingLimits, overLimit } from "./limits.js";
|
|
28
|
+
import { accountStep, codeStep, codeUrl, emailStep, joinStep, PATHS } from "./pages.js";
|
|
29
|
+
import { TURNSTILE_ORIGIN, turnstileSetup, verifyTurnstile } from "./turnstile.js";
|
|
30
|
+
import { wordsWith } from "./words.js";
|
|
31
|
+
/** Every path the tool answers, so a Worker can route them before its own. */
|
|
32
|
+
export const ACCOUNTS_PATHS = Object.values(PATHS);
|
|
33
|
+
/** Session cookies a request's handler hasn't put on its response yet (see sessionCookies). */
|
|
34
|
+
const owed = new WeakMap();
|
|
35
|
+
/** The response with any session cookie this request still owes. A Worker calls it on every response it returns. */
|
|
36
|
+
export function sessionCookies(request, res) {
|
|
37
|
+
const cookies = owed.get(request);
|
|
38
|
+
if (!cookies || cookies.length === 0)
|
|
39
|
+
return res;
|
|
40
|
+
owed.delete(request);
|
|
41
|
+
return withCookies(res, cookies);
|
|
42
|
+
}
|
|
43
|
+
/** Adds Set-Cookie lines and keeps a signed-in page out of every cache. */
|
|
44
|
+
export function withCookies(res, cookies) {
|
|
45
|
+
const out = new Response(res.body, res);
|
|
46
|
+
for (const c of cookies)
|
|
47
|
+
out.headers.append("set-cookie", c);
|
|
48
|
+
out.headers.set("cache-control", "private, no-store");
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/** True for paths that answer JSON to a program rather than a page to a person. */
|
|
52
|
+
const isApi = (path) => path === "/api" || path.startsWith("/api/");
|
|
53
|
+
/** The account pages and the signed-in check for one Worker env. Make it once per isolate. */
|
|
54
|
+
export function createAccounts(o) {
|
|
55
|
+
const sessions = o.SESSION_SECRET
|
|
56
|
+
? createSessions({ url: o.SUPABASE_URL, publishableKey: o.SUPABASE_PUBLISHABLE_KEY, secret: o.SESSION_SECRET, ...(o.timers ? { timers: o.timers } : {}), ...(o.fetch ? { fetch: o.fetch } : {}) })
|
|
57
|
+
: null;
|
|
58
|
+
const doFetch = o.fetch ?? ((input, init) => fetch(input, init));
|
|
59
|
+
const codeLength = o.codeLength ?? 6;
|
|
60
|
+
const t = wordsWith(o.t);
|
|
61
|
+
const w = (key, params) => t(key, params) ?? key;
|
|
62
|
+
const askAge = o.answers?.ask_age === true;
|
|
63
|
+
const plain = (body, status, cookies = []) => withCookies(new Response(`${body}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } }), cookies);
|
|
64
|
+
const redirect = (to) => new Response(null, { status: 303, headers: { location: to } });
|
|
65
|
+
const notSetUp = () => {
|
|
66
|
+
console.error("SESSION_SECRET is not set: sign-in is off");
|
|
67
|
+
return plain(w("ui.wbaccounts.problem.not_set_up"), 503);
|
|
68
|
+
};
|
|
69
|
+
function signedIn(request, r) {
|
|
70
|
+
if (r.cookie)
|
|
71
|
+
owed.set(request, [r.cookie]);
|
|
72
|
+
return {
|
|
73
|
+
user: r.user,
|
|
74
|
+
accessToken: r.accessToken,
|
|
75
|
+
fresh: r.fresh,
|
|
76
|
+
finish: (res) => {
|
|
77
|
+
const cookies = owed.get(request) ?? [];
|
|
78
|
+
owed.delete(request);
|
|
79
|
+
return withCookies(res, cookies);
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async function requireUser(request) {
|
|
84
|
+
const url = new URL(request.url);
|
|
85
|
+
if (request.method !== "GET" && request.method !== "HEAD" && !sameOrigin(request)) {
|
|
86
|
+
return plain("This change has to come from this site's own pages.", 403);
|
|
87
|
+
}
|
|
88
|
+
if (!sessions)
|
|
89
|
+
return notSetUp();
|
|
90
|
+
const r = await sessions.read(request);
|
|
91
|
+
if (r.state === "signed_in")
|
|
92
|
+
return signedIn(request, r);
|
|
93
|
+
if (r.state === "unavailable")
|
|
94
|
+
return plain("Sign-in can't be checked right now. Try again in a minute.", 503);
|
|
95
|
+
const cookies = r.state === "ended" ? [r.cookie] : [];
|
|
96
|
+
if (isApi(url.pathname)) {
|
|
97
|
+
return withCookies(Response.json({ ok: false, error: "signed_out", message: "Sign in first." }, { status: 401 }), cookies);
|
|
98
|
+
}
|
|
99
|
+
const next = `${url.pathname}${url.search}`;
|
|
100
|
+
return withCookies(redirect(`/sign-in?next=${encodeURIComponent(next)}`), cookies);
|
|
101
|
+
}
|
|
102
|
+
async function currentUser(request) {
|
|
103
|
+
if (!sessions)
|
|
104
|
+
return null;
|
|
105
|
+
const r = await sessions.read(request);
|
|
106
|
+
if (r.state !== "signed_in")
|
|
107
|
+
return null;
|
|
108
|
+
return signedIn(request, r);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A page: not framable, forms post only here, scripts only by nonce. The
|
|
112
|
+
* one third-party script is Turnstile's, from Cloudflare, when the check is on.
|
|
113
|
+
*/
|
|
114
|
+
function page(step, status = 200) {
|
|
115
|
+
const nonce = crypto.randomUUID().replace(/-/g, "");
|
|
116
|
+
const tail = (step.script ? `<script nonce="${nonce}">${step.script}</script>` : "") + (step.turnstile ? `<script nonce="${nonce}" src="${TURNSTILE_ORIGIN}/turnstile/v0/api.js" async defer></script>` : "");
|
|
117
|
+
const html = o.shell({
|
|
118
|
+
title: step.title,
|
|
119
|
+
site: o.appName,
|
|
120
|
+
top: o.topBar({ name: o.appName, href: "/" }),
|
|
121
|
+
...(o.stylesheets ? { stylesheets: o.stylesheets } : {}),
|
|
122
|
+
head: STYLE,
|
|
123
|
+
body: step.body,
|
|
124
|
+
...(tail ? { tail } : {}),
|
|
125
|
+
});
|
|
126
|
+
const csp = [
|
|
127
|
+
"default-src 'none'",
|
|
128
|
+
"style-src 'self' 'unsafe-inline'",
|
|
129
|
+
`script-src 'nonce-${nonce}'${step.turnstile ? ` ${TURNSTILE_ORIGIN}` : ""}`,
|
|
130
|
+
...(step.turnstile ? [`frame-src ${TURNSTILE_ORIGIN}`, `connect-src ${TURNSTILE_ORIGIN}`] : []),
|
|
131
|
+
"img-src 'self' data:",
|
|
132
|
+
"form-action 'self'",
|
|
133
|
+
"frame-ancestors 'none'",
|
|
134
|
+
"base-uri 'none'",
|
|
135
|
+
].join("; ");
|
|
136
|
+
return withCookies(new Response(html, {
|
|
137
|
+
status,
|
|
138
|
+
headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": csp, "referrer-policy": "same-origin", "x-content-type-options": "nosniff" },
|
|
139
|
+
}), []);
|
|
140
|
+
}
|
|
141
|
+
/** Null when the Turnstile check passed (or is off in development), else what to tell the person. */
|
|
142
|
+
async function passed(bot, form, request) {
|
|
143
|
+
if (bot.state !== "on")
|
|
144
|
+
return null;
|
|
145
|
+
const r = await verifyTurnstile(bot.secret, form.get("cf-turnstile-response"), request, bot.strict);
|
|
146
|
+
if (r.ok)
|
|
147
|
+
return null;
|
|
148
|
+
if (r.reason === "unavailable")
|
|
149
|
+
return { words: w("ui.wbaccounts.problem.down"), status: 503 };
|
|
150
|
+
return { words: w("ui.wbaccounts.problem.bot_check"), status: 400 };
|
|
151
|
+
}
|
|
152
|
+
/** The plain line for a refusal. Never says which check failed or whether an account exists. */
|
|
153
|
+
function message(code) {
|
|
154
|
+
if (code === "invalid_email")
|
|
155
|
+
return w("ui.wbaccounts.problem.bad_email");
|
|
156
|
+
if (code === "invalid_code")
|
|
157
|
+
return w("ui.wbaccounts.problem.bad_code");
|
|
158
|
+
if (code === "auth_unavailable")
|
|
159
|
+
return w("ui.wbaccounts.problem.down");
|
|
160
|
+
// A wrong code and an expired one read the same (§8, E4).
|
|
161
|
+
if (code === "otp_expired" || code === "invalid_credentials")
|
|
162
|
+
return w("ui.wbaccounts.problem.wrong_code");
|
|
163
|
+
return plainAuthError({ code }, { appName: o.appName });
|
|
164
|
+
}
|
|
165
|
+
/** The person's name, from Supabase's user record (its user_metadata), or null. */
|
|
166
|
+
async function nameOf(accessToken) {
|
|
167
|
+
try {
|
|
168
|
+
const res = await doFetch(`${o.SUPABASE_URL}/auth/v1/user`, { headers: { apikey: o.SUPABASE_PUBLISHABLE_KEY, authorization: `Bearer ${accessToken}` }, signal: AbortSignal.timeout(5000) });
|
|
169
|
+
if (!res.ok)
|
|
170
|
+
return null;
|
|
171
|
+
const u = (await res.json());
|
|
172
|
+
const n = u.user_metadata?.name;
|
|
173
|
+
return typeof n === "string" && n.length > 0 ? n.slice(0, NAME_MAX) : null;
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function saveName(accessToken, name) {
|
|
180
|
+
try {
|
|
181
|
+
const res = await doFetch(`${o.SUPABASE_URL}/auth/v1/user`, {
|
|
182
|
+
method: "PUT",
|
|
183
|
+
headers: { apikey: o.SUPABASE_PUBLISHABLE_KEY, authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
|
|
184
|
+
body: JSON.stringify({ data: { name } }),
|
|
185
|
+
signal: AbortSignal.timeout(5000),
|
|
186
|
+
});
|
|
187
|
+
return res.ok;
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function route(request, url = new URL(request.url)) {
|
|
194
|
+
if (!ACCOUNTS_PATHS.includes(url.pathname))
|
|
195
|
+
return null;
|
|
196
|
+
if (url.pathname === PATHS.account || url.pathname === PATHS.name)
|
|
197
|
+
return accountRoute(request, url);
|
|
198
|
+
if (!sessions)
|
|
199
|
+
return notSetUp();
|
|
200
|
+
const bot = turnstileSetup({ WORKBENCH_ENV: o.environment, TURNSTILE_SITE_KEY: o.TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY: o.TURNSTILE_SECRET_KEY });
|
|
201
|
+
const d = { w, t, codeLength, check: bot.state === "on" ? bot.siteKey : null, privacy: o.privacyPath ?? null };
|
|
202
|
+
if (url.pathname === PATHS.signIn || url.pathname === PATHS.join) {
|
|
203
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
204
|
+
return plain("Method not allowed.", 405);
|
|
205
|
+
if (bot.state === "missing")
|
|
206
|
+
return plain(w("ui.wbaccounts.problem.not_set_up"), 503);
|
|
207
|
+
const next = safeReturnPath(url.searchParams.get("next"));
|
|
208
|
+
const now = await sessions.read(request);
|
|
209
|
+
if (now.state === "signed_in")
|
|
210
|
+
return withCookies(redirect(next), now.cookie ? [now.cookie] : []);
|
|
211
|
+
const cookies = now.state === "ended" ? [now.cookie] : [];
|
|
212
|
+
if (url.pathname === PATHS.join)
|
|
213
|
+
return withCookies(page(joinStep(d, next, askAge)), cookies);
|
|
214
|
+
if (url.searchParams.get("step") === "code") {
|
|
215
|
+
const pending = await sessions.pendingSignIn(request);
|
|
216
|
+
if (pending)
|
|
217
|
+
return withCookies(page(codeStep(d, next, pending)), cookies);
|
|
218
|
+
}
|
|
219
|
+
return withCookies(page(emailStep(d, next, "")), cookies);
|
|
220
|
+
}
|
|
221
|
+
if (request.method !== "POST")
|
|
222
|
+
return plain("Method not allowed.", 405);
|
|
223
|
+
if (!sameOrigin(request))
|
|
224
|
+
return plain(w("ui.wbaccounts.problem.cross_site"), 403);
|
|
225
|
+
const form = await formOf(request);
|
|
226
|
+
const next = safeReturnPath(form.get("next"));
|
|
227
|
+
if (url.pathname === PATHS.signOut) {
|
|
228
|
+
const clear = await sessions.signOut(request);
|
|
229
|
+
return withCookies(redirect("/"), [clear, sessions.clearSignIn()]);
|
|
230
|
+
}
|
|
231
|
+
const ip = ipKey(request.headers.get("cf-connecting-ip") ?? "unknown");
|
|
232
|
+
if (missingLimits(o.limits, o.environment))
|
|
233
|
+
return plain(w("ui.wbaccounts.problem.not_set_up"), 503);
|
|
234
|
+
const sends = url.pathname === PATHS.code || url.pathname === PATHS.joinCode || url.pathname === PATHS.resend;
|
|
235
|
+
if (sends && bot.state === "missing")
|
|
236
|
+
return plain(w("ui.wbaccounts.problem.not_set_up"), 503);
|
|
237
|
+
if (url.pathname === PATHS.code) {
|
|
238
|
+
const email = String(form.get("email") ?? "");
|
|
239
|
+
const again = (words, status) => page(emailStep(d, next, email, words), status);
|
|
240
|
+
// IP first, then the bot check, then the address: a bot without a passed check can't use up someone's address.
|
|
241
|
+
if (await overLimit(o.limits, sessions, { ip }))
|
|
242
|
+
return again(w("ui.wbaccounts.problem.too_many"), 429);
|
|
243
|
+
const human = await passed(bot, form, request);
|
|
244
|
+
if (human)
|
|
245
|
+
return again(human.words, human.status);
|
|
246
|
+
if (await overLimit(o.limits, sessions, { email }))
|
|
247
|
+
return again(w("ui.wbaccounts.problem.too_many"), 429);
|
|
248
|
+
const sent = await sessions.sendCode(email);
|
|
249
|
+
if (!sent.ok)
|
|
250
|
+
return again(message(sent.code), sent.status >= 500 ? 503 : 400);
|
|
251
|
+
return withCookies(redirect(codeUrl(next)), [await sessions.rememberSignIn(email)]);
|
|
252
|
+
}
|
|
253
|
+
if (url.pathname === PATHS.joinCode) {
|
|
254
|
+
const joinForm = askAge ? JOIN_ADULT_FORM : JOIN_FORM;
|
|
255
|
+
const input = readFields(joinForm, form);
|
|
256
|
+
const again = (o2, status) => page(joinStep(d, next, askAge, { ...o2, input }), status);
|
|
257
|
+
if (await overLimit(o.limits, sessions, { ip }))
|
|
258
|
+
return again({ error: w("ui.wbaccounts.problem.too_many") }, 429);
|
|
259
|
+
const human = await passed(bot, form, request);
|
|
260
|
+
if (human)
|
|
261
|
+
return again({ error: human.words }, human.status);
|
|
262
|
+
const result = validate(joinForm, input, FORM_CONTEXT);
|
|
263
|
+
if (!result.ok)
|
|
264
|
+
return again({ result }, 422);
|
|
265
|
+
const email = String(result.values.email ?? "");
|
|
266
|
+
if (await overLimit(o.limits, sessions, { email }))
|
|
267
|
+
return again({ error: w("ui.wbaccounts.problem.too_many") }, 429);
|
|
268
|
+
const data = { name: String(result.values.name ?? "") };
|
|
269
|
+
// A statement with its time, never proof (authentication standard C7).
|
|
270
|
+
if (askAge)
|
|
271
|
+
data.adult_declared_at = new Date().toISOString();
|
|
272
|
+
// Supabase ignores `data` for an address that has an account, so joining answers the same either way.
|
|
273
|
+
const sent = await sessions.sendCode(email, { data });
|
|
274
|
+
if (!sent.ok)
|
|
275
|
+
return again({ error: message(sent.code) }, sent.status >= 500 ? 503 : 400);
|
|
276
|
+
return withCookies(redirect(codeUrl(next)), [await sessions.rememberSignIn(email)]);
|
|
277
|
+
}
|
|
278
|
+
const pending = await sessions.pendingSignIn(request);
|
|
279
|
+
if (!pending)
|
|
280
|
+
return page(emailStep(d, next, "", w("ui.wbaccounts.problem.start_again")), 400);
|
|
281
|
+
if (url.pathname === PATHS.resend) {
|
|
282
|
+
const again = (words, status) => page(codeStep(d, next, pending, words), status);
|
|
283
|
+
if (await overLimit(o.limits, sessions, { ip }))
|
|
284
|
+
return again(w("ui.wbaccounts.problem.too_many"), 429);
|
|
285
|
+
const human = await passed(bot, form, request);
|
|
286
|
+
if (human)
|
|
287
|
+
return again(human.words, human.status);
|
|
288
|
+
if (await overLimit(o.limits, sessions, { email: pending.email }))
|
|
289
|
+
return again(w("ui.wbaccounts.problem.too_many"), 429);
|
|
290
|
+
const sent = await sessions.sendCode(pending.email);
|
|
291
|
+
if (!sent.ok)
|
|
292
|
+
return again(message(sent.code), sent.status >= 500 ? 503 : 400);
|
|
293
|
+
return withCookies(redirect(codeUrl(next)), [await sessions.rememberSignIn(pending.email)]);
|
|
294
|
+
}
|
|
295
|
+
// /auth/verify
|
|
296
|
+
if (await overLimit(o.limits, sessions, { ip, email: pending.email }))
|
|
297
|
+
return page(codeStep(d, next, pending, w("ui.wbaccounts.problem.too_many")), 429);
|
|
298
|
+
const code = form.has("code") ? String(form.get("code")) : Array.from({ length: codeLength }, (_, i) => String(form.get(`d${i + 1}`) ?? "")).join("");
|
|
299
|
+
const keep = form.get("keep") === "yes";
|
|
300
|
+
const r = await sessions.verifyCode(pending.email, code, { keep });
|
|
301
|
+
if (!r.ok) {
|
|
302
|
+
console.warn(JSON.stringify({ event: "sign_in_failed", reason: r.code }));
|
|
303
|
+
return page(codeStep(d, next, pending, message(r.code)), r.status >= 500 ? 503 : 400);
|
|
304
|
+
}
|
|
305
|
+
console.info(JSON.stringify({ event: "signed_in", user: r.user.id, shared: !keep }));
|
|
306
|
+
return withCookies(redirect(next), [r.cookie, sessions.clearSignIn()]);
|
|
307
|
+
}
|
|
308
|
+
async function accountRoute(request, url) {
|
|
309
|
+
const d = { w, t, codeLength, check: null };
|
|
310
|
+
if (url.pathname === PATHS.account) {
|
|
311
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
312
|
+
return plain("Method not allowed.", 405);
|
|
313
|
+
const s = await requireUser(request);
|
|
314
|
+
if (s instanceof Response)
|
|
315
|
+
return s;
|
|
316
|
+
const name = await nameOf(s.accessToken);
|
|
317
|
+
return s.finish(page(accountStep(d, { email: s.user.email, name }, { saved: url.searchParams.get("saved") === "name" })));
|
|
318
|
+
}
|
|
319
|
+
// POST /account/name
|
|
320
|
+
if (request.method !== "POST")
|
|
321
|
+
return plain("Method not allowed.", 405);
|
|
322
|
+
const s = await requireUser(request);
|
|
323
|
+
if (s instanceof Response)
|
|
324
|
+
return s;
|
|
325
|
+
const form = await formOf(request);
|
|
326
|
+
const input = readFields(NAME_FORM, form);
|
|
327
|
+
const result = validate(NAME_FORM, input, FORM_CONTEXT);
|
|
328
|
+
if (!result.ok)
|
|
329
|
+
return s.finish(page(accountStep(d, { email: s.user.email, name: null }, { result, input }), 422));
|
|
330
|
+
const name = String(result.values.name ?? "");
|
|
331
|
+
if (!(await saveName(s.accessToken, name))) {
|
|
332
|
+
console.error(JSON.stringify({ event: "account_name_not_saved" }));
|
|
333
|
+
return s.finish(page(accountStep(d, { email: s.user.email, name }, { error: w("ui.wbaccounts.problem.save_failed") }), 503));
|
|
334
|
+
}
|
|
335
|
+
console.info(JSON.stringify({ event: "account_name_changed", user: s.user.id }));
|
|
336
|
+
return s.finish(redirect(`${PATHS.account}?saved=name`));
|
|
337
|
+
}
|
|
338
|
+
return { route, requireUser, currentUser, sessions };
|
|
339
|
+
}
|
|
340
|
+
async function formOf(request) {
|
|
341
|
+
const type = request.headers.get("content-type") ?? "";
|
|
342
|
+
if (!type.startsWith("application/x-www-form-urlencoded") && !type.startsWith("multipart/form-data"))
|
|
343
|
+
return new FormData();
|
|
344
|
+
try {
|
|
345
|
+
return await request.formData();
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
return new FormData();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// The code boxes' layout, inline so the page is right before the project's
|
|
352
|
+
// workbench.css has the tool's rules (ACCOUNTS_STYLES holds the same ones).
|
|
353
|
+
const STYLE = `<style>.wb-accounts-digits{display:flex;gap:.5rem}.wb-accounts-digits input{width:2.5rem;font-size:1.5rem;text-align:center;padding:.45rem 0}.wb-accounts-code{border:0;padding:0;margin:0 0 1rem}.wb-accounts-code-label{margin-bottom:.5rem}</style>`;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AccountsAnswers } from "./accounts.ts";
|
|
2
|
+
/** What the manifest's questions set (capabilities/accounts.json `offer.questions`). */
|
|
3
|
+
export interface AccountsQuestions {
|
|
4
|
+
/** accounts.ask-age, yes or no. Default: false. */
|
|
5
|
+
ask_age?: boolean | null;
|
|
6
|
+
}
|
|
7
|
+
/** The answers file for these answers; a question left unanswered takes its named default. */
|
|
8
|
+
export declare function fromAnswers(answers?: AccountsQuestions, _project?: unknown): AccountsAnswers;
|
|
9
|
+
/** What's wrong with an answers file, in plain lines; empty when it is fine. */
|
|
10
|
+
export declare function accountsProblems(file: unknown): string[];
|
package/dist/answers.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The project's answers file, workbench/accounts.json, made from the
|
|
2
|
+
// manifest's questions by code (docs/builder-ready.md B3), and its checker.
|
|
3
|
+
// Pure: no file system, so Control, the web builder and AI through the
|
|
4
|
+
// Gateway get the same file Claude Code would.
|
|
5
|
+
/** The ways to sign in that are built. Password and Google come in later steps. */
|
|
6
|
+
const BUILT_METHODS = ["code"];
|
|
7
|
+
/** The answers file for these answers; a question left unanswered takes its named default. */
|
|
8
|
+
export function fromAnswers(answers = {}, _project) {
|
|
9
|
+
return { format: 1, methods: [...BUILT_METHODS], join: "anyone", ask_age: answers.ask_age === true };
|
|
10
|
+
}
|
|
11
|
+
/** What's wrong with an answers file, in plain lines; empty when it is fine. */
|
|
12
|
+
export function accountsProblems(file) {
|
|
13
|
+
const out = [];
|
|
14
|
+
if (!file || typeof file !== "object" || Array.isArray(file))
|
|
15
|
+
return ["workbench/accounts.json must be an object"];
|
|
16
|
+
const f = file;
|
|
17
|
+
const known = new Set(["format", "methods", "join", "ask_age"]);
|
|
18
|
+
for (const k of Object.keys(f))
|
|
19
|
+
if (!known.has(k))
|
|
20
|
+
out.push(`"${k}" isn't a setting of the accounts tool`);
|
|
21
|
+
if (f.format !== 1)
|
|
22
|
+
out.push("format must be 1");
|
|
23
|
+
if (f.methods !== undefined) {
|
|
24
|
+
if (!Array.isArray(f.methods) || f.methods.length === 0)
|
|
25
|
+
out.push("methods must be a list with at least \"code\"");
|
|
26
|
+
else {
|
|
27
|
+
for (const m of f.methods)
|
|
28
|
+
if (!BUILT_METHODS.includes(m))
|
|
29
|
+
out.push(`sign-in method ${JSON.stringify(m)} isn't built yet: only "code" is`);
|
|
30
|
+
if (!f.methods.includes("code"))
|
|
31
|
+
out.push("the emailed code is always on: methods must include \"code\"");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (f.join !== undefined && f.join !== "anyone")
|
|
35
|
+
out.push(`join ${JSON.stringify(f.join)} isn't built yet: only "anyone" is`);
|
|
36
|
+
if (f.ask_age !== undefined && typeof f.ask_age !== "boolean")
|
|
37
|
+
out.push("ask_age must be true or false");
|
|
38
|
+
return out;
|
|
39
|
+
}
|
package/dist/forms.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Bound, type Context } from "@mccaskie-labs/workbench-forms";
|
|
2
|
+
/** A display name: not unique, changeable (authentication standard C8). */
|
|
3
|
+
export declare const NAME_LIMIT = "accounts.name";
|
|
4
|
+
export declare const NAME_MAX = 80;
|
|
5
|
+
export declare const SIGN_IN_FORM: import("@mccaskie-labs/workbench-forms").Form<{
|
|
6
|
+
email: import("@mccaskie-labs/workbench-forms").EmailField;
|
|
7
|
+
}>;
|
|
8
|
+
export declare const JOIN_FORM: import("@mccaskie-labs/workbench-forms").Form<{
|
|
9
|
+
email: import("@mccaskie-labs/workbench-forms").EmailField;
|
|
10
|
+
name: import("@mccaskie-labs/workbench-forms").TextField;
|
|
11
|
+
}>;
|
|
12
|
+
/** Join with the "I am 18 or over" tick: a statement recorded with its time, never proof (C7). */
|
|
13
|
+
export declare const JOIN_ADULT_FORM: import("@mccaskie-labs/workbench-forms").Form<{
|
|
14
|
+
email: import("@mccaskie-labs/workbench-forms").EmailField;
|
|
15
|
+
name: import("@mccaskie-labs/workbench-forms").TextField;
|
|
16
|
+
adult: import("@mccaskie-labs/workbench-forms").TickField;
|
|
17
|
+
}>;
|
|
18
|
+
export declare const NAME_FORM: import("@mccaskie-labs/workbench-forms").Form<{
|
|
19
|
+
name: import("@mccaskie-labs/workbench-forms").TextField;
|
|
20
|
+
}>;
|
|
21
|
+
export declare const BOUNDS: Readonly<Record<string, Bound>>;
|
|
22
|
+
export declare const FORM_CONTEXT: Context;
|
package/dist/forms.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The account forms, as workbench-forms forms: the same validator checks them
|
|
2
|
+
// on the server, and renderForm draws their fields (fieldsOnly, so the page
|
|
3
|
+
// keeps its own form element, the return path and the Turnstile check).
|
|
4
|
+
import { defineForm, email, text, tick } from "@mccaskie-labs/workbench-forms";
|
|
5
|
+
/** A display name: not unique, changeable (authentication standard C8). */
|
|
6
|
+
export const NAME_LIMIT = "accounts.name";
|
|
7
|
+
export const NAME_MAX = 80;
|
|
8
|
+
export const SIGN_IN_FORM = defineForm("accounts_sign_in", { email: email({ required: true }) });
|
|
9
|
+
export const JOIN_FORM = defineForm("accounts_join", {
|
|
10
|
+
email: email({ required: true }),
|
|
11
|
+
name: text({ limit: NAME_LIMIT, required: true }),
|
|
12
|
+
});
|
|
13
|
+
/** Join with the "I am 18 or over" tick: a statement recorded with its time, never proof (C7). */
|
|
14
|
+
export const JOIN_ADULT_FORM = defineForm("accounts_join", {
|
|
15
|
+
email: email({ required: true }),
|
|
16
|
+
name: text({ limit: NAME_LIMIT, required: true }),
|
|
17
|
+
adult: tick({ required: true }),
|
|
18
|
+
});
|
|
19
|
+
export const NAME_FORM = defineForm("accounts_name", { name: text({ limit: NAME_LIMIT, required: true }) });
|
|
20
|
+
export const BOUNDS = Object.freeze({ [NAME_LIMIT]: Object.freeze({ min: 1, max: NAME_MAX, width: "m" }) });
|
|
21
|
+
export const FORM_CONTEXT = { bounds: BOUNDS };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { accountsProblems, fromAnswers, type AccountsQuestions } from "./answers.ts";
|
|
2
|
+
export { ACCOUNTS_PATHS, createAccounts, sessionCookies, withCookies, type Accounts, type AccountsAnswers, type AccountsOptions, type SignedIn } from "./accounts.ts";
|
|
3
|
+
export { ipKey, missingLimits, overLimit, type Limiter, type Limits } from "./limits.ts";
|
|
4
|
+
export { TURNSTILE_ACTION, TURNSTILE_ORIGIN, turnstileSetup, verifyTurnstile, type TurnstileKeys, type TurnstileResult, type TurnstileSetup } from "./turnstile.ts";
|
|
5
|
+
export { BOUNDS, JOIN_ADULT_FORM, JOIN_FORM, NAME_FORM, NAME_LIMIT, NAME_MAX, SIGN_IN_FORM } from "./forms.ts";
|
|
6
|
+
export { PATHS } from "./pages.ts";
|
|
7
|
+
export { ACCOUNTS_WORDS, fill, wordsWith, type AccountsWordKey, type Words } from "./words.ts";
|
|
8
|
+
export { ACCOUNTS_STYLES } from "./styles.ts";
|
|
9
|
+
export { ACCOUNTS_SAMPLES } from "./samples.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// @mccaskie-labs/workbench-accounts: the ways people sign in to a Workbench
|
|
2
|
+
// app and the account features that go with them (docs/accounts.md). Step 1:
|
|
3
|
+
// today's emailed six-digit code, moved out of the project template, with
|
|
4
|
+
// Join and the name on Your account. The Worker makes every Supabase Auth
|
|
5
|
+
// call; the browser never does. No Gateway call of its own: codes are mailed
|
|
6
|
+
// by the app's Send Email hook.
|
|
7
|
+
export { accountsProblems, fromAnswers } from "./answers.js";
|
|
8
|
+
export { ACCOUNTS_PATHS, createAccounts, sessionCookies, withCookies } from "./accounts.js";
|
|
9
|
+
export { ipKey, missingLimits, overLimit } from "./limits.js";
|
|
10
|
+
export { TURNSTILE_ACTION, TURNSTILE_ORIGIN, turnstileSetup, verifyTurnstile } from "./turnstile.js";
|
|
11
|
+
export { BOUNDS, JOIN_ADULT_FORM, JOIN_FORM, NAME_FORM, NAME_LIMIT, NAME_MAX, SIGN_IN_FORM } from "./forms.js";
|
|
12
|
+
export { PATHS } from "./pages.js";
|
|
13
|
+
export { ACCOUNTS_WORDS, fill, wordsWith } from "./words.js";
|
|
14
|
+
export { ACCOUNTS_STYLES } from "./styles.js";
|
|
15
|
+
export { ACCOUNTS_SAMPLES } from "./samples.js";
|
package/dist/limits.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Sessions } from "@mccaskie-labs/workbench-supabase";
|
|
2
|
+
/** A Workers rate limiting binding (SIGN_IN_IP_LIMIT, SIGN_IN_EMAIL_LIMIT). */
|
|
3
|
+
export interface Limiter {
|
|
4
|
+
limit(o: {
|
|
5
|
+
key: string;
|
|
6
|
+
}): Promise<{
|
|
7
|
+
success: boolean;
|
|
8
|
+
}>;
|
|
9
|
+
}
|
|
10
|
+
export interface Limits {
|
|
11
|
+
ip?: Limiter | undefined;
|
|
12
|
+
email?: Limiter | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The IP as the limiter counts it: IPv4 whole, IPv6 by its /64, since one
|
|
16
|
+
* connection usually holds a whole /64 and could otherwise pick a new key per try.
|
|
17
|
+
*/
|
|
18
|
+
export declare function ipKey(ip: string): string;
|
|
19
|
+
/** Outside development both limiters must be bound: sign-in refuses rather than run without them. */
|
|
20
|
+
export declare function missingLimits(limits: Limits, environment: string): boolean;
|
|
21
|
+
/** True when this IP or this address (whichever are given) has tried too often in the last minute. */
|
|
22
|
+
export declare function overLimit(limits: Limits, sessions: Sessions, { ip, email }: {
|
|
23
|
+
ip?: string;
|
|
24
|
+
email?: string;
|
|
25
|
+
}): Promise<boolean>;
|