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

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pirate & Fox LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,41 +1,99 @@
1
- # PageStack
1
+ <p align="center">
2
+ <img src="docs/media/logo.svg" width="72" height="72" alt="">
3
+ </p>
4
+ <h1 align="center">PageStack</h1>
5
+
6
+ <p align="center">
7
+ <strong>A block editor for Astro sites. Your content stays in your repo.</strong><br>
8
+ Click a heading on the real page and type. Drag sections around. Press Save, and it's a git commit.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@pirateandfox/pagestack"><img src="https://img.shields.io/npm/v/@pirateandfox/pagestack/beta?label=npm%20%40beta&color=2563eb" alt="npm beta version"></a>
13
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-1e1e1e" alt="MIT license"></a>
14
+ <img src="https://img.shields.io/badge/status-beta-f59e0b" alt="Beta">
15
+ </p>
16
+
17
+ <p align="center">
18
+ <img src="docs/media/demo.gif" width="860" alt="Editing a bakery's home page in PageStack: clicking a heading to change it, adding a section, and saving">
19
+ </p>
20
+
21
+ ## Why
22
+
23
+ Static Astro sites are fast, cheap and hard to break, and the people who write for them usually
24
+ can't touch them. The usual fix is a headless CMS: another service, another login, content in
25
+ someone else's database, and a site that no longer builds from the repo alone.
26
+
27
+ PageStack takes the other route. It adds an editor **to the site itself**:
28
+
29
+ - **Edit on the real page.** The preview is your site, rendered by your own components. Click text to
30
+ change it, click an image to swap it, press **+** or **/** to add a block. If you've used the
31
+ WordPress block editor, you already know it.
32
+ - **Content is files in your repo.** Pages are JSON, posts are Markdown. Saving writes a file in dev
33
+ and makes **one commit** in production. No database, nothing stored anywhere else. `git log` is
34
+ your revision history.
35
+ - **The public site stays fully static.** `astro build` is unchanged and ships no editor code. The
36
+ editor is a separate small deployment (a Cloudflare Worker or any Node host) that only exists
37
+ when you build it with `EDITOR=1`.
38
+ - **Passkey sign-in.** Touch ID, Face ID, Windows Hello or a security key. No passwords, no user
39
+ database: invite someone with a single-use link.
40
+ - **Draft, stage, publish.** Saves can go to a staging branch, and **Publish changes** puts them live
41
+ in one step, so a dozen edits make one production build.
42
+
43
+ ## How it works
2
44
 
3
- A visual editor for Astro sites where pages are a stack of sections. Git-only: saving is a commit,
4
- the public site stays static, and nothing lives outside the repo.
5
-
6
- - The public site stays **fully static**. `astro build` is unchanged.
7
- - The editor (`/edit/*`, `/api/editor/*`) is on-demand rendered and only exists when asked for:
8
- `EDITOR=dev astro dev`, or a build made with `EDITOR=1` (which adds `@astrojs/node` unless the site has an adapter).
9
- - Pages are JSON documents in the repo (`src/content/pages/<slug>.json`). Saving writes a file
10
- (dev) or makes **one commit** through the GitHub API (production). Nothing is stored anywhere else.
11
- - Login is **passkeys** (WebAuthn). Users' public keys live in a committed `editor-users.json`;
12
- the only server secret is `EDITOR_SECRET`. No database, no session store.
13
- - Live preview renders the real page with the site's own components, in the browser's iframe.
45
+ ```
46
+ your repo on GitHub the editor (edit.example.com)
47
+ ┌──────────────────────────┐ reads ┌───────────────────────────────────┐
48
+ │ src/content/pages/*.json │ ───────────▶ │ your Astro site + PageStack, │
49
+ │ src/content/posts/*.md │ │ built with EDITOR=1 │
50
+ │ public/images/… │ ◀─────────── │ previews use your own components │
51
+ └────────────┬─────────────┘ one commit │ passkey sign-in │
52
+ │ per save └───────────────────────────────────┘
53
+ │ your normal deploy (Pages, Netlify, Vercel…)
54
+ ▼
55
+ ┌──────────────────────────┐
56
+ │ public site: astro build │ static files, no editor code
57
+ └──────────────────────────┘
58
+ ```
14
59
 
15
- Status: **early beta** (`0.1.0-beta.x`). The API will move; pin a version. See [ROADMAP.md](ROADMAP.md)
16
- and [CHANGELOG.md](CHANGELOG.md).
60
+ The editor only needs a GitHub token with *Contents: read and write* on the one repo. It never
61
+ leaves the server.
17
62
 
18
- ## Versions
63
+ ## Try it in two minutes
19
64
 
20
- Published on npm as **`@pirateandfox/pagestack`** (betas under the `beta` dist-tag):
65
+ The repo includes a demo site, an invented bakery called **Crumb & Co.**
21
66
 
22
67
  ```bash
23
- npm install @pirateandfox/pagestack@beta
68
+ git clone https://github.com/pirateandfox/pagestack.git
69
+ cd pagestack/examples/bakery
70
+ npm install
71
+ npm run dev:editor # then open http://localhost:4321/edit
24
72
  ```
25
73
 
26
- Or install from a git tag and bump the tag to upgrade:
74
+ In dev there is no sign-in, and saving writes straight to `examples/bakery/src/content`. Run
75
+ `git diff` afterwards to see exactly what the editor wrote.
27
76
 
28
- ```json
29
- "dependencies": { "@pirateandfox/pagestack": "github:pirateandfox/pagestack#v0.1.0-beta.4" }
30
- ```
77
+ ## Status
78
+
79
+ **Beta** (`0.1.0-beta.x`). It runs real sites today, and the API can still change between betas, so
80
+ pin an exact version. What's solid: block pages, Markdown collections edited in place, media,
81
+ global content, synced patterns, revisions, Browse, passkeys, staging and publish. What's next is
82
+ in the [roadmap](ROADMAP.md); every release is in the [changelog](CHANGELOG.md). Found a security
83
+ problem? See [SECURITY.md](SECURITY.md).
84
+
85
+ ---
86
+
87
+ # Guide
88
+
89
+ ## Install
31
90
 
32
91
  ```bash
33
- npm install # after changing the tag
92
+ npm install @pirateandfox/pagestack@beta --save-exact
34
93
  ```
35
94
 
36
- Releases are tags `vX.Y.Z[-beta.N]` on `main`; each one has a CHANGELOG entry.
95
+ Requires Node 22.23.4+ and Astro 7.2.1+.
37
96
 
38
- ## Install
39
97
 
40
98
  ```js
41
99
  // astro.config.mjs
@@ -152,6 +210,17 @@ const { node, edit } = Astro.props;
152
210
  passes `child(edit, i)` to each child. The `renderer` component takes `{ page, editing }` and
153
211
  renders the page inside the site's normal layout.
154
212
 
213
+ A few things worth knowing while you set up the schema:
214
+
215
+ - **Components can live in the schema or beside it.** The editor strips `component` before sending
216
+ the registry to the browser, so either works. `examples/bakery` keeps them in a separate map
217
+ (`src/sections/components.ts`) so the schema stays plain data.
218
+ - **List View names a block after its first non-empty inline text field**, so put the field people
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*).
222
+ - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
223
+
155
224
  ## Editing
156
225
 
157
226
  Coming from the WordPress block editor:
@@ -390,13 +459,36 @@ Dev only. A build with `auth: "none"` is refused.
390
459
 
391
460
  ## Deploying the editor
392
461
 
393
- Requires Node 22.23.4+ and Astro 7.2.1+. On Cloudflare, add `@astrojs/cloudflare` as the host's
394
- adapter and set `EDITOR_SECRET`, `EDITOR_ORIGIN` and `GITHUB_TOKEN` as secrets.
462
+ Requires Node 22.23.4+ and Astro 7.2.1+.
463
+
464
+ **On Cloudflare Workers**, add `@astrojs/cloudflare` as the host's adapter in the editor build only,
465
+ and give the Worker three secrets: `EDITOR_SECRET` (32+ random characters), `EDITOR_ORIGIN` (its
466
+ https address) and `GITHUB_TOKEN`. Until `EDITOR_SECRET` and `GITHUB_TOKEN` are set, every editor page says
467
+ which one is missing. PageStack takes care of the rest: in the editor build it wraps the adapter's Worker entry
468
+ and sets `assets.run_worker_first` in the generated `dist/server/wrangler.json`, so the built copies
469
+ of your site pages need a sign-in and, opened directly, land in Browse.
470
+
471
+ ```js
472
+ // astro.config.mjs: the adapter only in the editor's build
473
+ const editorBuild = process.env.EDITOR === '1' && process.argv.includes('build');
474
+ const { default: cloudflare } = editorBuild ? await import('@astrojs/cloudflare') : {};
475
+ export default defineConfig({
476
+ ...(cloudflare ? { adapter: cloudflare({ configPath: 'wrangler.editor.jsonc' }) } : {}),
477
+ // …
478
+ });
479
+ ```
480
+
481
+ ```bash
482
+ EDITOR=1 astro build && wrangler deploy --config dist/server/wrangler.json
483
+ EDITOR_SECRET=… npx pagestack-invite --name "You" --email you@example.com --origin https://edit.example.com
484
+ ```
395
485
 
396
- The editor server is a normal `@astrojs/node` standalone build. Run `node dist/server/entry.mjs`
486
+ **On a Node host**, the editor server is a normal `@astrojs/node` standalone build. Run `node dist/server/entry.mjs`
397
487
  on any small Node host (Fly, Railway, a VPS…) with `EDITOR_SECRET`, `GITHUB_TOKEN` and
398
488
  `EDITOR_ORIGIN` set, behind HTTPS. It serves the editor routes and the static pages it was built
399
- with; the public site is still deployed separately from the same repo as static files. Every
489
+ with; the public site is still deployed separately from the same repo as static files. (Here the
490
+ built site pages are served as plain files, without a sign-in; put the host behind an access proxy
491
+ if staged work must stay private.) Every
400
492
  editor response is `noindex` and `no-store`.
401
493
 
402
494
  ## Options
@@ -429,4 +521,4 @@ editor response is `noindex` and `no-store`.
429
521
  - [@astrojs/node](https://docs.astro.build/en/guides/integrations-guide/node/) (MIT) as the editor's adapter.
430
522
  - [Puck](https://puckeditor.com) was used as a design reference for JSON page editing only; no code.
431
523
 
432
- MIT.
524
+ MIT © Pirate & Fox LLC. See [LICENSE](LICENSE).
package/index.mjs CHANGED
@@ -21,11 +21,29 @@ function writeEditorHeaders(clientDir, previewScripts) {
21
21
  if (!fs.existsSync(clientDir)) return;
22
22
  const file = path.join(clientDir, '_headers');
23
23
  const scripts = previewScripts === 'all' ? "script-src-attr 'none'" : "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; script-src-attr 'none'";
24
- const block = `\n# pagestack: built pages served by the editor\n/*\n Content-Security-Policy: ${scripts}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n X-Frame-Options: SAMEORIGIN\n`;
24
+ const block = `\n# pagestack: built pages served by the editor\n/*\n Content-Security-Policy: ${scripts}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n X-Frame-Options: SAMEORIGIN\n X-Robots-Tag: noindex\n`;
25
25
  const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
26
26
  if (!existing.includes('# pagestack: built pages served by the editor')) fs.writeFileSync(file, existing + block);
27
27
  }
28
28
 
29
+ /**
30
+ * Cloudflare serves files in the assets directory before the Worker runs, which would put every
31
+ * built site page on the editor's domain with no sign-in. Send everything but hashed build assets
32
+ * through the Worker (src/worker.ts decides). Leaves a host's own `run_worker_first` alone.
33
+ */
34
+ function routeThroughWorker(serverDir, logger) {
35
+ const file = path.join(serverDir, 'wrangler.json');
36
+ if (!fs.existsSync(file)) return;
37
+ const conf = JSON.parse(fs.readFileSync(file, 'utf8'));
38
+ if (!conf.assets) return;
39
+ if (conf.assets.run_worker_first === undefined) {
40
+ conf.assets.run_worker_first = ['/*', '!/_astro/*'];
41
+ fs.writeFileSync(file, JSON.stringify(conf));
42
+ } else if (conf.assets.run_worker_first === false) {
43
+ logger?.warn('wrangler assets.run_worker_first is false: built site pages on the editor are served without sign-in.');
44
+ }
45
+ }
46
+
29
47
  const VIRTUAL = 'virtual:pagestack/site';
