@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,364 @@
1
+ // Editor API handlers. Each takes a Repo and plain values and returns
2
+ // {status, body}; dispatch.js turns that into a Response with respond().
3
+ // They never throw for bad input; errors from the Repo (code "upstream")
4
+ // propagate to dispatch.js, which answers them. Runs in Workers and Node.
5
+ import {
6
+ DOC_PATH_RE, MAX_CUSTOM_PAGES, SHA_RE, UPLOAD_NAME_RE, isUsableSlug,
7
+ } from "../editor/shared/rules.js";
8
+ import {
9
+ collectImages, docTypeForPath, imageFiles, validateDoc,
10
+ } from "../editor/shared/validate.js";
11
+ import { blobSha } from "./blob-sha.js";
12
+ import { RepoMoved } from "./github.js";
13
+
14
+ export const SCHEMA_PATH = "content/schema.json";
15
+ const MAX_DOCS = 20;
16
+ const MAX_DELETES = 20;
17
+ // Photo files per publish, unless the site's config (maxPublishFiles) says
18
+ // otherwise: up to three per photo, so a slideshow of 80 photos at three
19
+ // widths, plus a lead photo, with room.
20
+ export const MAX_IMAGES = 250;
21
+ const MAX_MESSAGE = 200;
22
+ const PUBLISH_KEYS = ["docs", "deletes", "images"];
23
+ // Documents that exist from the start: they may be edited, never created or removed.
24
+ const FIXED_DOC_RE = /^content\/(site|pages\/[a-z0-9-]+)\.json$/;
25
+ const CUSTOM_PREFIX = "content/custom/";
26
+ const PAGE_RE = /^content\/pages\/([a-z0-9-]+)\.json$/;
27
+ const CUSTOM_RE = /^content\/custom\/([a-z0-9-]+)\.json$/;
28
+ // Sentences for a new simple page the site will not take; the editor shows
29
+ // them as its own (editor/copy.js has the same words).
30
+ const BAD_ADDRESS = "That page address can't be used. Delete this page and add it again with a different title.";
31
+ const TOO_MANY_PAGES = `The site can hold ${MAX_CUSTOM_PAGES} extra pages. Delete one before adding another.`;
32
+ const UPLOAD_PREFIX = "assets/img/uploads/";
33
+ export const MAX_UPLOAD_BYTES = 2000000;
34
+ /** The longest base64 text of an upload: every 3 bytes, or part of 3, take 4 characters. */
35
+ export const MAX_UPLOAD_CHARS = 4 * Math.ceil(MAX_UPLOAD_BYTES / 3);
36
+ // Only the 64 characters, then at most two "=". With the length a multiple
37
+ // of 4 this is canonical base64 with no whitespace. \w is A-Z, a-z, 0-9 and
38
+ // "_", so "_" is refused separately. Written this way the engine scans the
39
+ // class natively: on real photo data at 2,000,000 bytes it takes about
40
+ // 1.3 ms, where the spelled-out class [A-Za-z0-9+/] takes about 13 ms
41
+ // (Node 24, Apple Silicon; a body of one repeated letter hid the difference).
42
+ const BASE64_RE = /^[\w+/]*={0,2}$/;
43
+
44
+ const HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
45
+
46
+ /** The one way an API response is built, so none lacks the headers. */
47
+ export function respond({ status, body }) {
48
+ return Response.json(body, { status, headers: HEADERS });
49
+ }
50
+
51
+ export function failure(status, error, message, extra = {}) {
52
+ return { status, body: { error, message, ...extra } };
53
+ }
54
+
55
+ /** The cross-site request check: a request that can change something must
56
+ * name this site as its Origin. Returns null to go ahead, or the failure. */
57
+ export function crossSiteFailure(request) {
58
+ if (request.method === "GET" || request.method === "HEAD") return null;
59
+ const origin = request.headers.get("Origin");
60
+ if (!origin || origin !== new URL(request.url).origin) {
61
+ return failure(403, "forbidden", "This request did not come from the editor.");
62
+ }
63
+ return null;
64
+ }
65
+
66
+ const RELOAD = "Reload the editor and try again.";
67
+ export const badRequest = (message = `The editor sent something the site cannot use. ${RELOAD}`) =>
68
+ failure(400, "bad_request", message);
69
+ export const photoTooLarge = () => failure(413, "too_large",
70
+ "This photo is too large to save. Pick a smaller photo.");
71
+ const photoUnusable = () => badRequest("That photo could not be saved. Pick it again.");
72
+ const MISSING_PHOTO = "This photo did not finish uploading. Pick it again, then publish.";
73
+ const unreadable = (path) => failure(500, "server_error",
74
+ `The saved file ${path} could not be read. Ask your web developer to look at it.`);
75
+
76
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
77
+ const isSha = (v) => typeof v === "string" && SHA_RE.test(v);
78
+ const isDocPath = (v) => typeof v === "string" && DOC_PATH_RE.test(v);
79
+ const isUploadPath = (v) => typeof v === "string" && v.startsWith(UPLOAD_PREFIX)
80
+ && UPLOAD_NAME_RE.test(v.slice(UPLOAD_PREFIX.length));
81
+ const hasExactly = (obj, keys) => {
82
+ const own = Object.keys(obj);
83
+ return own.length === keys.length && keys.every((k) => Object.hasOwn(obj, k));
84
+ };
85
+
86
+ /** The parsed JSON of a blob, or undefined when it is not JSON. */
87
+ async function readJson(repo, sha) {
88
+ const text = await repo.readText(sha);
89
+ try {
90
+ return JSON.parse(text);
91
+ } catch {
92
+ return undefined;
93
+ }
94
+ }
95
+
96
+ export async function getState(repo, user) {
97
+ const head = await repo.head();
98
+ const docs = {};
99
+ for (const [path, sha] of head.files) {
100
+ if (path.startsWith("content/") && path.endsWith(".json")) docs[path] = sha;
101
+ }
102
+ return { status: 200, body: { head: head.commit, docs, user } };
103
+ }
104
+
105
+ export async function getDoc(repo, path) {
106
+ if (path !== SCHEMA_PATH && !isDocPath(path)) return badRequest();
107
+ const head = await repo.head();
108
+ const sha = head.files.get(path);
109
+ if (sha === undefined) {
110
+ return failure(404, "not_found", "That page could not be found. It may have been removed.");
111
+ }
112
+ const doc = await readJson(repo, sha);
113
+ if (doc === undefined) return unreadable(path);
114
+ return { status: 200, body: { path, sha, doc } };
115
+ }
116
+
117
+ export async function getStatus(repo, mine, deployed) {
118
+ if (!isSha(mine) || !isSha(deployed)) return badRequest();
119
+ return { status: 200, body: { contains: await repo.contains(mine, deployed) } };
120
+ }
121
+
122
+ /** True when the file starts the way its extension says: a WebP with "RIFF"
123
+ * at 0 and "WEBP" at 8, a JPEG with FF D8 FF. Decodes only the first 16
124
+ * characters (12 bytes). */
125
+ function signatureMatches(ext, base64) {
126
+ const start = atob(base64.slice(0, 16));
127
+ if (ext === "webp") return start.startsWith("RIFF") && start.slice(8, 12) === "WEBP";
128
+ return start.startsWith("\xff\xd8\xff");
129
+ }
130
+
131
+ /** Stores one photo file sent as base64 text. Touches the whole text only
132
+ * through BASE64_RE; size comes from the length and the "=" padding. One
133
+ * repo call, createBlob. */
134
+ export async function postUpload(repo, name, base64) {
135
+ if (typeof name !== "string" || !UPLOAD_NAME_RE.test(name)) return badRequest();
136
+ if (typeof base64 !== "string" || base64 === "") return photoUnusable();
137
+ if (base64.length > MAX_UPLOAD_CHARS) return photoTooLarge();
138
+ if (base64.length % 4 !== 0 || !BASE64_RE.test(base64) || base64.includes("_")) {
139
+ return photoUnusable();
140
+ }
141
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
142
+ if ((base64.length / 4) * 3 - padding > MAX_UPLOAD_BYTES) return photoTooLarge();
143
+ if (!signatureMatches(name.slice(name.lastIndexOf(".") + 1), base64)) return photoUnusable();
144
+ const sha = await repo.createBlob(base64);
145
+ return { status: 200, body: { path: UPLOAD_PREFIX + name, sha } };
146
+ }
147
+
148
+ const shortName = (path) => DOC_PATH_RE.exec(path)[1].replace(/^(pages|custom)\//, "");
149
+
150
+ /** "Edit site content: <names> (by <email>)": one line of printable ASCII,
151
+ * at most 200 characters. */
152
+ export function commitMessage(user, paths) {
153
+ const names = [...new Set(paths.map(shortName))].sort();
154
+ const full = `Edit site content: ${names.join(", ")} (by ${user})`;
155
+ const ascii = Array.from(full, (ch) => (ch >= " " && ch <= "~" ? ch : "?")).join("");
156
+ return ascii.length <= MAX_MESSAGE ? ascii : `${ascii.slice(0, MAX_MESSAGE - 3)}...`;
157
+ }
158
+
159
+ /** Step 1: the request's shape and limits. Returns {docs, deletes, images}
160
+ * or a failure. */
161
+ function readPublishRequest(body, maxImages) {
162
+ if (!isObject(body) || !Object.keys(body).every((k) => PUBLISH_KEYS.includes(k))) {
163
+ return { failure: badRequest() };
164
+ }
165
+ const list = (key) => (Object.hasOwn(body, key) ? body[key] : []);
166
+ const [docs, deletes, images] = PUBLISH_KEYS.map(list);
167
+ if (!Array.isArray(docs) || !Array.isArray(deletes) || !Array.isArray(images)) {
168
+ return { failure: badRequest() };
169
+ }
170
+ if (docs.length > MAX_DOCS || deletes.length > MAX_DELETES) {
171
+ return { failure: badRequest(`Publish at most ${MAX_DOCS} pages at a time.`) };
172
+ }
173
+ if (images.length > maxImages) {
174
+ return { failure: badRequest(`Publish at most ${maxImages} photos at a time.`) };
175
+ }
176
+ if (docs.length === 0 && deletes.length === 0) {
177
+ return { failure: badRequest("There is nothing to publish.") };
178
+ }
179
+ for (const d of docs) {
180
+ if (!isObject(d) || !hasExactly(d, ["path", "sha", "doc"]) || !isDocPath(d.path)
181
+ || !(d.sha === null || isSha(d.sha)) || !isObject(d.doc)) {
182
+ return { failure: badRequest() };
183
+ }
184
+ }
185
+ for (const d of deletes) {
186
+ if (!isObject(d) || !hasExactly(d, ["path", "sha"]) || !isDocPath(d.path) || !isSha(d.sha)) {
187
+ return { failure: badRequest() };
188
+ }
189
+ }
190
+ for (const i of images) {
191
+ if (!isObject(i) || !hasExactly(i, ["path", "sha"]) || !isUploadPath(i.path) || !isSha(i.sha)) {
192
+ return { failure: badRequest() };
193
+ }
194
+ }
195
+ const paths = [...docs, ...deletes].map((e) => e.path);
196
+ if (new Set(paths).size !== paths.length) return { failure: badRequest() };
197
+ if (new Set(images.map((i) => i.path)).size !== images.length) return { failure: badRequest() };
198
+ return { docs, deletes, images };
199
+ }
200
+
201
+ /** Each image in doc with the validator's field path to it ("photos[1].photo").
202
+ * collectImages decides what is an image; this walk only names them. */
203
+ function imagesWithFields(schema, docType, doc) {
204
+ const images = new Set(collectImages(schema, docType, doc));
205
+ const found = [];
206
+ const walk = (value, path) => {
207
+ if (images.has(value)) found.push({ field: path, image: value });
208
+ else if (Array.isArray(value)) value.forEach((v, i) => walk(v, `${path}[${i}]`));
209
+ else if (isObject(value)) {
210
+ for (const [k, v] of Object.entries(value)) walk(v, path ? `${path}.${k}` : k);
211
+ }
212
+ };
213
+ walk(doc, "");
214
+ return found;
215
+ }
216
+
217
+ /** Steps 2 to 7 against the current head. Throws RepoMoved when the branch
218
+ * moves before the commit lands. */
219
+ async function publishAtHead(repo, user, { docs, deletes, images }) {
220
+ const head = await repo.head();
221
+
222
+ // Path rules.
223
+ for (const d of docs) {
224
+ if (FIXED_DOC_RE.test(d.path) && (!head.files.has(d.path) || d.sha === null)) {
225
+ return badRequest(`This page could not be matched to the site as it is now. ${RELOAD}`);
226
+ }
227
+ }
228
+ for (const d of deletes) {
229
+ if (!d.path.startsWith(CUSTOM_PREFIX)) {
230
+ return badRequest("Only pages you added yourself can be removed.");
231
+ }
232
+ }
233
+ // A new simple page needs an address no page has or may have. The fixed
234
+ // documents were refused above, so a new one here is under custom/.
235
+ const pageSlugs = new Set();
236
+ for (const path of head.files.keys()) {
237
+ const m = PAGE_RE.exec(path);
238
+ if (m) pageSlugs.add(m[1]);
239
+ }
240
+ for (const d of docs) {
241
+ if (d.sha === null && !isUsableSlug(CUSTOM_RE.exec(d.path)?.[1], pageSlugs)) {
242
+ return badRequest(BAD_ADDRESS);
243
+ }
244
+ }
245
+ let schema;
246
+ if (docs.length > 0) {
247
+ const schemaSha = head.files.get(SCHEMA_PATH);
248
+ schema = schemaSha === undefined ? undefined : await readJson(repo, schemaSha);
249
+ if (!isObject(schema) || !isObject(schema.documents)) return unreadable(SCHEMA_PATH);
250
+ for (const d of docs) {
251
+ if (!Object.hasOwn(schema.documents, docTypeForPath(d.path))) {
252
+ return badRequest("This kind of page cannot be published yet.");
253
+ }
254
+ }
255
+ }
256
+
257
+ // What each document would be once published. A document whose blob is
258
+ // already the one at head, or a delete whose file is already gone, has
259
+ // been published (by this same request, when an answer was lost and it was
260
+ // sent again): it takes no part in the stale check and needs no change.
261
+ const prepared = [];
262
+ for (const d of docs) {
263
+ const text = JSON.stringify(d.doc, null, 2) + "\n";
264
+ prepared.push({ ...d, text, blob: await blobSha(text) });
265
+ }
266
+ const pending = prepared.filter((d) => d.blob !== head.files.get(d.path));
267
+ const pendingDeletes = deletes.filter((d) => head.files.has(d.path));
268
+
269
+ // Stale check: every file still to change must be the blob the editor loaded.
270
+ const stale = [...pending, ...pendingDeletes]
271
+ .filter((e) => (head.files.get(e.path) ?? null) !== e.sha)
272
+ .map((e) => e.path);
273
+ if (stale.length > 0) {
274
+ return failure(409, "stale", stale.length === 1
275
+ ? "Someone else changed this page since you opened it."
276
+ : "Someone else changed these pages since you opened them.", { paths: stale });
277
+ }
278
+
279
+ // The cap, counted after this request: a creation still to happen passed
280
+ // the stale check, so its path is not at head; a delete counts only when
281
+ // its page is there. Only a request that adds a page can be refused.
282
+ const created = pending.filter((d) => d.sha === null).length;
283
+ if (created > 0) {
284
+ const atHead = [...head.files.keys()].filter((path) => CUSTOM_RE.test(path)).length;
285
+ if (atHead + created - pendingDeletes.length > MAX_CUSTOM_PAGES) return badRequest(TOO_MANY_PAGES);
286
+ }
287
+
288
+ // Validation.
289
+ const problems = [];
290
+ for (const d of docs) {
291
+ for (const p of validateDoc(schema, docTypeForPath(d.path), d.doc)) {
292
+ problems.push({ path: d.path, field: p.field, code: p.code, message: p.message });
293
+ }
294
+ }
295
+ if (problems.length > 0) {
296
+ return failure(422, "invalid", "Some of the content needs fixing before it can be published.",
297
+ { problems });
298
+ }
299
+
300
+ // Photos. Every photo sent must be one a document here names, and new at
301
+ // its path; one already there with the same blob was published by this
302
+ // same request and needs no change. Every file a document names must be
303
+ // at head or arrive with this request.
304
+ const sent = new Set(images.map((i) => i.path));
305
+ const named = new Set();
306
+ const missing = [];
307
+ for (const d of docs) {
308
+ for (const { field, image } of imagesWithFields(schema, docTypeForPath(d.path), d.doc)) {
309
+ const files = imageFiles(image);
310
+ for (const f of files) named.add(f);
311
+ if (files.some((f) => !head.files.has(f) && !sent.has(f))) {
312
+ missing.push({ path: d.path, field, code: "missing_image", message: MISSING_PHOTO });
313
+ }
314
+ }
315
+ }
316
+ if (!images.every((i) => named.has(i.path))) return badRequest();
317
+ if (images.some((i) => head.files.has(i.path) && head.files.get(i.path) !== i.sha)) {
318
+ return badRequest(
319
+ "A photo with the same name is already on the site. Pick the photo again, then publish.");
320
+ }
321
+ if (missing.length > 0) {
322
+ return failure(422, "invalid", "Some of the content needs fixing before it can be published.",
323
+ { problems: missing });
324
+ }
325
+ const pendingImages = images.filter((i) => !head.files.has(i.path));
326
+
327
+ // Every document's blob at the new head, so the editor can publish again
328
+ // without reading the page back. A deleted path is not listed.
329
+ const shas = Object.fromEntries(prepared.map((d) => [d.path, d.blob]));
330
+ const changes = [
331
+ ...pending.map((d) => ({ path: d.path, text: d.text })),
332
+ ...pendingDeletes.map((d) => ({ path: d.path, remove: true })),
333
+ ...pendingImages.map((i) => ({ path: i.path, sha: i.sha })),
334
+ ];
335
+ if (changes.length === 0) {
336
+ return { status: 200, body: { commit: head.commit, unchanged: true, docs: shas } };
337
+ }
338
+
339
+ // The message names pages: those that change, or when only photos do,
340
+ // the pages sent with them.
341
+ const changedPages = [...pending, ...pendingDeletes].map((e) => e.path);
342
+ const commit = await repo.commit({
343
+ parent: head.commit,
344
+ changes,
345
+ message: commitMessage(user, changedPages.length > 0 ? changedPages : docs.map((d) => d.path)),
346
+ });
347
+ return { status: 200, body: { commit, docs: shas } };
348
+ }
349
+
350
+ export async function postPublish(repo, user, body, { maxPublishFiles = MAX_IMAGES } = {}) {
351
+ const request = readPublishRequest(body, maxPublishFiles);
352
+ if (request.failure) return request.failure;
353
+ for (let attempt = 1; ; attempt++) {
354
+ try {
355
+ return await publishAtHead(repo, user, request);
356
+ } catch (err) {
357
+ if (!(err instanceof RepoMoved)) throw err;
358
+ if (attempt === 2) {
359
+ return failure(409, "busy",
360
+ "The site was being changed at the same moment. Please publish again.");
361
+ }
362
+ }
363
+ }
364
+ }
@@ -0,0 +1,153 @@
1
+ // @ts-check
2
+ // The editor's API as a site builds it: its config file, a sign-in provider
3
+ // (signin/code.js or signin/access.js), and the few things from outside
4
+ // (fetch, the clock, the log, and for local editing a repository of the
5
+ // working tree). The config is checked once, here, so a wrong one fails when
6
+ // the API is built, not on some later request. Runs in Workers and Node: no
7
+ // node: import reaches this file (tests/pages-graph.test.js).
8
+ import { BROWSER_KEYS, browserConfig, configureSite, siteProblems } from "../editor/shared/site.js";
9
+ import { isLocalMode } from "./config.js";
10
+ import { MAX_PUBLISH_CHARS, handleAdminRequest } from "./dispatch.js";
11
+ import { createGithubRepo } from "./github.js";
12
+ import { MAX_UPLOAD_BYTES, MAX_UPLOAD_CHARS } from "./handlers.js";
13
+ import { mapRepo } from "./mapped-repo.js";
14
+ import { isPathMap } from "./path-map.js";
15
+
16
+ // The request-size limits, for a site's own dev server.
17
+ export { isLocalMode, MAX_PUBLISH_CHARS, MAX_UPLOAD_BYTES, MAX_UPLOAD_CHARS };
18
+
19
+ /** @typedef {import("./signin/refusal.js").SignInProvider} SignInProvider */
20
+ /** @typedef {import("./signin/refusal.js").SiteConfig} SiteConfig */
21
+ /** @typedef {import("./dispatch.js").Repo} Repo */
22
+
23
+ /** The keys only the server reads, beside the browser's (BROWSER_KEYS). */
24
+ export const SERVER_KEYS = Object.freeze([
25
+ "paths", "commit", "cookie", "liveBranchGuard", "maxPublishFiles", "guide",
26
+ ]);
27
+
28
+ const ADDRESS = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
29
+ // A cookie name: an HTTP token (RFC 6265 cookie-name).
30
+ const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
31
+ const PRINTABLE = /^[\x20-\x7e]+$/;
32
+
33
+ /**
34
+ * @param {unknown} v
35
+ * @returns {v is Record<string, any>}
36
+ */
37
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
38
+ /** @param {unknown} v */
39
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
40
+ /**
41
+ * @param {Record<string, unknown>} obj
42
+ * @param {string[]} keys
43
+ */
44
+ const hasExactly = (obj, keys) =>
45
+ Object.keys(obj).length === keys.length && keys.every((k) => Object.hasOwn(obj, k));
46
+
47
+ /** @type {Record<string, (v: any) => boolean>} */
48
+ const CHECKS = {
49
+ // The two maps are judged on their own below, each by its own name.
50
+ paths: (v) => isObject(v) && hasExactly(v, ["repo", "local"]),
51
+ commit: (v) => isObject(v) && hasExactly(v, ["identity", "userAgent"])
52
+ && (v.identity === null || (isObject(v.identity) && hasExactly(v.identity, ["name", "email"])
53
+ && isText(v.identity.name) && typeof v.identity.email === "string"
54
+ && ADDRESS.test(v.identity.email)))
55
+ && typeof v.userAgent === "string" && PRINTABLE.test(v.userAgent) && isText(v.userAgent),
56
+ cookie: (v) => typeof v === "string" && COOKIE_NAME.test(v),
57
+ liveBranchGuard: (v) => v === "vercel" || v === null,
58
+ maxPublishFiles: (v) => Number.isSafeInteger(v) && v > 0,
59
+ guide: isText,
60
+ };
61
+ // Every site sets these; cookie only with the code sign-in.
62
+ const REQUIRED = ["paths", "commit", "liveBranchGuard", "maxPublishFiles", "guide"];
63
+
64
+ /**
65
+ * The names of what is wrong with a site's whole config file: keys that
66
+ * belong to neither the browser nor the server, server keys missing or
67
+ * malformed, and the browser keys as siteProblems judges them. Empty when
68
+ * the config is usable.
69
+ * @param {unknown} config
70
+ * @returns {string[]}
71
+ */
72
+ export function serverConfigProblems(config) {
73
+ if (!isObject(config)) return ["(not an object)"];
74
+ /** @type {string[]} */
75
+ const problems = [];
76
+ for (const key of Object.keys(config)) {
77
+ if (!BROWSER_KEYS.includes(key) && !SERVER_KEYS.includes(key)) problems.push(key);
78
+ }
79
+ const signIn = Object.hasOwn(config, "signIn") ? config.signIn : "code";
80
+ for (const key of SERVER_KEYS) {
81
+ const present = Object.hasOwn(config, key);
82
+ if (key === "cookie") {
83
+ // Needed to sign in by code; meaningless (and so refused) with Access.
84
+ if (signIn === "code" ? !present || !CHECKS.cookie(config.cookie) : present) problems.push(key);
85
+ } else if (present ? !CHECKS[key](config[key]) : REQUIRED.includes(key)) {
86
+ problems.push(key);
87
+ } else if (key === "paths") {
88
+ for (const which of ["repo", "local"]) {
89
+ if (!isPathMap(config.paths[which])) problems.push(`paths.${which}`);
90
+ }
91
+ } else if (key === "liveBranchGuard" && signIn !== "code" && config.liveBranchGuard !== null) {
92
+ // The guard reads Vercel's settings for the code sign-in; with any
93
+ // other kind it would be silently ignored.
94
+ problems.push(key);
95
+ }
96
+ }
97
+ for (const name of siteProblems(browserConfig(config))) {
98
+ if (!problems.includes(name)) problems.push(name);
99
+ }
100
+ return problems;
101
+ }
102
+
103
+ /**
104
+ * @typedef {object} EditorApiOptions
105
+ * @property {SiteConfig} config the site's config file (site-editor.config.js)
106
+ * @property {SignInProvider} signIn of the kind config.signIn names
107
+ * @property {(input: string, init?: RequestInit) => Promise<Response>} [fetch]
108
+ * for GitHub; the global fetch when not given
109
+ * @property {() => number} [now] milliseconds; Date.now when not given
110
+ * @property {{ user: string, repo: Repo }} [local] local editing: the
111
+ * address to edit as and the working tree's repository, under its own
112
+ * paths (config.paths.local maps them). Used only when the settings ask
113
+ * for local mode (isLocalMode).
114
+ * @property {(line: string) => void} [log] console.error when not given
115
+ */
116
+
117
+ /**
118
+ * The API. Throws `site config: <names>` when the config is wrong.
119
+ * @param {EditorApiOptions} options
120
+ * @returns {{ handle(request: Request, env: Record<string, string | undefined>): Promise<Response> }}
121
+ */
122
+ export function createEditorApi({ config, signIn, fetch, now, local, log }) {
123
+ const problems = serverConfigProblems(config);
124
+ if (problems.length > 0) throw new Error(`site config: ${problems.join(", ")}`);
125
+ const kind = config.signIn ?? "code";
126
+ if (signIn?.kind !== kind) {
127
+ throw new Error(`site config: signIn is "${kind}" but the sign-in given is "${signIn?.kind}"`);
128
+ }
129
+ // The server's checks (reserved page addresses among them) read SITE.
130
+ configureSite(browserConfig(config));
131
+
132
+ const fetchFn = fetch ?? ((input, init) => globalThis.fetch(input, init));
133
+ const { identity, userAgent } = config.commit;
134
+ /** @param {import("./signin/refusal.js").GithubSettings} settings */
135
+ const repoFor = ({ token, repo, branch }) => /** @type {Repo} */ (mapRepo(
136
+ createGithubRepo({ token, repo, branch, fetch: fetchFn, identity, userAgent }),
137
+ config.paths.repo,
138
+ ));
139
+ const mappedLocal = local
140
+ ? { user: local.user, repo: /** @type {Repo} */ (mapRepo(local.repo, config.paths.local)) }
141
+ : undefined;
142
+ const deps = {
143
+ config,
144
+ signIn,
145
+ repoFor,
146
+ now: now ?? (() => Date.now()),
147
+ log: log ?? ((line) => console.error(line)),
148
+ local: mappedLocal,
149
+ };
150
+ return {
151
+ handle: (request, env) => handleAdminRequest(request, { ...deps, env }),
152
+ };
153
+ }
@@ -0,0 +1,171 @@
1
+ // A Repo (see memory-repo.js) backed by the working tree, for the
2
+ // local editor server. Commits write files under rootDir and rebuild; the
3
+ // parent chain of commit ids lives in memory only. Node only.
4
+ import { randomBytes } from "node:crypto";
5
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { blobSha } from "./blob-sha.js";
8
+ import { checkChanges } from "./changes.js";
9
+ import { RepoMoved } from "./github.js";
10
+ import { isPathMap } from "./path-map.js";
11
+ import { UPLOAD_NAME_RE } from "../editor/shared/rules.js";
12
+
13
+ /** The folders read and written under rootDir, from a paths.local map. */
14
+ function foldersFor(paths) {
15
+ const folder = (logical) => paths.find(([name]) => name === logical)[1];
16
+ const content = folder("content/");
17
+ const uploads = `${folder("assets/")}img/uploads/`;
18
+ return {
19
+ roots: [content.slice(0, -1), `${folder("assets/")}img`],
20
+ writable: [content, uploads],
21
+ uploads,
22
+ };
23
+ }
24
+
25
+ const newId = () => randomBytes(20).toString("hex");
26
+
27
+ /** Throws unless the path is a plain relative path inside a writable folder. */
28
+ function checkPath(p, writable) {
29
+ const ok = typeof p === "string"
30
+ && !p.includes("\\") && !p.includes("\0")
31
+ && writable.some((prefix) => p.startsWith(prefix))
32
+ && p.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
33
+ if (!ok) throw new Error(`Refusing to change ${JSON.stringify(p)}`);
34
+ }
35
+
36
+ /** Throws unless the path is an uploaded photo's file, as the upload route names them. */
37
+ function checkPhotoPath(p, { writable, uploads }) {
38
+ checkPath(p, writable);
39
+ if (!p.startsWith(uploads) || !UPLOAD_NAME_RE.test(p.slice(uploads.length))) {
40
+ throw new Error(`Refusing to write a photo to ${JSON.stringify(p)}`);
41
+ }
42
+ }
43
+
44
+ async function listFiles(rootDir, rel, out) {
45
+ let entries;
46
+ try {
47
+ entries = await readdir(path.join(rootDir, rel), { withFileTypes: true });
48
+ } catch (err) {
49
+ if (err.code === "ENOENT") return;
50
+ throw err;
51
+ }
52
+ for (const entry of entries) {
53
+ if (entry.name.startsWith(".")) continue;
54
+ const child = `${rel}/${entry.name}`;
55
+ if (entry.isDirectory()) await listFiles(rootDir, child, out);
56
+ else if (entry.isFile()) out.push(child);
57
+ }
58
+ }
59
+
60
+ /** @typedef {import("./dispatch.js").Repo} Repo */
61
+
62
+ /**
63
+ * paths: the site config's paths.local, [[logical, folder], ...] (its
64
+ * folders for content/ and assets/, under rootDir). Required: a layout
65
+ * guessed wrong would lose photos without a word. Throws when it is missing
66
+ * or not of the form the config check takes.
67
+ * rebuild: called with each new commit's id after its files are written.
68
+ * @param {string} rootDir
69
+ * @param {{ rebuild: (commit: string) => unknown, paths: ReadonlyArray<readonly string[]> }} options
70
+ * @returns {Repo}
71
+ */
72
+ export function createLocalRepo(rootDir, { rebuild, paths }) {
73
+ if (!isPathMap(paths)) {
74
+ throw new Error("createLocalRepo: paths must be the site config's paths.local, "
75
+ + '[["content/", "<folder>/"], ["assets/", "<folder>/"]]');
76
+ }
77
+ const folders = foldersFor(paths);
78
+ let current = newId();
79
+ const parents = new Map([[current, null]]); // commit id -> parent id
80
+ const blobs = new Map(); // blob sha -> bytes, until committed
81
+ let pathBySha = new Map(); // from the most recent head()
82
+ let queue = Promise.resolve(); // reads and commits, one at a time
83
+
84
+ /** Run fn after everything already queued; a failure does not stop the queue. */
85
+ function enqueue(fn) {
86
+ const run = queue.then(fn);
87
+ queue = run.catch(() => {});
88
+ return run;
89
+ }
90
+
91
+ // The map is built whole and swapped in at the end.
92
+ async function readHead() {
93
+ const paths = [];
94
+ for (const root of folders.roots) await listFiles(rootDir, root, paths);
95
+ const files = new Map();
96
+ const bySha = new Map();
97
+ for (const p of paths.sort()) {
98
+ const sha = await blobSha(await readFile(path.join(rootDir, p)));
99
+ files.set(p, sha);
100
+ bySha.set(sha, p);
101
+ }
102
+ pathBySha = bySha;
103
+ return { commit: current, files };
104
+ }
105
+
106
+ // Queued with commits: a read never sees half-written files, a commit
107
+ // never lands during a read, and the last head asked for is the last
108
+ // whose map is kept.
109
+ function head() {
110
+ return enqueue(readHead);
111
+ }
112
+
113
+ async function readText(sha) {
114
+ const p = pathBySha.get(sha);
115
+ if (p === undefined) throw new Error(`Unknown blob ${sha}`);
116
+ return new TextDecoder().decode(await readFile(path.join(rootDir, p)));
117
+ }
118
+
119
+ async function createBlob(base64) {
120
+ const bytes = new Uint8Array(Buffer.from(base64, "base64"));
121
+ const sha = await blobSha(bytes);
122
+ blobs.set(sha, bytes);
123
+ return sha;
124
+ }
125
+
126
+ async function commitNow({ parent, changes }) {
127
+ checkChanges(changes);
128
+ if (parent !== current) throw new RepoMoved();
129
+ // Validate everything first so a refusal leaves the tree untouched.
130
+ const writes = [];
131
+ for (const c of changes) {
132
+ const target = path.join(rootDir, c.path);
133
+ if (c.sha !== undefined) {
134
+ checkPhotoPath(c.path, folders);
135
+ if (!blobs.has(c.sha)) throw new Error(`Unknown blob ${c.sha}`);
136
+ writes.push({ target, data: blobs.get(c.sha) });
137
+ } else {
138
+ checkPath(c.path, folders.writable);
139
+ writes.push(c.remove ? { target, remove: true } : { target, data: c.text });
140
+ }
141
+ }
142
+ for (const w of writes) {
143
+ if (w.remove) {
144
+ await rm(w.target, { force: true });
145
+ } else {
146
+ await mkdir(path.dirname(w.target), { recursive: true });
147
+ await writeFile(w.target, w.data);
148
+ }
149
+ }
150
+ for (const c of changes) if (c.sha !== undefined) blobs.delete(c.sha);
151
+ const id = newId();
152
+ parents.set(id, current);
153
+ current = id;
154
+ await rebuild(id);
155
+ return id;
156
+ }
157
+
158
+ function commit(args) {
159
+ return enqueue(() => commitNow(args));
160
+ }
161
+
162
+ async function contains(ancestor, descendant) {
163
+ for (let id = descendant; id; id = parents.get(id)) {
164
+ if (!parents.has(id)) return false;
165
+ if (id === ancestor) return true;
166
+ }
167
+ return false;
168
+ }
169
+
170
+ return { head, readText, createBlob, commit, contains };
171
+ }