@pirateandfox/pagestack 0.1.0-beta.12 → 0.1.0-beta.14

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
@@ -217,8 +217,10 @@ A few things worth knowing while you set up the schema:
217
217
  (`src/sections/components.ts`) so the schema stays plain data.
218
218
  - **List View names a block after its first non-empty inline text field**, so put the field people
219
219
  recognise (the title) first.
220
- - **`text` fields are plain text.** Typing in them replaces any markup they held. For a styled word
221
- in a heading, give the block its own field for it (the bakery's hero has *Word in italics*).
220
+ - **`text` fields are plain text, unless you add `marks: true`.** With it, the field allows bold
221
+ and italic, as a WordPress heading does: select words and press **B** / **I** (or ⌘B / ⌘I) on the
222
+ page or in the sidebar. The value is then HTML holding only `<strong>` and `<em>` (everything else
223
+ is removed on save), so render it with `set:html`. The bakery's section titles use it.
222
224
  - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
223
225
 
224
226
  ## Editing
@@ -405,6 +407,8 @@ than setting a hard limit. Passkeys are what actually stops guessing.
405
407
  With `github.live`, saves stay on `github.branch` (staging) and the public site builds from `live`.
406
408
  Every screen gets a **Publish changes** button (Go live) counting the saved changes the live site doesn't have yet;
407
409
  it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
410
+ Only admins can publish; editors see what's waiting, and their saves stay on staging until an admin
411
+ publishes.
408
412
  That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
409
413
  commit and moves staging to it; when their change conflicts, it refuses and says so, and a person
410
414
  merges in GitHub. A burst of saves becomes one production build. Drafts (the **Ready to publish**
@@ -432,7 +436,9 @@ like any other push.
432
436
  invite links (3 days). Tokens are `base64url(json).base64url(hmac-sha256)` with the expiry inside,
433
437
  so there is no server state.
434
438
  - **Invites** are single-use: the invite id is recorded on the credential it created. Make the first
435
- one from the CLI, later ones from the "Invite another editor" panel on `/edit`:
439
+ one from the CLI, later ones from **Users** (`/edit/users`), which lists invites not used yet and
440
+ lets an admin withdraw one; a withdrawn link stops working at once. Links made with the CLI aren't
441
+ listed there.
436
442
 
437
443
  ```bash
438
444
  EDITOR_SECRET=… npx pagestack-invite --name "Jane Doe" --email jane@example.com --origin https://example.com
@@ -442,6 +448,10 @@ like any other push.
442
448
  - Set `EDITOR_ORIGIN` when a proxy rewrites `Host`; WebAuthn binds credentials to the origin the
443
449
  browser sees.
444
450
  - The signature counter is not persisted (it would mean a commit per login; synced passkeys report 0).
451
+ - Changes to the users file are conditional: when two of them race (two admins, or an invite used
452
+ while an admin edits roles), the later one is re-read and re-applied, so neither is lost.
453
+ - Signing out is a POST from the editor's own pages. Opening `/api/editor/auth/logout` from a link
454
+ only shows a Sign out button, so another site can't sign anyone out.
445
455
 
446
456
  ### `auth: "none-behind-proxy"`
447
457
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.12",
3
+ "version": "0.1.0-beta.14",
4
4
  "description": "A block editor for Astro sites. Content stays in your repo, saves are git commits, the public site stays static, sign-in is passkeys.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -4,7 +4,7 @@ import type { Field, Node, PageDoc, SchemaRegistry } from '../runtime';
4
4
  import { cloneWithNewIds } from '../runtime';
5
5
  import { getAt, insertNode, isNodePath, moveNode, nodeAt, nodePathOf, pathOfId, removeNode, replaceNode, setAt, splitNodePath } from '../core/patch';
6
6
  import { transformNode, transformTargets } from '../core/transform';
7
- import { accepts, allowedChildTypes, createNode, nodeLabel } from '../core/schema';
7
+ import { accepts, allowedChildTypes, createNode, fieldOf, nodeLabel } from '../core/schema';
8
8
  import type { InsertItem, Pattern, SavedPattern } from '../core/insert';
9
9
  import { insertItems } from '../core/insert';
10
10
  import { slugProblem } from '../core/pages';
@@ -118,6 +118,11 @@ function onPreviewClick(e: MouseEvent) {
118
118
 
119
119
  const inline = new InlineEditor({
120
120
  onSlash: (fieldPath) => slash(fieldPath),
121
+ marks: (fieldPath) => {
122
+ const nodePath = nodePathOf(fieldPath);
123
+ const node: Node | undefined = getAt(state.doc, nodePath);
124
+ return !!(node && fieldOf(registry[node.type], fieldPath.slice(nodePath.length + '.settings.'.length))?.marks);
125
+ },
121
126
  pages: pageLinks,
122
127
  onStart: () => { state.snapshot(); idoc().body.setAttribute('data-ps-typing', ''); },
123
128
  onInput: (path, value) => { state.apply(setAt(state.doc, path, value), 'inline', false); refreshButtons(); },
@@ -784,7 +789,7 @@ $('#ps-more').addEventListener('click', (e) => {
784
789
  { label: 'Revisions', run: showRevisions },
785
790
  { label: 'All pages', run: () => { location.href = '/edit'; }, separator: true },
786
791
  ];
787
- if (boot.options.auth === 'passkey' && boot.options.user) items.push({ label: `Sign out ${boot.options.user}`, run: () => { location.href = '/api/editor/auth/logout'; } });
792
+ if (boot.options.auth === 'passkey' && boot.options.user) items.push({ label: `Sign out ${boot.options.user}`, run: async () => { await fetch('/api/editor/auth/logout', { method: 'POST', headers: { accept: 'application/json' } }).catch(() => {}); location.href = '/edit/login'; } });
788
793
  openMenu(e.currentTarget as HTMLElement, items);
789
794
  });
790
795
 
@@ -1,7 +1,7 @@
1
1
  // Schema -> sidebar form. One widget per field type; changes are reported through `onChange`.
2
2
  import type { BlockSchema, Field, ImageValue } from '../runtime';
3
3
  import { formModel } from '../core/schema';
4
- import { richField } from './rich';
4
+ import { marksField, richField } from './rich';
5
5
 
6
6
  export interface FormCallbacks {
7
7
  onChange: (name: string, value: unknown, opts?: { live?: boolean }) => void;
@@ -40,6 +40,11 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
40
40
  // `cancel` matters: a live update landing after `change` would reorder the edit and split its undo step.
41
41
  const debounce = (fn: () => void, ms = 250) => { let t: ReturnType<typeof setTimeout>; const run = () => { clearTimeout(t); t = setTimeout(fn, ms); }; run.cancel = () => clearTimeout(t); return run; };
42
42
 
43
+ if (field.type === 'text' && field.marks) {
44
+ wrap.append(marksField(id, (value as string) ?? '', (html, live) => cb.onChange(name, html, { live })));
45
+ if (help) wrap.append(help);
46
+ return wrap;
47
+ }
43
48
  switch (field.type) {
44
49
  case 'text':
45
50
  case 'link': {
@@ -1,9 +1,11 @@
1
1
  // In-page editing of text / richtext fields inside the preview iframe.
2
2
  // - text: contenteditable="plaintext-only", Enter commits, Escape reverts.
3
+ // - text with `marks`: one line too, with just bold and italic (headings).
3
4
  // - richtext: contenteditable with the floating formatting toolbar.
4
5
  // Edits stream to `onInput` (silent draft updates); `onCommit` fires on blur.
5
6
  import type { PageLink } from './rich';
6
- import { cleanPaste, exec, linkPopover, richToolbar } from './rich';
7
+ import { sanitizeMarks } from '../core/sanitize';
8
+ import { cleanPaste, exec, linkPopover, markKey, marksPaste, marksToolbar, richToolbar } from './rich';
7
9
 
8
10
  export interface InlineCallbacks {
9
11
  onStart: (fieldPath: string) => void;
@@ -11,6 +13,8 @@ export interface InlineCallbacks {
11
13
  onCommit: (fieldPath: string, value: string, changed: boolean) => void;
12
14
  /** `/` typed in an empty field: the block inserter takes over. */
13
15
  onSlash?: (fieldPath: string) => void;
16
+ /** Is this text field allowed bold and italic (`marks` in its schema)? */
17
+ marks?: (fieldPath: string) => boolean;
14
18
  pages?: PageLink[];
15
19
  }
16
20
 
@@ -25,8 +29,9 @@ export class InlineEditor {
25
29
  if (this.active?.el === el) return;
26
30
  this.stop();
27
31
  const path = el.dataset.psField!;
28
- const type = el.dataset.psFieldType!;
32
+ let type = el.dataset.psFieldType!;
29
33
  if (type !== 'text' && type !== 'richtext') return;
34
+ if (type === 'text' && this.cb.marks?.(path)) type = 'marks';
30
35
  const original = el.innerHTML;
31
36
  this.active = { el, path, type, original };
32
37
  el.setAttribute('contenteditable', type === 'text' ? 'plaintext-only' : 'true');
@@ -34,13 +39,13 @@ export class InlineEditor {
34
39
  el.addEventListener('input', this.onInput);
35
40
  el.addEventListener('keydown', this.onKey);
36
41
  el.addEventListener('blur', this.onBlur);
37
- if (type === 'richtext') el.addEventListener('paste', this.onPaste);
42
+ if (type !== 'text') el.addEventListener('paste', this.onPaste);
38
43
  el.focus();
39
44
  const doc = el.ownerDocument;
40
45
  // caret at end
41
46
  const range = doc.createRange(); range.selectNodeContents(el); range.collapse(false);
42
47
  const sel = doc.getSelection(); sel?.removeAllRanges(); sel?.addRange(range);
43
- if (type === 'richtext') this.mountToolbar(el);
48
+ if (type !== 'text') this.mountToolbar(el);
44
49
  this.cb.onStart(path);
45
50
  }
46
51
 
@@ -64,16 +69,18 @@ export class InlineEditor {
64
69
  private parse(html: string, like: HTMLElement) { const t = like.ownerDocument.createElement(like.tagName); t.innerHTML = html; return t; }
65
70
  private read(el: HTMLElement, type: string): string {
66
71
  if (type === 'text') return el.textContent?.replace(/ /g, ' ') ?? '';
72
+ if (type === 'marks') return sanitizeMarks(el.innerHTML);
67
73
  return el.innerHTML.trim();
68
74
  }
69
75
 
70
76
  private onInput = () => { const a = this.active; if (a) this.cb.onInput(a.path, this.read(a.el, a.type)); };
71
- private onPaste = (e: ClipboardEvent) => { const a = this.active; if (a) cleanPaste(e, a.el, this.onInput); };
77
+ private onPaste = (e: ClipboardEvent) => { const a = this.active; if (a) (a.type === 'marks' ? marksPaste : cleanPaste)(e, a.el, this.onInput); };
72
78
  private onKey = (e: KeyboardEvent) => {
73
79
  const a = this.active; if (!a) return;
74
80
  if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.stop(false); return; }
75
- if (e.key === 'Enter' && a.type === 'text') { e.preventDefault(); a.el.blur(); return; }
81
+ if (e.key === 'Enter' && a.type !== 'richtext') { e.preventDefault(); a.el.blur(); return; }
76
82
  if (e.key === '/' && !a.el.textContent?.trim() && this.cb.onSlash) { e.preventDefault(); this.cb.onSlash(a.path); return; }
83
+ if (a.type === 'marks') { markKey(e, a.el, this.onInput); return; }
77
84
  if ((e.metaKey || e.ctrlKey) && a.type === 'richtext') {
78
85
  const k = e.key.toLowerCase();
79
86
  const cmd = ({ b: 'bold', i: 'italic', u: 'underline' } as Record<string, string>)[k];
@@ -89,7 +96,7 @@ export class InlineEditor {
89
96
 
90
97
  private mountToolbar(el: HTMLElement) {
91
98
  const doc = el.ownerDocument;
92
- const tb = richToolbar(el, this.richOptions());
99
+ const tb = this.active!.type === 'marks' ? marksToolbar(el, this.onInput, 'Esc cancels') : richToolbar(el, this.richOptions());
93
100
  doc.body.append(tb);
94
101
  this.active!.toolbar = tb;
95
102
  this.place();
@@ -14,4 +14,5 @@ form?.addEventListener('submit', async (e) => {
14
14
  copy.addEventListener('click', async () => { await navigator.clipboard.writeText(data.url); copy.textContent = 'Copied'; });
15
15
  const hint = Object.assign(document.createElement('small'), { className: 'ps-muted', textContent: `Send this link to ${fd.get('name')}. It works once and expires in ${Math.round(data.expiresIn / 86400)} days.` });
16
16
  out.append(input, copy, hint);
17
+ document.dispatchEvent(new CustomEvent('ps:invited'));
17
18
  });
@@ -3,7 +3,7 @@
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';
5
5
 
6
- interface Pending { enabled: true; branch: string; live: string; count: number; changes: { sha: string; message: string; author: string; date: string }[]; stagingUrl: string | null }
6
+ interface Pending { enabled: true; branch: string; live: string; count: number; changes: { sha: string; message: string; author: string; date: string }[]; stagingUrl: string | null; canPublish?: boolean }
7
7
 
8
8
  const btn = document.getElementById('ps-live') as HTMLButtonElement | null;
9
9
  let state: Pending | null = null;
@@ -24,7 +24,8 @@ function draw() {
24
24
  btn.disabled = n === 0;
25
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
- btn.title = n ? `${n} saved change${n === 1 ? '' : 's'} not on the live site yet` : 'Everything saved is on the live site';
27
+ btn.title = !n ? 'Everything saved is on the live site'
28
+ : `${n} saved change${n === 1 ? '' : 's'} not on the live site yet${state.canPublish === false ? '. An admin publishes them.' : ''}`;
28
29
  }
29
30
 
30
31
  let inflight: Promise<void> | null = null;
@@ -54,6 +55,7 @@ async function goLive() {
54
55
  const meta = document.createElement('span'); meta.className = 'ps-muted'; meta.textContent = [c.author, ago(c.date)].filter(Boolean).join(' · ');
55
56
  li.append(what, meta); list.append(li);
56
57
  }
58
+ if (state.canPublish === false) intro.textContent = `${state.count} saved change${state.count === 1 ? ' is' : 's are'} waiting for the public site. Only an admin can publish them; nothing is lost in the meantime.`;
57
59
  body.append(intro, list);
58
60
  if (state.count > state.changes.length) { const more = document.createElement('p'); more.className = 'ps-muted'; more.textContent = `…and ${state.count - state.changes.length} earlier.`; body.append(more); }
59
61
  if (state.stagingUrl) {
@@ -61,6 +63,7 @@ async function goLive() {
61
63
  a.href = state.stagingUrl; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'See them on the staging site first ↗';
62
64
  p.append(a); body.append(p);
63
65
  }
66
+ if (state.canPublish === false) { dialog('Waiting to publish', body, [{ label: 'Close', kind: 'primary' }], { wide: true }); return; }
64
67
  dialog('Publish changes?', body, [
65
68
  { label: 'Cancel' },
66
69
  {
@@ -62,3 +62,6 @@ body[data-ps-typing] .ps-toolbar { display: none; }
62
62
  .ps-popmenu button.is-danger { color: #b91c1c; }
63
63
  .ps-popmenu kbd { font: inherit; color: #6b7280; }
64
64
  .ps-popmenu hr { width: 100%; border: 0; border-top: 1px solid #e2e4e8; margin: 4px 0; }
65
+
66
+ /* Astro's dev toolbar belongs to the site's developer, not the person editing in the preview. */
67
+ astro-dev-toolbar { display: none !important; }
@@ -1,6 +1,6 @@
1
1
  // Rich text formatting, shared by in-page editing and the sidebar: the toolbar, the link popover
2
2
  // and clean paste. Everything acts on one contenteditable element, in whichever document it lives.
3
- import { safeUrl, sanitizeHtml } from '../core/sanitize';
3
+ import { safeUrl, sanitizeHtml, sanitizeMarks } from '../core/sanitize';
4
4
 
5
5
  export interface PageLink { url: string; title: string }
6
6
  export interface RichOptions { pages?: PageLink[]; onChange: () => void; hint?: string }
@@ -230,3 +230,115 @@ export function richField(id: string, value: string, onChange: (html: string, li
230
230
  box.append(bar, body, source);
231
231
  return box;
232
232
  }
233
+
234
+ // ---- Bold and italic in one line (text fields with `marks`) ----
235
+ // Headings are usually bold already, and the browser's own bold command "unbolds" them with inline
236
+ // styles we strip, so these two marks are applied by hand: wrap the selection, or unwrap the mark it's in.
237
+
238
+ const MARK_TAGS = { bold: ['STRONG', 'B'], italic: ['EM', 'I'] } as const;
239
+ type Mark = keyof typeof MARK_TAGS;
240
+
241
+ function markAt(target: HTMLElement, mark: Mark, node: Node | null | undefined): HTMLElement | null {
242
+ for (let n = node; n && n !== target; n = n.parentNode) if (n.nodeType === 1 && (MARK_TAGS[mark] as readonly string[]).includes((n as Element).tagName)) return n as HTMLElement;
243
+ return null;
244
+ }
245
+
246
+ /** Wraps the selection in <strong>/<em>, or takes the mark off when the selection is already inside one. */
247
+ export function toggleMark(target: HTMLElement, mark: Mark): boolean {
248
+ const doc = target.ownerDocument;
249
+ const sel = doc.getSelection();
250
+ if (!sel?.rangeCount) return false;
251
+ const range = sel.getRangeAt(0);
252
+ if (!target.contains(range.commonAncestorContainer)) return false;
253
+ const inside = markAt(target, mark, range.commonAncestorContainer);
254
+ if (inside) {
255
+ const first = inside.firstChild, last = inside.lastChild;
256
+ inside.replaceWith(...inside.childNodes);
257
+ if (first && last) { const r = doc.createRange(); r.setStartBefore(first); r.setEndAfter(last); sel.removeAllRanges(); sel.addRange(r); }
258
+ target.normalize();
259
+ return true;
260
+ }
261
+ if (range.collapsed) return false;
262
+ const frag = range.extractContents();
263
+ frag.querySelectorAll(MARK_TAGS[mark].join(',')).forEach((el) => el.replaceWith(...el.childNodes));
264
+ const wrap = doc.createElement(mark === 'bold' ? 'strong' : 'em');
265
+ wrap.append(frag);
266
+ range.insertNode(wrap);
267
+ const r = doc.createRange(); r.selectNodeContents(wrap); sel.removeAllRanges(); sel.addRange(r);
268
+ return true;
269
+ }
270
+
271
+ /** Just B and I, for one line. */
272
+ export function marksToolbar(target: HTMLElement, onChange: () => void, hint?: string): HTMLElement {
273
+ const doc = target.ownerDocument;
274
+ const bar = doc.createElement('div');
275
+ bar.setAttribute('data-ps-toolbar', '');
276
+ bar.className = 'ps-rt ps-rt--marks';
277
+ for (const b of BUTTONS.filter((x) => x.cmd === 'bold' || x.cmd === 'italic')) {
278
+ const el = doc.createElement('button');
279
+ el.type = 'button'; el.title = b.title; el.setAttribute('aria-label', b.title); el.dataset.cmd = b.cmd;
280
+ el.innerHTML = b.html;
281
+ bar.append(el);
282
+ }
283
+ if (hint) { const h = doc.createElement('span'); h.className = 'ps-rt__hint'; h.textContent = hint; bar.append(h); }
284
+ const sync = () => {
285
+ if (!bar.isConnected) { doc.removeEventListener('selectionchange', sync); return; }
286
+ const n = doc.getSelection()?.anchorNode;
287
+ if (!n || !target.contains(n)) return;
288
+ bar.querySelectorAll<HTMLButtonElement>('button[data-cmd]').forEach((b) => b.classList.toggle('is-on', !!markAt(target, b.dataset.cmd as Mark, n)));
289
+ };
290
+ bar.addEventListener('mousedown', (e) => e.preventDefault());
291
+ bar.addEventListener('click', (e) => {
292
+ const b = (e.target as HTMLElement).closest<HTMLButtonElement>('button[data-cmd]');
293
+ if (!b) return;
294
+ e.preventDefault();
295
+ target.focus();
296
+ if (toggleMark(target, b.dataset.cmd as Mark)) onChange();
297
+ sync();
298
+ });
299
+ doc.addEventListener('selectionchange', sync);
300
+ return bar;
301
+ }
302
+
303
+ /** ⌘B / ⌘I in a one-line field. True when the key was handled. */
304
+ export function markKey(e: KeyboardEvent, target: HTMLElement, onChange: () => void): boolean {
305
+ if (!(e.metaKey || e.ctrlKey)) return false;
306
+ const mark = ({ b: 'bold', i: 'italic' } as Record<string, Mark>)[e.key.toLowerCase()];
307
+ if (!mark) return false;
308
+ e.preventDefault();
309
+ if (toggleMark(target, mark)) onChange();
310
+ return true;
311
+ }
312
+
313
+ /** Paste into one line: bold and italic survive, everything else becomes plain words. */
314
+ export function marksPaste(e: ClipboardEvent, target: HTMLElement, onChange: () => void) {
315
+ const data = e.clipboardData;
316
+ if (!data) return;
317
+ e.preventDefault();
318
+ const html = data.getData('text/html');
319
+ const esc = (t: string) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
320
+ const clean = html ? sanitizeMarks(html.replace(/<b[^>]*docs-internal-guid[^>]*>/i, '')) : esc(data.getData('text/plain').replace(/\s+/g, ' ').trim());
321
+ target.ownerDocument.execCommand('insertHTML', false, clean || ' ');
322
+ onChange();
323
+ }
324
+
325
+ /** The sidebar's version of a text field with `marks`: one line you can make bold or italic. */
326
+ export function marksField(id: string, value: string, onChange: (html: string, live: boolean) => void): HTMLElement {
327
+ const box = document.createElement('div');
328
+ box.className = 'ps-rich ps-rich--line';
329
+ const body = document.createElement('div');
330
+ body.id = id; body.className = 'ps-rich__body'; body.contentEditable = 'true'; body.setAttribute('role', 'textbox');
331
+ body.innerHTML = sanitizeMarks(value);
332
+ let last = body.innerHTML, timer: ReturnType<typeof setTimeout> | undefined;
333
+ const emit = (live: boolean) => { clearTimeout(timer); const html = sanitizeMarks(body.innerHTML); if (html !== last) { last = html; onChange(html, live); } };
334
+ const changed = () => { clearTimeout(timer); timer = setTimeout(() => emit(true), 250); };
335
+ body.addEventListener('input', changed);
336
+ body.addEventListener('blur', () => emit(false));
337
+ body.addEventListener('paste', (e) => marksPaste(e, body, changed));
338
+ body.addEventListener('keydown', (e) => {
339
+ if (e.key === 'Enter') { e.preventDefault(); emit(false); return; }
340
+ markKey(e, body, () => emit(true));
341
+ });
342
+ box.append(marksToolbar(body, () => emit(true)), body);
343
+ return box;
344
+ }
@@ -226,6 +226,7 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
226
226
  .ps-rich .ps-rt button:hover { background: #e8ebf0; }
227
227
  .ps-rich .ps-rt button.is-on { background: #e8efff; color: var(--ps-accent); }
228
228
  .ps-rich__body { min-height: 96px; max-height: 320px; overflow: auto; padding: 6px 8px; outline: none; font-size: 13px; }
229
+ .ps-rich--line .ps-rich__body { min-height: 0; white-space: nowrap; overflow-x: auto; }
229
230
  .ps-rich__body:focus { box-shadow: inset 0 0 0 1px var(--ps-accent); }
230
231
  .ps-rich__body > :first-child { margin-top: 0; } .ps-rich__body > :last-child { margin-bottom: 0; }
231
232
  .ps-rich textarea { border: 0 !important; border-radius: 0 0 6px 6px !important; }
@@ -332,8 +333,12 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
332
333
  .ps-browse__actions { display: flex; align-items: center; gap: 10px; }
333
334
  .ps-browse__actions .ps-btn { padding: 5px 12px; }
334
335
  .ps-browse__actions .ps-live:not(.ps-btn--primary) { background: transparent; color: #fff; border-color: #4b5563; }
335
- .ps-browse__out { color: #9ca3af; text-decoration: none; }
336
- .ps-browse__out:hover { color: #fff; }
336
+ /* Sign out is a form (a POST), drawn as a link. */
337
+ .ps-signout { display: inline; margin: 0; }
338
+ .ps-signout button { all: unset; cursor: pointer; color: inherit; text-decoration: underline; }
339
+ .ps-signout button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
340
+ .ps-browse__out button { color: #9ca3af; text-decoration: none; }
341
+ .ps-browse__out button:hover { color: #fff; }
337
342
  .ps-browse__frame { width: 100%; height: 100%; border: 0; background: #fff; grid-row: 2; grid-column: 1; }
338
343
  /* While the frame loads: a moving strip under the bar and a word in the middle, not a blank page. */
339
344
  .ps-browse__bar { position: relative; }
@@ -361,3 +366,8 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
361
366
  .ps-switch input:focus-visible + .ps-switch__track { outline: 2px solid #2563eb; outline-offset: 2px; }
362
367
  .ps-switch:has(input:disabled) { cursor: default; opacity: .6; }
363
368
  @media (prefers-reduced-motion: reduce) { .ps-switch__track, .ps-switch__track::after { transition: none; } }
369
+
370
+ /* Users: invites not used yet */
371
+ .ps-invites { margin: 28px 0 8px; }
372
+ .ps-invites[hidden] { display: none; }
373
+ .ps-invites h2 { font-size: 15px; font-weight: 600; margin: 0 0 8px; }
@@ -1,17 +1,21 @@
1
- // The Users screen.
1
+ // The Users screen: people, their passkeys, and invites not used yet.
2
2
  import { confirmDialog, toast } from './ui';
3
3
 
4
4
  interface Passkey { id: string; label: string | null; createdAt: string; synced: boolean }
5
5
  interface User { id: string; name: string; email: string; role: 'admin' | 'editor'; passkeys: Passkey[] }
6
+ interface Invite { id: string; name: string; email: string; role: 'admin' | 'editor'; createdAt: string; expiresAt: string; by?: string }
6
7
  const list = document.getElementById('ps-users')!;
8
+ const waiting = document.getElementById('ps-invites');
7
9
 
8
10
  async function call(method: string, body?: unknown) {
9
11
  const res = await fetch('/api/editor/users', { method, headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
10
12
  const data = await res.json();
11
13
  if (!res.ok) { toast(data.error || 'That did not work.', 'error'); return load(); }
12
- draw(data.users);
14
+ draw(data.users); drawInvites(data.invites ?? []);
13
15
  }
14
- async function load() { const r = await fetch('/api/editor/users'); draw((await r.json()).users ?? []); }
16
+ async function load() { const r = await fetch('/api/editor/users'); const d = await r.json(); draw(d.users ?? []); drawInvites(d.invites ?? []); }
17
+ // The invite form says when it made a new link.
18
+ document.addEventListener('ps:invited', () => { load(); });
15
19
 
16
20
  const text = (tag: string, s: string, cls?: string) => { const e = document.createElement(tag); e.textContent = s; if (cls) e.className = cls; return e; };
17
21
 
@@ -37,4 +41,24 @@ function draw(users: User[]) {
37
41
  return li;
38
42
  }));
39
43
  }
44
+
45
+ function timeLeft(iso: string): string {
46
+ const h = Math.max(0, Math.round((Date.parse(iso) - Date.now()) / 3_600_000));
47
+ return h >= 24 ? `${Math.round(h / 24)} day${Math.round(h / 24) === 1 ? '' : 's'} left` : `${h} h left`;
48
+ }
49
+
50
+ function drawInvites(invites: Invite[]) {
51
+ if (!waiting) return;
52
+ waiting.hidden = !invites.length;
53
+ waiting.querySelector('ul')!.replaceChildren(...invites.map((i) => {
54
+ const li = document.createElement('li'); li.dataset.invite = i.email;
55
+ const who = document.createElement('div'); who.className = 'ps-pagelist__edit';
56
+ who.append(text('strong', i.name), text('span', [i.email, i.role === 'admin' ? 'Admin' : 'Editor', timeLeft(i.expiresAt), i.by ? `invited by ${i.by}` : ''].filter(Boolean).join(' · '), 'ps-muted'));
57
+ const del = text('button', 'Withdraw', 'ps-btn ps-btn--small ps-btn--ghost ps-btn--danger') as HTMLButtonElement; del.type = 'button';
58
+ del.addEventListener('click', async () => { if (await confirmDialog('Withdraw invite', `The link sent to ${i.name} stops working at once. You can invite them again later.`, 'Withdraw', 'danger')) call('DELETE', { invite: i.id }); });
59
+ li.append(who, del);
60
+ return li;
61
+ }));
62
+ }
63
+
40
64
  load();
@@ -202,6 +202,17 @@ export function sanitizeHtml(html: string, { paste = false }: { paste?: boolean
202
202
  return paste ? out.replace(/<p>(\s|&nbsp;|<br>)*<\/p>/g, '').trim() : out;
203
203
  }
204
204
 
205
+ const MARK = { b: 'strong', strong: 'strong', i: 'em', em: 'em' } as Record<string, string>;
206
+ /** One line with bold and italic only (a text field with `marks`): every other tag goes, its text stays. */
207
+ export function sanitizeMarks(html: string): string {
208
+ return sanitizeHtml(html)
209
+ .replace(/<(\/?)([a-zA-Z][\w-]*)[^>]*>/g, (_, close, tag) => { const t = MARK[tag.toLowerCase()]; return t ? `<${close}${t}>` : tag.toLowerCase() === 'br' ? ' ' : ''; })
210
+ .replace(/<(strong|em)>(\s*)<\/\1>/g, '$2')
211
+ .replace(/&nbsp;/g, ' ')
212
+ .replace(/\s+/g, ' ')
213
+ .trim();
214
+ }
215
+
205
216
  /** Text with no markup at all, for values that end up in `<title>` and `<meta>`. */
206
217
  export const plainText = (s: string) => s.replace(/<!--[\s\S]*?(-->|$)/g, '').replace(/<\/?[a-zA-Z][^>]*>?/g, '').replace(/</g, '');
207
218
 
@@ -248,7 +259,9 @@ function cleanField(v: any, field: Field, o: CleanOptions): any {
248
259
  return typeof v === 'string' ? sanitizeSvg(v) : undefined;
249
260
  case 'code':
250
261
  return typeof v !== 'string' || o.rawOk?.(v) ? v : sanitizeHtml(v);
251
- default: // text, textarea, richtext
262
+ case 'text':
263
+ return cleanDeep(v, field.marks ? sanitizeMarks : sanitizeHtml);
264
+ default: // textarea, richtext
252
265
  return cleanDeep(v, sanitizeHtml);
253
266
  }
254
267
  }
@@ -45,6 +45,22 @@ export function inlineFields(schema: BlockSchema): string[] {
45
45
  return Object.entries(schema.fields).filter(([, f]) => f.inline).map(([k]) => k);
46
46
  }
47
47
 
48
+ /**
49
+ * The field a path inside a node's settings names: `title`, or `items.2.label` through a list's rows.
50
+ * Undefined for anything the schema doesn't describe.
51
+ */
52
+ export function fieldOf(schema: BlockSchema | undefined, settingsPath: string): Field | undefined {
53
+ let fields = schema?.fields;
54
+ let f: Field | undefined;
55
+ for (const key of settingsPath.split('.')) {
56
+ if (/^\d+$/.test(key)) { if (f?.type !== 'list') return undefined; continue; }
57
+ f = fields && Object.hasOwn(fields, key) ? fields[key] : undefined;
58
+ if (!f) return undefined;
59
+ fields = f.fields;
60
+ }
61
+ return f;
62
+ }
63
+
48
64
  /** Validate a document against the registry. Returns human-readable problems (empty = ok). */
49
65
  export function validateDoc(doc: unknown, registry: SchemaRegistry): string[] {
50
66
  const errors: string[] = [];
@@ -8,7 +8,7 @@
8
8
  // branch goes away. Keeping them in the repo rather than in memory means an upload and the save
9
9
  // after it can land on different server instances (Workers), and a restart loses nothing.
10
10
  import type { CommitResult, FileChange, PendingChanges, Revision, Storage } from './storage';
11
- import { fromBase64, isSha, safeRelPath, toBase64 } from './storage';
11
+ import { fromBase64, isSha, safeRelPath, StaleWrite, toBase64 } from './storage';
12
12
 
13
13
  export interface GitHubOptions {
14
14
  /** "owner/name" */
@@ -199,13 +199,16 @@ export class GitHubStorage implements Storage {
199
199
  }
200
200
 
201
201
  async readAt(p: string, sha: string): Promise<string | null> {
202
- if (!isSha(sha)) return null;
203
- const data = await this.req<any>('GET', `${this.repoUrl}/contents/${encodePath(safeRelPath(p))}?ref=${sha}`, undefined, true);
202
+ return isSha(sha) ? this.textAt(p, sha) : null;
203
+ }
204
+ /** `ref` here is trusted: a branch name or a sha this adapter got from GitHub itself. */
205
+ private async textAt(p: string, ref: string): Promise<string | null> {
206
+ const data = await this.req<any>('GET', `${this.repoUrl}/contents/${encodePath(safeRelPath(p))}?ref=${encodeURIComponent(ref)}`, undefined, true);
204
207
  if (!data || data.type !== 'file') return null;
205
208
  return new TextDecoder().decode(fromBase64(String(data.content).replace(/\n/g, '')));
206
209
  }
207
210
 
208
- async commit({ message, files, deletes = [] }: { message: string; files: FileChange[]; deletes?: string[] }): Promise<CommitResult> {
211
+ async commit({ message, files, deletes = [], expect }: { message: string; files: FileChange[]; deletes?: string[]; expect?: Record<string, string | null> }): Promise<CommitResult> {
209
212
  const all: FileChange[] = files.map((f) => ({ ...f, path: safeRelPath(f.path) }));
210
213
  const removed = deletes.map(safeRelPath);
211
214
  const uploads = (await this.waiting()).filter((u) => !removed.includes(u.path));
@@ -213,6 +216,9 @@ export class GitHubStorage implements Storage {
213
216
  const base = await this.req<any>('GET', `${this.repoUrl}/git/ref/heads/${encodeURIComponent(this.branch)}`);
214
217
  const baseSha: string = base.object.sha;
215
218
  const baseCommit = await this.req<any>('GET', `${this.repoUrl}/git/commits/${baseSha}`);
219
+ for (const [p, want] of Object.entries(expect ?? {})) {
220
+ if ((await this.textAt(p, baseSha)) !== want) throw new StaleWrite(p);
221
+ }
216
222
 
217
223
  const tree: { path: string; mode: string; type: string; sha: string | null }[] = [...removed.map((path) => ({ path, mode: '100644', type: 'blob', sha: null })), ...uploads];
218
224
  for (const f of all) {
@@ -230,7 +236,10 @@ export class GitHubStorage implements Storage {
230
236
  const pr = await this.req<any>('POST', `${this.repoUrl}/pulls`, { title: message, head: branch, base: this.branch, body: `Opened by the site editor.\n\nFiles:\n${[...all.map((f) => f.path), ...uploads.map((u) => u.path), ...removed].map((f) => `- ${f}`).join('\n')}` });
231
237
  pullRequest = pr.html_url;
232
238
  } else {
233
- await this.req('PATCH', `${this.repoUrl}/git/refs/heads/${encodeURIComponent(this.branch)}`, { sha: commit.sha, force: false });
239
+ const moved = await this.raw('PATCH', `${this.repoUrl}/git/refs/heads/${encodeURIComponent(this.branch)}`, { sha: commit.sha, force: false });
240
+ // Not a fast-forward: another save landed after this one read the branch.
241
+ if (moved.status === 422 && expect) throw new StaleWrite(Object.keys(expect)[0]);
242
+ if (!moved.ok) throw new Error(`GitHub PATCH ${this.branch} -> ${moved.status} ${(await moved.text()).slice(0, 300)}`);
234
243
  }
235
244
  if (uploads.length) await this.req('DELETE', `${this.repoUrl}/git/refs/heads/${UPLOADS}`, undefined, true).catch(() => { /* an empty next commit is harmless */ });
236
245
  return { kind: 'github', files: [...all.map((f) => f.path), ...uploads.map((u) => u.path), ...removed], commit: commit.sha, url: commit.html_url ?? `https://github.com/${this.opts.repo}/commit/${commit.sha}`, branch, pullRequest };
@@ -6,7 +6,7 @@ import path from 'node:path';
6
6
  import { execFile } from 'node:child_process';
7
7
  import { promisify } from 'node:util';
8
8
  import type { CommitResult, FileChange, Revision, Storage } from './storage';
9
- import { isSha, safeRelPath } from './storage';
9
+ import { isSha, safeRelPath, StaleWrite } from './storage';
10
10
 
11
11
  const run = promisify(execFile);
12
12
 
@@ -46,7 +46,11 @@ export class LocalStorage implements Storage {
46
46
  await fs.mkdir(path.dirname(f), { recursive: true });
47
47
  await fs.writeFile(f, bytes);
48
48
  }
49
- async commit({ files, deletes = [] }: { message: string; files: FileChange[]; deletes?: string[] }): Promise<CommitResult> {
49
+ async commit({ files, deletes = [], expect }: { message: string; files: FileChange[]; deletes?: string[]; expect?: Record<string, string | null> }): Promise<CommitResult> {
50
+ for (const [p, want] of Object.entries(expect ?? {})) {
51
+ const now = await fs.readFile(this.abs(p), 'utf8').catch(() => null);
52
+ if (now !== want) throw new StaleWrite(p);
53
+ }
50
54
  for (const f of files) {
51
55
  const abs = this.abs(f.path);
52
56
  noteWrite(abs);
@@ -58,8 +58,12 @@ export interface Storage {
58
58
  lastChange?(): Promise<string | null>;
59
59
  /** Stage a binary (upload). It must be reachable at its URL before the next commit. */
60
60
  putAsset(path: string, bytes: Uint8Array): Promise<void>;
61
- /** Make a set of text changes durable, together with any staged assets. `deletes` are repo-relative paths. */
62
- commit(opts: { message: string; files: FileChange[]; deletes?: string[] }): Promise<CommitResult>;
61
+ /**
62
+ * Make a set of text changes durable, together with any staged assets. `deletes` are repo-relative
63
+ * paths. With `expect`, each named file must still hold that text (null: must not exist) in the
64
+ * version the commit builds on, else nothing is written and it throws `StaleWrite`.
65
+ */
66
+ commit(opts: { message: string; files: FileChange[]; deletes?: string[]; expect?: Record<string, string | null> }): Promise<CommitResult>;
63
67
  /** Commits that touched a file, newest first. [] when there is no history to read. */
64
68
  history(path: string, limit?: number): Promise<Revision[]>;
65
69
  /** Text of a file as of a commit from `history`, or null. */
@@ -77,6 +81,11 @@ export interface Storage {
77
81
  goLive?(message: string): Promise<{ commit: string; url: string; merged: boolean } | null>;
78
82
  }
79
83
 
84
+ /** A conditional commit found the file changed since it was read. Read it again and retry. */
85
+ export class StaleWrite extends Error {
86
+ constructor(path: string) { super(`${path} changed while saving; try again.`); this.name = 'StaleWrite'; }
87
+ }
88
+
80
89
  export async function sha256(text: string): Promise<string> {
81
90
  const data = new TextEncoder().encode(text);
82
91
  const hash = await crypto.subtle.digest('SHA-256', data);
package/src/core/users.ts CHANGED
@@ -30,11 +30,25 @@ export interface EditorUser {
30
30
  credentials: StoredCredential[];
31
31
  }
32
32
 
33
+ /** An invite link made from the Users screen that nobody has used yet. Listed so it can be withdrawn. */
34
+ export interface PendingInvite {
35
+ id: string;
36
+ name: string;
37
+ email: string;
38
+ role: Role;
39
+ createdAt: string;
40
+ expiresAt: string;
41
+ /** Name of the admin who made it. */
42
+ by?: string;
43
+ }
44
+
33
45
  export interface UsersFile {
34
46
  version: 1;
35
47
  users: EditorUser[];
36
- /** Ids of invites that have been used. Kept when the person or passkey is removed, so a link never works twice. */
48
+ /** Ids of invites that have been used or withdrawn. Kept when the person or passkey is removed, so a link never works twice. */
37
49
  usedInvites?: string[];
50
+ /** Invites waiting to be used. Links made with the command-line tool aren't listed. */
51
+ invites?: PendingInvite[];
38
52
  }
39
53
 
40
54
  export const emptyUsers = (): UsersFile => ({ version: 1, users: [] });
@@ -46,7 +60,12 @@ export function parseUsers(raw: string | null | undefined): UsersFile {
46
60
  for (const u of data.users) {
47
61
  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)}`);
48
62
  }
49
- return { version: 1, users: data.users, ...(Array.isArray(data.usedInvites) ? { usedInvites: data.usedInvites.filter((x: unknown) => typeof x === 'string') } : {}) };
63
+ const invites = Array.isArray(data.invites) ? data.invites.filter((i: any) => i && typeof i.id === 'string' && typeof i.email === 'string' && typeof i.expiresAt === 'string') : null;
64
+ return {
65
+ version: 1, users: data.users,
66
+ ...(Array.isArray(data.usedInvites) ? { usedInvites: data.usedInvites.filter((x: unknown) => typeof x === 'string') } : {}),
67
+ ...(invites?.length ? { invites } : {}),
68
+ };
50
69
  }
51
70
 
52
71
  export const serializeUsers = (file: UsersFile): string => JSON.stringify(file, null, 2) + '\n';
@@ -79,7 +98,10 @@ export function addCredential(file: UsersFile, who: { name: string; email: strin
79
98
  }
80
99
  user.credentials.push(credential);
81
100
  // 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);
101
+ if (credential.inviteId) {
102
+ copy.usedInvites = [...(copy.usedInvites ?? []), credential.inviteId].slice(-500);
103
+ dropInvite(copy, credential.inviteId, now.getTime());
104
+ }
83
105
  return { file: copy, user };
84
106
  }
85
107
 
@@ -89,6 +111,33 @@ const keepInvites = (file: UsersFile, gone: StoredCredential[]): string[] | unde
89
111
  return ids.length ? [...new Set(ids)].slice(-500) : undefined;
90
112
  };
91
113
 
114
+ /** Takes an invite off the waiting list, and expired ones with it. Mutates `file`. */
115
+ function dropInvite(file: UsersFile, id: string | null, now: number) {
116
+ const left = (file.invites ?? []).filter((i) => i.id !== id && Date.parse(i.expiresAt) > now);
117
+ if (left.length) file.invites = left; else delete file.invites;
118
+ }
119
+
120
+ /** Invites that can still be used, newest first. */
121
+ export const pendingInvites = (file: UsersFile, now = Date.now()) =>
122
+ (file.invites ?? []).filter((i) => Date.parse(i.expiresAt) > now && !inviteUsed(file, i.id)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
123
+
124
+ export function addInvite(file: UsersFile, invite: PendingInvite, now = Date.now()): UsersFile {
125
+ const copy: UsersFile = structuredClone(file);
126
+ dropInvite(copy, null, now);
127
+ copy.invites = [...(copy.invites ?? []), invite];
128
+ return copy;
129
+ }
130
+
131
+ /** The link stops working at once: its id joins the used ones. */
132
+ export function withdrawInvite(file: UsersFile, id: string, now = Date.now()): { file: UsersFile; invite: PendingInvite } {
133
+ const invite = pendingInvites(file, now).find((i) => i.id === id);
134
+ if (!invite) throw new Error('That invite has already been used, withdrawn or has expired.');
135
+ const copy: UsersFile = structuredClone(file);
136
+ copy.usedInvites = [...(copy.usedInvites ?? []), id].slice(-500);
137
+ dropInvite(copy, id, now);
138
+ return { file: copy, invite };
139
+ }
140
+
92
141
  export function removeCredential(file: UsersFile, credentialId: string): UsersFile {
93
142
  const copy: UsersFile = structuredClone(file);
94
143
  const used = keepInvites(file, file.users.flatMap((u) => u.credentials.filter((c) => c.id === credentialId)));
@@ -18,7 +18,7 @@ const links = [
18
18
  <span class="ps-nav__user">
19
19
  <a href="/edit/site" aria-current={current === 'site' ? 'page' : undefined}>Browse site</a>
20
20
  {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-btn--primary ps-live" hidden>Publish changes</button>}
21
- {user && opts.auth === 'passkey' && <span>Signed in as <strong>{user.name}</strong> · <a href="/api/editor/auth/logout">Sign out</a></span>}
21
+ {user && opts.auth === 'passkey' && <span>Signed in as <strong>{user.name}</strong> · <form method="post" action="/api/editor/auth/logout" class="ps-signout"><button type="submit">Sign out</button></form></span>}
22
22
  </span>
23
23
  </nav>
24
24
  <script>import '../client/live.ts';</script>
@@ -1,19 +1,22 @@
1
1
  // /api/editor/auth/<action> — passkey login, enrolment via invite, logout, invites.
2
2
  // Everything here is reachable without a session except `invite` (and `me` reports the session).
3
3
  import type { APIRoute } from 'astro';
4
- import { activeUser, bad, json, opts, secret } from '../../server/context';
4
+ import { activeUser, bad, json, opts, secret, updateUsers } from '../../server/context';
5
5
  import { AuthError, loginOptions, loginVerify, registerOptions, registerVerify, relyingParty } from '../../server/webauthn';
6
- import { SESSION_COOKIE, SESSION_TTL, INVITE_TTL, clearCookieHeader, cookieHeader, createInvite, readSession, safeNext } from '../../core/auth';
7
- import { roleOf } from '../../core/users';
6
+ import { SESSION_COOKIE, SESSION_TTL, INVITE_TTL, clearCookieHeader, cookieHeader, createInvite, readInvite, readSession, safeNext } from '../../core/auth';
7
+ import { addInvite, roleOf } from '../../core/users';
8
8
  export const prerender = false;
9
9
 
10
10
  export const ALL: APIRoute = async ({ params, request, url }) => {
11
11
  const action = params.action;
12
12
  const { secure } = relyingParty(url);
13
13
  if (action === 'logout') {
14
+ // A link elsewhere can't sign anyone out: GET only offers the button, POST (same-site only,
15
+ // see the middleware) does it.
16
+ if (request.method === 'GET') return new Response(SIGN_OUT_PAGE, { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } });
14
17
  const headers = { 'set-cookie': clearCookieHeader(SESSION_COOKIE, secure) };
15
- if (request.method === 'GET') return new Response(null, { status: 303, headers: { ...headers, location: '/edit/login' } });
16
- return json({ ok: true }, 200, headers);
18
+ if ((request.headers.get('accept') ?? '').includes('application/json')) return json({ ok: true }, 200, headers);
19
+ return new Response(null, { status: 303, headers: { ...headers, location: '/edit/login' } });
17
20
  }
18
21
  if (action === 'me') {
19
22
  const s = opts.auth === 'passkey' ? await readSession(request.headers.get('cookie'), secret()) : null;
@@ -42,7 +45,12 @@ export const ALL: APIRoute = async ({ params, request, url }) => {
42
45
  if (roleOf(inviter) !== 'admin') return bad('Only admins can invite people.', 403);
43
46
  const name = String(body.name ?? '').trim(), email = String(body.email ?? '').trim();
44
47
  if (!name || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return bad('name and a valid email are required');
45
- const token = await createInvite(name, email, secret(), INVITE_TTL, Date.now(), body.role === 'admin' ? 'admin' : 'editor');
48
+ const role = body.role === 'admin' ? 'admin' : 'editor';
49
+ const now = Date.now();
50
+ const token = await createInvite(name, email, secret(), INVITE_TTL, now, role);
51
+ const invite = (await readInvite(token, secret()))!;
52
+ // Listed on the Users screen until it's used, so it can be withdrawn.
53
+ await updateUsers((f) => addInvite(f, { id: invite.id, name: invite.name, email: invite.email, role, createdAt: new Date(now).toISOString(), expiresAt: new Date(now + INVITE_TTL * 1000).toISOString(), by: s.name }, now), `Invite ${invite.name} (site editor)\n\nBy ${s.name}`);
46
54
  const { origin } = relyingParty(url);
47
55
  return json({ url: `${origin}/edit/enroll?invite=${encodeURIComponent(token)}`, expiresIn: INVITE_TTL, invitedBy: s.name });
48
56
  }
@@ -54,3 +62,8 @@ export const ALL: APIRoute = async ({ params, request, url }) => {
54
62
  return bad('Sign-in failed. Try again, or ask an admin for a new invite.', 400); // details stay in the log
55
63
  }
56
64
  };
65
+
66
+ const SIGN_OUT_PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Sign out</title></head>
67
+ <body style="font:16px/1.5 system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0">
68
+ <form method="post" action="/api/editor/auth/logout"><p>Sign out of the site editor?</p><button type="submit">Sign out</button> <a href="/edit">Cancel</a></form>
69
+ </body></html>`;
@@ -1,22 +1,24 @@
1
1
  // Go live: with `github.live` set, saves wait on the staging branch and this puts them on the
2
2
  // branch the public site builds from, in one step.
3
3
  // GET /api/editor/live -> { enabled: false } | { enabled: true, branch, live, count, changes, stagingUrl? }
4
- // POST /api/editor/live -> { ok, commit, url, merged } | { ok, nothing: true }
4
+ // POST /api/editor/live -> { ok, commit, url, merged } | { ok, nothing: true } (admins only)
5
5
  import type { APIRoute } from 'astro';
6
- import { bad, editorOf, json, opts, storage } from '../../server/context';
6
+ import { bad, editorOf, isAdmin, json, opts, storage } from '../../server/context';
7
7
  export const prerender = false;
8
8
 
9
9
  const enabled = () => !!(opts.github?.live && storage().pending && storage().goLive);
10
10
 
11
- export const GET: APIRoute = async () => {
11
+ export const GET: APIRoute = async ({ locals }) => {
12
12
  if (!enabled()) return json({ enabled: false });
13
13
  try {
14
- return json({ enabled: true, ...await storage().pending!(), stagingUrl: opts.github?.stagingUrl ?? null });
14
+ return json({ enabled: true, ...await storage().pending!(), stagingUrl: opts.github?.stagingUrl ?? null, canPublish: isAdmin(locals) });
15
15
  } catch (e: any) { return bad(`Could not check what is waiting: ${e.message}`, 502); }
16
16
  };
17
17
 
18
18
  export const POST: APIRoute = async ({ locals }) => {
19
19
  if (!enabled()) return bad('Saving goes straight to the site here; there is nothing to put live.', 404);
20
+ // Editors save; an admin decides when it reaches the public site.
21
+ if (!isAdmin(locals)) return bad('Only admins can publish changes. Your saves are kept and go live when an admin publishes.', 403);
20
22
  const who = editorOf(locals)?.name;
21
23
  try {
22
24
  const { count } = await storage().pending!();
@@ -1,26 +1,28 @@
1
1
  // Admins only.
2
- // GET /api/editor/users -> { users }
2
+ // GET /api/editor/users -> { users, invites }
3
3
  // PATCH /api/editor/users { id, role } -> changes a role
4
4
  // DELETE /api/editor/users { id } -> removes a person; their sessions end within seconds
5
5
  // DELETE /api/editor/users { credential } -> removes one passkey
6
+ // DELETE /api/editor/users { invite } -> withdraws an unused invite link
6
7
  import type { APIRoute } from 'astro';
7
- import { bad, editorOf, isAdmin, json, loadUsers, opts, saveUsers } from '../../server/context';
8
- import { publicUsers, removeCredential, removeUser, setRole, type Role } from '../../core/users';
8
+ import { bad, editorOf, isAdmin, json, loadUsers, opts, updateUsers } from '../../server/context';
9
+ import { pendingInvites, publicUsers, removeCredential, removeUser, setRole, withdrawInvite, type Role, type UsersFile } from '../../core/users';
9
10
  export const prerender = false;
10
11
 
11
12
  const guard = (locals: unknown) => (opts.auth !== 'passkey' ? bad('Users are managed by your login proxy.', 400) : isAdmin(locals) ? null : bad('Only admins can manage users.', 403));
12
13
  const named = (who: string, what: string, locals: unknown) => `${what} ${who} (site editor)\n\nBy ${editorOf(locals)?.name ?? 'unknown'}`;
14
+ const view = (file: UsersFile) => ({ users: publicUsers(file), invites: pendingInvites(file) });
13
15
 
14
- export const GET: APIRoute = async ({ locals }) => guard(locals) ?? json({ users: publicUsers(await loadUsers()) });
16
+ export const GET: APIRoute = async ({ locals }) => guard(locals) ?? json(view(await loadUsers()));
15
17
 
16
18
  export const PATCH: APIRoute = async ({ request, locals }) => {
17
19
  const denied = guard(locals); if (denied) return denied;
18
20
  const body = await request.json().catch(() => null);
19
21
  if (body?.role !== 'admin' && body?.role !== 'editor') return bad('Unknown role.');
20
22
  try {
21
- const file = setRole(await loadUsers(), String(body.id), body.role as Role);
22
- await saveUsers(file, named(file.users.find((u) => u.id === body.id)!.name, `Make ${body.role}:`, locals));
23
- return json({ ok: true, users: publicUsers(file) });
23
+ const who = (await loadUsers()).users.find((u) => u.id === body.id)?.name ?? 'unknown';
24
+ const { file } = await updateUsers((f) => setRole(f, String(body.id), body.role as Role), named(who, `Make ${body.role}:`, locals));
25
+ return json({ ok: true, ...view(file) });
24
26
  } catch (e: any) { return bad(e.message); }
25
27
  };
26
28
 
@@ -28,19 +30,23 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
28
30
  const denied = guard(locals); if (denied) return denied;
29
31
  const body = await request.json().catch(() => null);
30
32
  try {
31
- const before = await loadUsers();
32
- let file; let who: string;
33
- if (body?.credential) {
34
- const owner = before.users.find((u) => u.credentials.some((c) => c.id === body.credential));
35
- if (!owner) return bad('No such passkey.', 404);
36
- who = owner.name;
37
- // Their last passkey takes the person with it, so the last-admin rule has to hold here too.
38
- file = owner.credentials.length === 1 ? removeUser(before, owner.id) : removeCredential(before, body.credential);
39
- } else {
40
- who = before.users.find((u) => u.id === body?.id)?.name ?? '';
41
- file = removeUser(before, String(body?.id));
33
+ // Names for the commit message, from the file as it is now; the change itself re-reads it.
34
+ const now = await loadUsers();
35
+ if (body?.invite) {
36
+ const name = pendingInvites(now).find((i) => i.id === body.invite)?.name ?? 'unknown';
37
+ const { file } = await updateUsers((f) => withdrawInvite(f, String(body.invite)).file, named(name, 'Withdraw invite for', locals));
38
+ return json({ ok: true, ...view(file) });
42
39
  }
43
- await saveUsers(file, named(who, 'Remove access for', locals));
44
- return json({ ok: true, users: publicUsers(file) });
40
+ const who = (body?.credential ? now.users.find((u) => u.credentials.some((c) => c.id === body.credential)) : now.users.find((u) => u.id === body?.id))?.name ?? 'unknown';
41
+ const { file } = await updateUsers((before) => {
42
+ if (body?.credential) {
43
+ const owner = before.users.find((u) => u.credentials.some((c) => c.id === body.credential));
44
+ if (!owner) throw new Error('No such passkey.');
45
+ // Their last passkey takes the person with it, so the last-admin rule has to hold here too.
46
+ return owner.credentials.length === 1 ? removeUser(before, owner.id) : removeCredential(before, body.credential);
47
+ }
48
+ return removeUser(before, String(body?.id));
49
+ }, named(who, 'Remove access for', locals));
50
+ return json({ ok: true, ...view(file) });
45
51
  } catch (e: any) { return bad(e.message); }
46
52
  };
@@ -29,7 +29,7 @@ const user = (Astro.locals as any).editorUser as { name: string } | undefined;
29
29
  <span class="ps-browse__actions">
30
30
  <a id="ps-browse-edit" class="ps-btn ps-btn--primary" href={first.edit ?? '#'} hidden={!first.edit}>✎ Edit this page</a>
31
31
  {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Publish changes</button>}
32
- {user && opts.auth === 'passkey' && <a class="ps-browse__out" href="/api/editor/auth/logout">Sign out</a>}
32
+ {user && opts.auth === 'passkey' && <form method="post" action="/api/editor/auth/logout" class="ps-signout ps-browse__out"><button type="submit">Sign out</button></form>}
33
33
  </span>
34
34
  </header>
35
35
  <div class="ps-browse__loading" aria-hidden="true">Loading page…</div>
@@ -23,6 +23,10 @@ const passkey = opts.auth === 'passkey';
23
23
  {passkey ? (
24
24
  <>
25
25
  <ul class="ps-pagelist" id="ps-users"></ul>
26
+ <section id="ps-invites" class="ps-invites" hidden>
27
+ <h2>Invites not used yet</h2>
28
+ <ul class="ps-pagelist"></ul>
29
+ </section>
26
30
  <details class="ps-invite" open>
27
31
  <summary>Invite someone</summary>
28
32
  <form id="ps-invite" class="ps-invite__form">
@@ -32,7 +36,7 @@ const passkey = opts.auth === 'passkey';
32
36
  <button type="submit" class="ps-btn ps-btn--primary ps-btn--small">Create invite link</button>
33
37
  <output></output>
34
38
  </form>
35
- <p class="ps-muted">The link lets them create a passkey for this site. It works once and expires after 3 days. Their public key is committed to <code>{opts.usersFile}</code>; nothing secret is stored.</p>
39
+ <p class="ps-muted">The link lets them create a passkey for this site. It works once and expires after 3 days. Until it's used it's listed above, where you can withdraw it. Their public key is committed to <code>{opts.usersFile}</code>; nothing secret is stored.</p>
36
40
  </details>
37
41
  </>
38
42
  ) : <p>People are managed by your login proxy, not here.</p>}
@@ -13,7 +13,7 @@ if (opts.auth !== 'passkey') error = `Passkey sign-in is not enabled for this si
13
13
  else {
14
14
  const inv = await readInvite(token, secret());
15
15
  if (!inv) error = 'This invite link is invalid or has expired. Ask for a new one.';
16
- else if (inviteUsed(await loadUsers(), inv.id)) error = 'This invite link has already been used.';
16
+ else if (inviteUsed(await loadUsers(), inv.id)) error = 'This invite link has already been used or was withdrawn.';
17
17
  else invite = { name: inv.name, email: inv.email };
18
18
  }
19
19
  ---
package/src/runtime.ts CHANGED
@@ -23,6 +23,11 @@ export interface Field {
23
23
  default?: unknown;
24
24
  /** Field can be edited by clicking it in the page (text, richtext, image). */
25
25
  inline?: boolean;
26
+ /**
27
+ * For 'text': allow bold and italic in the line (headings, titles). The value is then HTML holding
28
+ * only `<strong>` and `<em>`; render it with `set:html`. Without it, a text field is plain text.
29
+ */
30
+ marks?: boolean;
26
31
  options?: { value: string; label: string }[];
27
32
  /** Sidebar grouping. Defaults to 'content'. */
28
33
  group?: 'content' | 'style' | 'advanced';
@@ -1,8 +1,8 @@
1
1
  // Server-side glue shared by the routes: resolved options, the storage adapter, page IO.
2
2
  import { options, site } from 'virtual:pagestack/site';
3
3
  import type { CollectionDoc, Field, GlobalDoc, Node, PageDoc, PageTemplate, SchemaRegistry } from '../runtime';
4
- import type { Storage } from '../core/storage';
5
- import { sha256 } from '../core/storage';
4
+ import type { CommitResult, Storage } from '../core/storage';
5
+ import { sha256, StaleWrite } from '../core/storage';
6
6
  import { LocalStorage } from '../core/storage-local';
7
7
  import { GitHubStorage } from '../core/storage-github';
8
8
  import { serializeRegistry, validateDoc } from '../core/schema';
@@ -142,10 +142,23 @@ export const cleanNode = (node: Node, locals: unknown, keep?: Node) => sanitizeN
142
142
  // ---- people ----
143
143
  export async function loadUsers(): Promise<UsersFile> { return parseUsers(await storage().readFile(opts.usersFile)); }
144
144
  let usersCache: { file: UsersFile; at: number } | null = null;
145
- export async function saveUsers(file: UsersFile, message: string) {
146
- const result = await storage().commit({ message, files: [{ path: opts.usersFile, content: serializeUsers(file) }] });
147
- usersCache = null;
148
- return result;
145
+ /**
146
+ * Read the users file, change it and save it, as one step: if someone else saved it in between
147
+ * (two admins at once, or an invite used while an admin edits roles), it is read again and the
148
+ * change re-applied, so neither save is lost. `change` may throw to refuse.
149
+ */
150
+ export async function updateUsers(change: (file: UsersFile) => UsersFile, message: string): Promise<{ file: UsersFile; commit: CommitResult }> {
151
+ for (let attempt = 0; ; attempt++) {
152
+ const raw = await storage().readFile(opts.usersFile);
153
+ const file = change(parseUsers(raw));
154
+ try {
155
+ const commit = await storage().commit({ message, files: [{ path: opts.usersFile, content: serializeUsers(file) }], expect: { [opts.usersFile]: raw } });
156
+ usersCache = null;
157
+ return { file, commit };
158
+ } catch (e) {
159
+ if (!(e instanceof StaleWrite) || attempt >= 3) throw e instanceof StaleWrite ? new Error('Someone else changed the user list at the same moment. Try again.') : e;
160
+ }
161
+ }
149
162
  }
150
163
  const USERS_TTL = 15_000;
151
164
  /** A miss may mean "saved a moment ago by another instance": re-read, but not more than this often. */
@@ -3,9 +3,9 @@
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 { cachedUsers, loadUsers, opts, secret, saveUsers } from './context';
6
+ import { cachedUsers, loadUsers, opts, secret, updateUsers } from './context';
7
7
  import { b64url, createChallengeToken, createSession, readChallengeToken, readInvite, unb64url, type InvitePayload } from '../core/auth';
8
- import { addCredential, findByCredential, findByEmail, inviteUsed, type StoredCredential } from '../core/users';
8
+ import { addCredential, findByCredential, findByEmail, inviteUsed, type EditorUser, type StoredCredential } from '../core/users';
9
9
 
10
10
  /**
11
11
  * Relying-party identity. WebAuthn binds credentials to the origin the browser sees, so behind a
@@ -16,7 +16,7 @@ export function relyingParty(url: URL) {
16
16
  return { origin, rpID: new URL(origin).hostname, rpName: opts.siteName, secure: origin.startsWith('https:') };
17
17
  }
18
18
 
19
- export { loadUsers, saveUsers };
19
+ export { loadUsers };
20
20
 
21
21
  export async function loginOptions(url: URL) {
22
22
  const { rpID } = relyingParty(url);
@@ -49,7 +49,7 @@ export async function registerOptions(url: URL, inviteToken: string) {
49
49
  const invite = await readInvite(inviteToken, secret());
50
50
  if (!invite) throw new AuthError('This invite link is invalid or has expired. Ask for a new one.');
51
51
  const users = await loadUsers();
52
- if (inviteUsed(users, invite.id)) throw new AuthError('This invite link has already been used.');
52
+ if (inviteUsed(users, invite.id)) throw new AuthError('This invite link has already been used or was withdrawn.');
53
53
  const existing = findByEmail(users, invite.email);
54
54
  const options = await generateRegistrationOptions({
55
55
  rpName, rpID,
@@ -72,7 +72,7 @@ export async function registerVerify(url: URL, token: string, response: Registra
72
72
  claimed.add(invite.id); // two tabs racing the same link: only one gets past here
73
73
  try {
74
74
  const users = await loadUsers();
75
- if (inviteUsed(users, invite.id)) throw new AuthError('This invite link has already been used.');
75
+ if (inviteUsed(users, invite.id)) throw new AuthError('This invite link has already been used or was withdrawn.');
76
76
  const result = await verifyRegistrationResponse({ response, expectedChallenge: ch.challenge, expectedOrigin: origin, expectedRPID: rpID });
77
77
  if (!result.verified) throw new AuthError('Passkey registration failed.');
78
78
  const info = result.registrationInfo;
@@ -81,8 +81,14 @@ export async function registerVerify(url: URL, token: string, response: Registra
81
81
  transports: info.credential.transports, deviceType: info.credentialDeviceType, backedUp: info.credentialBackedUp,
82
82
  createdAt: new Date().toISOString(), inviteId: invite.id, label: label?.slice(0, 60) || undefined,
83
83
  };
84
- const { file, user } = addCredential(users, invite, credential);
85
- const commit = await saveUsers(file, `Add passkey for ${user.name} (site editor)`);
84
+ let user!: EditorUser;
85
+ const { commit } = await updateUsers((f) => {
86
+ // Read again on a retry: the invite may have been withdrawn in the meantime.
87
+ if (inviteUsed(f, invite.id)) throw new AuthError('This invite link has already been used or was withdrawn.');
88
+ const added = addCredential(f, invite, credential);
89
+ user = added.user;
90
+ return added.file;
91
+ }, `Add passkey for ${invite.name} (site editor)`);
86
92
  return { user, commit, session: await createSession({ id: user.id, name: user.name }, secret(), credential.id) };
87
93
  } finally { claimed.delete(invite.id); }
88
94
  }