@tryghost/app-sdk 0.1.0-alpha.8 → 0.1.0-alpha.9

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
@@ -12,6 +12,7 @@ its route in sync with Admin's URL, and send the publisher elsewhere in Admin.
12
12
  | `@tryghost/app-sdk` | The app's page | Talking to Admin (below) |
13
13
  | `@tryghost/app-sdk/backend` | Any platform with web APIs | [Answering Ghost's challenge and serving the manifest](#the-backend) |
14
14
  | `@tryghost/app-sdk/tooling` | Node 22.12 or later | [Creating keys, and signing and checking 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) |
15
16
  | `ghost-app` | Node 22.12 or later | [The same tooling on the command line](#the-ghost-app-cli) |
16
17
 
17
18
  The page's entry point loads none of the others' code.
@@ -297,8 +298,9 @@ which only Ghost knows.
297
298
  Each mode has its own identity key and backend key, as two pairs of private
298
299
  Ed25519 JWKs, in files only their owner can read:
299
300
 
300
- - `.ghost-app/development/identity.json` and `backend.json`, for apps on this
301
- machine, such as on `my-app.localhost`, which `ghost-app keys` creates;
301
+ - `.ghost-app/development/identity.json` and `backend.json`, for `vite dev`
302
+ and apps on this machine, such as on `my-app.localhost`, which `ghost-app keys`
303
+ or the Vite plugin's first run creates;
302
304
  - `.ghost-app/production/identity.json` and `backend.json`, which only
303
305
  `ghost-app keys --production` creates.
304
306
 
@@ -324,6 +326,68 @@ In CI, set `GHOST_APP_IDENTITY_KEY` to the production identity key and
324
326
  `ghost-app backend-key --production --public` prints, in place of the files. CI
325
327
  only signs, so it never needs the backend's private key.
326
328
 
329
+ ### The Vite plugin
330
+
331
+ ```ts
332
+ import { cloudflare } from '@cloudflare/vite-plugin';
333
+ import { ghostApp } from '@tryghost/app-sdk/vite';
334
+ import { defineConfig } from 'vite';
335
+
336
+ export default defineConfig({ plugins: [ghostApp(), cloudflare()] });
337
+ ```
338
+
339
+ In `vite dev`, the plugin creates the development keys if there are none, and
340
+ serves `/ghost-app.json` signed for the address it's requested at: a name for
341
+ this machine, such as `localhost`, `127.0.0.1` or any `.localhost` name, or a
342
+ tunnel named by the `tunnelUrl` option or `GHOST_APP_TUNNEL_URL`
343
+ (comma-separated). It refuses any other host with a 421, so the dev server never
344
+ signs a manifest for someone else's address. Ghost in Docker reaches the machine
345
+ through `host.docker.internal` with the original Host, which counts as the
346
+ machine. It prints the app at a name of its own under `.localhost`, from the
347
+ last part of its ID, such as
348
+ `http://hello-world.localhost:<port>/ghost-app.json` for
349
+ `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host
350
+ on any port. It prints the install link too, for `GHOST_URL` or
351
+ `http://localhost:2368`.
352
+
353
+ The dev server is for development only. The plugin adds `.ghost-app/`,
354
+ `.dev.vars*`, `.env` and `.env.*` to Vite's `server.fs.deny`, and refuses to
355
+ start with `server.fs.strict` off, which would make Vite skip that list. In dev
356
+ and in a build, it refuses an `envPrefix` that the key variables start with, such as
357
+ `GHOST_APP_`, which would put the keys in the page's bundle. Like Vite's own
358
+ `.env` protection, the list matches files by name: a link or alias you make to
359
+ the keys elsewhere in the project is served like any other file. Keep the keys
360
+ out of `publicDir`, which Vite serves and copies into the build as it is.
361
+
362
+ In a Cloudflare Workers project (one with a `wrangler.json`, `wrangler.jsonc`
363
+ or `wrangler.toml`), it adds `GHOST_APP_BACKEND_KEY` to `.dev.vars` with the
364
+ development backend key, so the Worker answers challenges in development as it
365
+ does in production. It never changes a value that's already there, and says so
366
+ when it isn't the development key. Wrangler reads `.env` and `.env.local` only
367
+ when there's no `.dev.vars`, so in a project with either and no `.dev.vars`, it
368
+ asks you to add the key to `.env.local` instead. Git must ignore whichever file
369
+ holds it.
370
+
371
+ In `vite build`, it signs `ghost-app.json` for `GHOST_APP_URL`, the app's public
372
+ address (the manifest is at `<GHOST_APP_URL>/ghost-app.json`), with the
373
+ production keys, and emits it with the client build. A missing key fails the
374
+ build with how to create one; the plugin never creates a production key.
375
+ Without `GHOST_APP_URL`, the build emits no manifest and warns, and deploying
376
+ it takes the app down wherever it's installed.
377
+
378
+ The plugin reads `GHOST_APP_URL`, `GHOST_APP_TUNNEL_URL` and `GHOST_URL` from
379
+ the environment, or from the mode's `.env` files as Vite reads them; the
380
+ environment wins. `.env.development` is the easy way to name a tunnel or your
381
+ Ghost in development, on Windows too. Commit the app's address in `.env.production` once it has
382
+ one, so no deploy can forget it:
383
+
384
+ ```sh
385
+ GHOST_APP_URL=https://hello.example.com
386
+ ```
387
+
388
+ List the plugin before `cloudflare()`. `options.manifest` names another file
389
+ than `ghost-app.json`.
390
+
327
391
  ### The ghost-app CLI
328
392
 
329
393
  ```sh
@@ -445,7 +509,7 @@ This is a workspace package in the Ghost monorepo. From the package directory:
445
509
  ```bash
446
510
  pnpm build # the package to build/ and the browser bundle to dist/, with Vite
447
511
  pnpm test # type-check + unit tests (jsdom for the page, with a fake Admin on a real
448
- # MessageChannel; Node for the backend, tooling and CLI), which build both
512
+ # MessageChannel; Node for the backend, tooling, CLI and plugin), which build both
449
513
  # afresh to check what they import, and pack build/ and dist/ to use them from an
450
514
  # app outside the workspace (after pnpm build; Nx runs it)
451
515
  pnpm lint # lint source and tests
@@ -465,10 +529,11 @@ per entry point, which share chunks:
465
529
  - `index.js` loads only `@quilted/threads`, never `jose`, `zod` or a Node
466
530
  builtin;
467
531
  - `backend.js` loads only `jose` and `zod`, and no Node builtin;
468
- - `tooling.js` loads Node builtins, `jose` and `zod`, and `bin.js` those and
469
- `commander`;
532
+ - `tooling.js`, `vite.js` and `bin.js` load Node builtins, `jose` and `zod`, and
533
+ `bin.js` `commander` too; `vite.js` imports Vite only when Vite runs the
534
+ plugin, not when it loads, as Vite is an optional peer dependency;
470
535
  - each entry point's declarations, emitted by TypeScript 7 and bundled by
471
- `rolldown-plugin-dts`, import nothing;
536
+ `rolldown-plugin-dts`, import nothing, but Vite's types for `vite.d.ts`;
472
537
  - `dist/` imports nothing at all.
473
538
 
474
539
  `test/bundle.test.ts` checks this on a fresh build. The build keeps `node:`
package/build/backend.js CHANGED
@@ -1,4 +1,5 @@
1
- import { c as CHALLENGE_PATH, i as readBytes, l as answerChallenge, s as parseOrigin, t as MANIFEST_PATH } from "./chunks/manifest-DX1GTozy.js";
1
+ import { o as parseOrigin, t as MANIFEST_PATH } from "./chunks/manifest-iOwbzAil.js";
2
+ import { n as CHALLENGE_PATH, r as answerChallenge, t as readBytes } from "./chunks/body-CshsXE1J.js";
2
3
  //#region src/backend/body.ts
3
4
  /**
4
5
  * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
@@ -1 +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,KA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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"}
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,aAA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C,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"}
package/build/bin.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { a as signProject, c as KEYS_DIRECTORY, f as keyFile, g as checkApp, l as KEY_NAMES, m as readBackendKey, p as publicKeyOf, r as serialiseSigned, u as createKeys } from "./chunks/sign-BhNJAPta.js";
3
- import { r as formatErrors } from "./chunks/manifest-DX1GTozy.js";
2
+ import { a as signProject, c as KEYS_DIRECTORY, f as keyFile, l as KEY_NAMES, m as readBackendKey, p as publicKeyOf, r as serialiseSigned, u as createKeys } from "./chunks/sign-DygdzQYY.js";
3
+ import { r as formatErrors } from "./chunks/manifest-iOwbzAil.js";
4
+ import { t as checkApp } from "./chunks/check-3oU5pDJc.js";
4
5
  import { lstatSync, readlinkSync, realpathSync } from "node:fs";
5
6
  import { mkdir, writeFile } from "node:fs/promises";
6
7
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
package/build/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","names":[],"sources":["../src/tooling/paths.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["import { lstatSync, readlinkSync, realpathSync } from 'node:fs';\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\n\n/** Whether `child` is `parent` or anything inside it. Both are absolute. */\nexport function isWithin(parent: string, child: string): boolean {\n const path = relative(parent, child);\n // Only `..` as a whole segment climbs out: `..signed.json` is a file inside.\n return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));\n}\n\nconst realpath = (path: string) => {\n try {\n // The native one gives the case the path has on disk, where the filesystem ignores case.\n return realpathSync.native(path);\n } catch {\n return undefined;\n }\n};\n\n// As many links as Linux follows before it gives up with ELOOP.\nconst MAX_LINKS = 40;\n\n/**\n * Where writing to `path` really lands: through every link, as far as the path exists, and\n * along a chain of dangling links to where its last one points, as writing follows them all. A\n * path that doesn't exist yet lands in its directory, wherever that really is.\n */\nexport function canonicalPath(path: string, links = 0): string {\n const existing = realpath(path);\n if (existing) {\n return existing;\n }\n if (links < MAX_LINKS && lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {\n return canonicalPath(resolve(dirname(path), readlinkSync(path)), links + 1);\n }\n const parent = dirname(path);\n return join(parent === path ? parent : canonicalPath(parent, links), basename(path));\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { Command, CommanderError } from 'commander';\n\nimport { checkApp } from './tooling/check.ts';\nimport {\n KEYS_DIRECTORY,\n KEY_NAMES,\n createKeys,\n keyFile,\n publicKeyOf,\n readBackendKey,\n type Mode,\n} from './tooling/keys.ts';\nimport { canonicalPath, isWithin } from './tooling/paths.ts';\nimport { formatErrors } from './shared/manifest.ts';\nimport { MANIFEST_FILE, serialiseSigned, signProject } from './tooling/sign.ts';\n\nexport interface Io {\n out: (text: string) => void;\n err: (text: string) => void;\n}\n\nconst modeOf = (production: boolean | undefined): Mode =>\n production ? 'production' : 'development';\n\nasync function keys(root: string, mode: Mode, io: Io) {\n const { created, kept } = await createKeys({ root, mode });\n for (const name of created) {\n io.err(`Created ${keyFile(mode, name)}`);\n }\n for (const name of kept) {\n io.err(`Kept ${keyFile(mode, name)}, which already exists`);\n }\n if (mode === 'production' && created.includes('identity')) {\n io.err(\n '\\nKeep a copy of the production identity key somewhere safe, such as a password manager. ' +\n 'Sites that install the app keep its identity key, and an app signed with another key is another app.',\n );\n }\n}\n\nconst MODES: readonly Mode[] = ['development', 'production'];\n\n/** Throws if writing to `written` would overwrite the manifest it's signed from, or a key. */\nfunction refuseToOverwrite(root: string, written: string, manifestFile: string) {\n // Where the write would really land, through every link.\n const lands = canonicalPath(written);\n if (lands === canonicalPath(resolve(root, manifestFile))) {\n throw new Error(\n `Refusing to write the signed manifest over ${manifestFile}, which it's signed from`,\n );\n }\n // Refused by the path as written, by where it really lands, and by where each key really is,\n // so neither a link out of .ghost-app/ nor a key that is itself a link lets it reach a key.\n const keysDirectory = join(root, KEYS_DIRECTORY);\n const keyFiles = MODES.flatMap((mode) =>\n KEY_NAMES.map((name) => canonicalPath(join(root, keyFile(mode, name)))),\n );\n if (\n isWithin(keysDirectory, written) ||\n isWithin(canonicalPath(keysDirectory), lands) ||\n keyFiles.includes(lands)\n ) {\n throw new Error(\n `Refusing to write the signed manifest into ${KEYS_DIRECTORY}/, which holds the keys`,\n );\n }\n}\n\nasync function sign(\n root: string,\n {\n url,\n production,\n out,\n manifest,\n }: { url: string; production?: boolean; out?: string; manifest?: string },\n io: Io,\n) {\n const manifestFile = manifest ?? MANIFEST_FILE;\n // Against the project's directory, like --manifest and the keys.\n const written = out === undefined ? undefined : resolve(root, out);\n if (written) {\n refuseToOverwrite(root, written, manifestFile);\n }\n const result = await signProject({\n root,\n mode: modeOf(production),\n manifestUrl: url,\n manifestFile,\n });\n if (!result.success) {\n io.err(`${result.code}: ${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n return 1;\n }\n const text = serialiseSigned(result.signed);\n if (written) {\n await mkdir(dirname(written), { recursive: true });\n await writeFile(written, text);\n io.err(`Wrote ${written}, signed for ${String(result.manifest.manifest_url)}`);\n } else {\n io.out(text);\n }\n return 0;\n}\n\nasync function check(url: string, io: Io) {\n const result = await checkApp(url);\n if (!result.success) {\n io.err(`${result.code}: ${result.message}`);\n io.err(result.errors ? formatErrors(result.errors) : result.detail);\n return 1;\n }\n const { manifest } = result;\n io.out(\n `OK: ${manifest.name} (${manifest.id}) at ${result.manifestUrl} is signed with the identity key it names, and its origin answered the challenge with its backend key.`,\n );\n if (manifest.development) {\n io.out('It is a development build, which Admin labels as one.');\n }\n return 0;\n}\n\nasync function backendKey(\n root: string,\n {\n production,\n public: publicHalf,\n check: checkOnly,\n }: { production?: boolean; public?: boolean; check?: boolean },\n io: Io,\n) {\n // Reading the key checks it, and fails with what's wrong, never with the key.\n const key = await readBackendKey({ root, mode: modeOf(production) });\n if (!checkOnly) {\n io.out(JSON.stringify(publicHalf ? publicKeyOf(key) : key));\n }\n}\n\n/** Runs the CLI with its arguments (without `node` and the script), resolving with the exit code. */\nexport async function run(args: string[], io: Io): Promise<number> {\n let exitCode = 0;\n const program = new Command('ghost-app')\n .description(\"Creates an app's keys, signs its manifest, and checks it as Ghost does.\")\n .option('--dir <directory>', \"the project's directory\", '.')\n .showHelpAfterError()\n // Thrown rather than exiting, so `run` resolves with the code, and prints through `io`.\n .exitOverride()\n .configureOutput({ writeOut: io.out, writeErr: io.err });\n const root = () => resolve(program.opts<{ dir: string }>().dir);\n\n program\n .command('keys')\n .description(\n \"Creates the mode's identity and backend keys in .ghost-app/, keeping any that exist\",\n )\n .option('--production', 'the production keys instead of the development ones')\n .action(async ({ production }: { production?: boolean }) => {\n await keys(root(), modeOf(production), io);\n });\n\n program\n .command('sign')\n .description('Signs ghost-app.json for the address it will be served from')\n .requiredOption('--url <manifest URL>', 'the address the signed manifest will be served from')\n .option('--production', 'with the production keys instead of the development ones')\n .option('--out <file>', \"write it to a file in the project's directory instead of printing it\")\n .option('--manifest <file>', 'sign another file than ghost-app.json')\n .action(async (options: Parameters<typeof sign>[1]) => {\n exitCode = await sign(root(), options, io);\n });\n\n program\n .command('check')\n .description('Checks an app as Ghost does before installing it')\n .argument('<manifest URL>', 'the address of its signed manifest')\n .action(async (url: string) => {\n exitCode = await check(url, io);\n });\n\n program\n .command('backend-key')\n .description(\n \"Prints the mode's private backend key, to pipe into a secret store: ghost-app backend-key --production --check && ghost-app backend-key --production | wrangler secret put GHOST_APP_BACKEND_KEY\",\n )\n .option('--production', 'the production key instead of the development one')\n .option('--public', 'print only its public half, which is all CI needs to sign')\n .option('--check', 'print nothing, and exit 0 only if the key is there and usable')\n .action(async (options: Parameters<typeof backendKey>[1]) => {\n await backendKey(root(), options, io);\n });\n\n try {\n await program.parseAsync(args, { from: 'user' });\n return exitCode;\n } catch (error) {\n // Commander has already printed help, or the mistake and the help: 0 for asking for help,\n // and 2 for a mistake in how the CLI was called.\n if (error instanceof CommanderError) {\n return error.exitCode === 0 ? 0 : 2;\n }\n io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n","#!/usr/bin/env node\nimport { run } from './cli.ts';\n\nconst line = (text: string) => (text.endsWith('\\n') ? text : `${text}\\n`);\n\nrun(process.argv.slice(2), {\n out: (text) => process.stdout.write(line(text)),\n err: (text) => process.stderr.write(line(text)),\n}).then(\n (code) => {\n process.exitCode = code;\n },\n // run reports its own failures, so this is a bug: say what, without a stack trace.\n (error: unknown) => {\n process.stderr.write(line(error instanceof Error ? error.message : String(error)));\n process.exitCode = 1;\n },\n);\n"],"mappings":";;;;;;;;;AAIA,SAAgB,SAAS,QAAgB,OAAwB;CAC/D,MAAM,OAAO,SAAS,QAAQ,KAAK;CAEnC,OAAO,SAAS,MAAO,SAAS,QAAQ,CAAC,KAAK,WAAW,KAAK,KAAK,KAAK,CAAC,WAAW,IAAI;AAC1F;AAEA,IAAM,YAAY,SAAiB;CACjC,IAAI;EAEF,OAAO,aAAa,OAAO,IAAI;CACjC,QAAQ;EACN;CACF;AACF;AAGA,IAAM,YAAY;;;;;;AAOlB,SAAgB,cAAc,MAAc,QAAQ,GAAW;CAC7D,MAAM,WAAW,SAAS,IAAI;CAC9B,IAAI,UACF,OAAO;CAET,IAAI,QAAQ,aAAa,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,eAAe,GAClF,OAAO,cAAc,QAAQ,QAAQ,IAAI,GAAG,aAAa,IAAI,CAAC,GAAG,QAAQ,CAAC;CAE5E,MAAM,SAAS,QAAQ,IAAI;CAC3B,OAAO,KAAK,WAAW,OAAO,SAAS,cAAc,QAAQ,KAAK,GAAG,SAAS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,KAAK;AAErE,IAAI,QAAQ,KAAK,MAAM,CAAC,GAAG;CACzB,MAAM,SAAS,QAAQ,OAAO,MAAM,KAAK,IAAI,CAAC;CAC9C,MAAM,SAAS,QAAQ,OAAO,MAAM,KAAK,IAAI,CAAC;AAChD,CAAC,CAAC,CAAC,MACA,SAAS;CACR,QAAQ,WAAW;AACrB,IAEC,UAAmB;CAClB,QAAQ,OAAO,MAAM,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,CAAC;CACjF,QAAQ,WAAW;AACrB,CACF"}
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/tooling/paths.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["import { lstatSync, readlinkSync, realpathSync } from 'node:fs';\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\n\n/** Whether `child` is `parent` or anything inside it. Both are absolute. */\nexport function isWithin(parent: string, child: string): boolean {\n const path = relative(parent, child);\n // Only `..` as a whole segment climbs out: `..signed.json` is a file inside.\n return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));\n}\n\nconst realpath = (path: string) => {\n try {\n // The native one gives the case the path has on disk, where the filesystem ignores case.\n return realpathSync.native(path);\n } catch {\n return undefined;\n }\n};\n\n// As many links as Linux follows before it gives up with ELOOP.\nconst MAX_LINKS = 40;\n\n/**\n * Where writing to `path` really lands: through every link, as far as the path exists, and\n * along a chain of dangling links to where its last one points, as writing follows them all. A\n * path that doesn't exist yet lands in its directory, wherever that really is.\n */\nexport function canonicalPath(path: string, links = 0): string {\n const existing = realpath(path);\n if (existing) {\n return existing;\n }\n if (links < MAX_LINKS && lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {\n return canonicalPath(resolve(dirname(path), readlinkSync(path)), links + 1);\n }\n const parent = dirname(path);\n return join(parent === path ? parent : canonicalPath(parent, links), basename(path));\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { Command, CommanderError } from 'commander';\n\nimport { checkApp } from './tooling/check.ts';\nimport {\n KEYS_DIRECTORY,\n KEY_NAMES,\n createKeys,\n keyFile,\n publicKeyOf,\n readBackendKey,\n type Mode,\n} from './tooling/keys.ts';\nimport { canonicalPath, isWithin } from './tooling/paths.ts';\nimport { formatErrors } from './shared/manifest.ts';\nimport { MANIFEST_FILE, serialiseSigned, signProject } from './tooling/sign.ts';\n\nexport interface Io {\n out: (text: string) => void;\n err: (text: string) => void;\n}\n\nconst modeOf = (production: boolean | undefined): Mode =>\n production ? 'production' : 'development';\n\nasync function keys(root: string, mode: Mode, io: Io) {\n const { created, kept } = await createKeys({ root, mode });\n for (const name of created) {\n io.err(`Created ${keyFile(mode, name)}`);\n }\n for (const name of kept) {\n io.err(`Kept ${keyFile(mode, name)}, which already exists`);\n }\n if (mode === 'production' && created.includes('identity')) {\n io.err(\n '\\nKeep a copy of the production identity key somewhere safe, such as a password manager. ' +\n 'Sites that install the app keep its identity key, and an app signed with another key is another app.',\n );\n }\n}\n\nconst MODES: readonly Mode[] = ['development', 'production'];\n\n/** Throws if writing to `written` would overwrite the manifest it's signed from, or a key. */\nfunction refuseToOverwrite(root: string, written: string, manifestFile: string) {\n // Where the write would really land, through every link.\n const lands = canonicalPath(written);\n if (lands === canonicalPath(resolve(root, manifestFile))) {\n throw new Error(\n `Refusing to write the signed manifest over ${manifestFile}, which it's signed from`,\n );\n }\n // Refused by the path as written, by where it really lands, and by where each key really is,\n // so neither a link out of .ghost-app/ nor a key that is itself a link lets it reach a key.\n const keysDirectory = join(root, KEYS_DIRECTORY);\n const keyFiles = MODES.flatMap((mode) =>\n KEY_NAMES.map((name) => canonicalPath(join(root, keyFile(mode, name)))),\n );\n if (\n isWithin(keysDirectory, written) ||\n isWithin(canonicalPath(keysDirectory), lands) ||\n keyFiles.includes(lands)\n ) {\n throw new Error(\n `Refusing to write the signed manifest into ${KEYS_DIRECTORY}/, which holds the keys`,\n );\n }\n}\n\nasync function sign(\n root: string,\n {\n url,\n production,\n out,\n manifest,\n }: { url: string; production?: boolean; out?: string; manifest?: string },\n io: Io,\n) {\n const manifestFile = manifest ?? MANIFEST_FILE;\n // Against the project's directory, like --manifest and the keys.\n const written = out === undefined ? undefined : resolve(root, out);\n if (written) {\n refuseToOverwrite(root, written, manifestFile);\n }\n const result = await signProject({\n root,\n mode: modeOf(production),\n manifestUrl: url,\n manifestFile,\n });\n if (!result.success) {\n io.err(`${result.code}: ${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n return 1;\n }\n const text = serialiseSigned(result.signed);\n if (written) {\n await mkdir(dirname(written), { recursive: true });\n await writeFile(written, text);\n io.err(`Wrote ${written}, signed for ${String(result.manifest.manifest_url)}`);\n } else {\n io.out(text);\n }\n return 0;\n}\n\nasync function check(url: string, io: Io) {\n const result = await checkApp(url);\n if (!result.success) {\n io.err(`${result.code}: ${result.message}`);\n io.err(result.errors ? formatErrors(result.errors) : result.detail);\n return 1;\n }\n const { manifest } = result;\n io.out(\n `OK: ${manifest.name} (${manifest.id}) at ${result.manifestUrl} is signed with the identity key it names, and its origin answered the challenge with its backend key.`,\n );\n if (manifest.development) {\n io.out('It is a development build, which Admin labels as one.');\n }\n return 0;\n}\n\nasync function backendKey(\n root: string,\n {\n production,\n public: publicHalf,\n check: checkOnly,\n }: { production?: boolean; public?: boolean; check?: boolean },\n io: Io,\n) {\n // Reading the key checks it, and fails with what's wrong, never with the key.\n const key = await readBackendKey({ root, mode: modeOf(production) });\n if (!checkOnly) {\n io.out(JSON.stringify(publicHalf ? publicKeyOf(key) : key));\n }\n}\n\n/** Runs the CLI with its arguments (without `node` and the script), resolving with the exit code. */\nexport async function run(args: string[], io: Io): Promise<number> {\n let exitCode = 0;\n const program = new Command('ghost-app')\n .description(\"Creates an app's keys, signs its manifest, and checks it as Ghost does.\")\n .option('--dir <directory>', \"the project's directory\", '.')\n .showHelpAfterError()\n // Thrown rather than exiting, so `run` resolves with the code, and prints through `io`.\n .exitOverride()\n .configureOutput({ writeOut: io.out, writeErr: io.err });\n const root = () => resolve(program.opts<{ dir: string }>().dir);\n\n program\n .command('keys')\n .description(\n \"Creates the mode's identity and backend keys in .ghost-app/, keeping any that exist\",\n )\n .option('--production', 'the production keys instead of the development ones')\n .action(async ({ production }: { production?: boolean }) => {\n await keys(root(), modeOf(production), io);\n });\n\n program\n .command('sign')\n .description('Signs ghost-app.json for the address it will be served from')\n .requiredOption('--url <manifest URL>', 'the address the signed manifest will be served from')\n .option('--production', 'with the production keys instead of the development ones')\n .option('--out <file>', \"write it to a file in the project's directory instead of printing it\")\n .option('--manifest <file>', 'sign another file than ghost-app.json')\n .action(async (options: Parameters<typeof sign>[1]) => {\n exitCode = await sign(root(), options, io);\n });\n\n program\n .command('check')\n .description('Checks an app as Ghost does before installing it')\n .argument('<manifest URL>', 'the address of its signed manifest')\n .action(async (url: string) => {\n exitCode = await check(url, io);\n });\n\n program\n .command('backend-key')\n .description(\n \"Prints the mode's private backend key, to pipe into a secret store: ghost-app backend-key --production --check && ghost-app backend-key --production | wrangler secret put GHOST_APP_BACKEND_KEY\",\n )\n .option('--production', 'the production key instead of the development one')\n .option('--public', 'print only its public half, which is all CI needs to sign')\n .option('--check', 'print nothing, and exit 0 only if the key is there and usable')\n .action(async (options: Parameters<typeof backendKey>[1]) => {\n await backendKey(root(), options, io);\n });\n\n try {\n await program.parseAsync(args, { from: 'user' });\n return exitCode;\n } catch (error) {\n // Commander has already printed help, or the mistake and the help: 0 for asking for help,\n // and 2 for a mistake in how the CLI was called.\n if (error instanceof CommanderError) {\n return error.exitCode === 0 ? 0 : 2;\n }\n io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n","#!/usr/bin/env node\nimport { run } from './cli.ts';\n\nconst line = (text: string) => (text.endsWith('\\n') ? text : `${text}\\n`);\n\nrun(process.argv.slice(2), {\n out: (text) => process.stdout.write(line(text)),\n err: (text) => process.stderr.write(line(text)),\n}).then(\n (code) => {\n process.exitCode = code;\n },\n // run reports its own failures, so this is a bug: say what, without a stack trace.\n (error: unknown) => {\n process.stderr.write(line(error instanceof Error ? error.message : String(error)));\n process.exitCode = 1;\n },\n);\n"],"mappings":";;;;;;;;;;AAIA,SAAgB,SAAS,QAAgB,OAAwB;CAC/D,MAAM,OAAO,SAAS,QAAQ,KAAK;CAEnC,OAAO,SAAS,MAAO,SAAS,QAAQ,CAAC,KAAK,WAAW,KAAK,KAAK,KAAK,CAAC,WAAW,IAAI;AAC1F;AAEA,IAAM,YAAY,SAAiB;CACjC,IAAI;EAEF,OAAO,aAAa,OAAO,IAAI;CACjC,QAAQ;EACN;CACF;AACF;AAGA,IAAM,YAAY;;;;;;AAOlB,SAAgB,cAAc,MAAc,QAAQ,GAAW;CAC7D,MAAM,WAAW,SAAS,IAAI;CAC9B,IAAI,UACF,OAAO;CAET,IAAI,QAAQ,aAAa,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,eAAe,GAClF,OAAO,cAAc,QAAQ,QAAQ,IAAI,GAAG,aAAa,IAAI,CAAC,GAAG,QAAQ,CAAC;CAE5E,MAAM,SAAS,QAAQ,IAAI;CAC3B,OAAO,KAAK,WAAW,OAAO,SAAS,cAAc,QAAQ,KAAK,GAAG,SAAS,IAAI,CAAC;AACrF;;;ACbA,IAAM,UAAU,eACd,aAAa,eAAe;AAE9B,eAAe,KAAK,MAAc,MAAY,IAAQ;CACpD,MAAM,EAAE,SAAS,SAAS,MAAM,WAAW;EAAE;EAAM;CAAK,CAAC;CACzD,KAAK,MAAM,QAAQ,SACjB,GAAG,IAAI,WAAW,QAAQ,MAAM,IAAI,GAAG;CAEzC,KAAK,MAAM,QAAQ,MACjB,GAAG,IAAI,QAAQ,QAAQ,MAAM,IAAI,EAAE,uBAAuB;CAE5D,IAAI,SAAS,gBAAgB,QAAQ,SAAS,UAAU,GACtD,GAAG,IACD,+LAEF;AAEJ;AAEA,IAAM,QAAyB,CAAC,eAAe,YAAY;;AAG3D,SAAS,kBAAkB,MAA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, compactVerify, importJWK } from "jose";
2
3
  import { z } from "zod";
3
- //#region ../app-contracts/build/identity/keys.js
4
- function decodeUtf8(bytes) {
5
- return new TextDecoder("utf-8", {
6
- fatal: true,
7
- ignoreBOM: true
8
- }).decode(bytes);
9
- }
10
- function decodeText(encoded) {
11
- try {
12
- return decodeUtf8(base64url.decode(encoded));
13
- } catch {
14
- return;
15
- }
16
- }
17
- function decodeJson(encoded) {
18
- const text = decodeText(encoded);
19
- if (text === void 0) return;
20
- try {
21
- return JSON.parse(text);
22
- } catch {
23
- return;
24
- }
25
- }
26
- //#endregion
27
- //#region ../app-contracts/build/identity/jws.js
28
- /** The only algorithm either key signs with. */
29
- var ALGORITHM = "Ed25519";
30
- /**
31
- * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any
32
- * other member could change what the signature covers, as `b64: false` does, or name
33
- * another key, so the header is checked before the signature and again when verifying.
34
- */
35
- function readExactHeader(encoded, shape) {
36
- const parsed = shape.safeParse(decodeJson(encoded));
37
- return parsed.success ? parsed.data : void 0;
38
- }
39
- //#endregion
40
4
  //#region ../app-contracts/build/identity/challenge.js
41
5
  /** Where on an origin Ghost posts a challenge. */
42
6
  var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
@@ -145,28 +109,6 @@ function parseJson(text) {
145
109
  }
146
110
  }
147
111
  //#endregion
148
- //#region src/shared/parse.ts
149
- var UNSAFE_IN_POLICY = /[\s;,'"*]/;
150
- /**
151
- * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
152
- * `,` into a host, so the origin must also read back as itself, and hold nothing that would end
153
- * a source in a Content-Security-Policy.
154
- */
155
- function parseOrigin(entry) {
156
- const url = URL.parse(entry);
157
- const origin = url?.origin;
158
- if (!url || !origin || url.protocol !== "https:" && url.protocol !== "http:" || url.href !== `${origin}/` || URL.parse(origin)?.origin !== origin || UNSAFE_IN_POLICY.test(entry) || UNSAFE_IN_POLICY.test(origin)) return;
159
- return origin;
160
- }
161
- /** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
162
- function parseJsonText(text) {
163
- return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
164
- }
165
- //#endregion
166
- //#region src/shared/ignore.ts
167
- /** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
168
- var ignoreError = () => void 0;
169
- //#endregion
170
112
  //#region src/shared/body.ts
171
113
  /**
172
114
  * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
@@ -200,20 +142,6 @@ async function readBytes(message, maxBytes) {
200
142
  return bytes;
201
143
  }
202
144
  //#endregion
203
- //#region src/shared/manifest.ts
204
- /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
205
- var MANIFEST_PATH = "/ghost-app.json";
206
- /**
207
- * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but
208
- * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost
209
- * applies them.
210
- */
211
- var UNKNOWN_GHOST_URL = "https://ghost.invalid/";
212
- /** A manifest's problems, one per line, as `path: message`. */
213
- function formatErrors(errors, separator = "\n") {
214
- return errors.map(({ path, message }) => path ? `${path}: ${message}` : message).join(separator);
215
- }
216
- //#endregion
217
- export { ignoreError as a, CHALLENGE_PATH as c, createChallenge as d, verifyChallengeAnswer as f, decodeText as h, readBytes as i, answerChallenge as l, readExactHeader as m, UNKNOWN_GHOST_URL as n, parseJsonText as o, ALGORITHM as p, formatErrors as r, parseOrigin as s, MANIFEST_PATH as t, challengeUrl as u };
145
+ export { createChallenge as a, challengeUrl as i, CHALLENGE_PATH as n, verifyChallengeAnswer as o, answerChallenge as r, readBytes as t };
218
146
 
219
- //# sourceMappingURL=manifest-DX1GTozy.js.map
147
+ //# sourceMappingURL=body-CshsXE1J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body-CshsXE1J.js","names":[],"sources":["../../../app-contracts/build/identity/challenge.js","../../src/shared/body.ts"],"sourcesContent":["import { CompactSign, base64url, compactVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeUtf8 } from './keys.js';\n/** Where on an origin Ghost posts a challenge. */\nexport const CHALLENGE_PATH = '/.well-known/ghost-app/challenge';\n/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */\nexport const CHALLENGE_PURPOSE = 'ghost-app-challenge';\nconst NONCE_BYTES = 32;\nconst ProtectedHeader = z.strictObject({ alg: z.literal(ALGORITHM) });\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM });\nconst ChallengeShape = z.strictObject({\n purpose: z.literal(CHALLENGE_PURPOSE),\n origin: z.string(),\n nonce: z.string(),\n});\nconst ChallengeAnswerShape = z.object({ signature: z.string() });\n/** The URL to post a challenge for an origin to. */\nexport function challengeUrl(origin) {\n return new URL(CHALLENGE_PATH, origin).href;\n}\n/** A fresh challenge for an origin, as the exact text to post and to verify the answer with. */\nexport function createChallenge(origin) {\n const challenge = {\n purpose: CHALLENGE_PURPOSE,\n origin: new URL(origin).origin,\n nonce: base64url.encode(crypto.getRandomValues(new Uint8Array(NONCE_BYTES))),\n };\n return JSON.stringify(challenge);\n}\n/**\n * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is\n * the URL the request arrived at, as the platform reports it (`request.url` on Workers):\n * never one built from `X-Forwarded-Host` or any other header the sender controls. A\n * challenge for any origin but that one is refused, so whoever takes over a name the app\n * used to serve can't relay Ghost's challenge to the real backend to prove it.\n *\n * Ghost can't see this check, so it only helps where the platform routes requests by host,\n * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.\n */\nexport async function answerChallenge(body, { backendKey, requestUrl }) {\n const challenge = ChallengeShape.safeParse(parseJson(body));\n if (!challenge.success) {\n return { success: false, error: 'Expected a challenge of {purpose, origin, nonce}' };\n }\n const arrivedAt = URL.parse(requestUrl)?.origin;\n if (arrivedAt !== challenge.data.origin) {\n return {\n success: false,\n error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? 'an unknown origin'}`,\n };\n }\n const signature = await new CompactSign(new TextEncoder().encode(body))\n .setProtectedHeader({ alg: ALGORITHM })\n .sign(backendKey);\n return { success: true, answer: { signature } };\n}\n/**\n * Checks an origin's answer to a challenge: a signature with the backend key over the\n * exact text Ghost posted, under a protected header of only `alg`. The error only says how\n * the answer fell short.\n */\nexport async function verifyChallengeAnswer(challenge, answer, backendKey) {\n const parsed = ChallengeAnswerShape.safeParse(parseJson(answer));\n if (!parsed.success) {\n return { success: false, error: 'Expected an answer of {\"signature\": \"<compact JWS>\"}' };\n }\n let key;\n try {\n key = await importJWK(backendKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'backend_key is not a usable Ed25519 key' };\n }\n const [header = ''] = parsed.data.signature.split('.');\n if (!readExactHeader(header, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n let payload;\n try {\n ({ payload } = await compactVerify(parsed.data.signature, key, { algorithms: [ALGORITHM] }));\n }\n catch {\n return { success: false, error: 'The signature was not made with backend_key' };\n }\n if (!sameText(payload, challenge)) {\n return { success: false, error: 'The signature is not over the challenge that was sent' };\n }\n return { success: true };\n}\nfunction sameText(bytes, text) {\n try {\n return decodeUtf8(bytes) === text;\n }\n catch {\n return false;\n }\n}\nfunction parseJson(text) {\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=challenge.js.map","import { ignoreError } from './ignore.ts';\n\n/**\n * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It\n * stops reading as soon as the body passes the limit, so a large body is never held whole.\n */\nexport async function readBytes(\n message: Request | Response,\n maxBytes: number,\n): Promise<Uint8Array | undefined> {\n if (Number(message.headers.get('content-length')) > maxBytes) {\n // Too large either way, so a body that refuses to be cancelled changes nothing. Not waited\n // for: one branch of a teed body, as a cloned request's is, cancels only once the other does.\n message.body?.cancel().catch(ignoreError);\n return undefined;\n }\n if (!message.body) {\n return new Uint8Array();\n }\n const reader = message.body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n length += value.byteLength;\n if (length > maxBytes) {\n reader.cancel().catch(ignoreError);\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n"],"mappings":";;;;;AAKA,IAAa,iBAAiB;;AAE9B,IAAa,oBAAoB;AACjC,IAAM,cAAc;AACpB,IAAM,kBAAkB,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,SAAS,EAAE,CAAC;AACpE,IAAM,kBAAkB,KAAK,UAAU,EAAE,KAAK,UAAU,CAAC;AACzD,IAAM,iBAAiB,EAAE,aAAa;CAClC,SAAS,EAAE,QAAQ,iBAAiB;CACpC,QAAQ,EAAE,OAAO;CACjB,OAAO,EAAE,OAAO;AACpB,CAAC;AACD,IAAM,uBAAuB,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;;AAE/D,SAAgB,aAAa,QAAQ;CACjC,OAAO,IAAI,IAAI,gBAAgB,MAAM,CAAC,CAAC;AAC3C;;AAEA,SAAgB,gBAAgB,QAAQ;CACpC,MAAM,YAAY;EACd,SAAS;EACT,QAAQ,IAAI,IAAI,MAAM,CAAC,CAAC;EACxB,OAAO,UAAU,OAAO,OAAO,gBAAgB,IAAI,WAAW,WAAW,CAAC,CAAC;CAC/E;CACA,OAAO,KAAK,UAAU,SAAS;AACnC;;;;;;;;;;;AAWA,eAAsB,gBAAgB,MAAM,EAAE,YAAY,cAAc;CACpE,MAAM,YAAY,eAAe,UAAU,UAAU,IAAI,CAAC;CAC1D,IAAI,CAAC,UAAU,SACX,OAAO;EAAE,SAAS;EAAO,OAAO;CAAmD;CAEvF,MAAM,YAAY,IAAI,MAAM,UAAU,CAAC,EAAE;CACzC,IAAI,cAAc,UAAU,KAAK,QAC7B,OAAO;EACH,SAAS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AAI,OAAO,QAAQ,QAAQ,IAAI,gBAAgB,CAAC,IAAI,UAAU;EAG5D,QAAQ,MAAM,OAAO,CAAC,CAAC,MAAM,WAAW;EACxC;CACF;CACA,IAAI,CAAC,QAAQ,MACX,uBAAO,IAAI,WAAW;CAExB,MAAM,SAAS,QAAQ,KAAK,UAAU;CACtC,MAAM,SAAuB,CAAC;CAC9B,IAAI,SAAS;CACb,SAAS;EACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;EAC1C,IAAI,MACF;EAEF,UAAU,MAAM;EAChB,IAAI,SAAS,UAAU;GACrB,OAAO,OAAO,CAAC,CAAC,MAAM,WAAW;GACjC;EACF;EACA,OAAO,KAAK,KAAK;CACnB;CACA,MAAM,QAAQ,IAAI,WAAW,MAAM;CACnC,IAAI,SAAS;CACb,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,IAAI,OAAO,MAAM;EACvB,UAAU,MAAM;CAClB;CACA,OAAO;AACT"}
@@ -0,0 +1,208 @@
1
+ import { C as parseManifest, E as verifySignedManifest, S as tooLargeMessage, T as readSignedManifest, _ as ANSWER_MAX_BYTES, b as TIMEOUT_MS, v as MANIFEST_MAX_BYTES, w as parseManifestUrl, x as storedSize, y as SIGNED_MANIFEST_MAX_BYTES } from "./sign-DygdzQYY.js";
2
+ import { a as parseJsonText, i as ignoreError, n as UNKNOWN_GHOST_URL, r as formatErrors } from "./manifest-iOwbzAil.js";
3
+ import { a as createChallenge, i as challengeUrl, o as verifyChallengeAnswer, t as readBytes } from "./body-CshsXE1J.js";
4
+ //#region src/tooling/check.ts
5
+ var MESSAGES = {
6
+ APP_MANIFEST_URL_INVALID: "The app manifest URL is not valid.",
7
+ APP_MANIFEST_UNREACHABLE: "Could not load the app’s manifest.",
8
+ APP_MANIFEST_REDIRECTED: "The app’s manifest redirects to another host.",
9
+ APP_MANIFEST_TOO_LARGE: `The app’s manifest is larger than ${MANIFEST_MAX_BYTES / 1024} KB.`,
10
+ APP_MANIFEST_NOT_JSON: "The app’s manifest is not JSON.",
11
+ APP_MANIFEST_UNSIGNED: "The app’s manifest is not signed.",
12
+ APP_MANIFEST_URL_MISMATCH: "The app’s manifest is for another address.",
13
+ APP_MANIFEST_INVALID: "The app manifest is not valid.",
14
+ APP_MANIFEST_SIGNATURE_INVALID: "The app’s manifest signature is not valid.",
15
+ APP_CHALLENGE_UNREACHABLE: "Could not reach the app to confirm it comes from its developer.",
16
+ APP_CHALLENGE_FAILED: "Ghost couldn’t confirm the app comes from its developer."
17
+ };
18
+ /** Thrown by any step, and turned into a failed `CheckResult` by `checkApp`. */
19
+ var Failure = class extends Error {
20
+ code;
21
+ detail;
22
+ errors;
23
+ constructor(code, detail, errors) {
24
+ super(MESSAGES[code]);
25
+ this.code = code;
26
+ this.detail = detail;
27
+ this.errors = errors;
28
+ }
29
+ };
30
+ /**
31
+ * Checks an app as Ghost does before installing it, and resolves with the code Ghost would
32
+ * refuse it with, or the manifest Ghost would install.
33
+ */
34
+ async function checkApp(manifestUrl, { fetch: fetchFn = globalThis.fetch } = {}) {
35
+ try {
36
+ return await runChecks(manifestUrl, fetchFn);
37
+ } catch (error) {
38
+ if (!(error instanceof Failure)) throw error;
39
+ return {
40
+ success: false,
41
+ code: error.code,
42
+ message: error.message,
43
+ detail: error.detail,
44
+ ...error.errors ? { errors: error.errors } : {}
45
+ };
46
+ }
47
+ }
48
+ async function runChecks(input, fetchFn) {
49
+ const manifestUrl = readManifestUrl(input);
50
+ const signed = readSigned(await fetchManifest(manifestUrl, fetchFn), manifestUrl);
51
+ const manifest = parse(signed.payload, manifestUrl);
52
+ await verifySignature(signed.signed, manifest);
53
+ checkStoredSize(manifest, manifestUrl);
54
+ await challenge(new URL(manifestUrl).origin, manifest.backend_key, fetchFn);
55
+ return {
56
+ success: true,
57
+ manifestUrl,
58
+ manifest
59
+ };
60
+ }
61
+ function readManifestUrl(input) {
62
+ const address = parseManifestUrl(input, {
63
+ ghostUrls: [UNKNOWN_GHOST_URL],
64
+ allowLocalhost: true
65
+ });
66
+ if (!address.success) throw new Failure("APP_MANIFEST_URL_INVALID", address.error);
67
+ return address.manifestUrl;
68
+ }
69
+ /** The signed manifest's bytes, following redirects on the same host, as Ghost does. */
70
+ async function fetchManifest(manifestUrl, fetchFn) {
71
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
72
+ let current = new URL(manifestUrl);
73
+ for (let redirects = 0;; redirects++) {
74
+ const answer = await fetchOnce(fetchFn, current, {
75
+ init: {
76
+ headers: { accept: "application/json" },
77
+ signal
78
+ },
79
+ maxBytes: SIGNED_MANIFEST_MAX_BYTES,
80
+ code: "APP_MANIFEST_UNREACHABLE",
81
+ wantsBody: isSuccess
82
+ });
83
+ if (REDIRECT_STATUSES.has(answer.status) && answer.location !== null) {
84
+ current = followRedirect(manifestUrl, current, answer.status, answer.location, redirects);
85
+ continue;
86
+ }
87
+ if (!isSuccess(answer.status)) throw new Failure("APP_MANIFEST_UNREACHABLE", `${current.href} answered with HTTP ${answer.status}`);
88
+ if (!answer.body) throw new Failure("APP_MANIFEST_TOO_LARGE", manifestUrl);
89
+ return answer.body;
90
+ }
91
+ }
92
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([
93
+ 301,
94
+ 302,
95
+ 303,
96
+ 307,
97
+ 308
98
+ ]);
99
+ /** The URL a redirect leads to, if Ghost would follow it. */
100
+ function followRedirect(manifestUrl, current, status, location, redirects) {
101
+ const target = URL.parse(Buffer.from(location, "binary").toString("utf8"), current);
102
+ if (!target) throw new Failure("APP_MANIFEST_UNREACHABLE", `${manifestUrl} answered with HTTP ${status} and a Location that is not a URL`);
103
+ if (!staysOnHost(current, target)) throw new Failure("APP_MANIFEST_REDIRECTED", `${manifestUrl} redirects to ${target.host}`);
104
+ if (redirects === 3) throw new Failure("APP_MANIFEST_UNREACHABLE", `${manifestUrl} redirects more than 3 times`);
105
+ target.username = "";
106
+ target.password = "";
107
+ return target;
108
+ }
109
+ /** Ghost follows a redirect on the same origin, or from HTTP to HTTPS on the same host. */
110
+ function staysOnHost(from, to) {
111
+ if (to.origin === from.origin) return true;
112
+ return from.protocol === "http:" && to.protocol === "https:" && to.hostname === from.hostname && from.port === "" && to.port === "";
113
+ }
114
+ function readSigned(body, manifestUrl) {
115
+ const signed = readSignedManifest(parseJson(decode(body), manifestUrl));
116
+ if (!signed.success) throw new Failure("APP_MANIFEST_UNSIGNED", signed.error);
117
+ return signed;
118
+ }
119
+ function parse(payload, manifestUrl) {
120
+ const parsed = parseManifest(parseJson(payload, manifestUrl), {
121
+ manifestUrl,
122
+ ghostUrls: [UNKNOWN_GHOST_URL],
123
+ allowLocalhost: true
124
+ });
125
+ if (parsed.success) return parsed.manifest;
126
+ const detail = formatErrors(parsed.errors, "; ");
127
+ if (parsed.reason === "manifest_url_mismatch") throw new Failure("APP_MANIFEST_URL_MISMATCH", detail);
128
+ throw new Failure("APP_MANIFEST_INVALID", detail, parsed.errors);
129
+ }
130
+ async function verifySignature(signed, manifest) {
131
+ const verified = await verifySignedManifest(signed, manifest.identity_key);
132
+ if (!verified.success) throw new Failure("APP_MANIFEST_SIGNATURE_INVALID", verified.error);
133
+ }
134
+ function checkStoredSize(manifest, manifestUrl) {
135
+ if (storedSize(manifest) > 65536) throw new Failure("APP_MANIFEST_TOO_LARGE", `${manifestUrl}: ${tooLargeMessage()}`);
136
+ }
137
+ /** Sends Ghost's challenge to the app's origin, and verifies the answer with the backend key. */
138
+ async function challenge(origin, backendKey, fetchFn) {
139
+ const sent = createChallenge(origin);
140
+ const answer = await fetchOnce(fetchFn, challengeUrl(origin), {
141
+ init: {
142
+ method: "POST",
143
+ body: sent,
144
+ headers: {
145
+ accept: "application/json",
146
+ "content-type": "application/json"
147
+ },
148
+ signal: AbortSignal.timeout(TIMEOUT_MS)
149
+ },
150
+ maxBytes: ANSWER_MAX_BYTES,
151
+ code: "APP_CHALLENGE_UNREACHABLE",
152
+ wantsBody: () => true
153
+ });
154
+ const text = answer.body && decode(answer.body);
155
+ if (!isSuccess(answer.status)) throw new Failure("APP_CHALLENGE_UNREACHABLE", describeRefusal(origin, answer.status, text));
156
+ if (text === void 0) throw new Failure("APP_CHALLENGE_FAILED", `${origin}: The answer is larger than ${ANSWER_MAX_BYTES / 1024} KB`);
157
+ const verified = await verifyChallengeAnswer(sent, text, backendKey);
158
+ if (!verified.success) throw new Failure("APP_CHALLENGE_FAILED", `${origin}: ${verified.error}`);
159
+ }
160
+ function describeRefusal(origin, status, text) {
161
+ return `${origin} answered the challenge with HTTP ${status}${isRedirect(status) ? " (Ghost follows no redirect for a challenge)" : ""}${text && text.length < 500 ? `: ${text.trim()}` : ""}`;
162
+ }
163
+ /** Requests a URL as Ghost does, following no redirect, and reads the body only if it's wanted. */
164
+ async function fetchOnce(fetchFn, url, { init, maxBytes, code, wantsBody }) {
165
+ try {
166
+ const response = await fetchFn(url, {
167
+ ...init,
168
+ redirect: "manual"
169
+ });
170
+ const answer = {
171
+ status: response.status,
172
+ location: response.headers.get("location")
173
+ };
174
+ if (!wantsBody(response.status)) {
175
+ response.body?.cancel().catch(ignoreError);
176
+ return {
177
+ ...answer,
178
+ body: void 0
179
+ };
180
+ }
181
+ return {
182
+ ...answer,
183
+ body: await readBytes(response, maxBytes)
184
+ };
185
+ } catch (error) {
186
+ throw new Failure(code, `${String(url)}: ${describeFetchError(error)}`);
187
+ }
188
+ }
189
+ /** A failed fetch's message, with the reason Node hides in its `cause`, such as ECONNREFUSED. */
190
+ function describeFetchError(error) {
191
+ const { message, cause } = typeof error === "object" && error !== null ? error : {};
192
+ const reason = cause?.code ?? cause?.message;
193
+ return reason ? `${message} (${reason})` : String(message ?? error);
194
+ }
195
+ function parseJson(text, manifestUrl) {
196
+ try {
197
+ return parseJsonText(text);
198
+ } catch {
199
+ throw new Failure("APP_MANIFEST_NOT_JSON", manifestUrl);
200
+ }
201
+ }
202
+ var decode = (bytes) => new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
203
+ var isRedirect = (status) => status >= 300 && status < 400;
204
+ var isSuccess = (status) => status >= 200 && status < 300;
205
+ //#endregion
206
+ export { checkApp as t };
207
+
208
+ //# sourceMappingURL=check-3oU5pDJc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check-3oU5pDJc.js","names":[],"sources":["../../src/tooling/check.ts"],"sourcesContent":["import {\n challengeUrl,\n createChallenge,\n readSignedManifest,\n verifyChallengeAnswer,\n verifySignedManifest,\n} from '@tryghost/app-contracts/identity';\nimport { parseManifest, parseManifestUrl } from '@tryghost/app-contracts/manifest';\n\nimport { readBytes } from '../shared/body.ts';\nimport { ignoreError } from '../shared/ignore.ts';\nimport { UNKNOWN_GHOST_URL, formatErrors } from '../shared/manifest.ts';\nimport { parseJsonText } from '../shared/parse.ts';\nimport type { PublicKeyJwk } from './keys.ts';\nimport {\n ANSWER_MAX_BYTES,\n MANIFEST_MAX_BYTES,\n MAX_REDIRECTS,\n SIGNED_MANIFEST_MAX_BYTES,\n TIMEOUT_MS,\n storedSize,\n tooLargeMessage,\n} from './limits.ts';\nimport type { AppManifest, ManifestError } from './types.ts';\n\n/** The codes Ghost refuses an app with, which `checkApp` reports the same problems with. */\nexport type CheckCode =\n | 'APP_MANIFEST_URL_INVALID'\n | 'APP_MANIFEST_UNREACHABLE'\n | 'APP_MANIFEST_REDIRECTED'\n | 'APP_MANIFEST_TOO_LARGE'\n | 'APP_MANIFEST_NOT_JSON'\n | 'APP_MANIFEST_UNSIGNED'\n | 'APP_MANIFEST_URL_MISMATCH'\n | 'APP_MANIFEST_INVALID'\n | 'APP_MANIFEST_SIGNATURE_INVALID'\n | 'APP_CHALLENGE_UNREACHABLE'\n | 'APP_CHALLENGE_FAILED';\n\n/** What `checkApp` resolves with: the manifest Ghost would install, or why Ghost would refuse. */\nexport type CheckResult =\n | {\n success: true;\n manifestUrl: string;\n /** The manifest as Ghost parses it, with every path resolved. */\n manifest: AppManifest;\n }\n | {\n success: false;\n code: CheckCode;\n /** Ghost's own message for the code. */\n message: string;\n /** What exactly was wrong. Unlike Ghost, it says why a request failed. */\n detail: string;\n /** For `APP_MANIFEST_INVALID`, each problem by the path to its field. */\n errors?: ManifestError[];\n };\n\nexport interface CheckOptions {\n /** The fetch to make requests with. Node's own, by default. */\n fetch?: typeof fetch;\n}\n\ntype Fetch = typeof fetch;\n\n// Ghost's own message for each code.\nconst MESSAGES: Record<CheckCode, string> = {\n APP_MANIFEST_URL_INVALID: 'The app manifest URL is not valid.',\n APP_MANIFEST_UNREACHABLE: 'Could not load the app’s manifest.',\n APP_MANIFEST_REDIRECTED: 'The app’s manifest redirects to another host.',\n APP_MANIFEST_TOO_LARGE: `The app’s manifest is larger than ${MANIFEST_MAX_BYTES / 1024} KB.`,\n APP_MANIFEST_NOT_JSON: 'The app’s manifest is not JSON.',\n APP_MANIFEST_UNSIGNED: 'The app’s manifest is not signed.',\n APP_MANIFEST_URL_MISMATCH: 'The app’s manifest is for another address.',\n APP_MANIFEST_INVALID: 'The app manifest is not valid.',\n APP_MANIFEST_SIGNATURE_INVALID: 'The app’s manifest signature is not valid.',\n APP_CHALLENGE_UNREACHABLE: 'Could not reach the app to confirm it comes from its developer.',\n APP_CHALLENGE_FAILED: 'Ghost couldn’t confirm the app comes from its developer.',\n};\n\n/** Thrown by any step, and turned into a failed `CheckResult` by `checkApp`. */\nclass Failure extends Error {\n constructor(\n readonly code: CheckCode,\n readonly detail: string,\n readonly errors?: ManifestError[],\n ) {\n super(MESSAGES[code]);\n }\n}\n\n/**\n * Checks an app as Ghost does before installing it, and resolves with the code Ghost would\n * refuse it with, or the manifest Ghost would install.\n */\nexport async function checkApp(\n manifestUrl: string,\n { fetch: fetchFn = globalThis.fetch }: CheckOptions = {},\n): Promise<CheckResult> {\n try {\n return await runChecks(manifestUrl, fetchFn);\n } catch (error) {\n if (!(error instanceof Failure)) {\n throw error;\n }\n return {\n success: false,\n code: error.code,\n message: error.message,\n detail: error.detail,\n ...(error.errors ? { errors: error.errors } : {}),\n };\n }\n}\n\n// The steps run in the order Ghost runs them, so the first failure is the one Ghost would report.\n// Some things only a site knows can't be checked: Ghost's own hosts, the identity key the site\n// installed the app with, and backend keys a newer manifest replaced.\nasync function runChecks(input: string, fetchFn: Fetch): Promise<CheckResult> {\n const manifestUrl = readManifestUrl(input);\n const body = await fetchManifest(manifestUrl, fetchFn);\n const signed = readSigned(body, manifestUrl);\n const manifest = parse(signed.payload, manifestUrl);\n await verifySignature(signed.signed, manifest);\n checkStoredSize(manifest, manifestUrl);\n // Sent even to localhost, which Ghost in development skips, so a backend is checked before\n // it's deployed.\n await challenge(new URL(manifestUrl).origin, manifest.backend_key, fetchFn);\n return { success: true, manifestUrl, manifest };\n}\n\nfunction readManifestUrl(input: string): string {\n // The site's own URL is a name no site has, as only a site knows its own hosts.\n const address = parseManifestUrl(input, { ghostUrls: [UNKNOWN_GHOST_URL], allowLocalhost: true });\n if (!address.success) {\n throw new Failure('APP_MANIFEST_URL_INVALID', address.error);\n }\n return address.manifestUrl;\n}\n\n/** The signed manifest's bytes, following redirects on the same host, as Ghost does. */\nasync function fetchManifest(manifestUrl: string, fetchFn: Fetch): Promise<Uint8Array> {\n // One deadline for the whole read, redirects included, as in Ghost, so a slow app can't stall\n // it several times over.\n const signal = AbortSignal.timeout(TIMEOUT_MS);\n let current = new URL(manifestUrl);\n for (let redirects = 0; ; redirects++) {\n const answer = await fetchOnce(fetchFn, current, {\n init: { headers: { accept: 'application/json' }, signal },\n maxBytes: SIGNED_MANIFEST_MAX_BYTES,\n code: 'APP_MANIFEST_UNREACHABLE',\n // A redirect's or an error's body is dropped unread, as Ghost drops it.\n wantsBody: isSuccess,\n });\n // Ghost's HTTP client follows only these, and treats any other status as an answer.\n if (REDIRECT_STATUSES.has(answer.status) && answer.location !== null) {\n current = followRedirect(manifestUrl, current, answer.status, answer.location, redirects);\n continue;\n }\n if (!isSuccess(answer.status)) {\n throw new Failure(\n 'APP_MANIFEST_UNREACHABLE',\n `${current.href} answered with HTTP ${answer.status}`,\n );\n }\n if (!answer.body) {\n throw new Failure('APP_MANIFEST_TOO_LARGE', manifestUrl);\n }\n return answer.body;\n }\n}\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\n/** The URL a redirect leads to, if Ghost would follow it. */\nfunction followRedirect(\n manifestUrl: string,\n current: URL,\n status: number,\n location: string,\n redirects: number,\n): URL {\n // Headers arrive as latin1, and Ghost reads the Location as UTF-8, as got and browsers do.\n const target = URL.parse(Buffer.from(location, 'binary').toString('utf8'), current);\n if (!target) {\n throw new Failure(\n 'APP_MANIFEST_UNREACHABLE',\n `${manifestUrl} answered with HTTP ${status} and a Location that is not a URL`,\n );\n }\n if (!staysOnHost(current, target)) {\n throw new Failure('APP_MANIFEST_REDIRECTED', `${manifestUrl} redirects to ${target.host}`);\n }\n if (redirects === MAX_REDIRECTS) {\n throw new Failure(\n 'APP_MANIFEST_UNREACHABLE',\n `${manifestUrl} redirects more than ${MAX_REDIRECTS} times`,\n );\n }\n // Ghost drops credentials from a Location, as browsers do, and fetch would refuse them.\n target.username = '';\n target.password = '';\n return target;\n}\n\n/** Ghost follows a redirect on the same origin, or from HTTP to HTTPS on the same host. */\nfunction staysOnHost(from: URL, to: URL): boolean {\n if (to.origin === from.origin) {\n return true;\n }\n return (\n from.protocol === 'http:' &&\n to.protocol === 'https:' &&\n to.hostname === from.hostname &&\n from.port === '' &&\n to.port === ''\n );\n}\n\nfunction readSigned(body: Uint8Array, manifestUrl: string) {\n const signed = readSignedManifest(parseJson(decode(body), manifestUrl));\n if (!signed.success) {\n throw new Failure('APP_MANIFEST_UNSIGNED', signed.error);\n }\n return signed;\n}\n\nfunction parse(payload: string, manifestUrl: string): AppManifest {\n const parsed = parseManifest(parseJson(payload, manifestUrl), {\n manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (parsed.success) {\n return parsed.manifest;\n }\n const detail = formatErrors(parsed.errors, '; ');\n // A manifest signed for another address has its own code, as it's the usual mistake.\n if (parsed.reason === 'manifest_url_mismatch') {\n throw new Failure('APP_MANIFEST_URL_MISMATCH', detail);\n }\n throw new Failure('APP_MANIFEST_INVALID', detail, parsed.errors);\n}\n\nasync function verifySignature(\n signed: Parameters<typeof verifySignedManifest>[0],\n manifest: AppManifest,\n) {\n // With the identity key the manifest names: a site installing the app pins it from here.\n const verified = await verifySignedManifest(signed, manifest.identity_key);\n if (!verified.success) {\n throw new Failure('APP_MANIFEST_SIGNATURE_INVALID', verified.error);\n }\n}\n\nfunction checkStoredSize(manifest: AppManifest, manifestUrl: string) {\n // Ghost measures what it stores, with the paths resolved, after verifying the signature.\n if (storedSize(manifest) > MANIFEST_MAX_BYTES) {\n throw new Failure('APP_MANIFEST_TOO_LARGE', `${manifestUrl}: ${tooLargeMessage()}`);\n }\n}\n\n/** Sends Ghost's challenge to the app's origin, and verifies the answer with the backend key. */\nasync function challenge(origin: string, backendKey: PublicKeyJwk, fetchFn: Fetch) {\n const sent = createChallenge(origin);\n const answer = await fetchOnce(fetchFn, challengeUrl(origin), {\n init: {\n method: 'POST',\n body: sent,\n headers: { accept: 'application/json', 'content-type': 'application/json' },\n signal: AbortSignal.timeout(TIMEOUT_MS),\n },\n maxBytes: ANSWER_MAX_BYTES,\n code: 'APP_CHALLENGE_UNREACHABLE',\n // Read whatever the status, for the backend's explanation of a refusal.\n wantsBody: () => true,\n });\n const text = answer.body && decode(answer.body);\n if (!isSuccess(answer.status)) {\n throw new Failure('APP_CHALLENGE_UNREACHABLE', describeRefusal(origin, answer.status, text));\n }\n if (text === undefined) {\n throw new Failure(\n 'APP_CHALLENGE_FAILED',\n `${origin}: The answer is larger than ${ANSWER_MAX_BYTES / 1024} KB`,\n );\n }\n const verified = await verifyChallengeAnswer(sent, text, backendKey);\n if (!verified.success) {\n throw new Failure('APP_CHALLENGE_FAILED', `${origin}: ${verified.error}`);\n }\n}\n\nfunction describeRefusal(origin: string, status: number, text: string | undefined): string {\n // Ghost sends the challenge to one exact address, so a redirect means the app is set up wrong.\n const redirect = isRedirect(status) ? ' (Ghost follows no redirect for a challenge)' : '';\n // The backend's own explanation, such as handleChallenge's, if it's short enough to show.\n const said = text && text.length < 500 ? `: ${text.trim()}` : '';\n return `${origin} answered the challenge with HTTP ${status}${redirect}${said}`;\n}\n\ninterface Answer {\n status: number;\n location: string | null;\n /** Up to the limit; `undefined` past it, or when it wasn't wanted. */\n body: Uint8Array | undefined;\n}\n\n/** Requests a URL as Ghost does, following no redirect, and reads the body only if it's wanted. */\nasync function fetchOnce(\n fetchFn: Fetch,\n url: URL | string,\n {\n init,\n maxBytes,\n code,\n wantsBody,\n }: {\n init: RequestInit & { signal: AbortSignal };\n maxBytes: number;\n /** The code a failed request, or a body that breaks while it's read, fails with. */\n code: CheckCode;\n wantsBody: (status: number) => boolean;\n },\n): Promise<Answer> {\n try {\n const response = await fetchFn(url, { ...init, redirect: 'manual' });\n const answer = { status: response.status, location: response.headers.get('location') };\n if (!wantsBody(response.status)) {\n // Dropped unread, so a body that stalls or breaks doesn't matter.\n response.body?.cancel().catch(ignoreError);\n return { ...answer, body: undefined };\n }\n return { ...answer, body: await readBytes(response, maxBytes) };\n } catch (error) {\n throw new Failure(code, `${String(url)}: ${describeFetchError(error)}`);\n }\n}\n\n/** A failed fetch's message, with the reason Node hides in its `cause`, such as ECONNREFUSED. */\nfunction describeFetchError(error: unknown): string {\n // A fetch may reject with anything, `null` and `undefined` included.\n const { message, cause } = (typeof error === 'object' && error !== null ? error : {}) as {\n message?: string;\n cause?: { code?: string; message?: string };\n };\n const reason = cause?.code ?? cause?.message;\n return reason ? `${message} (${reason})` : String(message ?? error);\n}\n\nfunction parseJson(text: string, manifestUrl: string): unknown {\n try {\n return parseJsonText(text);\n } catch {\n throw new Failure('APP_MANIFEST_NOT_JSON', manifestUrl);\n }\n}\n\n// Decoded as UTF-8, which is what JSON should use, whatever charset the app names, as in Ghost.\n// Kept with any byte order mark, as Ghost's `Buffer#toString` keeps it: a manifest may start with\n// one, which its JSON parse allows, and an answer to the challenge may not.\nconst decode = (bytes: Uint8Array) => new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes);\n\nconst isRedirect = (status: number) => status >= 300 && status < 400;\nconst isSuccess = (status: number) => status >= 200 && status < 300;\n"],"mappings":";;;;AAkEA,IAAM,WAAsC;CAC1C,0BAA0B;CAC1B,0BAA0B;CAC1B,yBAAyB;CACzB,wBAAwB,qCAAqC,qBAAqB,KAAK;CACvF,uBAAuB;CACvB,uBAAuB;CACvB,2BAA2B;CAC3B,sBAAsB;CACtB,gCAAgC;CAChC,2BAA2B;CAC3B,sBAAsB;AACxB;;AAGA,IAAM,UAAN,cAAsB,MAAM;CAEf;CACA;CACA;CAHX,YACE,MACA,QACA,QACA;EACA,MAAM,SAAS,KAAK;EAJX,KAAA,OAAA;EACA,KAAA,SAAA;EACA,KAAA,SAAA;CAGX;AACF;;;;;AAMA,eAAsB,SACpB,aACA,EAAE,OAAO,UAAU,WAAW,UAAwB,CAAC,GACjC;CACtB,IAAI;EACF,OAAO,MAAM,UAAU,aAAa,OAAO;CAC7C,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,UACrB,MAAM;EAER,OAAO;GACL,SAAS;GACT,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,QAAQ,MAAM;GACd,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;EACjD;CACF;AACF;AAKA,eAAe,UAAU,OAAe,SAAsC;CAC5E,MAAM,cAAc,gBAAgB,KAAK;CAEzC,MAAM,SAAS,WAAW,MADP,cAAc,aAAa,OAAO,GACrB,WAAW;CAC3C,MAAM,WAAW,MAAM,OAAO,SAAS,WAAW;CAClD,MAAM,gBAAgB,OAAO,QAAQ,QAAQ;CAC7C,gBAAgB,UAAU,WAAW;CAGrC,MAAM,UAAU,IAAI,IAAI,WAAW,CAAC,CAAC,QAAQ,SAAS,aAAa,OAAO;CAC1E,OAAO;EAAE,SAAS;EAAM;EAAa;CAAS;AAChD;AAEA,SAAS,gBAAgB,OAAuB;CAE9C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