@bright-logic-digital/site-editor 0.0.0-stage → 1.0.0-rc.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 +30 -0
- package/LICENSE +4 -0
- package/README.md +318 -2
- package/bin/cli.js +92 -0
- package/bin/copy-editor.js +211 -0
- package/bin/node-version.js +20 -0
- package/bin/site-config.js +46 -0
- package/bin/site-editor.js +16 -0
- package/editor/admin.css +438 -0
- package/editor/api.js +138 -0
- package/editor/app.js +1178 -0
- package/editor/asset-map.js +38 -0
- package/editor/boot.js +72 -0
- package/editor/copy.js +239 -0
- package/editor/drafts.js +67 -0
- package/editor/format.js +80 -0
- package/editor/forms.js +918 -0
- package/editor/images.js +212 -0
- package/editor/index.html +27 -0
- package/editor/model.js +152 -0
- package/editor/pages.js +297 -0
- package/editor/photos.js +232 -0
- package/editor/publish.js +45 -0
- package/editor/shared/rules.js +118 -0
- package/editor/shared/site.js +128 -0
- package/editor/shared/validate.js +303 -0
- package/editor/signin.js +154 -0
- package/editor/status.js +90 -0
- package/editor/uploads.js +91 -0
- package/guide/check.js +233 -0
- package/hosts/next.js +19 -0
- package/hosts/pages.js +20 -0
- package/hosts/shared.js +42 -0
- package/package.json +91 -4
- package/server/blob-sha.js +10 -0
- package/server/changes.js +24 -0
- package/server/check-content.js +197 -0
- package/server/config.js +97 -0
- package/server/dispatch.js +207 -0
- package/server/github.js +149 -0
- package/server/handlers.js +364 -0
- package/server/index.js +153 -0
- package/server/local-repo.js +171 -0
- package/server/mapped-repo.js +48 -0
- package/server/memory-repo.js +104 -0
- package/server/path-map.js +26 -0
- package/server/signin/access.js +329 -0
- package/server/signin/code-store.sql +60 -0
- package/server/signin/code.js +192 -0
- package/server/signin/codes.js +171 -0
- package/server/signin/refusal.js +76 -0
- package/server/signin/session.js +90 -0
- package/tests/fixtures/image-files.json +14 -0
- package/tests/fixtures/slugs.json +202 -0
- package/tests/fixtures/validation.json +12734 -0
- package/types/bin/cli.d.ts +1 -0
- package/types/bin/copy-editor.d.ts +32 -0
- package/types/bin/node-version.d.ts +8 -0
- package/types/bin/site-config.d.ts +17 -0
- package/types/bin/site-editor.d.ts +2 -0
- package/types/editor/api.d.ts +37 -0
- package/types/editor/copy.d.ts +153 -0
- package/types/editor/shared/rules.d.ts +33 -0
- package/types/editor/shared/site.d.ts +35 -0
- package/types/editor/shared/validate.d.ts +19 -0
- package/types/guide/check.d.ts +31 -0
- package/types/hosts/next.d.ts +12 -0
- package/types/hosts/pages.d.ts +9 -0
- package/types/hosts/shared.d.ts +21 -0
- package/types/server/blob-sha.d.ts +1 -0
- package/types/server/changes.d.ts +2 -0
- package/types/server/check-content.d.ts +16 -0
- package/types/server/config.d.ts +46 -0
- package/types/server/dispatch.d.ts +51 -0
- package/types/server/github.d.ts +27 -0
- package/types/server/handlers.d.ts +116 -0
- package/types/server/index.d.ts +75 -0
- package/types/server/local-repo.d.ts +16 -0
- package/types/server/mapped-repo.d.ts +10 -0
- package/types/server/memory-repo.d.ts +28 -0
- package/types/server/path-map.d.ts +3 -0
- package/types/server/signin/access.d.ts +68 -0
- package/types/server/signin/code.d.ts +44 -0
- package/types/server/signin/codes.d.ts +98 -0
- package/types/server/signin/refusal.d.ts +122 -0
- package/types/server/signin/session.d.ts +29 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Sign-in by emailed code: the owner asks for a code, types it in, and gets
|
|
3
|
+
// a signed session cookie (named by the site's config). Uses node:crypto
|
|
4
|
+
// (through codes.js and session.js), so the Pages entry point never imports
|
|
5
|
+
// this file. Nothing here logs or returns a code, a code hash, a session or
|
|
6
|
+
// the secret.
|
|
7
|
+
import { badRequest, failure, respond } from "../handlers.js";
|
|
8
|
+
import { configProblems, normalizeEmail, readAdminConfig } from "../config.js";
|
|
9
|
+
import { hashCode, normalizeCode, randomCode as defaultRandomCode, sameHash } from "./codes.js";
|
|
10
|
+
import {
|
|
11
|
+
NOT_ALLOWED_MESSAGE, SignInRefused, failureLine, notConfigured,
|
|
12
|
+
} from "./refusal.js";
|
|
13
|
+
import { clearedCookie, readSession, sessionCookie, signSession } from "./session.js";
|
|
14
|
+
|
|
15
|
+
export { createMemoryCodeStore, createSupabaseCodeStore } from "./codes.js";
|
|
16
|
+
|
|
17
|
+
/** @typedef {import("./codes.js").CodeStore} CodeStore */
|
|
18
|
+
/** @typedef {import("./refusal.js").SignInProvider} SignInProvider */
|
|
19
|
+
/** @typedef {import("./refusal.js").SignInContext} SignInContext */
|
|
20
|
+
/** @typedef {import("../config.js").AdminConfig} AdminConfig */
|
|
21
|
+
|
|
22
|
+
// A sign-in body is an address and a code; anything far longer is not one.
|
|
23
|
+
const MAX_SIGN_IN_CHARS = 10000;
|
|
24
|
+
|
|
25
|
+
/** The sentences the sign-in screen shows as they are; a site's guide quotes
|
|
26
|
+
* them (guide/check.js holds the two together). */
|
|
27
|
+
export const SIGN_IN_SENTENCES = Object.freeze({
|
|
28
|
+
tooMany: "Too many tries. Wait a few minutes, then try again.",
|
|
29
|
+
down: "Sign-in is not available right now. Try again in a few minutes.",
|
|
30
|
+
badCode: "That code is not right or has expired. Ask for a new one.",
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const TOO_MANY = () => failure(429, "too_many", SIGN_IN_SENTENCES.tooMany);
|
|
34
|
+
const SIGN_IN_DOWN = () => failure(502, "upstream", SIGN_IN_SENTENCES.down);
|
|
35
|
+
const BAD_CODE = () => failure(401, "bad_code", SIGN_IN_SENTENCES.badCode);
|
|
36
|
+
const UNAUTHORIZED = "Your sign-in could not be confirmed. Sign in again.";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {unknown} v
|
|
40
|
+
* @returns {v is Record<string, unknown>}
|
|
41
|
+
*/
|
|
42
|
+
const isObject = (v) =>
|
|
43
|
+
typeof v === "object" && v !== null && !Array.isArray(v);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {{ status: number, body: unknown }} result
|
|
47
|
+
* @param {string} cookie
|
|
48
|
+
* @returns {Response}
|
|
49
|
+
*/
|
|
50
|
+
function withCookie(result, cookie) {
|
|
51
|
+
const res = respond(result);
|
|
52
|
+
res.headers.append("Set-Cookie", cookie);
|
|
53
|
+
return res;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The parsed JSON body, or undefined when it is not JSON (or far too long).
|
|
58
|
+
* @param {Request} request
|
|
59
|
+
* @returns {Promise<unknown>}
|
|
60
|
+
*/
|
|
61
|
+
async function readJsonBody(request) {
|
|
62
|
+
if (Number(request.headers.get("Content-Length")) > MAX_SIGN_IN_CHARS) return undefined;
|
|
63
|
+
const text = await request.text();
|
|
64
|
+
if (text.length > MAX_SIGN_IN_CHARS) return undefined;
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(text);
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The settings as this kind reads them. The dispatcher has already checked
|
|
74
|
+
* them (problems), so this is never null when a provider method runs.
|
|
75
|
+
* @param {SignInContext} ctx
|
|
76
|
+
* @returns {AdminConfig}
|
|
77
|
+
*/
|
|
78
|
+
function settings(ctx) {
|
|
79
|
+
const read = readAdminConfig(ctx.env, { liveBranchGuard: ctx.config.liveBranchGuard });
|
|
80
|
+
if (!read) throw new Error("the sign-in settings were not checked first");
|
|
81
|
+
return read;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @typedef {object} CodeSignInOptions
|
|
86
|
+
* @property {CodeStore | null} codes null when the code store is not set up
|
|
87
|
+
* @property {(to: string, code: string) => Promise<void>} sendCode
|
|
88
|
+
* @property {() => string} [randomCode] eight digits; a secure default
|
|
89
|
+
* @property {(request: Request) => Promise<boolean>} allowRequest
|
|
90
|
+
* false when this caller has asked too often; the site reads the address
|
|
91
|
+
* itself. Asked on every request for a code (session/request) and every
|
|
92
|
+
* check of one (session/verify); false answers 429.
|
|
93
|
+
*/
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* @param {CodeSignInOptions} options
|
|
97
|
+
* @returns {SignInProvider}
|
|
98
|
+
*/
|
|
99
|
+
export function codeSignIn({ codes, sendCode, randomCode = defaultRandomCode, allowRequest }) {
|
|
100
|
+
/**
|
|
101
|
+
* @param {Request} request
|
|
102
|
+
* @param {SignInContext} ctx
|
|
103
|
+
*/
|
|
104
|
+
async function requestCode(request, ctx) {
|
|
105
|
+
const body = await readJsonBody(request);
|
|
106
|
+
if (!isObject(body) || typeof body.email !== "string") return respond(badRequest());
|
|
107
|
+
if (!(await allowRequest(request))) return respond(TOO_MANY());
|
|
108
|
+
if (!codes) return respond(notConfigured());
|
|
109
|
+
const config = settings(ctx);
|
|
110
|
+
const email = normalizeEmail(body.email);
|
|
111
|
+
if (email && config.emails.includes(email)) {
|
|
112
|
+
const code = randomCode();
|
|
113
|
+
/** @type {boolean} */
|
|
114
|
+
let issued;
|
|
115
|
+
try {
|
|
116
|
+
issued = await codes.issue(email, hashCode(email, code, config.secret));
|
|
117
|
+
} catch (err) {
|
|
118
|
+
ctx.log(failureLine("session/request issue", err));
|
|
119
|
+
return respond(SIGN_IN_DOWN());
|
|
120
|
+
}
|
|
121
|
+
if (issued) {
|
|
122
|
+
try {
|
|
123
|
+
await sendCode(email, code);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
// No code will arrive, so say so rather than answer ok.
|
|
126
|
+
ctx.log(failureLine("session/request send", err));
|
|
127
|
+
return respond(SIGN_IN_DOWN());
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Sent, not on the list, or the cap reached: the same answer.
|
|
132
|
+
return respond({ status: 200, body: { ok: true } });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* @param {Request} request
|
|
137
|
+
* @param {SignInContext} ctx
|
|
138
|
+
*/
|
|
139
|
+
async function verifyCode(request, ctx) {
|
|
140
|
+
const body = await readJsonBody(request);
|
|
141
|
+
if (body === undefined) return respond(badRequest());
|
|
142
|
+
// Asked before the store counts a guess, so that a caller refused here
|
|
143
|
+
// cannot spend a code's tries.
|
|
144
|
+
if (!(await allowRequest(request))) return respond(TOO_MANY());
|
|
145
|
+
if (!codes) return respond(notConfigured());
|
|
146
|
+
const config = settings(ctx);
|
|
147
|
+
const email = isObject(body) ? normalizeEmail(body.email) : null;
|
|
148
|
+
const code = isObject(body) ? normalizeCode(body.code) : null;
|
|
149
|
+
// An unlisted address or an unusable code never reaches the store.
|
|
150
|
+
if (!email || !code || !config.emails.includes(email)) return respond(BAD_CODE());
|
|
151
|
+
try {
|
|
152
|
+
// attempt() counts this guess; consume() does not, so it runs only on a match.
|
|
153
|
+
const stored = await codes.attempt(email);
|
|
154
|
+
if (stored === null) return respond(BAD_CODE());
|
|
155
|
+
const hash = hashCode(email, code, config.secret);
|
|
156
|
+
if (!sameHash(hash, stored)) return respond(BAD_CODE());
|
|
157
|
+
if (!(await codes.consume(email, hash))) return respond(BAD_CODE());
|
|
158
|
+
} catch (err) {
|
|
159
|
+
ctx.log(failureLine("session/verify", err));
|
|
160
|
+
return respond(SIGN_IN_DOWN());
|
|
161
|
+
}
|
|
162
|
+
const session = signSession(email, config.secret, ctx.now());
|
|
163
|
+
return withCookie({ status: 200, body: { ok: true, user: email } },
|
|
164
|
+
sessionCookie(ctx.config.cookie, session));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
kind: "code",
|
|
169
|
+
problems: (env, config) => configProblems(env, { liveBranchGuard: config.liveBranchGuard }),
|
|
170
|
+
github: (env) => ({
|
|
171
|
+
token: /** @type {string} */ (env.GITHUB_TOKEN),
|
|
172
|
+
repo: /** @type {string} */ (env.GITHUB_REPO),
|
|
173
|
+
branch: /** @type {string} */ (env.GITHUB_BRANCH),
|
|
174
|
+
}),
|
|
175
|
+
async route(request, name, ctx) {
|
|
176
|
+
if (request.method !== "POST") return null;
|
|
177
|
+
if (name === "session/request") return requestCode(request, ctx);
|
|
178
|
+
if (name === "session/verify") return verifyCode(request, ctx);
|
|
179
|
+
if (name === "session/signout") {
|
|
180
|
+
return withCookie({ status: 200, body: { ok: true } }, clearedCookie(ctx.config.cookie));
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
},
|
|
184
|
+
async user(request, ctx) {
|
|
185
|
+
const config = settings(ctx);
|
|
186
|
+
const user = readSession(request.headers.get("Cookie"), config.secret, ctx.now(), ctx.config.cookie);
|
|
187
|
+
if (user === null) throw new SignInRefused(401, "unauthorized", UNAUTHORIZED);
|
|
188
|
+
if (!config.emails.includes(user)) throw new SignInRefused(403, "forbidden", NOT_ALLOWED_MESSAGE);
|
|
189
|
+
return user;
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createHmac, randomInt, timingSafeEqual } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
// These numbers are the same ones the SQL in code-store.sql (beside this
|
|
5
|
+
// file) hard-codes (10 minutes, 5 attempts, 5 codes an hour, 10 a day).
|
|
6
|
+
// Change them together.
|
|
7
|
+
export const CODE_DIGITS = 8;
|
|
8
|
+
export const CODE_TTL_MS = 600_000;
|
|
9
|
+
export const MAX_ATTEMPTS = 5;
|
|
10
|
+
export const MAX_CODES_PER_HOUR = 5;
|
|
11
|
+
export const MAX_CODES_PER_DAY = 10;
|
|
12
|
+
|
|
13
|
+
const HOUR_MS = 3_600_000;
|
|
14
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
15
|
+
const KEEP_MS = 2 * DAY_MS;
|
|
16
|
+
|
|
17
|
+
/** @returns {string} */
|
|
18
|
+
export function randomCode() {
|
|
19
|
+
return String(randomInt(0, 10 ** CODE_DIGITS)).padStart(CODE_DIGITS, "0");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The code with spaces and hyphens removed, or null unless it is 8 digits.
|
|
24
|
+
* @param {unknown} input
|
|
25
|
+
* @returns {string | null}
|
|
26
|
+
*/
|
|
27
|
+
export function normalizeCode(input) {
|
|
28
|
+
if (typeof input !== "string") return null;
|
|
29
|
+
const code = input.replace(/[\s-]/g, "");
|
|
30
|
+
return /^\d{8}$/.test(code) ? code : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {string} email
|
|
35
|
+
* @param {string} code
|
|
36
|
+
* @param {string} secret
|
|
37
|
+
* @returns {string}
|
|
38
|
+
*/
|
|
39
|
+
export function hashCode(email, code, secret) {
|
|
40
|
+
return createHmac("sha256", secret).update(`${email}\n${code}`).digest("hex");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Constant-time comparison; unequal lengths are simply false.
|
|
45
|
+
* @param {string} a
|
|
46
|
+
* @param {string} b
|
|
47
|
+
* @returns {boolean}
|
|
48
|
+
*/
|
|
49
|
+
export function sameHash(a, b) {
|
|
50
|
+
const x = Buffer.from(a);
|
|
51
|
+
const y = Buffer.from(b);
|
|
52
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @typedef {object} CodeStore
|
|
57
|
+
* @property {(email: string, codeHash: string) => Promise<boolean>} issue
|
|
58
|
+
* False when an hourly or daily cap is reached.
|
|
59
|
+
* @property {(email: string) => Promise<string | null>} attempt
|
|
60
|
+
* Counts the attempt; the hash to compare, or null.
|
|
61
|
+
* @property {(email: string, codeHash: string) => Promise<boolean>} consume
|
|
62
|
+
* True only when this call used that live code.
|
|
63
|
+
*/
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @typedef {object} Row
|
|
67
|
+
* @property {string} email
|
|
68
|
+
* @property {string} hash
|
|
69
|
+
* @property {number} createdAt
|
|
70
|
+
* @property {number} expiresAt
|
|
71
|
+
* @property {number} attempts
|
|
72
|
+
* @property {boolean} used
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Any object with an `rpc(name, args)` method returning `{ data, error }`,
|
|
77
|
+
* such as a Supabase client.
|
|
78
|
+
* @typedef {object} RpcClient
|
|
79
|
+
* @property {(name: string, args: Record<string, string>) =>
|
|
80
|
+
* PromiseLike<{ data: unknown, error: { message: string } | null }>} rpc
|
|
81
|
+
*/
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* In-memory store with the same rules as the SQL functions.
|
|
85
|
+
* @param {() => number} now
|
|
86
|
+
* @returns {CodeStore}
|
|
87
|
+
*/
|
|
88
|
+
export function createMemoryCodeStore(now) {
|
|
89
|
+
/** @type {Row[]} */
|
|
90
|
+
let rows = [];
|
|
91
|
+
return {
|
|
92
|
+
async issue(email, codeHash) {
|
|
93
|
+
const t = now();
|
|
94
|
+
rows = rows.filter((r) => r.createdAt >= t - KEEP_MS);
|
|
95
|
+
const mine = rows.filter((r) => r.email === email);
|
|
96
|
+
const inHour = mine.filter((r) => r.createdAt > t - HOUR_MS).length;
|
|
97
|
+
const inDay = mine.filter((r) => r.createdAt > t - DAY_MS).length;
|
|
98
|
+
if (inHour >= MAX_CODES_PER_HOUR || inDay >= MAX_CODES_PER_DAY) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
for (const r of mine) r.used = true;
|
|
102
|
+
rows.push({
|
|
103
|
+
email,
|
|
104
|
+
hash: codeHash,
|
|
105
|
+
createdAt: t,
|
|
106
|
+
expiresAt: t + CODE_TTL_MS,
|
|
107
|
+
attempts: 0,
|
|
108
|
+
used: false,
|
|
109
|
+
});
|
|
110
|
+
return true;
|
|
111
|
+
},
|
|
112
|
+
async attempt(email) {
|
|
113
|
+
const t = now();
|
|
114
|
+
const live = rows
|
|
115
|
+
.filter((r) => r.email === email && !r.used && r.expiresAt > t)
|
|
116
|
+
.sort((a, b) => b.createdAt - a.createdAt)[0];
|
|
117
|
+
if (!live) return null;
|
|
118
|
+
live.attempts += 1;
|
|
119
|
+
return live.attempts <= MAX_ATTEMPTS ? live.hash : null;
|
|
120
|
+
},
|
|
121
|
+
async consume(email, codeHash) {
|
|
122
|
+
const t = now();
|
|
123
|
+
const latest = rows
|
|
124
|
+
.filter((r) => r.email === email && !r.used && r.expiresAt > t)
|
|
125
|
+
.sort((a, b) => b.createdAt - a.createdAt)[0];
|
|
126
|
+
if (!latest || latest.hash !== codeHash) return false;
|
|
127
|
+
latest.used = true;
|
|
128
|
+
return true;
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Store backed by the three SQL functions; errors never include the arguments.
|
|
135
|
+
* @param {RpcClient} client
|
|
136
|
+
* @returns {CodeStore}
|
|
137
|
+
*/
|
|
138
|
+
export function createSupabaseCodeStore(client) {
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} name
|
|
141
|
+
* @param {Record<string, string>} args
|
|
142
|
+
* @returns {Promise<unknown>}
|
|
143
|
+
*/
|
|
144
|
+
async function call(name, args) {
|
|
145
|
+
const { data, error } = await client.rpc(name, args);
|
|
146
|
+
if (error) throw new Error(`${name} failed: ${error.message}`);
|
|
147
|
+
return /** @type {unknown} */ (data);
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
async issue(email, codeHash) {
|
|
151
|
+
return (
|
|
152
|
+
(await call("admin_login_code_issue", {
|
|
153
|
+
p_email: email,
|
|
154
|
+
p_code_hash: codeHash,
|
|
155
|
+
})) === true
|
|
156
|
+
);
|
|
157
|
+
},
|
|
158
|
+
async attempt(email) {
|
|
159
|
+
const hash = await call("admin_login_code_attempt", { p_email: email });
|
|
160
|
+
return typeof hash === "string" ? hash : null;
|
|
161
|
+
},
|
|
162
|
+
async consume(email, codeHash) {
|
|
163
|
+
return (
|
|
164
|
+
(await call("admin_login_code_consume", {
|
|
165
|
+
p_email: email,
|
|
166
|
+
p_code_hash: codeHash,
|
|
167
|
+
})) === true
|
|
168
|
+
);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The sign-in contract: what dispatch.js knows about a sign-in, whichever
|
|
3
|
+
// kind it is. Both providers (code.js, access.js) are built to this, and
|
|
4
|
+
// this file uses only what Workers and Node both have, because the Pages
|
|
5
|
+
// entry point reaches it.
|
|
6
|
+
import { failure } from "../handlers.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A sign-in provider.
|
|
10
|
+
*
|
|
11
|
+
* @typedef {object} SignInProvider
|
|
12
|
+
* @property {"code" | "access"} kind matches the site config's `signIn`
|
|
13
|
+
* @property {(env: Env, config: SiteConfig) => string[]} problems
|
|
14
|
+
* The NAMES of the settings that are missing or malformed (plus a guard's
|
|
15
|
+
* own words when it refuses), never a value. Empty when the settings are
|
|
16
|
+
* usable. The dispatcher answers not_configured and logs these otherwise.
|
|
17
|
+
* @property {(env: Env) => GithubSettings} github
|
|
18
|
+
* GITHUB_TOKEN, GITHUB_REPO and GITHUB_BRANCH as this kind reads them.
|
|
19
|
+
* Called only when problems is empty.
|
|
20
|
+
* @property {(request: Request, name: string, ctx: SignInContext) => Promise<Response | null>} route
|
|
21
|
+
* The kind's own routes, which need no sign-in (for example asking for a
|
|
22
|
+
* code). A Response answers the request; null passes it on.
|
|
23
|
+
* @property {(request: Request, ctx: SignInContext) => Promise<string>} user
|
|
24
|
+
* The signed-in address, checked against the kind's own list of addresses.
|
|
25
|
+
* Throws SignInRefused for a caller who is not signed in or not listed;
|
|
26
|
+
* anything else it throws is an error like any other (500, or 502 for
|
|
27
|
+
* code "upstream").
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** @typedef {Record<string, string | undefined>} Env */
|
|
31
|
+
/** @typedef {Record<string, any>} SiteConfig the site's whole config file */
|
|
32
|
+
/** @typedef {{ token: string, repo: string, branch: string }} GithubSettings */
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* What the dispatcher hands a provider with each request.
|
|
36
|
+
* @typedef {object} SignInContext
|
|
37
|
+
* @property {Env} env the settings
|
|
38
|
+
* @property {SiteConfig} config the site's config
|
|
39
|
+
* @property {() => number} now milliseconds
|
|
40
|
+
* @property {(line: string) => void} log one line; never a secret
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/** A caller refused by the sign-in: the status, code and sentence the owner sees. */
|
|
44
|
+
export class SignInRefused extends Error {
|
|
45
|
+
/**
|
|
46
|
+
* @param {number} status
|
|
47
|
+
* @param {string} code
|
|
48
|
+
* @param {string} message
|
|
49
|
+
*/
|
|
50
|
+
constructor(status, code, message) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "SignInRefused";
|
|
53
|
+
this.status = status;
|
|
54
|
+
this.code = code;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The same sentence for both kinds. */
|
|
59
|
+
export const NOT_ALLOWED_MESSAGE = "This account is not allowed to edit the site.";
|
|
60
|
+
|
|
61
|
+
/** The answer when the editor's settings are missing; the dispatcher and the
|
|
62
|
+
* code sign-in (when it has no code store) give the same one. */
|
|
63
|
+
export const notConfigured = () =>
|
|
64
|
+
failure(503, "not_configured",
|
|
65
|
+
"The editor is not set up yet. Ask your web developer to finish the setup.");
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* One log line: the step and the error's message, nothing else.
|
|
69
|
+
* @param {string} step
|
|
70
|
+
* @param {unknown} err
|
|
71
|
+
* @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
export function failureLine(step, err) {
|
|
74
|
+
const message = err instanceof Error ? err.message : "non-error thrown";
|
|
75
|
+
return `admin api: ${step} failed: ${message}`;
|
|
76
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
// The cookie's name is the site's (its config's `cookie`), passed in.
|
|
5
|
+
export const SESSION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {string} secret
|
|
9
|
+
* @param {string} data
|
|
10
|
+
* @returns {string}
|
|
11
|
+
*/
|
|
12
|
+
function sign(secret, data) {
|
|
13
|
+
return createHmac("sha256", secret).update(data).digest("base64url");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `v1.<payload>.<signature>`; the payload carries the address and expiry.
|
|
18
|
+
* @param {string} email
|
|
19
|
+
* @param {string} secret
|
|
20
|
+
* @param {number} nowMs
|
|
21
|
+
* @returns {string}
|
|
22
|
+
*/
|
|
23
|
+
export function signSession(email, secret, nowMs) {
|
|
24
|
+
const payload = Buffer.from(
|
|
25
|
+
JSON.stringify({ e: email, x: nowMs + SESSION_MS }),
|
|
26
|
+
).toString("base64url");
|
|
27
|
+
return `v1.${payload}.${sign(secret, `v1.${payload}`)}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The signed-in address, or null for anything missing, forged, expired or malformed.
|
|
32
|
+
* @param {string | null} cookieHeader
|
|
33
|
+
* @param {string} secret
|
|
34
|
+
* @param {number} nowMs
|
|
35
|
+
* @param {string} name the session cookie's name
|
|
36
|
+
* @returns {string | null}
|
|
37
|
+
*/
|
|
38
|
+
export function readSession(cookieHeader, secret, nowMs, name) {
|
|
39
|
+
try {
|
|
40
|
+
if (!cookieHeader) return null;
|
|
41
|
+
/** @type {string | null} */
|
|
42
|
+
let value = null;
|
|
43
|
+
for (const part of cookieHeader.split(";")) {
|
|
44
|
+
const eq = part.indexOf("=");
|
|
45
|
+
if (eq > 0 && part.slice(0, eq).trim() === name) {
|
|
46
|
+
value = part.slice(eq + 1).trim();
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (!value) return null;
|
|
51
|
+
|
|
52
|
+
const parts = value.split(".");
|
|
53
|
+
if (parts.length !== 3 || parts[0] !== "v1") return null;
|
|
54
|
+
const [, payload, signature] = parts;
|
|
55
|
+
|
|
56
|
+
const expected = Buffer.from(sign(secret, `v1.${payload}`));
|
|
57
|
+
const given = Buffer.from(signature);
|
|
58
|
+
if (given.length !== expected.length) return null;
|
|
59
|
+
if (!timingSafeEqual(given, expected)) return null;
|
|
60
|
+
|
|
61
|
+
/** @type {unknown} */
|
|
62
|
+
const data = JSON.parse(
|
|
63
|
+
Buffer.from(payload, "base64url").toString("utf8"),
|
|
64
|
+
);
|
|
65
|
+
if (typeof data !== "object" || data === null) return null;
|
|
66
|
+
const { e, x } = /** @type {{ e?: unknown, x?: unknown }} */ (data);
|
|
67
|
+
if (typeof e !== "string" || e === "" || typeof x !== "number") return null;
|
|
68
|
+
if (!Number.isFinite(x) || nowMs >= x) return null;
|
|
69
|
+
return e;
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @param {string} name
|
|
77
|
+
* @param {string} value
|
|
78
|
+
* @returns {string}
|
|
79
|
+
*/
|
|
80
|
+
export function sessionCookie(name, value) {
|
|
81
|
+
return `${name}=${value}; Path=/; Max-Age=${SESSION_MS / 1000}; HttpOnly; Secure; SameSite=Strict`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {string} name
|
|
86
|
+
* @returns {string}
|
|
87
|
+
*/
|
|
88
|
+
export function clearedCookie(name) {
|
|
89
|
+
return `${name}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Strict`;
|
|
90
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"image": {"base": "/assets/img/hero", "ext": "webp", "widths": [700, 1100, 1800], "width": 1800, "height": 1202, "alt": "A lawn"},
|
|
4
|
+
"files": ["assets/img/hero-700.webp", "assets/img/hero-1100.webp", "assets/img/hero-1800.webp"]
|
|
5
|
+
},
|
|
6
|
+
{
|
|
7
|
+
"image": {"base": "/assets/img/uploads/oak-k3x9qa", "ext": "jpg", "widths": [700], "width": 700, "height": 466, "alt": "An oak"},
|
|
8
|
+
"files": ["assets/img/uploads/oak-k3x9qa-700.jpg"]
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"image": {"base": "/assets/img/band", "ext": "webp", "widths": [700.0, 1800.0], "width": 1800.0, "height": 900, "alt": ""},
|
|
12
|
+
"files": ["assets/img/band-700.webp", "assets/img/band-1800.webp"]
|
|
13
|
+
}
|
|
14
|
+
]
|