@pirateandfox/pagestack 0.1.0-beta.11 → 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.
@@ -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
  };
@@ -17,6 +17,7 @@ const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reserved
17
17
  <meta charset="utf-8" />
18
18
  <meta name="viewport" content="width=device-width, initial-scale=1" />
19
19
  <meta name="robots" content="noindex" />
20
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
20
21
  <title>{c.label} — {opts.siteName}</title>
21
22
  </head>
22
23
  <body class="ps-index">
@@ -18,6 +18,7 @@ const boot = {
18
18
  <meta charset="utf-8" />
19
19
  <meta name="viewport" content="width=device-width, initial-scale=1" />
20
20
  <meta name="robots" content="noindex" />
21
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
21
22
  <title>{def.label} — {opts.siteName}</title>
22
23
  </head>
23
24
  <body class="ps-index">
@@ -22,6 +22,7 @@ const globalLinks = Object.entries(globals).map(([id, g]) => ({ id, label: g.lab
22
22
  <meta charset="utf-8" />
23
23
  <meta name="viewport" content="width=device-width, initial-scale=1" />
24
24
  <meta name="robots" content="noindex" />
25
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
25
26
  <title>{opts.siteName} — pages</title>
26
27
  </head>
27
28
  <body class="ps-index">
@@ -27,6 +27,7 @@ const boot = {
27
27
  <meta charset="utf-8" />
28
28
  <meta name="viewport" content="width=device-width, initial-scale=1" />
29
29
  <meta name="robots" content="noindex" />
30
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
30
31
  <title>Edit: {data.title ?? slug}</title>
31
32
  </head>
32
33
  <body class="ps-index ps-item">
@@ -11,6 +11,7 @@ export const prerender = false;
11
11
  <meta charset="utf-8" />
12
12
  <meta name="viewport" content="width=device-width, initial-scale=1" />
13
13
  <meta name="robots" content="noindex" />
14
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
14
15
  <title>Media — {opts.siteName}</title>
15
16
  </head>
16
17
  <body class="ps-index">
@@ -21,6 +21,7 @@ const boot = {
21
21
  <meta charset="utf-8" />
22
22
  <meta name="viewport" content="width=device-width, initial-scale=1" />
23
23
  <meta name="robots" content="noindex" />
24
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
24
25
  <title>Edit: {r.page.title}</title>
25
26
  </head>
26
27
  <body class="ps">
@@ -16,6 +16,7 @@ const user = (Astro.locals as any).editorUser as { name: string } | undefined;
16
16
  <meta charset="utf-8" />
17
17
  <meta name="viewport" content="width=device-width, initial-scale=1" />
18
18
  <meta name="robots" content="noindex" />
19
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
19
20
  <title>{opts.siteName}</title>
20
21
  </head>
21
22
  <body class="ps-browse is-loading">
@@ -28,7 +29,7 @@ const user = (Astro.locals as any).editorUser as { name: string } | undefined;
28
29
  <span class="ps-browse__actions">
29
30
  <a id="ps-browse-edit" class="ps-btn ps-btn--primary" href={first.edit ?? '#'} hidden={!first.edit}>✎ Edit this page</a>
30
31
  {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Publish changes</button>}
31
- {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>}
32
33
  </span>
33
34
  </header>
34
35
  <div class="ps-browse__loading" aria-hidden="true">Loading page…</div>
@@ -13,6 +13,7 @@ const passkey = opts.auth === 'passkey';
13
13
  <meta charset="utf-8" />
14
14
  <meta name="viewport" content="width=device-width, initial-scale=1" />
15
15
  <meta name="robots" content="noindex" />
16
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
16
17
  <title>Users — {opts.siteName}</title>
17
18
  </head>
18
19
  <body class="ps-index">
@@ -22,6 +23,10 @@ const passkey = opts.auth === 'passkey';
22
23
  {passkey ? (
23
24
  <>
24
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>
25
30
  <details class="ps-invite" open>
26
31
  <summary>Invite someone</summary>
27
32
  <form id="ps-invite" class="ps-invite__form">
@@ -31,7 +36,7 @@ const passkey = opts.auth === 'passkey';
31
36
  <button type="submit" class="ps-btn ps-btn--primary ps-btn--small">Create invite link</button>
32
37
  <output></output>
33
38
  </form>
34
- <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>
35
40
  </details>
36
41
  </>
37
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
  ---
@@ -23,6 +23,7 @@ else {
23
23
  <meta charset="utf-8" />
24
24
  <meta name="viewport" content="width=device-width, initial-scale=1" />
25
25
  <meta name="robots" content="noindex" />
26
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
26
27
  <title>Set up your passkey — {opts.siteName}</title>
27
28
  </head>
28
29
  <body class="ps-index">
@@ -15,6 +15,7 @@ if (await readSession(Astro.request.headers.get('cookie'), secret())) return Ast
15
15
  <meta charset="utf-8" />
16
16
  <meta name="viewport" content="width=device-width, initial-scale=1" />
17
17
  <meta name="robots" content="noindex" />
18
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect x=%276%27 y=%2730%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.22%27/%3E%3Crect x=%2712%27 y=%2720%27 width=%2740%27 height=%2726%27 rx=%276%27 fill=%27%231e1e1e%27 opacity=%27.5%27/%3E%3Crect x=%2718%27 y=%278%27 width=%2740%27 height=%2728%27 rx=%276%27 fill=%27%232563eb%27/%3E%3C/svg%3E" />
18
19
  <title>Sign in — {opts.siteName}</title>
19
20
  </head>
20
21
  <body class="ps-index">
@@ -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. */
@@ -0,0 +1,32 @@
1
+ // Site pages on a deployed editor. The editor build carries a built copy of every site page, and
2
+ // Cloudflare would hand those files out before the editor's code runs: no sign-in, no editor bar.
3
+ // The editor's Worker entry (src/worker.ts) asks here first, for every request.
4
+ import { readSession } from '../core/auth';
5
+
6
+ /** Paths the editor's own middleware already handles (sign-in included). */
7
+ const EDITOR = /^\/(edit(\/|$)|api\/editor\/)/;
8
+ /** Files with an extension other than .html (styles, scripts, images, fonts) stay as public as on the site. */
9
+ const FILE = /\.[a-z0-9]{1,8}$/i;
10
+
11
+ export interface GateOptions { auth: 'none' | 'passkey' | 'none-behind-proxy'; secret: () => string }
12
+
13
+ /**
14
+ * null: carry on to the normal handler. Otherwise the response to send instead:
15
+ * a page opened directly goes to Browse (which signs in first); a page loaded any other way (the
16
+ * Browse frame, a fetch) needs a session.
17
+ */
18
+ export async function gateSitePage(request: Request, o: GateOptions): Promise<Response | null> {
19
+ if (request.method !== 'GET' && request.method !== 'HEAD') return null;
20
+ const url = new URL(request.url);
21
+ const p = url.pathname;
22
+ if (EDITOR.test(p) || p.startsWith('/_astro/') || p.startsWith('/_image')) return null;
23
+ const last = p.slice(p.lastIndexOf('/') + 1);
24
+ if (FILE.test(last) && !/\.html?$/i.test(last)) return null;
25
+ const browse = `/edit/site?path=${encodeURIComponent(p)}`;
26
+ if (request.headers.get('sec-fetch-dest') === 'document') return redirect(browse);
27
+ if (o.auth !== 'passkey') return null; // behind a proxy, the proxy already signed them in
28
+ const session = await readSession(request.headers.get('cookie'), o.secret()).catch(() => null);
29
+ return session ? null : redirect(`/edit/login?next=${encodeURIComponent(browse)}`);
30
+ }
31
+
32
+ const redirect = (location: string) => new Response(null, { status: 302, headers: { location, 'cache-control': 'no-store' } });
@@ -61,6 +61,23 @@ function sameText(a: string, b: string): boolean {
61
61
  }
62
62
 
63
63
 
64
+ /** A deployed editor missing a secret it can't work without: said plainly rather than a 500. */
65
+ function setupProblem(): string | null {
66
+ if (opts.storage === 'github' && !(process.env.GITHUB_TOKEN || process.env.EDITOR_GITHUB_TOKEN)) {
67
+ return 'The editor is not connected to GitHub yet. Add a GITHUB_TOKEN secret (a fine-grained token for this repository with Contents: read and write) to the editor deployment.';
68
+ }
69
+ if (opts.auth === 'passkey' && (process.env[opts.secretEnv] ?? '').length < 16) {
70
+ return `The editor has no signing key yet. Add an ${opts.secretEnv} secret (at least 16 random characters) to the editor deployment.`;
71
+ }
72
+ return null;
73
+ }
74
+ const escapeHtml = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
75
+ function setupPage(message: string): string {
76
+ return `<!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>Editor setup needed</title>
77
+ <style>body{font:16px/1.55 system-ui,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;background:#f6f6f4;color:#1d1d1b}main{max-width:34rem;padding:2rem;background:#fff;border:1px solid #e3e3df;border-radius:12px}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:.5rem 0 0}</style></head>
78
+ <body><main><h1>One more setup step</h1><p>${escapeHtml(message)}</p><p>Once it is added, reload this page.</p></main></body></html>`;
79
+ }
80
+
64
81
  export const onRequest = defineMiddleware(async (ctx, next) => {
65
82
  if (ctx.isPrerendered) return next(); // public pages, which never carry a session
66
83
  // Host list pages rendered here (liveRoutes) read collections from storage. Set on the first
@@ -86,6 +103,11 @@ export const onRequest = defineMiddleware(async (ctx, next) => {
86
103
  if (opts.auth === 'passkey' && !process.env.EDITOR_ORIGIN) console.warn('[pagestack] Set EDITOR_ORIGIN to the public https origin: without it invite links trust the Host header, and behind a proxy cookies may not be marked Secure.');
87
104
  }
88
105
  if (crossSite(request, ctx.url)) return done(json({ error: 'cross-site request refused' }, 403));
106
+ const missing = setupProblem();
107
+ if (missing) {
108
+ if (pathname.startsWith('/api/')) return done(json({ error: missing }, 503));
109
+ return done(new Response(setupPage(missing), { status: 503, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } }));
110
+ }
89
111
 
90
112
  if (pathname.startsWith('/api/editor/auth/') && request.method === 'POST') {
91
113
  const { ok, retryAfter } = authAttempts(clientIp(ctx));
@@ -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
  }
package/src/worker.ts ADDED
@@ -0,0 +1,13 @@
1
+ // The editor's Cloudflare Worker entry. PageStack puts it in place of @astrojs/cloudflare's own
2
+ // entry in editor builds (index.mjs), so hosts change nothing: site pages are checked here
3
+ // (server/gate.ts), then everything goes to the adapter as before.
4
+ // @ts-ignore: the host's dependency, present whenever this file is used
5
+ import { handle } from '@astrojs/cloudflare/handler';
6
+ import { gateSitePage } from './server/gate';
7
+ import { opts, secret } from './server/context';
8
+
9
+ export default {
10
+ async fetch(request: Request, env: unknown, ctx: unknown) {
11
+ return (await gateSitePage(request, { auth: opts.auth, secret })) ?? handle(request, env, ctx);
12
+ },
13
+ };