@bright-logic-digital/site-editor 0.0.0-stage → 1.0.0-rc.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +4 -0
  3. package/README.md +318 -2
  4. package/bin/cli.js +92 -0
  5. package/bin/copy-editor.js +211 -0
  6. package/bin/node-version.js +20 -0
  7. package/bin/site-config.js +46 -0
  8. package/bin/site-editor.js +16 -0
  9. package/editor/admin.css +438 -0
  10. package/editor/api.js +138 -0
  11. package/editor/app.js +1178 -0
  12. package/editor/asset-map.js +38 -0
  13. package/editor/boot.js +72 -0
  14. package/editor/copy.js +239 -0
  15. package/editor/drafts.js +67 -0
  16. package/editor/format.js +80 -0
  17. package/editor/forms.js +918 -0
  18. package/editor/images.js +212 -0
  19. package/editor/index.html +27 -0
  20. package/editor/model.js +152 -0
  21. package/editor/pages.js +297 -0
  22. package/editor/photos.js +232 -0
  23. package/editor/publish.js +45 -0
  24. package/editor/shared/rules.js +118 -0
  25. package/editor/shared/site.js +128 -0
  26. package/editor/shared/validate.js +303 -0
  27. package/editor/signin.js +154 -0
  28. package/editor/status.js +90 -0
  29. package/editor/uploads.js +91 -0
  30. package/guide/check.js +233 -0
  31. package/hosts/next.js +19 -0
  32. package/hosts/pages.js +20 -0
  33. package/hosts/shared.js +42 -0
  34. package/package.json +91 -4
  35. package/server/blob-sha.js +10 -0
  36. package/server/changes.js +24 -0
  37. package/server/check-content.js +197 -0
  38. package/server/config.js +97 -0
  39. package/server/dispatch.js +207 -0
  40. package/server/github.js +149 -0
  41. package/server/handlers.js +364 -0
  42. package/server/index.js +153 -0
  43. package/server/local-repo.js +171 -0
  44. package/server/mapped-repo.js +48 -0
  45. package/server/memory-repo.js +104 -0
  46. package/server/path-map.js +26 -0
  47. package/server/signin/access.js +329 -0
  48. package/server/signin/code-store.sql +60 -0
  49. package/server/signin/code.js +192 -0
  50. package/server/signin/codes.js +171 -0
  51. package/server/signin/refusal.js +76 -0
  52. package/server/signin/session.js +90 -0
  53. package/tests/fixtures/image-files.json +14 -0
  54. package/tests/fixtures/slugs.json +202 -0
  55. package/tests/fixtures/validation.json +12734 -0
  56. package/types/bin/cli.d.ts +1 -0
  57. package/types/bin/copy-editor.d.ts +32 -0
  58. package/types/bin/node-version.d.ts +8 -0
  59. package/types/bin/site-config.d.ts +17 -0
  60. package/types/bin/site-editor.d.ts +2 -0
  61. package/types/editor/api.d.ts +37 -0
  62. package/types/editor/copy.d.ts +153 -0
  63. package/types/editor/shared/rules.d.ts +33 -0
  64. package/types/editor/shared/site.d.ts +35 -0
  65. package/types/editor/shared/validate.d.ts +19 -0
  66. package/types/guide/check.d.ts +31 -0
  67. package/types/hosts/next.d.ts +12 -0
  68. package/types/hosts/pages.d.ts +9 -0
  69. package/types/hosts/shared.d.ts +21 -0
  70. package/types/server/blob-sha.d.ts +1 -0
  71. package/types/server/changes.d.ts +2 -0
  72. package/types/server/check-content.d.ts +16 -0
  73. package/types/server/config.d.ts +46 -0
  74. package/types/server/dispatch.d.ts +51 -0
  75. package/types/server/github.d.ts +27 -0
  76. package/types/server/handlers.d.ts +116 -0
  77. package/types/server/index.d.ts +75 -0
  78. package/types/server/local-repo.d.ts +16 -0
  79. package/types/server/mapped-repo.d.ts +10 -0
  80. package/types/server/memory-repo.d.ts +28 -0
  81. package/types/server/path-map.d.ts +3 -0
  82. package/types/server/signin/access.d.ts +68 -0
  83. package/types/server/signin/code.d.ts +44 -0
  84. package/types/server/signin/codes.d.ts +98 -0
  85. package/types/server/signin/refusal.d.ts +122 -0
  86. package/types/server/signin/session.d.ts +29 -0
