@pirateandfox/pagestack 0.1.0-beta.10 → 0.1.0-beta.11

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/README.md CHANGED
@@ -164,7 +164,7 @@ Coming from the WordPress block editor:
164
164
  | Block toolbar, ⋮ menu | Move, parent, add, duplicate, delete, copy, save as pattern |
165
165
  | Settings sidebar, Page / Block tabs | Same, generated from the schema |
166
166
  | Rich text toolbar, links | Same; `⌘B`, `⌘I`, `⌘K`, and an HTML view |
167
- | Save draft, Publish, Preview | Same; Preview opens the unsaved draft in a new tab |
167
+ | Status (Draft / Published), Publish, Preview | A **Ready to publish** switch (**Published** without `github.live`) that saves when flipped; Publish is **Publish changes** in the top bar with `github.live`; Preview opens the unsaved draft in a new tab |
168
168
  | Revisions | The page's git history |
169
169
  | Permalink | Change URL, which also adds a redirect |
170
170
  | Menus, site options | Global content, at `/edit/global/<id>` |
@@ -334,11 +334,12 @@ than setting a hard limit. Passkeys are what actually stops guessing.
334
334
  ### Staging and Go live
335
335
 
336
336
  With `github.live`, saves stay on `github.branch` (staging) and the public site builds from `live`.
337
- Every screen gets a **Go live** button counting the saved changes the live site doesn't have yet;
337
+ Every screen gets a **Publish changes** button (Go live) counting the saved changes the live site doesn't have yet;
338
338
  it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
339
339
  That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
340
340
  commit and moves staging to it; when their change conflicts, it refuses and says so, and a person
341
- merges in GitHub. A burst of saves becomes one production build.
341
+ merges in GitHub. A burst of saves becomes one production build. Drafts (the **Ready to publish**
342
+ switch off) stay in the files but out of the built site, whatever is published.
342
343
 
343
344
  ```js
344
345
  github: { repo: 'acme/site', branch: 'develop', live: 'main', stagingUrl: 'https://develop.acme.pages.dev/' }
package/index.mjs CHANGED
@@ -11,6 +11,21 @@ import { fileURLToPath } from 'node:url';
11
11
  import fs from 'node:fs';
12
12
  import path from 'node:path';
13
13
 
14
+ /**
15
+ * The editor's copy of the site serves its built pages as static files, on the editor's origin,
16
+ * where the editor API and the session cookie live. The platform answers those before any of our
17
+ * code runs, so the rules the middleware puts on everything else go in the static headers file
18
+ * (Cloudflare `_headers`): the site's own scripts only, no inline event handlers, framed only here.
19
+ */
20
+ function writeEditorHeaders(clientDir, previewScripts) {
21
+ if (!fs.existsSync(clientDir)) return;
22
+ const file = path.join(clientDir, '_headers');
23
+ const scripts = previewScripts === 'all' ? "script-src-attr 'none'" : "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; script-src-attr 'none'";
24
+ const block = `\n# pagestack: built pages served by the editor\n/*\n Content-Security-Policy: ${scripts}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n X-Frame-Options: SAMEORIGIN\n`;
25
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
26
+ if (!existing.includes('# pagestack: built pages served by the editor')) fs.writeFileSync(file, existing + block);
27
+ }
28
+
14
29
  const VIRTUAL = 'virtual:pagestack/site';
15
30
  const VIRTUAL_RENDERER = 'virtual:pagestack/renderer';
16
31
  const VIRTUAL_PREVIEWS = 'virtual:pagestack/previews';
