@tryghost/app-sdk 0.1.0-alpha.1 → 0.1.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,24 @@
1
1
  # @tryghost/app-sdk
2
2
 
3
- The SDK apps use to talk to Ghost from inside Admin.
3
+ The SDK apps use to talk to Ghost: from their page inside Admin, from their
4
+ backend, and from their tooling.
4
5
 
5
6
  An app's page runs in a frame inside Ghost Admin. The SDK connects it to Admin,
6
7
  gives it the site, the user and the theme, and lets it call the Admin API, keep
7
8
  its route in sync with Admin's URL, and send the publisher elsewhere in Admin.
8
9
 
10
+ | Entry point | Runs in | What it's for |
11
+ | --------------------------- | -------------------------- | ----------------------------------------------------------------------- |
12
+ | `@tryghost/app-sdk` | The app's page | Talking to Admin (below) |
13
+ | `@tryghost/app-sdk/backend` | Any platform with web APIs | [Answering Ghost's challenge and serving the manifest](#the-backend) |
14
+ | `@tryghost/app-sdk/tooling` | Node 22.12 or later | [Creating keys, and signing the manifest](#signing-the-manifest) |
15
+ | `@tryghost/app-sdk/vite` | Vite 6 or later | [Signing the manifest in `vite dev` and `vite build`](#the-vite-plugin) |
16
+ | `ghost-app` | Node 22.12 or later | [The same tooling on the command line](#the-ghost-app-cli) |
17
+
18
+ The page's entry point loads none of the others' code.
19
+
9
20
  > **Alpha.** CI publishes each change to npm as the next `0.1.0-alpha.N` under
10
- > the `alpha` tag. Alphas make no compatibility promise.
21
+ > the `latest` tag. Alphas make no compatibility promise.
11
22
 
12
23
  ## Quick start
13
24
 
@@ -29,10 +40,11 @@ ES module with everything inlined:
29
40
  ```
30
41
 
31
42
  With a bundler, install the package. It includes the types and code it uses
32
- from Ghost's contracts, so its only dependency is `@quilted/threads`:
43
+ from Ghost's contracts. The page needs only `@quilted/threads`, and the backend
44
+ adds `jose` and `zod`:
33
45
 
34
46
  ```sh
35
- pnpm add @tryghost/app-sdk@alpha
47
+ pnpm add @tryghost/app-sdk
36
48
  ```
37
49
 
38
50
  ```ts
@@ -251,24 +263,216 @@ documents in a row, each replaced within three seconds of starting. A publisher
251
263
  clicking quickly through more than five pages of a multi-page app would trip it
252
264
  too.
253
265
 
254
- ## Who can frame the page
266
+ ## Signing the manifest
267
+
268
+ Ghost installs an app from its manifest URL, where the app serves a signed
269
+ manifest: its `ghost-app.json`, with the fields below added, signed with the
270
+ app's identity key. Ghost pins that key when a site installs the app, and
271
+ challenges the app's origin to prove it holds the backend key the manifest
272
+ names. The manifest format is in
273
+ [`@tryghost/app-contracts`](../app-contracts/README.md#the-manifest).
274
+
275
+ `ghost-app.json` is the readable part, which the project keeps:
276
+
277
+ ```json
278
+ {
279
+ "id": "com.example.hello",
280
+ "name": "Hello",
281
+ "description": "Says hello.",
282
+ "author": { "name": "Example", "url": "https://example.com" },
283
+ "accent_color": "#ff5500",
284
+ "icon": { "name": "hand" },
285
+ "surfaces": [{ "type": "admin_page", "url": "/" }]
286
+ }
287
+ ```
255
288
 
256
- The SDK talks to whichever window frames the page. It can't know a site's Admin
257
- origin in advance, so if any site can frame the page, any site can fool it: send
258
- it a start context of its choosing, and answer every `fetch` itself. No Ghost
259
- credential is ever in the page. But whatever the publisher types into the page
260
- is exposed, and the app acts on whatever responses it gets.
289
+ Signing adds `manifest_url` (the address it's signed for), `identity_key` and
290
+ `backend_key` (the public keys) and `development`, and refuses a file that sets
291
+ any of them. It checks the manifest with the rules Ghost applies first, so a
292
+ manifest Ghost would refuse is never signed: the error lists every problem by
293
+ field. Ghost also refuses a manifest on the site's or Admin's host, on any port,
294
+ which only Ghost knows. To check a signed app end to end, install it on a Ghost
295
+ site, which fetches and verifies the manifest, challenges the backend, and says
296
+ why if it refuses.
297
+
298
+ ### Keys
299
+
300
+ Each mode has its own identity key and backend key, as two pairs of private
301
+ Ed25519 JWKs, in files only their owner can read:
302
+
303
+ - `.ghost-app/development/identity.json` and `backend.json`, for `vite dev`
304
+ and apps on this machine, such as on `my-app.localhost`, which `ghost-app keys`
305
+ or the Vite plugin's first run creates;
306
+ - `.ghost-app/production/identity.json` and `backend.json`, which only
307
+ `ghost-app keys --production` creates.
308
+
309
+ Only the owner can read a key on macOS and Linux. On Windows, a key gets the
310
+ permissions of the folder it's in, so keep the project in a folder only you can
311
+ read.
312
+
313
+ Keys are created only when git ignores `.ghost-app/` (in a repository), and an
314
+ existing key is never replaced. Keep a copy of the production identity key
315
+ somewhere safe: sites keep the identity key they installed an app with, and a
316
+ manifest signed with another one is another app. A development installation
317
+ and a production one are different apps for the same reason, so going from your
318
+ computer to a host means installing the app again.
319
+
320
+ The identity key stays with the developer, or CI. It never reaches the backend
321
+ or a build: only the signed manifest is served or emitted. The backend key goes
322
+ to the backend, which answers challenges with it. Developers who share a
323
+ development identity key must share its backend key too: a new backend key
324
+ retires the old one on every site that reads the new manifest.
325
+
326
+ In CI, set `GHOST_APP_IDENTITY_KEY` to the production identity key and
327
+ `GHOST_APP_BACKEND_KEY` to the backend key's public half, which
328
+ `ghost-app backend-key --production --public` prints, in place of the files. CI
329
+ only signs, so it never needs the backend's private key.
330
+
331
+ ### The Vite plugin
261
332
 
262
- Serve app pages with a `frame-ancestors` Content Security Policy that names the
263
- Ghost Admin origins of the sites using the app, so nothing else can frame them:
333
+ ```ts
334
+ import { cloudflare } from '@cloudflare/vite-plugin';
335
+ import { ghostApp } from '@tryghost/app-sdk/vite';
336
+ import { defineConfig } from 'vite';
337
+
338
+ export default defineConfig({ plugins: [ghostApp(), cloudflare()] });
339
+ ```
264
340
 
265
- ```http
266
- Content-Security-Policy: frame-ancestors https://site.example
341
+ In `vite dev`, the plugin creates the development keys if there are none, and
342
+ serves `/ghost-app.json` signed for the address it's requested at: a name for
343
+ this machine, such as `localhost`, `127.0.0.1` or any `.localhost` name, or a
344
+ tunnel named by the `tunnelUrl` option or `GHOST_APP_TUNNEL_URL`
345
+ (comma-separated). It refuses any other host with a 421, so the dev server never
346
+ signs a manifest for someone else's address. Ghost in Docker reaches the machine
347
+ through `host.docker.internal` with the original Host, which counts as the
348
+ machine. It prints the app at a name of its own under `.localhost`, from the
349
+ last part of its ID, such as
350
+ `http://hello-world.localhost:<port>/ghost-app.json` for
351
+ `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host
352
+ on any port. It prints the install link too, for `GHOST_URL` or
353
+ `http://localhost:2368`.
354
+
355
+ The dev server is for development only. The plugin adds `.ghost-app/`,
356
+ `.dev.vars*`, `.env` and `.env.*` to Vite's `server.fs.deny`, and refuses to
357
+ start with `server.fs.strict` off, which would make Vite skip that list. In dev
358
+ and in a build, it refuses an `envPrefix` that the key variables start with, such as
359
+ `GHOST_APP_`, which would put the keys in the page's bundle. Like Vite's own
360
+ `.env` protection, the list matches files by name: a link or alias you make to
361
+ the keys elsewhere in the project is served like any other file. Keep the keys
362
+ out of `publicDir`, which Vite serves and copies into the build as it is.
363
+
364
+ In a Cloudflare Workers project (one with a `wrangler.json`, `wrangler.jsonc`
365
+ or `wrangler.toml`), it adds `GHOST_APP_BACKEND_KEY` to `.dev.vars` with the
366
+ development backend key, so the Worker answers challenges in development as it
367
+ does in production. It never changes a value that's already there, and says so
368
+ when it isn't the development key. Wrangler reads `.env` and `.env.local` only
369
+ when there's no `.dev.vars`, so in a project with either and no `.dev.vars`, it
370
+ asks you to add the key to `.env.local` instead. Git must ignore whichever file
371
+ holds it.
372
+
373
+ In `vite build`, it signs `ghost-app.json` for `GHOST_APP_URL`, the app's public
374
+ address (the manifest is at `<GHOST_APP_URL>/ghost-app.json`), with the
375
+ production keys, and emits it with the client build. A missing key fails the
376
+ build with how to create one; the plugin never creates a production key.
377
+ Without `GHOST_APP_URL`, the build emits no manifest and warns, and deploying
378
+ it takes the app down wherever it's installed.
379
+
380
+ The plugin reads `GHOST_APP_URL`, `GHOST_APP_TUNNEL_URL` and `GHOST_URL` from
381
+ the environment, or from the mode's `.env` files as Vite reads them; the
382
+ environment wins. `.env.development` is the easy way to name a tunnel or your
383
+ Ghost in development, on Windows too. Commit the app's address in `.env.production` once it has
384
+ one, so no deploy can forget it:
385
+
386
+ ```sh
387
+ GHOST_APP_URL=https://hello.example.com
267
388
  ```
268
389
 
269
- Admin is usually on the site's own origin, or on a separate Admin domain when
270
- the site has one. An app installed on many sites can build the list from its
271
- own record of where it is installed.
390
+ List the plugin before `cloudflare()`. `options.manifest` names another file
391
+ than `ghost-app.json`.
392
+
393
+ ### The ghost-app CLI
394
+
395
+ ```sh
396
+ ghost-app keys [--production]
397
+ ghost-app sign --url <manifest URL> [--production] [--out <file>] [--manifest <file>]
398
+ ghost-app backend-key [--production] [--public | --check]
399
+ ```
400
+
401
+ - `keys` creates the mode's keys, keeping any that exist.
402
+ - `sign` prints the signed manifest, or writes it to `--out`.
403
+ - `backend-key` prints the mode's private backend key, for a host's secret
404
+ store. It's the only command that prints a private key. `--public` prints
405
+ only its public half, for CI. `--check` prints nothing, and exits with 0
406
+ only if the key is there and usable, with the reason on stderr otherwise,
407
+ so a script can stop before piping nothing into a secret store, in any shell:
408
+
409
+ ```sh
410
+ ghost-app backend-key --production --check && ghost-app backend-key --production | wrangler secret put GHOST_APP_BACKEND_KEY
411
+ ```
412
+
413
+ `--dir` points any of them at another project directory.
414
+
415
+ ### From code
416
+
417
+ `@tryghost/app-sdk/tooling` is what the CLI is built on, to sign from code:
418
+
419
+ | Export | What it does |
420
+ | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
421
+ | `createKeys({ root, mode })` | Creates the mode's missing keys. Resolves with `{ created, kept }`. |
422
+ | `readSigningKeys({ root, mode, env? })` | The identity key and the backend key's public half, from the files or, in production, `env`. |
423
+ | `readBackendKey({ root, mode })` | The mode's private backend key. |
424
+ | `signProject({ root, mode, manifestUrl, manifestFile? })` | Signs the project's `ghost-app.json` with the mode's keys. |
425
+ | `signAppManifest(source, { manifestUrl, identityKey, backendKey, development })` | Signs a manifest with the keys given. |
426
+ | `generateKey()`, `publicKeyOf(key)` | A new private key, and a key's public half. |
427
+
428
+ Signing resolves with `{ success: true, signed, manifest }`, or
429
+ `{ success: false, code, errors }`.
430
+
431
+ ## The backend
432
+
433
+ `@tryghost/app-sdk/backend` uses only `Request`, `Response`, `fetch` and
434
+ WebCrypto, so the same code runs on Cloudflare Workers, Node, Bun and Deno, and
435
+ in frameworks such as Hono. Configuration is passed in.
436
+
437
+ `withGhostApp` is the app's backend. It answers Ghost's challenge itself and
438
+ passes every other request to `fetch`. It returns `{ fetch }`, so a Worker
439
+ exports it as it is, reading its configuration from `cloudflare:workers`:
440
+
441
+ ```ts
442
+ import { env } from 'cloudflare:workers';
443
+ import { withGhostApp } from '@tryghost/app-sdk/backend';
444
+
445
+ export default withGhostApp({
446
+ backendKey: env.GHOST_APP_BACKEND_KEY,
447
+ fetch: (request) => env.ASSETS.fetch(request),
448
+ });
449
+ ```
450
+
451
+ It takes `handleChallenge`'s options and `fetch`, which gets whatever else the
452
+ platform passes too, such as a Worker's `env` and `ctx`. Frameworks that route
453
+ requests themselves, such as Hono, use `handleChallenge` directly.
454
+
455
+ | Export | What it does |
456
+ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
457
+ | `withGhostApp({ backendKey, fetch })` | The app's backend, as `{ fetch }`: answers the challenge at `CHALLENGE_PATH` with `handleChallenge`, and passes every other request to `fetch`. |
458
+ | `handleChallenge(request, { backendKey, origin? })` | Answers Ghost's challenge, posted to `CHALLENGE_PATH`, with the backend key: a private JWK, or its JSON as a secret holds it. `405` for any method but `POST`, `413` past 4 KB, `400` for anything that isn't a challenge for `origin` when it's given, or else `request.url`'s origin, `200` with the answer. |
459
+ | `serveManifest(signed)` | A response for the signed manifest, for a backend that doesn't serve it as a file. Caches must revalidate it, so a new manifest reaches Ghost the next time it reads it. |
460
+
461
+ `handleChallenge` refuses a challenge for any origin but the one the platform
462
+ reports in `request.url`, so pass the request as the platform hands it over,
463
+ never one rebuilt from `X-Forwarded-Host`. A server that doesn't see the public
464
+ scheme and host, such as Node behind a proxy that terminates TLS, passes the
465
+ app's public origin as `origin` (`https://app.example.com`), from its own
466
+ configuration, never from a request's headers. Workers don't need it.
467
+
468
+ ## Who can frame the page
469
+
470
+ The SDK talks to whichever window frames the page, and can't yet tell whether
471
+ it's Ghost Admin. A site that frames the page can send it a start context of
472
+ its choosing and answer every `fetch` itself. No Ghost credential is ever in the
473
+ page, but whatever the publisher types into the page reaches that site, and the
474
+ app acts on the responses it gets. Ghost will close this by vouching for the
475
+ site and the staff user to the app's backend.
272
476
 
273
477
  ## Serve only the app from its origin
274
478
 
@@ -280,15 +484,25 @@ content and third-party pages or widgets on another origin (a separate subdomain
280
484
  counts). An open redirect is a risk too: a link through it puts another site's
281
485
  page in the frame, inside Admin.
282
486
 
487
+ Serve the app from a host of its own, too. Ghost refuses an app on the site's
488
+ or Admin's host, whatever the port, because browsers send a host's cookies to
489
+ every port on it, Ghost's session cookie included. On your own machine, serve
490
+ the app from a name of its own under `.localhost`, such as `my-app.localhost`.
491
+ Browsers treat it as another host and send it to the machine itself, Vite
492
+ accepts it with no setup, and Ghost in development reaches it even where the
493
+ system's resolver doesn't know it. Open Admin on the name Ghost is configured
494
+ with, as Admin refuses an app on the host it's opened from too.
495
+
283
496
  ## Develop
284
497
 
285
498
  This is a workspace package in the Ghost monorepo. From the package directory:
286
499
 
287
500
  ```bash
288
501
  pnpm build # the package to build/ and the browser bundle to dist/, with Vite
289
- pnpm test # type-check + unit tests (jsdom, with a fake Admin on a real MessageChannel),
290
- # which build both afresh to check what they import, and pack build/ and dist/
291
- # to use them from an app outside the workspace (after pnpm build; Nx runs it)
502
+ pnpm test # type-check + unit tests (jsdom for the page, with a fake Admin on a real
503
+ # MessageChannel; Node for the backend, tooling, CLI and plugin), which build both
504
+ # afresh to check what they import, and pack build/ and dist/ to use them from an
505
+ # app outside the workspace (after pnpm build; Nx runs it)
292
506
  pnpm lint # lint source and tests
293
507
  ```
294
508
 
@@ -298,14 +512,22 @@ and also writes `dist/`, which is in `files` and in the Nx build outputs.
298
512
 
299
513
  It uses `@tryghost/app-contracts` for the bridge's message types, limits and
300
514
  shape checks, so the SDK and Admin apply the same rules to paths, themes and
301
- start contexts. It imports only the contracts' root entry point, which doesn't
302
- load `zod`, and the build inlines what it uses into the SDK, so the contracts
303
- are a dev dependency:
304
-
305
- - `build/index.js` imports only `@quilted/threads`;
306
- - `build/index.d.ts`, emitted by TypeScript 7 and bundled by
307
- `rolldown-plugin-dts`, imports nothing;
515
+ start contexts, and for signing and checking manifests and challenges, so the
516
+ tooling and the backend apply Ghost's own rules. The build inlines what it uses
517
+ into the SDK, so the contracts are a dev dependency. `build/` has an ES module
518
+ per entry point, which share chunks:
519
+
520
+ - `index.js` loads only `@quilted/threads`, never `jose`, `zod` or a Node
521
+ builtin;
522
+ - `backend.js` loads only `jose` and `zod`, and no Node builtin;
523
+ - `tooling.js`, `vite.js` and `bin.js` load Node builtins, `jose` and `zod`, and
524
+ `bin.js` `commander` too; `vite.js` imports Vite only when Vite runs the
525
+ plugin, not when it loads, as Vite is an optional peer dependency;
526
+ - each entry point's declarations, emitted by TypeScript 7 and bundled by
527
+ `rolldown-plugin-dts`, import nothing, but Vite's types for `vite.d.ts`;
308
528
  - `dist/` imports nothing at all.
309
529
 
310
- `test/bundle.test.ts` checks this on a fresh build. The build fails if the code
311
- imports a Node builtin, which Vite would otherwise replace with an empty stub.
530
+ `test/bundle.test.ts` checks this on a fresh build. The build keeps `node:`
531
+ imports as imports, so a builtin the page or the backend reaches shows up there.
532
+ Lint requires the `node:` prefix, as Vite replaces a builtin imported without it
533
+ with an empty stub.
@@ -0,0 +1,89 @@
1
+ import { r as SignedManifest, t as MANIFEST_PATH } from "./chunks/manifest-CYA0krtI.js";
2
+ //#region ../app-contracts/build/identity/challenge.d.ts
3
+ /** Where on an origin Ghost posts a challenge. */
4
+ declare const CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
5
+ //#endregion
6
+ //#region src/backend/challenge.d.ts
7
+ /**
8
+ * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's
9
+ * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and
10
+ * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.
11
+ */
12
+ type BackendJwk = {
13
+ alg?: string;
14
+ crv?: string;
15
+ d?: string;
16
+ dp?: string;
17
+ dq?: string;
18
+ e?: string;
19
+ ext?: boolean;
20
+ k?: string;
21
+ key_ops?: string[];
22
+ kid?: string;
23
+ kty?: string;
24
+ n?: string;
25
+ oth?: {
26
+ d?: string;
27
+ r?: string;
28
+ t?: string;
29
+ }[];
30
+ p?: string;
31
+ q?: string;
32
+ qi?: string;
33
+ use?: string;
34
+ x?: string;
35
+ y?: string;
36
+ };
37
+ /**
38
+ * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an
39
+ * environment variable, such as `GHOST_APP_BACKEND_KEY`.
40
+ */
41
+ type BackendKey = BackendJwk | string;
42
+ interface HandleChallengeOptions {
43
+ backendKey: BackendKey;
44
+ /**
45
+ * The app's public origin, such as `https://app.example.com`, for a server that doesn't see
46
+ * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees
47
+ * `http://`. Ghost challenges the public origin, so without it every challenge is refused.
48
+ * Take it from the app's own configuration, never from a request's headers, which the sender
49
+ * sets. Workers, and other platforms that report the public URL, don't need it.
50
+ */
51
+ origin?: string;
52
+ }
53
+ /**
54
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
55
+ * to it, or use `withGhostApp`, which does.
56
+ */
57
+ declare function handleChallenge(request: Request, { backendKey, origin }: HandleChallengeOptions): Promise<Response>;
58
+ //#endregion
59
+ //#region src/backend/app.d.ts
60
+ /**
61
+ * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`
62
+ * and `ctx`.
63
+ */
64
+ type FetchHandler<Args extends unknown[] = []> = (request: Request, ...args: Args) => Response | Promise<Response>;
65
+ interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {
66
+ /** The app's own handler, for every request but Ghost's challenge. */
67
+ fetch: FetchHandler<Args>;
68
+ }
69
+ /**
70
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
71
+ * passes every other request to `fetch`, with whatever else the platform passes.
72
+ *
73
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
74
+ */
75
+ declare function withGhostApp<Args extends unknown[] = []>({ fetch, ...challenge }: GhostAppOptions<Args>): {
76
+ fetch: (request: Request, ...args: Args) => Promise<Response>;
77
+ };
78
+ //#endregion
79
+ //#region src/backend/manifest.d.ts
80
+ /**
81
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
82
+ * file. Pass the file's text as it is, or the object it holds.
83
+ *
84
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
85
+ * Ghost the next time Ghost reads it.
86
+ */
87
+ declare function serveManifest(signed: SignedManifest | string): Response;
88
+ //#endregion
89
+ export { type BackendKey, CHALLENGE_PATH, type FetchHandler, type GhostAppOptions, type HandleChallengeOptions, MANIFEST_PATH, type SignedManifest, handleChallenge, serveManifest, withGhostApp };
@@ -0,0 +1,201 @@
1
+ import { i as ALGORITHM, r as ignoreError, t as MANIFEST_PATH } from "./chunks/manifest-BO_hJDEK.js";
2
+ import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
3
+ import { CompactSign } from "jose";
4
+ import { z } from "zod";
5
+ //#region ../app-contracts/build/identity/challenge.js
6
+ /** Where on an origin Ghost posts a challenge. */
7
+ var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
8
+ /** What a challenge is for, signed with it, so its answer can't pass for any other signature. */
9
+ var CHALLENGE_PURPOSE = "ghost-app-challenge";
10
+ z.strictObject({ alg: z.literal(ALGORITHM) });
11
+ JSON.stringify({ alg: ALGORITHM });
12
+ var ChallengeShape = z.strictObject({
13
+ purpose: z.literal(CHALLENGE_PURPOSE),
14
+ origin: z.string(),
15
+ nonce: z.string()
16
+ });
17
+ z.object({ signature: z.string() });
18
+ /**
19
+ * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is
20
+ * the URL the request arrived at, as the platform reports it (`request.url` on Workers):
21
+ * never one built from `X-Forwarded-Host` or any other header the sender controls. A
22
+ * challenge for any origin but that one is refused, so whoever takes over a name the app
23
+ * used to serve can't relay Ghost's challenge to the real backend to prove it.
24
+ *
25
+ * Ghost can't see this check, so it only helps where the platform routes requests by host,
26
+ * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.
27
+ */
28
+ async function answerChallenge(body, { backendKey, requestUrl }) {
29
+ const challenge = ChallengeShape.safeParse(parseJson(body));
30
+ if (!challenge.success) return {
31
+ success: false,
32
+ error: "Expected a challenge of {purpose, origin, nonce}"
33
+ };
34
+ const arrivedAt = URL.parse(requestUrl)?.origin;
35
+ if (arrivedAt !== challenge.data.origin) return {
36
+ success: false,
37
+ error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? "an unknown origin"}`
38
+ };
39
+ return {
40
+ success: true,
41
+ answer: { signature: await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: ALGORITHM }).sign(backendKey) }
42
+ };
43
+ }
44
+ function parseJson(text) {
45
+ try {
46
+ return JSON.parse(text);
47
+ } catch {
48
+ return;
49
+ }
50
+ }
51
+ //#endregion
52
+ //#region src/shared/body.ts
53
+ /**
54
+ * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
55
+ * stops reading as soon as the body passes the limit, so a large body is never held whole.
56
+ */
57
+ async function readBytes(message, maxBytes) {
58
+ if (Number(message.headers.get("content-length")) > maxBytes) {
59
+ message.body?.cancel().catch(ignoreError);
60
+ return;
61
+ }
62
+ if (!message.body) return /* @__PURE__ */ new Uint8Array();
63
+ const reader = message.body.getReader();
64
+ const chunks = [];
65
+ let length = 0;
66
+ for (;;) {
67
+ const { done, value } = await reader.read();
68
+ if (done) break;
69
+ length += value.byteLength;
70
+ if (length > maxBytes) {
71
+ reader.cancel().catch(ignoreError);
72
+ return;
73
+ }
74
+ chunks.push(value);
75
+ }
76
+ const bytes = new Uint8Array(length);
77
+ let offset = 0;
78
+ for (const chunk of chunks) {
79
+ bytes.set(chunk, offset);
80
+ offset += chunk.byteLength;
81
+ }
82
+ return bytes;
83
+ }
84
+ //#endregion
85
+ //#region src/backend/body.ts
86
+ /**
87
+ * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
88
+ * UTF-8 throws, as the exact text matters to whoever signs it.
89
+ */
90
+ async function readText(request, maxBytes) {
91
+ const bytes = await readBytes(request, maxBytes);
92
+ return bytes && new TextDecoder("utf-8", {
93
+ fatal: true,
94
+ ignoreBOM: true
95
+ }).decode(bytes);
96
+ }
97
+ function json(status, body, headers = {}) {
98
+ return new Response(JSON.stringify(body), {
99
+ status,
100
+ headers: {
101
+ "content-type": "application/json; charset=utf-8",
102
+ "cache-control": "no-store",
103
+ ...headers
104
+ }
105
+ });
106
+ }
107
+ //#endregion
108
+ //#region src/backend/challenge.ts
109
+ var CHALLENGE_MAX_BYTES = 4 * 1024;
110
+ var INVALID_KEY = "backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d";
111
+ var imported;
112
+ function importBackendKey(backendKey) {
113
+ const text = typeof backendKey === "string" ? backendKey : JSON.stringify(backendKey);
114
+ if (imported?.text !== text) {
115
+ const key = importPrivateKey(text);
116
+ imported = {
117
+ text,
118
+ key
119
+ };
120
+ key.catch(() => {
121
+ if (imported?.key === key) imported = void 0;
122
+ });
123
+ }
124
+ return imported.key;
125
+ }
126
+ async function importPrivateKey(text) {
127
+ let jwk;
128
+ try {
129
+ jwk = JSON.parse(text);
130
+ } catch {
131
+ throw new TypeError(`${INVALID_KEY}; it isn't JSON`);
132
+ }
133
+ const { kty, crv, x, d } = typeof jwk === "object" && jwk !== null ? jwk : {};
134
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") throw new TypeError(INVALID_KEY);
135
+ try {
136
+ return await crypto.subtle.importKey("jwk", {
137
+ kty,
138
+ crv,
139
+ x,
140
+ d
141
+ }, { name: "Ed25519" }, false, ["sign"]);
142
+ } catch (error) {
143
+ throw new TypeError(INVALID_KEY, { cause: error });
144
+ }
145
+ }
146
+ /**
147
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
148
+ * to it, or use `withGhostApp`, which does.
149
+ */
150
+ async function handleChallenge(request, { backendKey, origin }) {
151
+ const publicOrigin = origin === void 0 ? void 0 : parseOrigin(origin);
152
+ if (origin !== void 0 && !publicOrigin) throw new TypeError(`Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`);
153
+ if (request.method !== "POST") return json(405, { error: "Expected a POST" }, { allow: "POST" });
154
+ let body;
155
+ try {
156
+ body = await readText(request, CHALLENGE_MAX_BYTES);
157
+ } catch {
158
+ return json(400, { error: "Expected a challenge in UTF-8" });
159
+ }
160
+ if (body === void 0) return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });
161
+ const key = await importBackendKey(backendKey);
162
+ const result = await answerChallenge(body, {
163
+ backendKey: key,
164
+ requestUrl: publicOrigin ?? request.url
165
+ });
166
+ if (!result.success) return json(400, { error: result.error });
167
+ return json(200, result.answer);
168
+ }
169
+ //#endregion
170
+ //#region src/backend/app.ts
171
+ /**
172
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
173
+ * passes every other request to `fetch`, with whatever else the platform passes.
174
+ *
175
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
176
+ */
177
+ function withGhostApp({ fetch, ...challenge }) {
178
+ return { async fetch(request, ...args) {
179
+ if (new URL(request.url).pathname === "/.well-known/ghost-app/challenge") return handleChallenge(request, challenge);
180
+ return fetch(request, ...args);
181
+ } };
182
+ }
183
+ //#endregion
184
+ //#region src/backend/manifest.ts
185
+ /**
186
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
187
+ * file. Pass the file's text as it is, or the object it holds.
188
+ *
189
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
190
+ * Ghost the next time Ghost reads it.
191
+ */
192
+ function serveManifest(signed) {
193
+ return new Response(typeof signed === "string" ? signed : JSON.stringify(signed), { headers: {
194
+ "content-type": "application/json; charset=utf-8",
195
+ "cache-control": "no-cache"
196
+ } });
197
+ }
198
+ //#endregion
199
+ export { CHALLENGE_PATH, MANIFEST_PATH, handleChallenge, serveManifest, withGhostApp };
200
+
201
+ //# sourceMappingURL=backend.js.map