@pirateandfox/pagestack 0.1.0-beta.12 → 0.1.0-beta.13
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 +9 -1
- package/package.json +1 -1
- package/src/client/editor.ts +1 -1
- package/src/client/invite.ts +1 -0
- package/src/client/live.ts +5 -2
- package/src/client/preview.css +3 -0
- package/src/client/shell.css +11 -2
- package/src/client/users.ts +27 -3
- package/src/core/storage-github.ts +14 -5
- package/src/core/storage-local.ts +6 -2
- package/src/core/storage.ts +11 -2
- package/src/core/users.ts +52 -3
- package/src/routes/Nav.astro +1 -1
- package/src/routes/api/auth.ts +19 -6
- package/src/routes/api/live.ts +6 -4
- package/src/routes/api/users.ts +26 -20
- package/src/routes/edit-site.astro +1 -1
- package/src/routes/edit-users.astro +5 -1
- package/src/routes/enroll.astro +1 -1
- package/src/server/context.ts +19 -6
- package/src/server/webauthn.ts +13 -7
package/README.md
CHANGED
|
@@ -405,6 +405,8 @@ than setting a hard limit. Passkeys are what actually stops guessing.
|
|
|
405
405
|
With `github.live`, saves stay on `github.branch` (staging) and the public site builds from `live`.
|
|
406
406
|
Every screen gets a **Publish changes** button (Go live) counting the saved changes the live site doesn't have yet;
|
|
407
407
|
it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
|
|
408
|
+
Only admins can publish; editors see what's waiting, and their saves stay on staging until an admin
|
|
409
|
+
publishes.
|
|
408
410
|
That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
|
|
409
411
|
commit and moves staging to it; when their change conflicts, it refuses and says so, and a person
|
|
410
412
|
merges in GitHub. A burst of saves becomes one production build. Drafts (the **Ready to publish**
|
|
@@ -432,7 +434,9 @@ like any other push.
|
|
|
432
434
|
invite links (3 days). Tokens are `base64url(json).base64url(hmac-sha256)` with the expiry inside,
|
|
433
435
|
so there is no server state.
|
|
434
436
|
- **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
|
|
437
|
+
one from the CLI, later ones from **Users** (`/edit/users`), which lists invites not used yet and
|
|
438
|
+
lets an admin withdraw one; a withdrawn link stops working at once. Links made with the CLI aren't
|
|
439
|
+
listed there.
|
|
436
440
|
|
|
437
441
|
```bash
|
|
438
442
|
EDITOR_SECRET=… npx pagestack-invite --name "Jane Doe" --email jane@example.com --origin https://example.com
|
|
@@ -442,6 +446,10 @@ like any other push.
|
|
|
442
446
|
- Set `EDITOR_ORIGIN` when a proxy rewrites `Host`; WebAuthn binds credentials to the origin the
|
|
443
447
|
browser sees.
|
|
444
448
|
- The signature counter is not persisted (it would mean a commit per login; synced passkeys report 0).
|
|
449
|
+
- Changes to the users file are conditional: when two of them race (two admins, or an invite used
|
|
450
|
+
while an admin edits roles), the later one is re-read and re-applied, so neither is lost.
|
|
451
|
+
- Signing out is a POST from the editor's own pages. Opening `/api/editor/auth/logout` from a link
|
|
452
|
+
only shows a Sign out button, so another site can't sign anyone out.
|
|
445
453
|
|
|
446
454
|
### `auth: "none-behind-proxy"`
|
|
447
455
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pirateandfox/pagestack",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.13",
|
|
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",
|
package/src/client/editor.ts
CHANGED
|
@@ -784,7 +784,7 @@ $('#ps-more').addEventListener('click', (e) => {
|
|
|
784
784
|
{ label: 'Revisions', run: showRevisions },
|
|
785
785
|
{ label: 'All pages', run: () => { location.href = '/edit'; }, separator: true },
|
|
786
786
|
];
|
|
787
|
-
if (boot.options.auth === 'passkey' && boot.options.user) items.push({ label: `Sign out ${boot.options.user}`, run: () => {
|
|
787
|
+
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
788
|
openMenu(e.currentTarget as HTMLElement, items);
|
|
789
789
|
});
|
|
790
790
|
|
package/src/client/invite.ts
CHANGED
|
@@ -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
|
});
|
package/src/client/live.ts
CHANGED
|
@@ -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 ?
|
|
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
|
{
|
package/src/client/preview.css
CHANGED
|
@@ -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; }
|
package/src/client/shell.css
CHANGED
|
@@ -332,8 +332,12 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
|
|
|
332
332
|
.ps-browse__actions { display: flex; align-items: center; gap: 10px; }
|
|
333
333
|
.ps-browse__actions .ps-btn { padding: 5px 12px; }
|
|
334
334
|
.ps-browse__actions .ps-live:not(.ps-btn--primary) { background: transparent; color: #fff; border-color: #4b5563; }
|
|
335
|
-
|
|
336
|
-
.ps-
|
|
335
|
+
/* Sign out is a form (a POST), drawn as a link. */
|
|
336
|
+
.ps-signout { display: inline; margin: 0; }
|
|
337
|
+
.ps-signout button { all: unset; cursor: pointer; color: inherit; text-decoration: underline; }
|
|
338
|
+
.ps-signout button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
|
|
339
|
+
.ps-browse__out button { color: #9ca3af; text-decoration: none; }
|
|
340
|
+
.ps-browse__out button:hover { color: #fff; }
|
|
337
341
|
.ps-browse__frame { width: 100%; height: 100%; border: 0; background: #fff; grid-row: 2; grid-column: 1; }
|
|
338
342
|
/* While the frame loads: a moving strip under the bar and a word in the middle, not a blank page. */
|
|
339
343
|
.ps-browse__bar { position: relative; }
|
|
@@ -361,3 +365,8 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
|
|
|
361
365
|
.ps-switch input:focus-visible + .ps-switch__track { outline: 2px solid #2563eb; outline-offset: 2px; }
|
|
362
366
|
.ps-switch:has(input:disabled) { cursor: default; opacity: .6; }
|
|
363
367
|
@media (prefers-reduced-motion: reduce) { .ps-switch__track, .ps-switch__track::after { transition: none; } }
|
|
368
|
+
|
|
369
|
+
/* Users: invites not used yet */
|
|
370
|
+
.ps-invites { margin: 28px 0 8px; }
|
|
371
|
+
.ps-invites[hidden] { display: none; }
|
|
372
|
+
.ps-invites h2 { font-size: 15px; font-weight: 600; margin: 0 0 8px; }
|
package/src/client/users.ts
CHANGED
|
@@ -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');
|
|
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();
|
|
@@ -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
|
-
|
|
203
|
-
|
|
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.
|
|
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);
|
package/src/core/storage.ts
CHANGED
|
@@ -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
|
-
/**
|
|
62
|
-
|
|
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
|
-
|
|
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)
|
|
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)));
|
package/src/routes/Nav.astro
CHANGED
|
@@ -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> · <
|
|
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>
|
package/src/routes/api/auth.ts
CHANGED
|
@@ -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.
|
|
16
|
-
return
|
|
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
|
|
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>`;
|
package/src/routes/api/live.ts
CHANGED
|
@@ -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!();
|
package/src/routes/api/users.ts
CHANGED
|
@@ -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,
|
|
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(
|
|
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
|
|
22
|
-
|
|
23
|
-
return json({ ok: true,
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
if (body?.
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
44
|
-
|
|
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' && <
|
|
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>}
|
package/src/routes/enroll.astro
CHANGED
|
@@ -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/server/context.ts
CHANGED
|
@@ -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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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. */
|
package/src/server/webauthn.ts
CHANGED
|
@@ -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,
|
|
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
|
|
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
|
-
|
|
85
|
-
const commit = await
|
|
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
|
}
|