@tryghost/app-sdk 0.1.0-alpha.5 → 0.1.0-alpha.7

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,11 +1,20 @@
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.1 or later | [Creating keys, and signing and checking the manifest](#signing-the-manifest) |
15
+
16
+ The page's entry point loads none of the others' code.
17
+
9
18
  > **Alpha.** CI publishes each change to npm as the next `0.1.0-alpha.N` under
10
19
  > the `latest` tag. Alphas make no compatibility promise.
11
20
 
@@ -29,7 +38,8 @@ ES module with everything inlined:
29
38
  ```
30
39
 
31
40
  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`:
41
+ from Ghost's contracts. The page needs only `@quilted/threads`, and the backend
42
+ adds `jose` and `zod`:
33
43
 
34
44
  ```sh
35
45
  pnpm add @tryghost/app-sdk
@@ -251,24 +261,138 @@ documents in a row, each replaced within three seconds of starting. A publisher
251
261
  clicking quickly through more than five pages of a multi-page app would trip it
252
262
  too.
253
263
 
254
- ## Who can frame the page
264
+ ## Signing the manifest
265
+
266
+ Ghost installs an app from its manifest URL, where the app serves a signed
267
+ manifest: its `ghost-app.json`, with the fields below added, signed with the
268
+ app's identity key. Ghost pins that key when a site installs the app, and
269
+ challenges the app's origin to prove it holds the backend key the manifest
270
+ names. The manifest format is in
271
+ [`@tryghost/app-contracts`](../app-contracts/README.md#the-manifest).
272
+
273
+ `ghost-app.json` is the readable part, which the project keeps:
274
+
275
+ ```json
276
+ {
277
+ "id": "com.example.hello",
278
+ "name": "Hello",
279
+ "description": "Says hello.",
280
+ "author": { "name": "Example", "url": "https://example.com" },
281
+ "accent_color": "#ff5500",
282
+ "icon": { "name": "hand" },
283
+ "surfaces": [{ "type": "admin_page", "url": "/" }]
284
+ }
285
+ ```
286
+
287
+ Signing adds `manifest_url` (the address it's signed for), `identity_key` and
288
+ `backend_key` (the public keys) and `development`, and refuses a file that sets
289
+ any of them. It checks the manifest with the rules Ghost applies first, so a
290
+ manifest Ghost would refuse is never signed: the error lists every problem by
291
+ field. Ghost also refuses a manifest on the site's or Admin's host, on any port,
292
+ which only Ghost knows.
293
+
294
+ ### Keys
295
+
296
+ Each mode has its own identity key and backend key, as two pairs of private
297
+ Ed25519 JWKs, in files only their owner can read:
298
+
299
+ - `.ghost-app/development/identity.json` and `backend.json`, for apps on this
300
+ machine, such as on `my-app.localhost`;
301
+ - `.ghost-app/production/identity.json` and `backend.json`.
302
+
303
+ `createKeys({ root, mode })` creates them.
304
+
305
+ Only the owner can read a key on macOS and Linux. On Windows, a key gets the
306
+ permissions of the folder it's in, so keep the project in a folder only you can
307
+ read.
308
+
309
+ Keys are created only when git ignores `.ghost-app/` (in a repository), and an
310
+ existing key is never replaced. Keep a copy of the production identity key
311
+ somewhere safe: sites keep the identity key they installed an app with, and a
312
+ manifest signed with another one is another app. A development installation
313
+ and a production one are different apps for the same reason, so going from your
314
+ computer to a host means installing the app again.
315
+
316
+ The identity key stays with the developer, or CI. It never reaches the backend
317
+ or a build: only the signed manifest is served or emitted. The backend key goes
318
+ to the backend, which answers challenges with it. Developers who share a
319
+ development identity key must share its backend key too: a new backend key
320
+ retires the old one on every site that reads the new manifest.
321
+
322
+ In CI, set `GHOST_APP_IDENTITY_KEY` to the production identity key and
323
+ `GHOST_APP_BACKEND_KEY` to the backend key's public half, `publicKeyOf` of the
324
+ production backend key, in place of the files. CI only signs, so it never needs
325
+ the backend's private key.
326
+
327
+ ### From code
255
328
 
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.
329
+ `@tryghost/app-sdk/tooling` signs and checks from code:
261
330
 
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:
331
+ | Export | What it does |
332
+ | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
333
+ | `createKeys({ root, mode })` | Creates the mode's missing keys. Resolves with `{ created, kept }`. |
334
+ | `readSigningKeys({ root, mode, env? })` | The identity key and the backend key's public half, from the files or, in production, `env`. |
335
+ | `readBackendKey({ root, mode })` | The mode's private backend key. |
336
+ | `signProject({ root, mode, manifestUrl, manifestFile? })` | Signs the project's `ghost-app.json` with the mode's keys. |
337
+ | `signAppManifest(source, { manifestUrl, identityKey, backendKey, development })` | Signs a manifest with the keys given. |
338
+ | `checkApp(manifestUrl, { fetch? })` | Checks an app as Ghost does before installing it. Resolves with the parsed manifest, or a failure with Ghost's code. |
339
+ | `generateKey()`, `publicKeyOf(key)` | A new private key, and a key's public half. |
264
340
 
265
- ```http
266
- Content-Security-Policy: frame-ancestors https://site.example
341
+ Signing resolves with `{ success: true, signed, manifest }`, or
342
+ `{ success: false, code, errors }`.
343
+
344
+ `checkApp` fetches the signed manifest, verifies it, and challenges the app's
345
+ origin, even on `localhost`, which Ghost in development doesn't. A failure
346
+ carries Ghost's own code, such as `APP_MANIFEST_URL_MISMATCH`,
347
+ `APP_MANIFEST_SIGNATURE_INVALID` or `APP_CHALLENGE_FAILED`, and what exactly was
348
+ wrong. It can't check what only a site knows: the key it installed the app
349
+ with, and backend keys a newer manifest replaced.
350
+
351
+ ## The backend
352
+
353
+ `@tryghost/app-sdk/backend` uses only `Request`, `Response`, `fetch` and
354
+ WebCrypto, so the same code runs on Cloudflare Workers, Node, Bun and Deno, and
355
+ in frameworks such as Hono. Configuration is passed in.
356
+
357
+ `withGhostApp` is the app's backend. It answers Ghost's challenge itself and
358
+ passes every other request to `fetch`. It returns `{ fetch }`, so a Worker
359
+ exports it as it is, reading its configuration from `cloudflare:workers`:
360
+
361
+ ```ts
362
+ import { env } from 'cloudflare:workers';
363
+ import { withGhostApp } from '@tryghost/app-sdk/backend';
364
+
365
+ export default withGhostApp({
366
+ backendKey: env.GHOST_APP_BACKEND_KEY,
367
+ fetch: (request) => env.ASSETS.fetch(request),
368
+ });
267
369
  ```
268
370
 
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.
371
+ It takes `handleChallenge`'s options and `fetch`, which gets whatever else the
372
+ platform passes too, such as a Worker's `env` and `ctx`. Frameworks that route
373
+ requests themselves, such as Hono, use `handleChallenge` directly.
374
+
375
+ | Export | What it does |
376
+ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
377
+ | `withGhostApp({ backendKey, fetch })` | The app's backend, as `{ fetch }`: answers the challenge at `CHALLENGE_PATH` with `handleChallenge`, and passes every other request to `fetch`. |
378
+ | `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. |
379
+ | `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. |
380
+
381
+ `handleChallenge` refuses a challenge for any origin but the one the platform
382
+ reports in `request.url`, so pass the request as the platform hands it over,
383
+ never one rebuilt from `X-Forwarded-Host`. A server that doesn't see the public
384
+ scheme and host, such as Node behind a proxy that terminates TLS, passes the
385
+ app's public origin as `origin` (`https://app.example.com`), from its own
386
+ configuration, never from a request's headers. Workers don't need it.
387
+
388
+ ## Who can frame the page
389
+
390
+ The SDK talks to whichever window frames the page, and can't yet tell whether
391
+ it's Ghost Admin. A site that frames the page can send it a start context of
392
+ its choosing and answer every `fetch` itself. No Ghost credential is ever in the
393
+ page, but whatever the publisher types into the page reaches that site, and the
394
+ app acts on the responses it gets. Ghost will close this by vouching for the
395
+ site and the staff user to the app's backend.
272
396
 
273
397
  ## Serve only the app from its origin
274
398
 
@@ -295,9 +419,10 @@ This is a workspace package in the Ghost monorepo. From the package directory:
295
419
 
296
420
  ```bash
297
421
  pnpm build # the package to build/ and the browser bundle to dist/, with Vite
298
- pnpm test # type-check + unit tests (jsdom, with a fake Admin on a real MessageChannel),
299
- # which build both afresh to check what they import, and pack build/ and dist/
300
- # to use them from an app outside the workspace (after pnpm build; Nx runs it)
422
+ pnpm test # type-check + unit tests (jsdom for the page, with a fake Admin on a real
423
+ # MessageChannel; Node for the backend and tooling), which build both
424
+ # afresh to check what they import, and pack build/ and dist/ to use them from an
425
+ # app outside the workspace (after pnpm build; Nx runs it)
301
426
  pnpm lint # lint source and tests
302
427
  ```
303
428
 
@@ -307,14 +432,20 @@ and also writes `dist/`, which is in `files` and in the Nx build outputs.
307
432
 
308
433
  It uses `@tryghost/app-contracts` for the bridge's message types, limits and
309
434
  shape checks, so the SDK and Admin apply the same rules to paths, themes and
310
- start contexts. It imports only the contracts' root entry point, which doesn't
311
- load `zod`, and the build inlines what it uses into the SDK, so the contracts
312
- are a dev dependency:
313
-
314
- - `build/index.js` imports only `@quilted/threads`;
315
- - `build/index.d.ts`, emitted by TypeScript 7 and bundled by
316
- `rolldown-plugin-dts`, imports nothing;
435
+ start contexts, and for signing and checking manifests and challenges, so the
436
+ tooling and the backend apply Ghost's own rules. The build inlines what it uses
437
+ into the SDK, so the contracts are a dev dependency. `build/` has an ES module
438
+ per entry point, which share chunks:
439
+
440
+ - `index.js` loads only `@quilted/threads`, never `jose`, `zod` or a Node
441
+ builtin;
442
+ - `backend.js` loads only `jose` and `zod`, and no Node builtin;
443
+ - `tooling.js` loads Node builtins, `jose` and `zod`;
444
+ - each entry point's declarations, emitted by TypeScript 7 and bundled by
445
+ `rolldown-plugin-dts`, import nothing;
317
446
  - `dist/` imports nothing at all.
318
447
 
319
- `test/bundle.test.ts` checks this on a fresh build. The build fails if the code
320
- imports a Node builtin, which Vite would otherwise replace with an empty stub.
448
+ `test/bundle.test.ts` checks this on a fresh build. The build keeps `node:`
449
+ imports as imports, so a builtin the page or the backend reaches shows up there.
450
+ Lint requires the `node:` prefix, as Vite replaces a builtin imported without it
451
+ with an empty stub.
@@ -0,0 +1,89 @@
1
+ import { r as SignedManifest, t as MANIFEST_PATH } from "./chunks/manifest-CInTdKjI.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,118 @@
1
+ import { c as CHALLENGE_PATH, i as readBytes, l as answerChallenge, s as parseOrigin, t as MANIFEST_PATH } from "./chunks/manifest-DX1GTozy.js";
2
+ //#region src/backend/body.ts
3
+ /**
4
+ * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
5
+ * UTF-8 throws, as the exact text matters to whoever signs it.
6
+ */
7
+ async function readText(request, maxBytes) {
8
+ const bytes = await readBytes(request, maxBytes);
9
+ return bytes && new TextDecoder("utf-8", {
10
+ fatal: true,
11
+ ignoreBOM: true
12
+ }).decode(bytes);
13
+ }
14
+ function json(status, body, headers = {}) {
15
+ return new Response(JSON.stringify(body), {
16
+ status,
17
+ headers: {
18
+ "content-type": "application/json; charset=utf-8",
19
+ "cache-control": "no-store",
20
+ ...headers
21
+ }
22
+ });
23
+ }
24
+ //#endregion
25
+ //#region src/backend/challenge.ts
26
+ var CHALLENGE_MAX_BYTES = 4 * 1024;
27
+ var INVALID_KEY = "backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d";
28
+ var imported;
29
+ function importBackendKey(backendKey) {
30
+ const text = typeof backendKey === "string" ? backendKey : JSON.stringify(backendKey);
31
+ if (imported?.text !== text) {
32
+ const key = importPrivateKey(text);
33
+ imported = {
34
+ text,
35
+ key
36
+ };
37
+ key.catch(() => {
38
+ if (imported?.key === key) imported = void 0;
39
+ });
40
+ }
41
+ return imported.key;
42
+ }
43
+ async function importPrivateKey(text) {
44
+ let jwk;
45
+ try {
46
+ jwk = JSON.parse(text);
47
+ } catch {
48
+ throw new TypeError(`${INVALID_KEY}; it isn't JSON`);
49
+ }
50
+ const { kty, crv, x, d } = typeof jwk === "object" && jwk !== null ? jwk : {};
51
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") throw new TypeError(INVALID_KEY);
52
+ try {
53
+ return await crypto.subtle.importKey("jwk", {
54
+ kty,
55
+ crv,
56
+ x,
57
+ d
58
+ }, { name: "Ed25519" }, false, ["sign"]);
59
+ } catch (error) {
60
+ throw new TypeError(INVALID_KEY, { cause: error });
61
+ }
62
+ }
63
+ /**
64
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
65
+ * to it, or use `withGhostApp`, which does.
66
+ */
67
+ async function handleChallenge(request, { backendKey, origin }) {
68
+ const publicOrigin = origin === void 0 ? void 0 : parseOrigin(origin);
69
+ if (origin !== void 0 && !publicOrigin) throw new TypeError(`Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`);
70
+ if (request.method !== "POST") return json(405, { error: "Expected a POST" }, { allow: "POST" });
71
+ let body;
72
+ try {
73
+ body = await readText(request, CHALLENGE_MAX_BYTES);
74
+ } catch {
75
+ return json(400, { error: "Expected a challenge in UTF-8" });
76
+ }
77
+ if (body === void 0) return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });
78
+ const key = await importBackendKey(backendKey);
79
+ const result = await answerChallenge(body, {
80
+ backendKey: key,
81
+ requestUrl: publicOrigin ?? request.url
82
+ });
83
+ if (!result.success) return json(400, { error: result.error });
84
+ return json(200, result.answer);
85
+ }
86
+ //#endregion
87
+ //#region src/backend/app.ts
88
+ /**
89
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
90
+ * passes every other request to `fetch`, with whatever else the platform passes.
91
+ *
92
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
93
+ */
94
+ function withGhostApp({ fetch, ...challenge }) {
95
+ return { async fetch(request, ...args) {
96
+ if (new URL(request.url).pathname === "/.well-known/ghost-app/challenge") return handleChallenge(request, challenge);
97
+ return fetch(request, ...args);
98
+ } };
99
+ }
100
+ //#endregion
101
+ //#region src/backend/manifest.ts
102
+ /**
103
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
104
+ * file. Pass the file's text as it is, or the object it holds.
105
+ *
106
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
107
+ * Ghost the next time Ghost reads it.
108
+ */
109
+ function serveManifest(signed) {
110
+ return new Response(typeof signed === "string" ? signed : JSON.stringify(signed), { headers: {
111
+ "content-type": "application/json; charset=utf-8",
112
+ "cache-control": "no-cache"
113
+ } });
114
+ }
115
+ //#endregion
116
+ export { CHALLENGE_PATH, MANIFEST_PATH, handleChallenge, serveManifest, withGhostApp };
117
+
118
+ //# sourceMappingURL=backend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.js","names":[],"sources":["../src/backend/body.ts","../src/backend/challenge.ts","../src/backend/app.ts","../src/backend/manifest.ts"],"sourcesContent":["import { readBytes } from '../shared/body.ts';\n\n/**\n * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid\n * UTF-8 throws, as the exact text matters to whoever signs it.\n */\nexport async function readText(request: Request, maxBytes: number): Promise<string | undefined> {\n const bytes = await readBytes(request, maxBytes);\n return bytes && new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\n\nexport function json(status: number, body: unknown, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...headers,\n },\n });\n}\n","import { CHALLENGE_PATH, answerChallenge } from '@tryghost/app-contracts/identity';\n\nimport { parseOrigin } from '../shared/parse.ts';\nimport { json, readText } from './body.ts';\n\nexport { CHALLENGE_PATH };\n\n/**\n * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's\n * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and\n * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.\n */\nexport type BackendJwk = {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kid?: string;\n kty?: string;\n n?: string;\n oth?: { d?: string; r?: string; t?: string }[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n};\n\n/**\n * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an\n * environment variable, such as `GHOST_APP_BACKEND_KEY`.\n */\nexport type BackendKey = BackendJwk | string;\n\nexport interface HandleChallengeOptions {\n backendKey: BackendKey;\n /**\n * The app's public origin, such as `https://app.example.com`, for a server that doesn't see\n * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees\n * `http://`. Ghost challenges the public origin, so without it every challenge is refused.\n * Take it from the app's own configuration, never from a request's headers, which the sender\n * sets. Workers, and other platforms that report the public URL, don't need it.\n */\n origin?: string;\n}\n\n// Ghost's challenge is about 150 bytes. Anything much larger isn't one.\nconst CHALLENGE_MAX_BYTES = 4 * 1024;\n\nconst INVALID_KEY =\n 'backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d';\n\n// The last key imported, so a backend that answers with one key imports it once.\nlet imported: { text: string; key: Promise<CryptoKey> } | undefined;\n\nfunction importBackendKey(backendKey: BackendKey): Promise<CryptoKey> {\n const text = typeof backendKey === 'string' ? backendKey : JSON.stringify(backendKey);\n if (imported?.text !== text) {\n const key = importPrivateKey(text);\n imported = { text, key };\n // A key that failed to import is tried again next time, so a fixed secret takes effect.\n key.catch(() => {\n if (imported?.key === key) {\n imported = undefined;\n }\n });\n }\n return imported.key;\n}\n\nasync function importPrivateKey(text: string): Promise<CryptoKey> {\n let jwk: unknown;\n try {\n jwk = JSON.parse(text);\n } catch {\n // Never says what the text was: it's a secret.\n throw new TypeError(`${INVALID_KEY}; it isn't JSON`);\n }\n const { kty, crv, x, d } = (typeof jwk === 'object' && jwk !== null ? jwk : {}) as BackendJwk;\n if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || typeof d !== 'string') {\n throw new TypeError(INVALID_KEY);\n }\n try {\n return await crypto.subtle.importKey('jwk', { kty, crv, x, d }, { name: 'Ed25519' }, false, [\n 'sign',\n ]);\n } catch (error) {\n throw new TypeError(INVALID_KEY, { cause: error });\n }\n}\n\n/**\n * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`\n * to it, or use `withGhostApp`, which does.\n */\nexport async function handleChallenge(\n request: Request,\n { backendKey, origin }: HandleChallengeOptions,\n): Promise<Response> {\n // A bad `origin` is the app's own misconfiguration, so it throws, and the platform reports a\n // server error, rather than every challenge being refused with a 400 that looks like Ghost's\n // fault.\n const publicOrigin = origin === undefined ? undefined : parseOrigin(origin);\n if (origin !== undefined && !publicOrigin) {\n throw new TypeError(\n `Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`,\n );\n }\n\n // Ghost always POSTs the challenge.\n if (request.method !== 'POST') {\n return json(405, { error: 'Expected a POST' }, { allow: 'POST' });\n }\n\n // A challenge is about 150 bytes, so stop reading at 4 KB rather than buffer whatever a\n // sender streams.\n let body: string | undefined;\n try {\n body = await readText(request, CHALLENGE_MAX_BYTES);\n } catch {\n return json(400, { error: 'Expected a challenge in UTF-8' });\n }\n if (body === undefined) {\n return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });\n }\n\n // Imported once and cached. A `backendKey` that isn't a private Ed25519 key throws a\n // `TypeError`, a server error, for the same reason as a bad `origin`.\n const key = await importBackendKey(backendKey);\n\n // The challenge names the origin Ghost sent it to, and is answered only for this app's own:\n // the one the platform reports in `request.url`, or `origin` behind a proxy. Never one taken\n // from `X-Forwarded-Host` or another header the sender sets, or anyone could have this\n // backend sign a challenge meant for another app.\n const result = await answerChallenge(body, {\n backendKey: key,\n requestUrl: publicOrigin ?? request.url,\n });\n if (!result.success) {\n return json(400, { error: result.error });\n }\n\n // `{ signature }`: Ghost verifies it against the backend key the signed manifest names.\n return json(200, result.answer);\n}\n","import { CHALLENGE_PATH, handleChallenge, type HandleChallengeOptions } from './challenge.ts';\n\n/**\n * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`\n * and `ctx`.\n */\nexport type FetchHandler<Args extends unknown[] = []> = (\n request: Request,\n ...args: Args\n) => Response | Promise<Response>;\n\nexport interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {\n /** The app's own handler, for every request but Ghost's challenge. */\n fetch: FetchHandler<Args>;\n}\n\n/**\n * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and\n * passes every other request to `fetch`, with whatever else the platform passes.\n *\n * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.\n */\nexport function withGhostApp<Args extends unknown[] = []>({\n fetch,\n ...challenge\n}: GhostAppOptions<Args>): { fetch: (request: Request, ...args: Args) => Promise<Response> } {\n return {\n async fetch(request, ...args) {\n if (new URL(request.url).pathname === CHALLENGE_PATH) {\n return handleChallenge(request, challenge);\n }\n return fetch(request, ...args);\n },\n };\n}\n","import type { SignedManifest } from '../shared/manifest.ts';\n\nexport { MANIFEST_PATH, type SignedManifest } from '../shared/manifest.ts';\n\n/**\n * A response that serves the signed manifest, for a backend that doesn't serve it as a static\n * file. Pass the file's text as it is, or the object it holds.\n *\n * Caches may keep it, but must check it's still current each time, so a new manifest reaches\n * Ghost the next time Ghost reads it.\n */\nexport function serveManifest(signed: SignedManifest | string): Response {\n return new Response(typeof signed === 'string' ? signed : JSON.stringify(signed), {\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-cache',\n },\n });\n}\n"],"mappings":";;;;;;AAMA,eAAsB,SAAS,SAAkB,UAA+C;CAC9F,MAAM,QAAQ,MAAM,UAAU,SAAS,QAAQ;CAC/C,OAAO,SAAS,IAAI,YAAY,SAAS;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AACzF;AAEA,SAAgB,KAAK,QAAgB,MAAe,UAAkC,CAAC,GAAG;CACxF,OAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;EACxC;EACA,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,GAAG;EACL;CACF,CAAC;AACH;;;ACiCA,IAAM,sBAAsB,IAAI;AAEhC,IAAM,cACJ;AAGF,IAAI;AAEJ,SAAS,iBAAiB,YAA4C;CACpE,MAAM,OAAO,OAAO,eAAe,WAAW,aAAa,KAAK,UAAU,UAAU;CACpF,IAAI,UAAU,SAAS,MAAM;EAC3B,MAAM,MAAM,iBAAiB,IAAI;EACjC,WAAW;GAAE;GAAM;EAAI;EAEvB,IAAI,YAAY;GACd,IAAI,UAAU,QAAQ,KACpB,WAAW,KAAA;EAEf,CAAC;CACH;CACA,OAAO,SAAS;AAClB;AAEA,eAAe,iBAAiB,MAAkC;CAChE,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,IAAI;CACvB,QAAQ;EAEN,MAAM,IAAI,UAAU,GAAG,YAAY,gBAAgB;CACrD;CACA,MAAM,EAAE,KAAK,KAAK,GAAG,MAAO,OAAO,QAAQ,YAAY,QAAQ,OAAO,MAAM,CAAC;CAC7E,IAAI,QAAQ,SAAS,QAAQ,aAAa,OAAO,MAAM,YAAY,OAAO,MAAM,UAC9E,MAAM,IAAI,UAAU,WAAW;CAEjC,IAAI;EACF,OAAO,MAAM,OAAO,OAAO,UAAU,OAAO;GAAE;GAAK;GAAK;GAAG;EAAE,GAAG,EAAE,MAAM,UAAU,GAAG,OAAO,CAC1F,MACF,CAAC;CACH,SAAS,OAAO;EACd,MAAM,IAAI,UAAU,aAAa,EAAE,OAAO,MAAM,CAAC;CACnD;AACF;;;;;AAMA,eAAsB,gBACpB,SACA,EAAE,YAAY,UACK;CAInB,MAAM,eAAe,WAAW,KAAA,IAAY,KAAA,IAAY,YAAY,MAAM;CAC1E,IAAI,WAAW,KAAA,KAAa,CAAC,cAC3B,MAAM,IAAI,UACR,gFAAgF,QAClF;CAIF,IAAI,QAAQ,WAAW,QACrB,OAAO,KAAK,KAAK,EAAE,OAAO,kBAAkB,GAAG,EAAE,OAAO,OAAO,CAAC;CAKlE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,SAAS,SAAS,mBAAmB;CACpD,QAAQ;EACN,OAAO,KAAK,KAAK,EAAE,OAAO,gCAAgC,CAAC;CAC7D;CACA,IAAI,SAAS,KAAA,GACX,OAAO,KAAK,KAAK,EAAE,OAAO,mCAAmC,oBAAoB,QAAQ,CAAC;CAK5F,MAAM,MAAM,MAAM,iBAAiB,UAAU;CAM7C,MAAM,SAAS,MAAM,gBAAgB,MAAM;EACzC,YAAY;EACZ,YAAY,gBAAgB,QAAQ;CACtC,CAAC;CACD,IAAI,CAAC,OAAO,SACV,OAAO,KAAK,KAAK,EAAE,OAAO,OAAO,MAAM,CAAC;CAI1C,OAAO,KAAK,KAAK,OAAO,MAAM;AAChC;;;;;;;;;AChIA,SAAgB,aAA0C,EACxD,OACA,GAAG,aACwF;CAC3F,OAAO,EACL,MAAM,MAAM,SAAS,GAAG,MAAM;EAC5B,IAAI,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,aAAA,oCACvB,OAAO,gBAAgB,SAAS,SAAS;EAE3C,OAAO,MAAM,SAAS,GAAG,IAAI;CAC/B,EACF;AACF;;;;;;;;;;ACvBA,SAAgB,cAAc,QAA2C;CACvE,OAAO,IAAI,SAAS,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,MAAM,GAAG,EAChF,SAAS;EACP,gBAAgB;EAChB,iBAAiB;CACnB,EACF,CAAC;AACH"}
@@ -0,0 +1,19 @@
1
+ //#region src/shared/manifest.d.ts
2
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
3
+ declare const MANIFEST_PATH = "/ghost-app.json";
4
+ /** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */
5
+ interface SignedManifest {
6
+ protected: string;
7
+ payload: string;
8
+ signature: string;
9
+ }
10
+ /** One problem with a manifest. */
11
+ interface ManifestError {
12
+ /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */
13
+ path: string;
14
+ message: string;
15
+ }
16
+ /** A manifest's problems, one per line, as `path: message`. */
17
+ declare function formatErrors(errors: readonly ManifestError[], separator?: string): string;
18
+ //#endregion
19
+ export { formatErrors as i, ManifestError as n, SignedManifest as r, MANIFEST_PATH as t };