@@ -83,12 +98,23 @@ export default function sectionEditor(userOptions) {
83
98
  let adapter = null;
84
99
  // Set in astro:config:setup when the editor is on: page files to render on request (liveRoutes).
85
100
  let liveComponents = null;
101
+ // Set when building the editor: the site's built pages it serves need the editor's script rules.
102
+ let editorBuild = null;
86
103
  const forward = (hook) => async (params) => { if (adapter?.hooks?.[hook]) await adapter.hooks[hook](params); };
87
104
  const forwarded = Object.fromEntries(['astro:config:done', 'astro:server:setup', 'astro:server:start', 'astro:server:done', 'astro:build:start', 'astro:build:setup', 'astro:build:ssr', 'astro:build:generated', 'astro:build:done'].map((h) => [h, forward(h)]));
88
105
  return {
89
106
  name: 'pagestack',
90
107
  hooks: {
91
108
  ...forwarded,
109
+ 'astro:config:done': async (params) => {
110
+ if (editorBuild) editorBuild.dirs = [params.config.build.client, params.config.outDir]; // with an adapter, files go to build.client
111
+ await forwarded['astro:config:done'](params);
112
+ },
113
+ 'astro:build:done': async (params) => {
114
+ await forwarded['astro:build:done'](params);
115
+ const dir = editorBuild?.dirs?.map((u) => fileURLToPath(u)).find((d) => fs.existsSync(d));
116
+ if (dir) writeEditorHeaders(dir, editorBuild.previewScripts);
117
+ },
92
118
  // List pages named in `liveRoutes` render on request on the editor's server, reading what
93
119
  // has been saved. Only in the editor build: the public build never gets here.
94
120
  'astro:route:setup': ({ route }) => {
@@ -100,6 +126,7 @@ export default function sectionEditor(userOptions) {
100
126
  const enabled = userOptions.enabled ?? (flag === '1' || (command === 'dev' && flag === 'dev'));
101
127
  if (!enabled) { logger.info(command === 'dev' ? 'off. Run with EDITOR=dev to edit at /edit.' : 'off (static build). Set EDITOR=1 to build the editor.'); return; }
102
128
  const isBuild = command === 'build';
129
+ if (isBuild) editorBuild = { previewScripts: userOptions.previewScripts };
103
130
  const options = {
104
131
  pagesDir: 'src/content/pages',
105
132
  imagesDir: 'public/images',
@@ -196,7 +223,6 @@ export default function sectionEditor(userOptions) {
196
223
  injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
197
224
  injectRoute({ pattern: '/api/editor/browse', entrypoint: route('api/browse.ts'), prerender: false });
198
225
  injectRoute({ pattern: '/api/editor/live', entrypoint: route('api/live.ts'), prerender: false });
199
- injectRoute({ pattern: '/api/editor/asset/[...path]', entrypoint: route('api/asset.ts'), prerender: false });
200
226
  injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
201
227
  // Uploads saved after this editor was built aren't static files in it; serve them from the repo.
202
228
  const uploadsUrl = options.storage === 'github' && uploadsUrlPrefix(options.uploadsDir, options.publicDir);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.10",
3
+ "version": "0.1.0-beta.11",
4
4
  "description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -36,6 +36,7 @@
36
36
  "devDependencies": {
37
37
  "@types/sortablejs": "^1.15.8",
38
38
  "happy-dom": "^21.0.4",
39
+ "parse5": "^7.3.0",
39
40
  "vitest": "^4.0.0"
40
41
  },
41
42
  "keywords": [
@@ -33,7 +33,7 @@ function drawBar(r: Resolved) {
33
33
  note.textContent = 'Latest saved version';
34
34
  } else if (r.builtAt && r.savedAt && Date.parse(r.savedAt) > Date.parse(r.builtAt)) {
35
35
  note.textContent = `⚠ As of ${when(r.builtAt)}. May not show changes saved since.`;
36
- note.title = 'This page is the copy built into the editor. Changes saved after that show here once the editor is redeployed, and on the public site after Go live.';
36
+ note.title = 'This page is the copy built into the editor. Changes saved after that show here once the editor is redeployed, and on the public site after Publish changes.';
37
37
  note.classList.add('is-stale');
38
38
  } else {
39
39
  note.textContent = '';
@@ -343,12 +343,10 @@ function refreshButtons() {
343
343
  $<HTMLButtonElement>('#ps-redo').disabled = !state.canRedo;
344
344
  const save = $<HTMLButtonElement>('#ps-save');
345
345
  save.disabled = !dirty || saving;
346
- save.textContent = draft ? 'Save draft' : 'Save';
347
- save.classList.toggle('ps-btn--primary', !draft);
348
- save.classList.toggle('ps-btn--ghost', draft);
349
- const publish = $<HTMLButtonElement>('#ps-publish');
350
- publish.hidden = !draft;
351
- publish.disabled = saving;
346
+ const ready = $<HTMLInputElement>('#ps-ready');
347
+ ready.checked = !draft;
348
+ ready.disabled = saving || isHome;
349
+ if (isHome) $('#ps-ready-wrap').title = 'The home page is always published.';
352
350
  $('#ps-discard').hidden = !dirty;
353
351
  $('#ps-view').hidden = draft || boot.page.status === 'draft';
354
352
  $('#ps-draft-pill').hidden = !draft;
@@ -467,7 +465,7 @@ function renderPageTab(root: HTMLElement) {
467
465
  if (button) { const b = document.createElement('button'); b.type = 'button'; b.id = button.id; b.className = 'ps-linkbtn'; b.textContent = button.text; b.disabled = !!button.disabled; b.addEventListener('click', button.run); r.append(b); }
468
466
  summary.append(r);
469
467
  };
470
- row('Status', draft ? 'Draft' : 'Published', draft ? undefined : { text: 'Switch to draft', id: 'ps-unpublish', run: () => publish(false), disabled: isHome });
468
+ row('Status', draft ? 'Draft' : document.getElementById('ps-live') ? 'Ready to publish' : 'Published');
471
469
  row('URL', boot.options.viewUrl, isHome ? undefined : { text: 'Change', id: 'ps-change-url', run: changeUrl });
472
470
  root.append(summary);
473
471
 
@@ -772,7 +770,7 @@ $('#ps-discard').addEventListener('click', async () => {
772
770
  state.reset(r.page, r.hash);
773
771
  });
774
772
  $('#ps-save').addEventListener('click', () => save());
775
- $('#ps-publish').addEventListener('click', () => publish(true));
773
+ $<HTMLInputElement>('#ps-ready').addEventListener('change', (e) => publish((e.target as HTMLInputElement).checked));
776
774
  $('#ps-preview-tab').addEventListener('click', previewInTab);
777
775
  document.querySelectorAll<HTMLButtonElement>('.ps-top__devices button').forEach((b) => b.addEventListener('click', () => {
778
776
  document.querySelectorAll('.ps-top__devices button').forEach((x) => x.classList.remove('is-active'));
@@ -813,7 +811,7 @@ async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; resu
813
811
  state.markSaved(data.hash);
814
812
  boot.page = state.doc;
815
813
  const r = data.result;
816
- if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : document.getElementById('ps-live') ? 'Saved. Use Go live to put it on the site.' : `Committed ${String(r.commit).slice(0, 7)} to ${r.branch}. The host will rebuild the site.`, 'ok', { href: r.pullRequest || r.url });
814
+ if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : `Committed ${String(r.commit).slice(0, 7)} to ${r.branch}. The host will rebuild the site.`, 'ok', { href: r.pullRequest || r.url });
817
815
  else toast(`Saved to the working tree (${r.files.join(', ')}). Commit it with git when you're happy.`, 'ok');
818
816
  setSaveStatus('Saved');
819
817
  return data;
@@ -821,14 +819,17 @@ async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; resu
821
819
  finally { saving = false; refreshChrome(); }
822
820
  }
823
821
 
824
- /** Publish a draft, or take a published page back to draft. Saves straight away, like WordPress. */
822
+ /** The Ready to publish switch: a draft or not. Saves straight away, so the switch means what it shows. */
825
823
  async function publish(live: boolean) {
826
- if (!live && !await confirmDialog('Switch to draft', 'This page will be left out of the site the next time it is built.', 'Switch to draft')) return;
824
+ const staged = !!document.getElementById('ps-live');
825
+ // Without a Publish changes step, a draft leaves the site at the next build: ask first.
826
+ if (!live && !staged && !await confirmDialog('Make this a draft?', 'This page will be left out of the site the next time it is built.', 'Make it a draft')) { refreshButtons(); return; }
827
827
  inline.stop(true);
828
828
  const next = structuredClone(state.doc);
829
829
  if (live) delete next.status; else next.status = 'draft';
830
830
  state.apply(next);
831
- if (await save()) toast(live ? `${next.title} is published.` : `${next.title} is now a draft.`, 'ok'); else state.undo();
831
+ if (await save()) toast(live ? (staged ? `${next.title} is ready to publish. It goes on the site with the next Publish changes.` : `${next.title} is published.`) : `${next.title} is now a draft: kept off the site.`, 'ok');
832
+ else { state.undo(); refreshButtons(); }
832
833
  }
833
834
 
834
835
  async function changeUrl() {
@@ -28,6 +28,6 @@ saveBtn.addEventListener('click', async () => {
28
28
  const d = await r.json();
29
29
  if (!r.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; return; }
30
30
  hash = d.hash; dirty = false;
31
- toast(d.result.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Go live to put it on the site.' : 'Saved. The site will rebuild.') : "Saved to the working tree. Commit it with git when you're happy.", 'ok');
31
+ toast(d.result.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : 'Saved. The site will rebuild.') : "Saved to the working tree. Commit it with git when you're happy.", 'ok');
32
32
  });
33
33
  window.addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
@@ -18,8 +18,8 @@ const title = $<HTMLInputElement>('ps-item-title');
18
18
  const body = $<HTMLTextAreaElement>('ps-item-body');
19
19
  const preview = $('ps-item-preview');
20
20
  const saveBtn = $<HTMLButtonElement>('ps-item-save');
21
- const publishBtn = $<HTMLButtonElement>('ps-item-publish');
22
- const draftBtn = $<HTMLButtonElement>('ps-item-draft');
21
+ const ready = $<HTMLInputElement>('ps-item-ready');
22
+ const readyWrap = $('ps-item-ready-wrap');
23
23
  const status = $('ps-item-status');
24
24
 
25
25
  const data = structuredClone(boot.data);
@@ -29,12 +29,11 @@ let dirty = false;
29
29
 
30
30
  function chrome() {
31
31
  const draft = hasDraft && data.draft === true;
32
- saveBtn.textContent = !hasDraft ? 'Save' : draft ? 'Save draft' : 'Update';
33
- publishBtn.hidden = !draft;
34
- draftBtn.hidden = !hasDraft || draft;
32
+ readyWrap.hidden = !hasDraft;
33
+ ready.checked = !draft;
35
34
  saveBtn.disabled = !dirty;
36
35
  const view = document.getElementById('ps-item-view'); if (view) view.hidden = draft;
37
- status.textContent = dirty ? 'Unsaved changes' : draft ? 'Draft: not on the site yet' : '';
36
+ status.textContent = dirty ? 'Unsaved changes' : draft ? 'Draft: not on the site' : '';
38
37
  }
39
38
  const touch = () => { dirty = true; chrome(); };
40
39
 
@@ -87,20 +86,27 @@ body.addEventListener('keydown', (e) => {
87
86
  });
88
87
 
89
88
  // ---- saving ----
90
- async function save(): Promise<boolean> {
89
+ async function save(done?: string): Promise<boolean> {
91
90
  if (frame && inline.isActive) inline.stop(true);
92
91
  saveBtn.disabled = true; status.textContent = 'Saving…';
93
92
  const res = await fetch(`/api/editor/collection/${boot.id}/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data, body: body.value, base: hash }) });
94
93
  const d = await res.json();
95
94
  if (!res.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; status.textContent = 'Not saved'; return false; }
96
95
  hash = d.hash; dirty = false; chrome();
97
- toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Go live to put it on the site.' : 'Saved. The site will rebuild.') : 'Saved.', 'ok');
96
+ if (done && !d.result?.pullRequest) toast(done, 'ok'); else toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : 'Saved. The site will rebuild.') : 'Saved.', 'ok');
98
97
  return true;
99
98
  }
100
- saveBtn.addEventListener('click', save);
101
- const setDraft = async (v: boolean) => { const was = data.draft; data.draft = v; if (!await save()) { data.draft = was; chrome(); } };
102
- publishBtn.addEventListener('click', () => setDraft(false));
103
- draftBtn.addEventListener('click', () => setDraft(true));
99
+ saveBtn.addEventListener('click', () => save());
100
+ // The switch saves straight away (with any other unsaved changes), so it means what it shows.
101
+ ready.addEventListener('change', async () => {
102
+ const was = data.draft;
103
+ data.draft = !ready.checked;
104
+ ready.disabled = true;
105
+ const staged = !!document.getElementById('ps-live');
106
+ const ok = await save(ready.checked ? (staged ? 'Ready to publish. It goes on the site with the next Publish changes.' : 'Published. The site will rebuild.') : 'Now a draft: kept off the site.');
107
+ if (!ok) { data.draft = was; chrome(); }
108
+ ready.disabled = false;
109
+ });
104
110
  addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (dirty) save(); } });
105
111
  addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
106
112
 
@@ -1,4 +1,4 @@
1
- // The Go live button, in every screen's top bar. Hidden unless the site has a live branch
1
+ // The Publish changes button (Go live), in every screen's top bar. Hidden unless the site has a live branch
2
2
  // (`github.live`): then saves wait on staging, the button counts them, and one click puts them all
3
3
  // on the public site. It refreshes itself after any save, wherever on the screen that happened.
4
4
  import { dialog, toast } from './ui';
@@ -22,7 +22,7 @@ function draw() {
22
22
  btn.hidden = false;
23
23
  const n = state.count;
24
24
  btn.disabled = n === 0;
25
- btn.textContent = 'Go live';
25
+ btn.textContent = 'Publish changes';
26
26
  if (n) { const b = document.createElement('span'); b.className = 'ps-live__count'; b.textContent = String(n); btn.append(b); }
27
27
  btn.title = n ? `${n} saved change${n === 1 ? '' : 's'} not on the live site yet` : 'Everything saved is on the live site';
28
28
  }
@@ -61,15 +61,15 @@ async function goLive() {
61
61
  a.href = state.stagingUrl; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'See them on the staging site first ↗';
62
62
  p.append(a); body.append(p);
63
63
  }
64
- dialog('Go live?', body, [
64
+ dialog('Publish changes?', body, [
65
65
  { label: 'Cancel' },
66
66
  {
67
- label: 'Go live', kind: 'primary', run: async () => {
67
+ label: 'Publish changes', kind: 'primary', run: async () => {
68
68
  const r = await fetch('/api/editor/live', { method: 'POST', headers: { accept: 'application/json' } });
69
69
  const data = await r.json().catch(() => ({}));
70
- if (!r.ok) { toast(data.error ?? 'Could not go live.', 'error'); return false; }
71
- if (data.nothing) toast('Everything saved was already live.', 'info');
72
- else toast(`Live. ${data.count} change${data.count === 1 ? ' is' : 's are'} on the way to the site; it updates in a few minutes.`, 'ok', { href: data.url });
70
+ if (!r.ok) { toast(data.error ?? 'Could not publish.', 'error'); return false; }
71
+ if (data.nothing) toast('Everything saved was already on the site.', 'info');
72
+ else toast(`Published. ${data.count} change${data.count === 1 ? ' is' : 's are'} on the way to the site; it updates in a few minutes.`, 'ok', { href: data.url });
73
73
  await refresh();
74
74
  },
75
75
  },
@@ -28,7 +28,7 @@ function addPage(copyOf?: string) {
28
28
  <span class="ps-prefixed"><span class="ps-muted">/</span><input type="text" name="slug" autocomplete="off" spellcheck="false" /><span class="ps-muted">/</span></span></label>
29
29
  <p class="ps-error" hidden></p></div>
30
30
  <div class="ps-field"><label>Start from <select name="from"></select></label></div>
31
- <small class="ps-muted">New pages start as drafts. Nothing is public until you press Publish.</small>`;
31
+ <small class="ps-muted">New pages start as drafts. Nothing is public until you turn on ${document.getElementById('ps-live') ? 'Ready to publish' : 'Published'}.</small>`;
32
32
  const title = form.querySelector<HTMLInputElement>('[name=title]')!;
33
33
  const slug = form.querySelector<HTMLInputElement>('[name=slug]')!;
34
34
  const from = form.querySelector<HTMLSelectElement>('[name=from]')!;
@@ -349,3 +349,15 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
349
349
  .ps-browse__where:not(:has(.is-stale)) { display: none; } /* only the warning earns a second line */
350
350
  .ps-browse__path, .ps-browse__out { display: none; }
351
351
  }
352
+
353
+ /* Ready to publish: a switch that saves when flipped */
354
+ .ps-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px; white-space: nowrap; user-select: none; }
355
+ .ps-switch[hidden] { display: none; }
356
+ .ps-switch input { position: absolute; opacity: 0; width: 1px; height: 1px; margin: 0; }
357
+ .ps-switch__track { position: relative; flex: none; width: 34px; height: 20px; border-radius: 10px; background: #9ca3af; transition: background .15s; }
358
+ .ps-switch__track::after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(0 0 0 / .25); transition: transform .15s; }
359
+ .ps-switch input:checked + .ps-switch__track { background: #16a34a; }
360
+ .ps-switch input:checked + .ps-switch__track::after { transform: translateX(14px); }
361
+ .ps-switch input:focus-visible + .ps-switch__track { outline: 2px solid #2563eb; outline-offset: 2px; }
362
+ .ps-switch:has(input:disabled) { cursor: default; opacity: .6; }
363
+ @media (prefers-reduced-motion: reduce) { .ps-switch__track, .ps-switch__track::after { transition: none; } }
package/src/core/auth.ts CHANGED
@@ -62,12 +62,13 @@ export function cookieHeader(name: string, value: string, maxAge: number, secure
62
62
  export const clearCookieHeader = (name: string, secure: boolean) => cookieHeader(name, '', 0, secure);
63
63
 
64
64
  // ---- typed tokens ----
65
- export interface SessionPayload { kind: 'session'; sub: string; name: string }
65
+ /** `cred`: the passkey this session was opened with (sessions end when it is removed). */
66
+ export interface SessionPayload { kind: 'session'; sub: string; name: string; cred?: string }
66
67
  export interface ChallengePayload { kind: 'challenge'; challenge: string; purpose: 'login' | 'register'; invite?: InvitePayload }
67
68
  /** `id` makes an invite single-use: it's recorded on the credential created from it. */
68
69
  export interface InvitePayload { kind: 'invite'; id: string; name: string; email: string; role?: 'admin' | 'editor' }
69
70
 
70
- export const createSession = (user: { id: string; name: string }, secret: string) => sign<SessionPayload>({ kind: 'session', sub: user.id, name: user.name }, secret, SESSION_TTL);
71
+ export const createSession = (user: { id: string; name: string }, secret: string, cred?: string) => sign<SessionPayload>({ kind: 'session', sub: user.id, name: user.name, ...(cred ? { cred } : {}) }, secret, SESSION_TTL);
71
72
  export const readSession = async (cookieHeaderValue: string | null, secret: string) => {
72
73
  const p = await verify<SessionPayload>(parseCookies(cookieHeaderValue)[SESSION_COOKIE], secret);
73
74
  return p?.kind === 'session' ? p : null;
@@ -1,6 +1,11 @@
1
1
  // Rich text is untrusted: it is typed, pasted, or arrives from another site. This is an allowlist
2
2
  // sanitiser that needs no DOM, so the same code runs in the browser and on save. Tags that pass
3
- // untouched keep their exact bytes, which keeps saves from rewriting existing content.
3
+ // that are already in plain form keep their exact bytes, which keeps saves from rewriting existing content.
4
+ //
5
+ // Tags are read the way a browser's HTML tokenizer reads them (quotes only open a value straight
6
+ // after `=`), and every kept tag is written back from what was read, never passed through as it came:
7
+ // a reader that disagrees with the browser about where an attribute ends is how event handlers slip
8
+ // past an allowlist.
4
9
  import type { Field, Node, PageDoc, SchemaRegistry } from '../runtime';
5
10
 
6
11
  /** Dropped along with everything inside them. */
@@ -29,8 +34,64 @@ export function safeUrl(url: string): boolean {
29
34
  return !scheme || SAFE_SCHEME.test(flat);
30
35
  }
31
36
 
32
- const TAG = /<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/y;
33
- const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
37
+ interface Attr { key: string; value: string | null; quoted: boolean }
38
+ interface Tag { end: number; closing: boolean; rawName: string; attrs: Attr[]; selfClosing: boolean }
39
+ const isWs = (c: string | undefined) => c === ' ' || c === '\t' || c === '\n' || c === '\f' || c === '\r';
40
+
41
+ /**
42
+ * The tag starting at `lt`, read as the HTML spec's tokenizer does (tag open, attribute name and
43
+ * value states). Null when it is not a tag (`<` then a non-letter) or never ends: a browser shows
44
+ * the first as text and swallows the second, and the caller escapes the `<` either way.
45
+ */
46
+ export function scanTag(s: string, lt: number): Tag | null {
47
+ let i = lt + 1;
48
+ const closing = s[i] === '/';
49
+ if (closing) i++;
50
+ if (!/[a-zA-Z]/.test(s[i] ?? '')) return null;
51
+ const start = i;
52
+ while (i < s.length && !isWs(s[i]) && s[i] !== '/' && s[i] !== '>') i++;
53
+ const rawName = s.slice(start, i);
54
+ const attrs: Attr[] = [];
55
+ let selfClosing = false;
56
+ while (i < s.length) {
57
+ const c = s[i];
58
+ if (isWs(c)) { i++; continue; }
59
+ if (c === '>') return { end: i + 1, closing, rawName, attrs, selfClosing };
60
+ if (c === '/') { i++; selfClosing = s[i] === '>'; continue; }
61
+ selfClosing = false;
62
+ const a = i++; // the first character of a name may be anything, `=` and quotes included
63
+ while (i < s.length && !isWs(s[i]) && s[i] !== '/' && s[i] !== '>' && s[i] !== '=') i++;
64
+ const key = s.slice(a, i);
65
+ let j = i;
66
+ while (isWs(s[j])) j++;
67
+ if (s[j] !== '=') { attrs.push({ key, value: null, quoted: false }); continue; }
68
+ i = j + 1;
69
+ while (isWs(s[i])) i++;
70
+ const q = s[i];
71
+ if (q === '"' || q === "'") {
72
+ const e = s.indexOf(q, i + 1);
73
+ if (e < 0) return null;
74
+ attrs.push({ key, value: s.slice(i + 1, e), quoted: true });
75
+ i = e + 1;
76
+ } else {
77
+ const v = i; // unquoted: quotes, `=` and `<` here are part of the value
78
+ while (i < s.length && !isWs(s[i]) && s[i] !== '>') i++;
79
+ attrs.push({ key, value: s.slice(v, i), quoted: false });
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+
85
+ const attrText = (key: string, value: string | null) => (value === null ? key : `${key}="${value.replace(/"/g, '&quot;')}"`);
86
+ /**
87
+ * May a start tag go out exactly as written? Only when nothing was dropped and nothing in it reads
88
+ * two ways: plain names, and unquoted values without quotes, `=`, `<`, `>` or backticks.
89
+ */
90
+ const plainTag = (t: Tag, name: string, keptAll: boolean) => keptAll && t.rawName === name
91
+ && t.attrs.every((a) => /^[a-z][a-z0-9:-]*$/i.test(a.key) && (a.quoted || a.value === null || /^[^\s"'=<>`]+$/.test(a.value)));
92
+ /** The tag as written when it is plain, otherwise rebuilt from what was read. */
93
+ const emit = (whole: string, t: Tag, name: string, kept: string[]) =>
94
+ plainTag(t, name, kept.length === t.attrs.length) ? whole : `<${name}${kept.length ? ' ' + kept.join(' ') : ''}${t.selfClosing ? ' />' : '>'}`;
34
95
 
35
96
  /** Inline SVG (`svg` fields) and uploaded .svg files. No scripts, events, foreign content or animation. */
36
97
  const SVG_TAGS = new Set(['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', 'defs', 'lineargradient', 'radialgradient', 'stop', 'clippath', 'mask', 'use', 'symbol', 'pattern', 'title', 'desc', 'marker']);
@@ -51,13 +112,13 @@ function scrubSvg(svg: string, { file }: { file: boolean }): string {
51
112
  const e = open > 0 && open < gt ? svg.indexOf(']>', open) : gt;
52
113
  i = e < 0 ? svg.length : e + (open > 0 && open < gt ? 2 : 1); continue;
53
114
  }
54
- TAG.lastIndex = lt;
55
- const m = TAG.exec(svg);
56
- if (!m) { out += '&lt;'; i = lt + 1; continue; }
57
- i = TAG.lastIndex;
58
- const [whole, slash, rawName, rawAttrs] = m;
115
+ const t = scanTag(svg, lt);
116
+ if (!t) { out += '&lt;'; i = lt + 1; continue; }
117
+ const whole = svg.slice(lt, t.end);
118
+ i = t.end;
119
+ const { rawName, closing: slash } = t;
59
120
  const name = rawName.toLowerCase();
60
- const closes = rawAttrs.trimEnd().endsWith('/');
121
+ const closes = t.selfClosing;
61
122
  if (name === 'style' && file) { // stylesheets from design tools; never reached when inlined in a page
62
123
  if (slash || closes) continue;
63
124
  const end = svg.toLowerCase().indexOf('</style', i);
@@ -74,20 +135,19 @@ function scrubSvg(svg: string, { file }: { file: boolean }): string {
74
135
  }
75
136
  continue;
76
137
  }
77
- if (slash) { out += whole; continue; }
138
+ if (slash) { out += whole === `</${rawName}>` ? whole : `</${rawName}>`; continue; }
78
139
  const kept: string[] = [];
79
- let dropped = false;
80
- for (const a of rawAttrs.matchAll(ATTR)) {
81
- const key = a[1].toLowerCase();
82
- const value = a[2] ?? a[3] ?? a[4] ?? '';
140
+ for (const a of t.attrs) {
141
+ const key = a.key.toLowerCase();
142
+ const value = a.value ?? '';
83
143
  const allowed = (SVG_ATTRS.has(key) || key.startsWith('aria-') || key.startsWith('data-'))
84
144
  && (key !== 'href' && key !== 'xlink:href' || /^#[\w-]+$/.test(value.trim()))
85
145
  && (key !== 'style' || svgStyleOk(value))
86
146
  && (!/^(fill|stroke|filter|mask|clip-path)$/.test(key) || svgStyleOk(value));
87
- if (!allowed) { dropped = true; continue; }
88
- kept.push(`${a[1]}="${value.replace(/"/g, '&quot;')}"`);
147
+ if (!allowed || !/^[a-zA-Z_:][\w:.-]*$/.test(a.key)) continue;
148
+ kept.push(attrText(a.key, a.value)); // SVG names keep their case (viewBox)
89
149
  }
90
- out += dropped ? `<${rawName}${kept.length ? ' ' + kept.join(' ') : ''}${closes ? ' /' : ''}>` : whole;
150
+ out += emit(whole, t, rawName, kept);
91
151
  }
92
152
  return out;
93
153
  }
@@ -113,14 +173,14 @@ export function sanitizeHtml(html: string, { paste = false }: { paste?: boolean
113
173
  i = end < 0 ? html.length : end + 3;
114
174
  continue;
115
175
  }
116
- TAG.lastIndex = lt;
117
- const m = TAG.exec(html);
118
- if (!m) { out += '&lt;'; i = lt + 1; continue; }
119
- i = TAG.lastIndex;
120
- const [whole, slash, rawName, rawAttrs] = m;
176
+ const t = scanTag(html, lt);
177
+ if (!t) { out += '&lt;'; i = lt + 1; continue; }
178
+ const whole = html.slice(lt, t.end);
179
+ i = t.end;
180
+ const { rawName, closing: slash } = t;
121
181
  let name = rawName.toLowerCase();
122
182
  if (DROP.has(name)) {
123
- if (!slash && !rawAttrs.trimEnd().endsWith('/')) {
183
+ if (!slash && !t.selfClosing) {
124
184
  const end = html.toLowerCase().indexOf(`</${name}`, i);
125
185
  if (end < 0) break;
126
186
  const close = html.indexOf('>', end);
@@ -130,17 +190,14 @@ export function sanitizeHtml(html: string, { paste = false }: { paste?: boolean
130
190
  }
131
191
  if (paste && name === 'div') name = 'p'; // Word and Docs wrap lines in these
132
192
  if (!tags.has(name)) continue;
133
- if (slash) { out += name === rawName.toLowerCase() ? whole : `</${name}>`; continue; }
193
+ if (slash) { out += whole === `</${name}>` ? whole : `</${name}>`; continue; }
134
194
  const kept: string[] = [];
135
- let dropped = false;
136
- for (const a of rawAttrs.matchAll(ATTR)) {
137
- const key = a[1].toLowerCase();
138
- const value = a[2] ?? a[3] ?? a[4] ?? '';
139
- if (!attrs.has(key) || (URL_ATTRS.has(key) && !safeUrl(value))) { dropped = true; continue; }
140
- kept.push(a[2] === undefined && a[3] === undefined && a[4] === undefined ? key : `${key}="${value.replace(/"/g, '&quot;')}"`);
195
+ for (const a of t.attrs) {
196
+ const key = a.key.toLowerCase();
197
+ if (!attrs.has(key) || (URL_ATTRS.has(key) && !safeUrl(a.value ?? ''))) continue;
198
+ kept.push(attrText(key, a.value));
141
199
  }
142
- if (!dropped && name === rawName.toLowerCase()) out += whole;
143
- else out += `<${name}${kept.length ? ' ' + kept.join(' ') : ''}>`;
200
+ out += emit(whole, t, name, kept);
144
201
  }
145
202
  return paste ? out.replace(/<p>(\s|&nbsp;|<br>)*<\/p>/g, '').trim() : out;
146
203
  }
package/src/core/users.ts CHANGED
@@ -30,7 +30,12 @@ export interface EditorUser {
30
30
  credentials: StoredCredential[];
31
31
  }
32
32
 
33
- export interface UsersFile { version: 1; users: EditorUser[] }
33
+ export interface UsersFile {
34
+ version: 1;
35
+ users: EditorUser[];
36
+ /** Ids of invites that have been used. Kept when the person or passkey is removed, so a link never works twice. */
37
+ usedInvites?: string[];
38
+ }
34
39
 
35
40
  export const emptyUsers = (): UsersFile => ({ version: 1, users: [] });
36
41
 
@@ -41,7 +46,7 @@ export function parseUsers(raw: string | null | undefined): UsersFile {
41
46
  for (const u of data.users) {
42
47
  if (typeof u.id !== 'string' || typeof u.email !== 'string' || !Array.isArray(u.credentials)) throw new Error(`editor users file: malformed user ${JSON.stringify(u.id ?? u)}`);
43
48
  }
44
- return { version: 1, users: data.users };
49
+ return { version: 1, users: data.users, ...(Array.isArray(data.usedInvites) ? { usedInvites: data.usedInvites.filter((x: unknown) => typeof x === 'string') } : {}) };
45
50
  }
46
51
 
47
52
  export const serializeUsers = (file: UsersFile): string => JSON.stringify(file, null, 2) + '\n';
@@ -56,7 +61,7 @@ export function findByCredential(file: UsersFile, credentialId: string): { user:
56
61
 
57
62
  export const findByEmail = (file: UsersFile, email: string) => file.users.find((u) => u.email.toLowerCase() === email.trim().toLowerCase()) ?? null;
58
63
 
59
- export const inviteUsed = (file: UsersFile, inviteId: string) => file.users.some((u) => u.credentials.some((c) => c.inviteId === inviteId));
64
+ export const inviteUsed = (file: UsersFile, inviteId: string) => !!file.usedInvites?.includes(inviteId) || file.users.some((u) => u.credentials.some((c) => c.inviteId === inviteId));
60
65
 
61
66
  export function newUserId(): string {
62
67
  const buf = new Uint8Array(8); crypto.getRandomValues(buf);
@@ -73,11 +78,21 @@ export function addCredential(file: UsersFile, who: { name: string; email: strin
73
78
  copy.users.push(user);
74
79
  }
75
80
  user.credentials.push(credential);
81
+ // Invites live 3 days; the last few hundred ids cover far more than that.
82
+ if (credential.inviteId) copy.usedInvites = [...(copy.usedInvites ?? []), credential.inviteId].slice(-500);
76
83
  return { file: copy, user };
77
84
  }
78
85
 
86
+ /** Invite ids on credentials that are about to go: remembered, so those links stay used. */
87
+ const keepInvites = (file: UsersFile, gone: StoredCredential[]): string[] | undefined => {
88
+ const ids = [...(file.usedInvites ?? []), ...gone.map((c) => c.inviteId).filter((x): x is string => !!x)];
89
+ return ids.length ? [...new Set(ids)].slice(-500) : undefined;
90
+ };
91
+
79
92
  export function removeCredential(file: UsersFile, credentialId: string): UsersFile {
80
93
  const copy: UsersFile = structuredClone(file);
94
+ const used = keepInvites(file, file.users.flatMap((u) => u.credentials.filter((c) => c.id === credentialId)));
95
+ if (used) copy.usedInvites = used;
81
96
  for (const u of copy.users) u.credentials = u.credentials.filter((c) => c.id !== credentialId);
82
97
  copy.users = copy.users.filter((u) => u.credentials.length);
83
98
  return copy;
@@ -101,7 +116,8 @@ export function removeUser(file: UsersFile, userId: string): UsersFile {
101
116
  const user = file.users.find((u) => u.id === userId);
102
117
  if (!user) throw new Error('No such user.');
103
118
  if (roleOf(user) === 'admin' && admins(file).length === 1) throw new Error(LAST_ADMIN);
104
- return { ...file, users: file.users.filter((u) => u.id !== userId) };
119
+ const used = keepInvites(file, user.credentials);
120
+ return { ...file, users: file.users.filter((u) => u.id !== userId), ...(used ? { usedInvites: used } : {}) };
105
121
  }
106
122
 
107
123
  /** What the Users screen sees: no public keys. */
@@ -17,7 +17,7 @@ const links = [
17
17
  {links.map((l) => <a href={l.href} aria-current={l.id === current ? 'page' : undefined}>{l.label}</a>)}
18
18
  <span class="ps-nav__user">
19
19
  <a href="/edit/site" aria-current={current === 'site' ? 'page' : undefined}>Browse site</a>
20
- {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-btn--primary ps-live" hidden>Go live</button>}
20
+ {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-btn--primary ps-live" hidden>Publish changes</button>}
21
21
  {user && opts.auth === 'passkey' && <span>Signed in as <strong>{user.name}</strong> · <a href="/api/editor/auth/logout">Sign out</a></span>}
22
22
  </span>
23
23
  </nav>
@@ -37,7 +37,7 @@ export const ALL: APIRoute = async ({ params, request, url }) => {
37
37
  }
38
38
  case 'invite': {
39
39
  const s = await readSession(request.headers.get('cookie'), secret());
40
- const inviter = s && await activeUser(s.sub);
40
+ const inviter = s && await activeUser(s.sub, s.cred);
41
41
  if (!inviter) return bad('unauthenticated', 401);
42
42
  if (roleOf(inviter) !== 'admin') return bad('Only admins can invite people.', 403);
43
43
  const name = String(body.name ?? '').trim(), email = String(body.email ?? '').trim();
@@ -51,6 +51,6 @@ export const ALL: APIRoute = async ({ params, request, url }) => {
51
51
  } catch (e: any) {
52
52
  if (e instanceof AuthError) return bad(e.message, e.status);
53
53
  console.error('[pagestack] auth error', e);
54
- return bad(`authentication error: ${e?.message ?? e}`, 400);
54
+ return bad('Sign-in failed. Try again, or ask an admin for a new invite.', 400); // details stay in the log
55
55
  }
56
56
  };
@@ -43,9 +43,8 @@ const boot = {
43
43
  <span class="ps-item__actions">
44
44
  {boot.viewUrl && <a id="ps-item-view" class="ps-btn ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(boot.viewUrl)}`} title="See the saved version on the site, and click around from there">View on site</a>}
45
45
  {boot.preview && <button type="button" id="ps-item-tab" class="ps-btn ps-btn--ghost">Preview ↗</button>}
46
- <button type="button" id="ps-item-draft" class="ps-btn ps-btn--ghost" hidden>Switch to draft</button>
47
- <button type="button" id="ps-item-save" class="ps-btn" disabled>Save</button>
48
- <button type="button" id="ps-item-publish" class="ps-btn ps-btn--primary" hidden>Publish</button>
46
+ <label class="ps-switch" hidden id="ps-item-ready-wrap" title={opts.github?.live ? 'On: goes on the public site with the next Publish changes. Off: a draft, kept off the site.' : 'On: on the site after the next build. Off: a draft, kept off the site.'}><input type="checkbox" role="switch" id="ps-item-ready" /><span class="ps-switch__track" aria-hidden="true"></span><span>{opts.github?.live ? 'Ready to publish' : 'Published'}</span></label>
47
+ <button type="button" id="ps-item-save" class="ps-btn ps-btn--primary" disabled>Save</button>
49
48
  <button type="button" id="ps-item-more" class="ps-iconbtn" title="Options" aria-label="Options" data-icon="more"></button>
50
49
  </span>
51
50
  </header>
@@ -42,9 +42,9 @@ const boot = {
42
42
  <button type="button" id="ps-discard" class="ps-btn ps-btn--ghost" hidden>Discard</button>
43
43
  <button type="button" id="ps-preview-tab" class="ps-btn ps-btn--ghost" title="See this draft as visitors will, in a new tab">Preview</button>
44
44
  <a id="ps-view" class="ps-btn ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(publicPath(slug))}`} title="See the saved page on the site, and click around from there">View on site</a>
45
+ <label class="ps-switch" id="ps-ready-wrap" title={opts.github?.live ? 'On: goes on the public site with the next Publish changes. Off: a draft, kept off the site.' : 'On: on the site after the next build. Off: a draft, kept off the site.'}><input type="checkbox" role="switch" id="ps-ready" /><span class="ps-switch__track" aria-hidden="true"></span><span>{opts.github?.live ? 'Ready to publish' : 'Published'}</span></label>
45
46
  <button type="button" id="ps-save" class="ps-btn ps-btn--primary" disabled>Save</button>
46
- <button type="button" id="ps-publish" class="ps-btn ps-btn--primary" hidden>Publish</button>
47
- {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Go live</button>}
47
+ {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Publish changes</button>}
48
48
  <button type="button" id="ps-toggle-settings" class="ps-iconbtn is-active" title="Settings (⇧⌘,)" aria-label="Settings" data-icon="sidebar"></button>
49
49
  <button type="button" id="ps-more" class="ps-iconbtn" title="Options" aria-label="Options" data-icon="more"></button>
50
50
  </div>
@@ -27,7 +27,7 @@ const user = (Astro.locals as any).editorUser as { name: string } | undefined;
27
27
  </span>
28
28
  <span class="ps-browse__actions">
29
29
  <a id="ps-browse-edit" class="ps-btn ps-btn--primary" href={first.edit ?? '#'} hidden={!first.edit}>✎ Edit this page</a>
30
- {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Go live</button>}
30
+ {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Publish changes</button>}
31
31
  {user && opts.auth === 'passkey' && <a class="ps-browse__out" href="/api/editor/auth/logout">Sign out</a>}
32
32
  </span>
33
33
  </header>
@@ -4,7 +4,7 @@
4
4
  // site's static 404 page without running any of our code (Workers does), so this is a real route.
5
5
  // Signed-in editors only: drafts show these images, and visitors shouldn't spend the API quota.
6
6
  import type { APIRoute } from 'astro';
7
- import { opts, secret, storage } from '../server/context';
7
+ import { activeUser, opts, secret, storage } from '../server/context';
8
8
  import { readSession } from '../core/auth';
9
9
  import { EXT_MIME, IMAGE_RE } from '../core/media';
10
10
  export const prerender = false;
@@ -14,7 +14,10 @@ const notFound = () => new Response('Not found', { status: 404, headers: { 'cont
14
14
  export const GET: APIRoute = async ({ params, request }) => {
15
15
  const rel = params.path ?? '';
16
16
  if (!IMAGE_RE.test(rel) || rel.split('/').some((s) => s === '..' || s === '')) return notFound();
17
- if (opts.auth === 'passkey' && !(request.headers.get('cookie') && await readSession(request.headers.get('cookie'), secret()))) return notFound();
17
+ if (opts.auth === 'passkey') {
18
+ const session = await readSession(request.headers.get('cookie'), secret());
19
+ if (!session || !await activeUser(session.sub, session.cred)) return notFound(); // removed people too
20
+ }
18
21
  const bytes = await storage().asset(`${opts.uploadsDir.replace(/\/$/, '')}/${rel}`).catch(() => undefined);
19
22
  if (!bytes) return notFound();
20
23
  return new Response(bytes as BodyInit, { headers: {
@@ -148,21 +148,34 @@ export async function saveUsers(file: UsersFile, message: string) {
148
148
  return result;
149
149
  }
150
150
  const USERS_TTL = 15_000;
151
+ /** A miss may mean "saved a moment ago by another instance": re-read, but not more than this often. */
152
+ const MISS_REREAD = 5_000;
151
153
  /**
152
- * The user behind a session, so removing someone ends their sessions. Read at most every 15s; a
153
- * miss re-reads first, because a brand-new user may have been saved by another instance.
154
+ * The users file, read at most every 15s. `want` says what the caller is looking for; when it isn't
155
+ * there the file is read again (a brand-new user or passkey may have been saved elsewhere), at
156
+ * most every 5s, so requests for someone who doesn't exist can't each cost a GitHub read.
154
157
  */
155
- export async function activeUser(id: string, now = Date.now()): Promise<EditorUser | null> {
158
+ export async function cachedUsers(want: (f: UsersFile) => boolean = () => true, now = Date.now()): Promise<UsersFile> {
156
159
  if (!usersCache || now - usersCache.at > USERS_TTL) usersCache = { file: await loadUsers(), at: now };
157
- let user = usersCache.file.users.find((u) => u.id === id);
158
- if (!user && usersCache.at !== now) { usersCache = { file: await loadUsers(), at: now }; user = usersCache.file.users.find((u) => u.id === id); }
159
- return user ?? null;
160
+ if (!want(usersCache.file) && now - usersCache.at > MISS_REREAD) usersCache = { file: await loadUsers(), at: now };
161
+ return usersCache.file;
162
+ }
163
+ /**
164
+ * The user behind a session, so removing someone ends their sessions. With `credential`, the
165
+ * passkey the session was signed in with must still be on file too: removing a lost device's
166
+ * passkey ends the sessions it opened.
167
+ */
168
+ export async function activeUser(id: string, credential?: string, now = Date.now()): Promise<EditorUser | null> {
169
+ const match = (f: UsersFile) => f.users.find((u) => u.id === id && (!credential || u.credentials.some((c) => c.id === credential)));
170
+ return match(await cachedUsers((f) => !!match(f), now)) ?? null;
160
171
  }
161
172
 
162
173
  /** A commit message with the editor's name on it. */
163
174
  export function commitMessage(subject: string, locals: unknown): string {
164
175
  const name = (locals as { editorUser?: { name?: string } }).editorUser?.name;
165
- return subject + (name ? `\n\nEdited by ${name}` : '');
176
+ // A subject can come from the client: one line, and never one that claims to name the editor.
177
+ const line = subject.split(/\r?\n/)[0].replace(/^\s*edited by\b/i, 'Edit').slice(0, 120);
178
+ return line + (name ? `\n\nEdited by ${name}` : '');
166
179
  }
167
180
 
168
181
  export const pageName = (slug: string) => (slug === 'index' ? 'home page' : slug);
@@ -42,7 +42,9 @@ function harden(res: Response, url: URL, sandbox: boolean, frame = false): Respo
42
42
  h.set('x-frame-options', 'SAMEORIGIN');
43
43
  h.set('referrer-policy', 'same-origin');
44
44
  h.set('cross-origin-opener-policy', 'same-origin');
45
- h.set('content-security-policy', `frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'${sandbox ? '; sandbox allow-scripts allow-forms allow-popups' : ''}${frame ? SITE_SCRIPTS_ONLY : ''}`);
45
+ // No inline event handler attributes anywhere in the editor or the site pages it shows: the
46
+ // editor never writes them, and they are how injected markup would run.
47
+ h.set('content-security-policy', `frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'; script-src-attr 'none'${sandbox ? '; sandbox allow-scripts allow-forms allow-popups' : ''}${frame ? SITE_SCRIPTS_ONLY : ''}`);
46
48
  if ((process.env.EDITOR_ORIGIN || url.origin).startsWith('https:')) h.set('strict-transport-security', 'max-age=31536000');
47
49
  } catch { /* an immutable Response, e.g. a redirect from a host's own middleware */ }
48
50
  return res;
@@ -50,6 +52,14 @@ function harden(res: Response, url: URL, sandbox: boolean, frame = false): Respo
50
52
 
51
53
  let warned = false;
52
54
 
55
+ /** Compare secrets without an early exit, so response time says nothing about how much matched. */
56
+ function sameText(a: string, b: string): boolean {
57
+ const x = new TextEncoder().encode(a), y = new TextEncoder().encode(b);
58
+ let diff = x.length ^ y.length;
59
+ for (let i = 0; i < Math.max(x.length, y.length); i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
60
+ return diff === 0;
61
+ }
62
+
53
63
 
54
64
  export const onRequest = defineMiddleware(async (ctx, next) => {
55
65
  if (ctx.isPrerendered) return next(); // public pages, which never carry a session
@@ -84,7 +94,7 @@ export const onRequest = defineMiddleware(async (ctx, next) => {
84
94
 
85
95
  if (opts.auth === 'passkey' && !PUBLIC.some((re) => re.test(pathname))) {
86
96
  const session = await readSession(request.headers.get('cookie'), secret());
87
- const user = session && await activeUser(session.sub);
97
+ const user = session && await activeUser(session.sub, session.cred);
88
98
  if (!user) {
89
99
  // A valid session for someone who was removed ends here, without waiting for it to expire.
90
100
  const headers: Record<string, string> = session ? { 'set-cookie': clearCookieHeader(SESSION_COOKIE, ctx.url.protocol === 'https:') } : {};
@@ -97,7 +107,7 @@ export const onRequest = defineMiddleware(async (ctx, next) => {
97
107
  // oauth2-proxy, …). No identity means the request didn't come through it.
98
108
  const h = request.headers;
99
109
  const shared = process.env.EDITOR_PROXY_SECRET;
100
- if (shared && h.get('x-editor-proxy-secret') !== shared) return done(json({ error: 'not from the proxy' }, 403));
110
+ if (shared && !sameText(h.get('x-editor-proxy-secret') ?? '', shared)) return done(json({ error: 'not from the proxy' }, 403));
101
111
  const who = h.get('cf-access-authenticated-user-email') || h.get('x-forwarded-user') || h.get('x-forwarded-email');
102
112
  if (!who && opts.command === 'build') return done(json({ error: 'no identity from the proxy' }, 401));
103
113
  if (who) ctx.locals.editorUser = { id: who, name: who, role: 'admin' };
@@ -3,7 +3,7 @@
3
3
  // server-side state is the committed users file (public keys) read/written through storage.
4
4
  import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from '@simplewebauthn/server';
5
5
  import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server';
6
- import { loadUsers, opts, secret, saveUsers } from './context';
6
+ import { cachedUsers, loadUsers, opts, secret, saveUsers } from './context';
7
7
  import { b64url, createChallengeToken, createSession, readChallengeToken, readInvite, unb64url, type InvitePayload } from '../core/auth';
8
8
  import { addCredential, findByCredential, findByEmail, inviteUsed, type StoredCredential } from '../core/users';
9
9
 
@@ -31,8 +31,8 @@ export async function loginVerify(url: URL, token: string, response: Authenticat
31
31
  const { origin, rpID } = relyingParty(url);
32
32
  const ch = await readChallengeToken(token, secret());
33
33
  if (!ch || ch.purpose !== 'login') throw new AuthError('The sign-in attempt expired. Try again.');
34
- const users = await loadUsers();
35
- const found = findByCredential(users, response.id);
34
+ const id = String(response?.id ?? '');
35
+ const found = findByCredential(await cachedUsers((f) => !!findByCredential(f, id)), id);
36
36
  if (!found) throw new AuthError('This passkey is not registered for this site.');
37
37
  const { verified } = await verifyAuthenticationResponse({
38
38
  response, expectedChallenge: ch.challenge, expectedOrigin: origin, expectedRPID: rpID,
@@ -41,7 +41,7 @@ export async function loginVerify(url: URL, token: string, response: Authenticat
41
41
  if (!verified) throw new AuthError('Passkey verification failed.');
42
42
  // The signature counter is deliberately not persisted: it would mean a commit per login, and
43
43
  // synced passkeys (iCloud Keychain, Google Password Manager) always report 0 anyway.
44
- return { user: found.user, session: await createSession({ id: found.user.id, name: found.user.name }, secret()) };
44
+ return { user: found.user, session: await createSession({ id: found.user.id, name: found.user.name }, secret(), found.credential.id) };
45
45
  }
46
46
 
47
47
  export async function registerOptions(url: URL, inviteToken: string) {
@@ -83,7 +83,7 @@ export async function registerVerify(url: URL, token: string, response: Registra
83
83
  };
84
84
  const { file, user } = addCredential(users, invite, credential);
85
85
  const commit = await saveUsers(file, `Add passkey for ${user.name} (site editor)`);
86
- return { user, commit, session: await createSession({ id: user.id, name: user.name }, secret()) };
86
+ return { user, commit, session: await createSession({ id: user.id, name: user.name }, secret(), credential.id) };
87
87
  } finally { claimed.delete(invite.id); }
88
88
  }
89
89
  const claimed = new Set<string>();
@@ -1,10 +0,0 @@
1
- // Serves a staged (uncommitted) upload in github mode by repo path; the middleware handles the
2
- // public URL form (routes/uploaded.ts). Kept as an explicit endpoint for debugging.
3
- import type { APIRoute } from 'astro';
4
- import { bad, storage } from '../../server/context';
5
- export const prerender = false;
6
- export const GET: APIRoute = async ({ params }) => {
7
- const bytes = await storage().asset(params.path ?? '');
8
- if (!bytes) return bad('not staged', 404);
9
- return new Response(bytes, { headers: { 'cache-control': 'no-store' } });
10
- };