30
48
  const VIRTUAL_RENDERER = 'virtual:pagestack/renderer';
31
49
  const VIRTUAL_PREVIEWS = 'virtual:pagestack/previews';
@@ -107,13 +125,18 @@ export default function sectionEditor(userOptions) {
107
125
  hooks: {
108
126
  ...forwarded,
109
127
  'astro:config:done': async (params) => {
110
- if (editorBuild) editorBuild.dirs = [params.config.build.client, params.config.outDir]; // with an adapter, files go to build.client
128
+ if (editorBuild) {
129
+ editorBuild.dirs = [params.config.build.client, params.config.outDir]; // with an adapter, files go to build.client
130
+ editorBuild.server = params.config.build.server;
131
+ editorBuild.logger = params.logger;
132
+ }
111
133
  await forwarded['astro:config:done'](params);
112
134
  },
113
135
  'astro:build:done': async (params) => {
114
136
  await forwarded['astro:build:done'](params);
115
137
  const dir = editorBuild?.dirs?.map((u) => fileURLToPath(u)).find((d) => fs.existsSync(d));
116
138
  if (dir) writeEditorHeaders(dir, editorBuild.previewScripts);
139
+ if (editorBuild?.cloudflare && editorBuild.server) routeThroughWorker(fileURLToPath(editorBuild.server), editorBuild.logger);
117
140
  },
118
141
  // List pages named in `liveRoutes` render on request on the editor's server, reading what
119
142
  // has been saved. Only in the editor build: the public build never gets here.
@@ -169,7 +192,37 @@ export default function sectionEditor(userOptions) {
169
192
  vite: {
170
193
  plugins: [{
171
194
  name: 'pagestack:virtual',
172
- resolveId(id) { if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id; },
195
+ enforce: 'pre',
196
+ // A save in dev writes files the site's routes import, and Vite answers with a full
197
+ // reload of every open page, the editor included. Drop reloads caused by the editor's
198
+ // own writes (src/core/storage-local.ts); the editor refreshes its preview itself.
199
+ configureServer(server) {
200
+ const recent = () => {
201
+ const writes = globalThis.__PS_WRITES__;
202
+ if (!writes) return false;
203
+ const now = Date.now();
204
+ for (const [f, t] of writes) if (now - t > 3000) writes.delete(f);
205
+ return writes.size > 0;
206
+ };
207
+ const own = (payload) => {
208
+ if (payload?.type !== 'full-reload' || !recent()) return false;
209
+ const by = payload.triggeredBy ? path.resolve(payload.triggeredBy) : null;
210
+ return !by || globalThis.__PS_WRITES__.has(by) || /\.(json|md|mdx)$/.test(by);
211
+ };
212
+ const channels = [server.ws, ...Object.values(server.environments ?? {}).map((e) => e.hot)].filter(Boolean);
213
+ for (const ch of new Set(channels)) {
214
+ const send = ch.send.bind(ch);
215
+ ch.send = (payload, ...rest) => { if (!own(payload)) send(payload, ...rest); };
216
+ }
217
+ },
218
+ resolveId(id) {
219
+ if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id;
220
+ // On Cloudflare the editor's Worker checks site pages before the adapter (src/worker.ts).
221
+ if (isBuild && /^@astrojs\/cloudflare\/entrypoints\/server(\.js)?$/.test(id)) {
222
+ editorBuild.cloudflare = true;
223
+ return fileURLToPath(new URL('./src/worker.ts', import.meta.url));
224
+ }
225
+ },
173
226
  load(id) {
174
227
  // The renderer (and the site layout/CSS behind it) is only imported by the preview
175
228
  // route, so the editor shell doesn't drag the whole site's CSS into its page.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.11",
4
- "description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
3
+ "version": "0.1.0-beta.12",
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",
7
7
  "bin": {
@@ -23,7 +23,8 @@
23
23
  "test": "vitest run"
24
24
  },
25
25
  "peerDependencies": {
26
- "astro": ">=7.2.1"
26
+ "astro": ">=7.2.1",
27
+ "@astrojs/cloudflare": ">=13"
27
28
  },
28
29
  "dependencies": {
29
30
  "@astrojs/node": "11.1.11",
@@ -46,7 +47,14 @@
46
47
  "visual-editor",
47
48
  "cms",
48
49
  "git-based-cms",
49
- "sections"
50
+ "sections",
51
+ "astro",
52
+ "block-editor",
53
+ "page-builder",
54
+ "static-site",
55
+ "passkeys",
56
+ "webauthn",
57
+ "cloudflare-workers"
50
58
  ],
51
59
  "repository": {
52
60
  "type": "git",
@@ -58,5 +66,14 @@
58
66
  },
59
67
  "engines": {
60
68
  "node": ">=22.23.4"
61
- }
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "@astrojs/cloudflare": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "bugs": {
76
+ "url": "https://github.com/pirateandfox/pagestack/issues"
77
+ },
78
+ "author": "Pirate & Fox LLC (https://pirateandfox.com)"
62
79
  }
@@ -42,16 +42,18 @@ export class LocalStorage implements Storage {
42
42
  }
43
43
  async putAsset(p: string, bytes: Uint8Array): Promise<void> {
44
44
  const f = this.abs(p);
45
+ noteWrite(f);
45
46
  await fs.mkdir(path.dirname(f), { recursive: true });
46
47
  await fs.writeFile(f, bytes);
47
48
  }
48
49
  async commit({ files, deletes = [] }: { message: string; files: FileChange[]; deletes?: string[] }): Promise<CommitResult> {
49
50
  for (const f of files) {
50
51
  const abs = this.abs(f.path);
52
+ noteWrite(abs);
51
53
  await fs.mkdir(path.dirname(abs), { recursive: true });
52
54
  await fs.writeFile(abs, f.content);
53
55
  }
54
- for (const p of deletes) await fs.rm(this.abs(p), { force: true });
56
+ for (const p of deletes) { noteWrite(this.abs(p)); await fs.rm(this.abs(p), { force: true }); }
55
57
  return { kind: 'local', files: [...files.map((f) => f.path), ...deletes] };
56
58
  }
57
59
  /** Reads the working tree's git log; a folder that isn't a repository simply has no history. */
@@ -69,3 +71,12 @@ export class LocalStorage implements Storage {
69
71
  async pendingAsset(): Promise<undefined> { return undefined; }
70
72
  async asset(): Promise<undefined> { return undefined; } // the dev server serves the working tree
71
73
  }
74
+
75
+ /**
76
+ * Files the editor just wrote, so the dev server doesn't answer its own save with a full page
77
+ * reload (which would throw away the editor's selection and undo history). Read in index.mjs.
78
+ */
79
+ function noteWrite(abs: string) {
80
+ const g = globalThis as any;
81
+ (g.__PS_WRITES__ ??= new Map<string, number>()).set(path.resolve(abs), Date.now());
82
+ }
@@ -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">
@@ -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">
@@ -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">
@@ -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));
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
+ };