@@ -0,0 +1,48 @@
1
+ // Presents a Repo whose editable files sit under other prefixes (here, in a
2
+ // monorepo) as if they sat under the editor's own logical paths. The editor,
3
+ // validator and handlers only ever see logical paths such as content/site.json.
4
+ // prefixes: Array<[logical, actual]>, each prefix ending in "/".
5
+
6
+ export function mapRepo(repo, prefixes) {
7
+ const toLogical = (path) => {
8
+ for (const [logical, actual] of prefixes) {
9
+ if (path.startsWith(actual)) return logical + path.slice(actual.length);
10
+ }
11
+ return null;
12
+ };
13
+ // A path with an empty, "." or ".." segment, a backslash or a NUL is never mapped.
14
+ const tricky = (path) => /[\\\0]/.test(path)
15
+ || path.split("/").some((part) => part === "" || part === "." || part === "..");
16
+ const toActual = (path) => {
17
+ if (typeof path === "string" && tricky(path)) return null;
18
+ for (const [logical, actual] of prefixes) {
19
+ if (typeof path === "string" && path.startsWith(logical)) return actual + path.slice(logical.length);
20
+ }
21
+ return null;
22
+ };
23
+
24
+ return {
25
+ async head() {
26
+ const { commit, files } = await repo.head();
27
+ const mapped = new Map();
28
+ for (const [path, sha] of files) {
29
+ const logical = toLogical(path);
30
+ if (logical !== null) mapped.set(logical, sha);
31
+ }
32
+ return { commit, files: mapped };
33
+ },
34
+ readText: (sha) => repo.readText(sha),
35
+ createBlob: (base64) => repo.createBlob(base64),
36
+ async commit(input) {
37
+ // Not a list: the inner repo rejects it with its own error.
38
+ if (!Array.isArray(input.changes)) return repo.commit(input);
39
+ const changes = input.changes.map((change) => {
40
+ const path = toActual(change?.path);
41
+ if (path === null) throw new Error(`Path is outside the editable folders: ${change?.path}`);
42
+ return { ...change, path };
43
+ });
44
+ return repo.commit({ ...input, changes });
45
+ },
46
+ contains: (ancestor, descendant) => repo.contains(ancestor, descendant),
47
+ };
48
+ }
@@ -0,0 +1,104 @@
1
+ // In-memory Repo for tests. Runs in Workers and Node.
2
+ import { RepoMoved } from "./github.js";
3
+ import { blobSha } from "./blob-sha.js";
4
+ import { checkChanges } from "./changes.js";
5
+
6
+ const enc = new TextEncoder();
7
+ const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
8
+
9
+ /** @typedef {import("./dispatch.js").Repo} Repo */
10
+
11
+ /**
12
+ * A Repo, plus the two helpers tests use: files() is the head's files as
13
+ * {path: text}; moveHead(changes) adds a commit behind the caller's back.
14
+ * @typedef {Repo & {
15
+ * files(): Record<string, string>,
16
+ * moveHead(changes?: Array<{ path: string, text?: string, sha?: string, remove?: boolean }>): Promise<string>,
17
+ * }} MemoryRepo
18
+ */
19
+
20
+ /**
21
+ * @param {Record<string, string>} [initial] the head's files, {path: text}
22
+ * @returns {MemoryRepo}
23
+ */
24
+ export function createMemoryRepo(initial = {}) {
25
+ const blobs = new Map(); // blob sha -> bytes
26
+ const commits = new Map(); // commit sha -> {parent, tree: Map path -> blob sha}
27
+ let headSha;
28
+ let counter = 0;
29
+
30
+ async function store(bytes) {
31
+ const sha = await blobSha(bytes);
32
+ blobs.set(sha, bytes);
33
+ return sha;
34
+ }
35
+
36
+ async function addCommit(parent, tree) {
37
+ counter += 1;
38
+ const digest = await crypto.subtle.digest("SHA-1", enc.encode(`commit ${counter} ${parent ?? ""}`));
39
+ const sha = hex(new Uint8Array(digest));
40
+ commits.set(sha, { parent, tree });
41
+ headSha = sha;
42
+ return sha;
43
+ }
44
+
45
+ async function applied(changes) {
46
+ const tree = new Map(commits.get(headSha).tree);
47
+ for (const c of changes) {
48
+ if (c.remove) tree.delete(c.path);
49
+ else if (typeof c.text === "string") tree.set(c.path, await store(enc.encode(c.text)));
50
+ else if (blobs.has(c.sha)) tree.set(c.path, c.sha);
51
+ else throw new Error(`Unknown blob ${c.sha}`);
52
+ }
53
+ return tree;
54
+ }
55
+
56
+ const ready = (async () => {
57
+ const tree = new Map();
58
+ for (const [path, text] of Object.entries(initial)) tree.set(path, await store(enc.encode(text)));
59
+ await addCommit(null, tree);
60
+ })();
61
+
62
+ return {
63
+ async head() {
64
+ await ready;
65
+ return { commit: headSha, files: new Map(commits.get(headSha).tree) };
66
+ },
67
+ async readText(sha) {
68
+ await ready;
69
+ const bytes = blobs.get(sha);
70
+ if (!bytes) throw new Error(`Unknown blob ${sha}`);
71
+ return new TextDecoder().decode(bytes);
72
+ },
73
+ async createBlob(base64) {
74
+ await ready;
75
+ return store(Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)));
76
+ },
77
+ async commit({ parent, changes }) {
78
+ checkChanges(changes);
79
+ await ready;
80
+ if (parent !== headSha) throw new RepoMoved();
81
+ return addCommit(headSha, await applied(changes));
82
+ },
83
+ async contains(ancestor, descendant) {
84
+ await ready;
85
+ for (let sha = descendant; sha; sha = commits.get(sha)?.parent) {
86
+ if (!commits.has(sha)) return false;
87
+ if (sha === ancestor) return true;
88
+ }
89
+ return false;
90
+ },
91
+ // Test helpers.
92
+ files() {
93
+ const out = {};
94
+ for (const [path, sha] of commits.get(headSha).tree) {
95
+ out[path] = new TextDecoder().decode(blobs.get(sha));
96
+ }
97
+ return out;
98
+ },
99
+ async moveHead(changes = []) {
100
+ await ready;
101
+ return addCommit(headSha, await applied(changes));
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,26 @@
1
+ // @ts-check
2
+ // The form of a path map, the config's paths.repo and paths.local: where
3
+ // the editor's own folders, content/ and assets/, sit. Shared by the config
4
+ // check (index.js) and the working tree's repository (local-repo.js). Runs
5
+ // in Workers and Node: no node: import here (tests/pages-graph.test.js).
6
+
7
+ /** A folder inside the repository: relative, plain segments, ending in "/". */
8
+ function isFolder(/** @type {unknown} */ v) {
9
+ if (typeof v !== "string" || !v.endsWith("/") || v.length < 2) return false;
10
+ return v.slice(0, -1).split("/").every((part) => part !== "" && part !== "." && part !== ".."
11
+ && !/[\\\0]/.test(part));
12
+ }
13
+
14
+ // The editor's own folders; a path map places each once.
15
+ const LOGICAL = ["content/", "assets/"];
16
+
17
+ /** [[logical, physical], ...] placing content/ and assets/ once each, in two
18
+ * physical folders of which neither is, or is inside, the other. */
19
+ export function isPathMap(/** @type {unknown} */ v) {
20
+ if (!Array.isArray(v) || v.length !== LOGICAL.length) return false;
21
+ if (!v.every((pair) => Array.isArray(pair) && pair.length === 2 && pair.every(isFolder))) return false;
22
+ const logical = v.map((pair) => pair[0]);
23
+ if (!LOGICAL.every((name) => logical.includes(name))) return false;
24
+ const [a, b] = v.map((pair) => pair[1]);
25
+ return !a.startsWith(b) && !b.startsWith(a);
26
+ }
@@ -0,0 +1,329 @@
1
+ // @ts-check
2
+ // Sign-in by Cloudflare Access: Access signs the owner in before a request
3
+ // reaches the site and adds a signed token (Cf-Access-Jwt-Assertion) to
4
+ // every request. Verifies that token on every editor API request. The API
5
+ // is also reachable on hostnames Access may not cover, so this check is the
6
+ // real gate: every byte of the token is hostile until the signature has been
7
+ // verified. Runs in Workers and Node; uses only globals both have (the Pages
8
+ // entry point reaches this file). The verification is the Access check as
9
+ // it shipped before 1.0.0, unchanged; the provider at the end is new.
10
+ import { NOT_ALLOWED_MESSAGE, SignInRefused } from "./refusal.js";
11
+
12
+ /** @typedef {import("./refusal.js").SignInProvider} SignInProvider */
13
+ /** @typedef {import("./refusal.js").Env} Env */
14
+
15
+ const MAX_TOKEN_LENGTH = 8192;
16
+ const KEY_TTL_MS = 60 * 60 * 1000;
17
+ const REFETCH_GAP_MS = 60 * 1000;
18
+ const RETRY_AFTER_FAILURE_MS = 10 * 1000;
19
+ const MAX_IN_FLIGHT = 4;
20
+ const IN_FLIGHT_EXPIRY_MS = 30 * 1000;
21
+ const NBF_LEEWAY_S = 60;
22
+ const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
23
+
24
+ const TEAM_DOMAIN_RE = /^[a-z0-9-]+\.cloudflareaccess\.com$/;
25
+ const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
26
+ const B64URL_RE = /^[A-Za-z0-9_-]+$/;
27
+
28
+ export class AuthError extends Error {
29
+ /**
30
+ * @param {number} status
31
+ * @param {string} code
32
+ * @param {string} message
33
+ */
34
+ constructor(status, code, message) {
35
+ super(message);
36
+ this.name = "AuthError";
37
+ this.status = status;
38
+ this.code = code;
39
+ }
40
+ }
41
+
42
+ /** @param {string} message */
43
+ const unauthorized = (message) => new AuthError(401, "unauthorized", message);
44
+
45
+ /** @param {unknown} v */
46
+ const text = (v) => (typeof v === "string" ? v.trim() : "");
47
+
48
+ /**
49
+ * @typedef {object} AccessConfig
50
+ * @property {string} token
51
+ * @property {string} repo
52
+ * @property {string} branch
53
+ * @property {string} teamDomain
54
+ * @property {string} aud
55
+ * @property {string[]} emails
56
+ */
57
+
58
+ /**
59
+ * The settings, trimmed, or null unless every one is there and well formed.
60
+ * @param {any} env
61
+ * @returns {AccessConfig | null}
62
+ */
63
+ export function readConfig(env) {
64
+ if (!env || typeof env !== "object") return null;
65
+ const token = text(env.GITHUB_TOKEN);
66
+ const repo = text(env.GITHUB_REPO);
67
+ const branch = text(env.GITHUB_BRANCH);
68
+ const teamDomain = text(env.ACCESS_TEAM_DOMAIN);
69
+ const aud = text(env.ACCESS_AUD);
70
+ /** @type {string} */
71
+ const rawEmails = typeof env.ADMIN_EMAILS === "string" ? env.ADMIN_EMAILS : "";
72
+ const emails = rawEmails.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
73
+ if (!token || !repo || !branch || !teamDomain || !aud || !emails.length) return null;
74
+ if (!TEAM_DOMAIN_RE.test(teamDomain) || !REPO_RE.test(repo)) return null;
75
+ return { token, repo, branch, teamDomain, aud, emails };
76
+ }
77
+
78
+ /** @param {string} s */
79
+ function b64urlBytes(s) {
80
+ if (!B64URL_RE.test(s) || s.length % 4 === 1) throw unauthorized("Malformed token");
81
+ const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
82
+ const out = new Uint8Array(bin.length);
83
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * @param {string} segment
89
+ * @returns {Record<string, any>}
90
+ */
91
+ function jsonObject(segment) {
92
+ /** @type {any} */
93
+ let value;
94
+ try {
95
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(b64urlBytes(segment)));
96
+ } catch {
97
+ throw unauthorized("Malformed token");
98
+ }
99
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
100
+ throw unauthorized("Malformed token");
101
+ }
102
+ return value;
103
+ }
104
+
105
+ // teamDomain -> {keys: Map<kid, CryptoKey>, fetchedAt}
106
+ /** @type {Map<string, { keys: Map<string, CryptoKey>, fetchedAt: number }>} */
107
+ const cache = new Map();
108
+ // teamDomain -> {at, ok}: the last fetch attempt that settled, kept apart
109
+ // from the keys so a failed attempt is remembered even when there are no
110
+ // keys to keep.
111
+ /** @type {Map<string, { at: number, ok: boolean }>} */
112
+ const attempts = new Map();
113
+ // teamDomain -> Set of {at}: fetches started and not yet settled. Each request
114
+ // makes its own fetch (Workers ties I/O to the request that started it), so
115
+ // concurrent requests on a cold cache do not wait on one another.
116
+ /** @type {Map<string, Set<{ at: number }>>} */
117
+ const inFlight = new Map();
118
+
119
+ export function resetKeyCache() {
120
+ cache.clear();
121
+ attempts.clear();
122
+ inFlight.clear();
123
+ }
124
+
125
+ /** The fetches in flight for a team domain, dropping any started so long ago
126
+ * that its request must have ended without it settling.
127
+ * @param {string} teamDomain
128
+ * @param {number} now
129
+ */
130
+ function liveFetches(teamDomain, now) {
131
+ let set = inFlight.get(teamDomain);
132
+ if (!set) {
133
+ set = new Set();
134
+ inFlight.set(teamDomain, set);
135
+ }
136
+ for (const f of set) if (now - f.at >= IN_FLIGHT_EXPIRY_MS) set.delete(f);
137
+ return set;
138
+ }
139
+
140
+ /** @typedef {(url: string) => Promise<Response>} FetchKeys */
141
+ /** @typedef {{ now: () => number, fetch: FetchKeys }} VerifyDeps */
142
+
143
+ /**
144
+ * @param {AccessConfig} config
145
+ * @param {FetchKeys} fetchFn
146
+ * @returns {Promise<Map<string, CryptoKey>>}
147
+ */
148
+ async function fetchKeys(config, fetchFn) {
149
+ /** @type {any} */
150
+ let body;
151
+ try {
152
+ const res = await fetchFn(`https://${config.teamDomain}/cdn-cgi/access/certs`);
153
+ if (!res || res.status !== 200) throw new Error("bad status");
154
+ body = await res.json();
155
+ } catch {
156
+ throw unauthorized("Could not load signing keys");
157
+ }
158
+ if (!body || typeof body !== "object" || !Array.isArray(body.keys)) {
159
+ throw unauthorized("Could not load signing keys");
160
+ }
161
+ const keys = new Map();
162
+ for (const jwk of body.keys) {
163
+ if (!jwk || typeof jwk !== "object" || jwk.kty !== "RSA"
164
+ || typeof jwk.kid !== "string" || !jwk.kid
165
+ || typeof jwk.n !== "string" || typeof jwk.e !== "string") continue;
166
+ try {
167
+ keys.set(jwk.kid, await crypto.subtle.importKey(
168
+ "jwk", { kty: "RSA", n: jwk.n, e: jwk.e, alg: "RS256", ext: true },
169
+ RS256, false, ["verify"]));
170
+ } catch {
171
+ // A key that will not import is as good as absent.
172
+ }
173
+ }
174
+ return keys;
175
+ }
176
+
177
+ /**
178
+ * @param {AccessConfig} config
179
+ * @param {string} kid
180
+ * @param {VerifyDeps} deps
181
+ * @returns {Promise<CryptoKey>}
182
+ */
183
+ async function keyFor(config, kid, deps) {
184
+ const now = deps.now();
185
+ const entry = cache.get(config.teamDomain);
186
+ const fresh = entry && now - entry.fetchedAt < KEY_TTL_MS;
187
+ if (fresh && entry.keys.has(kid)) return /** @type {CryptoKey} */ (entry.keys.get(kid));
188
+ // Forged tokens must not cause a fetch each: space settled attempts out,
189
+ // whether or not keys are cached, and cap the fetches in flight.
190
+ const last = attempts.get(config.teamDomain);
191
+ if (last && now - last.at < (last.ok ? REFETCH_GAP_MS : RETRY_AFTER_FAILURE_MS)) {
192
+ throw unauthorized("Unknown signing key");
193
+ }
194
+ const running = liveFetches(config.teamDomain, now);
195
+ if (running.size >= MAX_IN_FLIGHT) throw unauthorized("Unknown signing key");
196
+ const mine = { at: now };
197
+ running.add(mine);
198
+ let keys;
199
+ try {
200
+ keys = await fetchKeys(config, deps.fetch);
201
+ } catch (err) {
202
+ attempts.set(config.teamDomain, { at: deps.now(), ok: false });
203
+ throw err;
204
+ } finally {
205
+ running.delete(mine);
206
+ }
207
+ const settled = deps.now();
208
+ attempts.set(config.teamDomain, { at: settled, ok: true });
209
+ cache.set(config.teamDomain, { keys, fetchedAt: settled });
210
+ const key = keys.get(kid);
211
+ if (!key) throw unauthorized("Unknown signing key");
212
+ return key;
213
+ }
214
+
215
+ /**
216
+ * The signed-in address, lower-cased, once the token is verified and the
217
+ * address is on the list. Throws AuthError (401, or 403 for an address not
218
+ * on the list); its message names the check, never the token or the address.
219
+ * @param {Request} request
220
+ * @param {AccessConfig} config
221
+ * @param {Partial<VerifyDeps>} [deps]
222
+ * @returns {Promise<{ email: string }>}
223
+ */
224
+ export async function verifyAccess(request, config, deps = {}) {
225
+ const now = deps.now || Date.now;
226
+ /** @type {FetchKeys} */
227
+ const fetchFn = deps.fetch || ((...args) => globalThis.fetch(...args));
228
+
229
+ const token = request.headers.get("Cf-Access-Jwt-Assertion");
230
+ if (!token || token.length > MAX_TOKEN_LENGTH) throw unauthorized("Missing or invalid token");
231
+ const parts = token.split(".");
232
+ if (parts.length !== 3) throw unauthorized("Malformed token");
233
+ const [h, p, s] = parts;
234
+
235
+ const header = jsonObject(h);
236
+ if (header.alg !== "RS256") throw unauthorized("Unsupported token algorithm");
237
+ if (typeof header.kid !== "string" || !header.kid) throw unauthorized("Malformed token");
238
+ const signature = b64urlBytes(s);
239
+
240
+ const key = await keyFor(config, header.kid, { now, fetch: fetchFn });
241
+ let ok;
242
+ try {
243
+ ok = await crypto.subtle.verify(
244
+ "RSASSA-PKCS1-v1_5", key, signature, new TextEncoder().encode(`${h}.${p}`));
245
+ } catch {
246
+ ok = false;
247
+ }
248
+ if (!ok) throw unauthorized("Bad token signature");
249
+
250
+ const claims = jsonObject(p);
251
+ const nowS = now() / 1000;
252
+ if (claims.iss !== `https://${config.teamDomain}`) throw unauthorized("Wrong token issuer");
253
+ if (!Array.isArray(claims.aud) || !claims.aud.includes(config.aud)) {
254
+ throw unauthorized("Wrong token audience");
255
+ }
256
+ if (typeof claims.exp !== "number" || !(claims.exp > nowS)) throw unauthorized("Token expired");
257
+ if (claims.nbf !== undefined
258
+ && (typeof claims.nbf !== "number" || !(claims.nbf <= nowS + NBF_LEEWAY_S))) {
259
+ throw unauthorized("Token not yet valid");
260
+ }
261
+ const email = typeof claims.email === "string" ? claims.email.trim().toLowerCase() : "";
262
+ if (!email) throw unauthorized("Token has no email");
263
+ if (!config.emails.includes(email)) throw new AuthError(403, "forbidden", "Not on the editor list");
264
+ return { email };
265
+ }
266
+
267
+ // ---- The provider (new in the package).
268
+
269
+ const SIGN_IN = "Your sign-in could not be confirmed. Reload the page to sign in again.";
270
+
271
+ /** The setting names readConfig reads, in its order. */
272
+ const NAMES = ["GITHUB_TOKEN", "GITHUB_REPO", "GITHUB_BRANCH", "ACCESS_TEAM_DOMAIN", "ACCESS_AUD",
273
+ "ADMIN_EMAILS"];
274
+
275
+ /**
276
+ * The NAMES of the settings readConfig would refuse, never a value: empty
277
+ * exactly when readConfig reads a configuration.
278
+ * @param {any} env
279
+ * @returns {string[]}
280
+ */
281
+ export function accessProblems(env) {
282
+ if (!env || typeof env !== "object") return [...NAMES];
283
+ const problems = NAMES.filter((name) => name !== "ADMIN_EMAILS" && !text(env[name]));
284
+ if (!problems.includes("GITHUB_REPO") && !REPO_RE.test(text(env.GITHUB_REPO))) {
285
+ problems.push("GITHUB_REPO");
286
+ }
287
+ if (!problems.includes("ACCESS_TEAM_DOMAIN") && !TEAM_DOMAIN_RE.test(text(env.ACCESS_TEAM_DOMAIN))) {
288
+ problems.push("ACCESS_TEAM_DOMAIN");
289
+ }
290
+ /** @type {string} */
291
+ const rawEmails = typeof env.ADMIN_EMAILS === "string" ? env.ADMIN_EMAILS : "";
292
+ if (!rawEmails.split(",").some((e) => e.trim())) problems.push("ADMIN_EMAILS");
293
+ return NAMES.filter((name) => problems.includes(name));
294
+ }
295
+
296
+ /**
297
+ * @param {{ fetch?: FetchKeys }} [options] fetch for the signing keys;
298
+ * the global fetch when not given
299
+ * @returns {SignInProvider}
300
+ */
301
+ export function accessSignIn({ fetch } = {}) {
302
+ /** @param {Env} env */
303
+ const read = (env) => {
304
+ const config = readConfig(env);
305
+ if (!config) throw new Error("the sign-in settings were not checked first");
306
+ return config;
307
+ };
308
+ return {
309
+ kind: "access",
310
+ problems: (env) => accessProblems(env),
311
+ github(env) {
312
+ const { token, repo, branch } = read(env);
313
+ return { token, repo, branch };
314
+ },
315
+ // Access signs the owner in before the site sees the request: no routes.
316
+ route: async () => null,
317
+ async user(request, ctx) {
318
+ try {
319
+ const { email } = await verifyAccess(request, read(ctx.env), { now: ctx.now, fetch });
320
+ return email;
321
+ } catch (err) {
322
+ if (!(err instanceof AuthError)) throw err;
323
+ throw err.status === 403
324
+ ? new SignInRefused(403, "forbidden", NOT_ALLOWED_MESSAGE)
325
+ : new SignInRefused(401, "unauthorized", SIGN_IN);
326
+ }
327
+ },
328
+ };
329
+ }
@@ -0,0 +1,60 @@
1
+ -- One-time sign-in codes for the owner editor at /admin.
2
+ --
3
+ -- Written server-side only, using the service-role key, through the three
4
+ -- functions below. RLS is enabled with no policies, so the anon/public key
5
+ -- cannot read or write this table. Only code hashes are stored.
6
+ -- The limits here (10 minutes, 5 attempts, 5 codes an hour, 10 a day) match
7
+ -- the constants in server/signin/codes.js. Change them together.
8
+
9
+ create table if not exists public.admin_login_codes (
10
+ id bigint generated always as identity primary key,
11
+ email text not null,
12
+ code_hash text not null,
13
+ created_at timestamptz not null default now(),
14
+ expires_at timestamptz not null,
15
+ attempts int not null default 0,
16
+ used_at timestamptz
17
+ );
18
+ create index if not exists admin_login_codes_email_idx on public.admin_login_codes (email, created_at desc);
19
+ alter table public.admin_login_codes enable row level security;
20
+
21
+ create or replace function public.admin_login_code_issue(p_email text, p_code_hash text)
22
+ returns boolean language plpgsql security definer set search_path = public, pg_temp as $$
23
+ begin
24
+ perform pg_advisory_xact_lock(hashtext(p_email));
25
+ delete from admin_login_codes where created_at < now() - interval '2 days';
26
+ if (select count(*) from admin_login_codes where email = p_email and created_at > now() - interval '1 hour') >= 5
27
+ or (select count(*) from admin_login_codes where email = p_email and created_at > now() - interval '1 day') >= 10 then
28
+ return false;
29
+ end if;
30
+ update admin_login_codes set used_at = now() where email = p_email and used_at is null;
31
+ insert into admin_login_codes (email, code_hash, expires_at) values (p_email, p_code_hash, now() + interval '10 minutes');
32
+ return true;
33
+ end $$;
34
+
35
+ create or replace function public.admin_login_code_attempt(p_email text)
36
+ returns text language sql security definer set search_path = public, pg_temp as $$
37
+ update admin_login_codes set attempts = attempts + 1
38
+ where id = (select id from admin_login_codes
39
+ where email = p_email and used_at is null and expires_at > now()
40
+ order by created_at desc limit 1)
41
+ and used_at is null and expires_at > now()
42
+ returning case when attempts <= 5 then code_hash end;
43
+ $$;
44
+
45
+ create or replace function public.admin_login_code_consume(p_email text, p_code_hash text)
46
+ returns boolean language sql security definer set search_path = public, pg_temp as $$
47
+ with used as (
48
+ update admin_login_codes set used_at = now()
49
+ where email = p_email and code_hash = p_code_hash and used_at is null and expires_at > now()
50
+ returning 1
51
+ )
52
+ select exists (select 1 from used);
53
+ $$;
54
+
55
+ revoke all on function public.admin_login_code_issue(text, text) from public, anon, authenticated;
56
+ revoke all on function public.admin_login_code_attempt(text) from public, anon, authenticated;
57
+ revoke all on function public.admin_login_code_consume(text, text) from public, anon, authenticated;
58
+ grant execute on function public.admin_login_code_issue(text, text) to service_role;
59
+ grant execute on function public.admin_login_code_attempt(text) to service_role;
60
+ grant execute on function public.admin_login_code_consume(text, text) to service_role;