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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { r as SignedManifest, t as MANIFEST_PATH } from "./chunks/manifest-DFLCKcwH.js";
1
+ import { r as SignedManifest, t as MANIFEST_PATH } from "./chunks/manifest-CYA0krtI.js";
2
2
  //#region ../app-contracts/build/identity/challenge.d.ts
3
3
  /** Where on an origin Ghost posts a challenge. */
4
4
  declare const CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
package/build/backend.js CHANGED
@@ -1,4 +1,5 @@
1
- import { i as ignoreError, o as parseOrigin, s as ALGORITHM, t as MANIFEST_PATH } from "./chunks/manifest-B9vQoSfm.js";
1
+ import { i as ALGORITHM, r as ignoreError, t as MANIFEST_PATH } from "./chunks/manifest-BO_hJDEK.js";
2
+ import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
2
3
  import { CompactSign } from "jose";
3
4
  import { z } from "zod";
4
5
  //#region ../app-contracts/build/identity/challenge.js
@@ -1 +1 @@
1
- {"version":3,"file":"backend.js","names":[],"sources":["../../app-contracts/build/identity/challenge.js","../src/shared/body.ts","../src/backend/body.ts","../src/backend/challenge.ts","../src/backend/app.ts","../src/backend/manifest.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","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":";;;;;AAKA,IAAa,iBAAiB;;AAE9B,IAAa,oBAAoB;AAET,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,SAAS,EAAE,CAAC;AAC5C,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;AAC4B,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;;;;;;;;;;;AAwB/D,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;EACT,OAAO,wBAAwB,UAAU,KAAK,OAAO,mBAAmB,aAAa;CACzF;CAKJ,OAAO;EAAE,SAAS;EAAM,QAAQ,EAAE,WAAA,MAHV,IAAI,YAAY,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,CAClE,mBAAmB,EAAE,KAAK,UAAU,CAAC,CAAC,CACtC,KAAK,UAAU,EACwB;CAAE;AAClD;AA0CA,SAAS,UAA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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":["../../app-contracts/build/identity/challenge.js","../src/shared/body.ts","../src/backend/body.ts","../src/backend/challenge.ts","../src/backend/app.ts","../src/backend/manifest.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","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":";;;;;;AAKA,IAAa,iBAAiB;;AAE9B,IAAa,oBAAoB;AAET,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,SAAS,EAAE,CAAC;AAC5C,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;AAC4B,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;;;;;;;;;;;AAwB/D,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;EACT,OAAO,wBAAwB,UAAU,KAAK,OAAO,mBAAmB,aAAa;CACzF;CAKJ,OAAO;EAAE,SAAS;EAAM,QAAQ,EAAE,WAAA,MAHV,IAAI,YAAY,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,CAClE,mBAAmB,EAAE,KAAK,UAAU,CAAC,CAAC,CACtC,KAAK,UAAU,EACwB;CAAE;AAClD;AA0CA,SAAS,UAAU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CAAmC,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"}
package/build/bin.js CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env node
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-Deg9TCUr.js";
3
- import { r as formatErrors } from "./chunks/manifest-B9vQoSfm.js";
2
+ import { d as createKeys, h as readBackendKey, i as serialiseSigned, l as KEYS_DIRECTORY, m as publicKeyOf, n as formatErrors, o as signProject, p as keyFile, u as KEY_NAMES } from "./chunks/sign-3ysEUyYt.js";
4
3
  import { lstatSync, readlinkSync, realpathSync } from "node:fs";
5
4
  import { mkdir, writeFile } from "node:fs/promises";
6
5
  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 {\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 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 and signs its manifest.\")\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('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;;;ACdA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uCAAuC,CAAC,CACpE,OAAO,OAAO,YAAwC;EACrD,WAAW,MAAM,KAAK,KAAK,GAAG,SAAS,EAAE;CAC3C,CAAC;CAEH,QACG,QAAQ,aAAa,CAAC,CACtB,YACC,kMACF,CAAC,CACA,OAAO,gBAAgB,mDAAmD,CAAC,CAC3E,OAAO,YAAY,2DAA2D,CAAC,CAC/E,OAAO,WAAW,+DAA+D,CAAC,CAClF,OAAO,OAAO,YAA8C;EAC3D,MAAM,WAAW,KAAK,GAAG,SAAS,EAAE;CACtC,CAAC;CAEH,IAAI;EACF,MAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;EAC/C,OAAO;CACT,SAAS,OAAO;EAGd,IAAI,iBAAiB,gBACnB,OAAO,MAAM,aAAa,IAAI,IAAI;EAEpC,GAAG,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;EAC7D,OAAO;CACT;AACF;;;ACjLA,IAAM,QAAQ,SAAkB,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,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 {\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 { MANIFEST_FILE, formatErrors, 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 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 and signs its manifest.\")\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('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;;;ACfA,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,MACj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,+DAA+D,CAAC,CAClF,OAAO,OAAO,YAA8C;EAC3D,MAAM,WAAW,KAAK,GAAG,SAAS,EAAE;CACtC,CAAC;CAEH,IAAI;EACF,MAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;EAC/C,OAAO;CACT,SAAS,OAAO;EAGd,IAAI,iBAAiB,gBACnB,OAAO,MAAM,aAAa,IAAI,IAAI;EAEpC,GAAG,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;EAC7D,OAAO;CACT;AACF;;;AChLA,IAAM,QAAQ,SAAkB,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,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"}
@@ -0,0 +1,21 @@
1
+ //#region ../app-contracts/build/identity/jws.js
2
+ /** The only algorithm either key signs with. */
3
+ var ALGORITHM = "Ed25519";
4
+ //#endregion
5
+ //#region src/shared/ignore.ts
6
+ /** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
7
+ var ignoreError = () => void 0;
8
+ //#endregion
9
+ //#region src/shared/manifest.ts
10
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
11
+ var MANIFEST_PATH = "/ghost-app.json";
12
+ /**
13
+ * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but
14
+ * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost
15
+ * applies them.
16
+ */
17
+ var UNKNOWN_GHOST_URL = "https://ghost.invalid/";
18
+ //#endregion
19
+ export { ALGORITHM as i, UNKNOWN_GHOST_URL as n, ignoreError as r, MANIFEST_PATH as t };
20
+
21
+ //# sourceMappingURL=manifest-BO_hJDEK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest-BO_hJDEK.js","names":[],"sources":["../../../app-contracts/build/identity/jws.js","../../src/shared/ignore.ts","../../src/shared/manifest.ts"],"sourcesContent":["import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n\n/** One problem with a manifest. */\nexport interface ManifestError {\n /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */\n path: string;\n message: string;\n}\n\n/**\n * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but\n * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost\n * applies them.\n */\nexport const UNKNOWN_GHOST_URL = 'https://ghost.invalid/';\n"],"mappings":";;AAEA,IAAa,YAAY;;;;ACDzB,IAAa,oBAA+B,KAAA;;;;ACG5C,IAAa,gBAAgB;;;;;;AAqB7B,IAAa,oBAAoB"}
@@ -13,7 +13,5 @@ interface ManifestError {
13
13
  path: string;
14
14
  message: string;
15
15
  }
16
- /** A manifest's problems, one per line, as `path: message`. */
17
- declare function formatErrors(errors: readonly ManifestError[]): string;
18
16
  //#endregion
19
- export { formatErrors as i, ManifestError as n, SignedManifest as r, MANIFEST_PATH as t };
17
+ export { ManifestError as n, SignedManifest as r, MANIFEST_PATH as t };
@@ -0,0 +1,17 @@
1
+ //#region src/shared/parse.ts
2
+ var UNSAFE_IN_POLICY = /[\s;,'"*]/;
3
+ /**
4
+ * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
5
+ * `,` into a host, so the origin must also read back as itself, and hold nothing that would end
6
+ * a source in a Content-Security-Policy.
7
+ */
8
+ function parseOrigin(entry) {
9
+ const url = URL.parse(entry);
10
+ const origin = url?.origin;
11
+ 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;
12
+ return origin;
13
+ }
14
+ //#endregion
15
+ export { parseOrigin as t };
16
+
17
+ //# sourceMappingURL=parse-C6hK3wRD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-C6hK3wRD.js","names":[],"sources":["../../src/shared/parse.ts"],"sourcesContent":["// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n"],"mappings":";AACA,IAAM,mBAAmB;;;;;;AAOzB,SAAgB,YAAY,OAAmC;CAC7D,MAAM,MAAM,IAAI,MAAM,KAAK;CAC3B,MAAM,SAAS,KAAK;CACpB,IACE,CAAC,OACD,CAAC,UACA,IAAI,aAAa,YAAY,IAAI,aAAa,WAC/C,IAAI,SAAS,GAAG,OAAO,MACvB,IAAI,MAAM,MAAM,CAAC,EAAE,WAAW,UAC9B,iBAAiB,KAAK,KAAK,KAC3B,iBAAiB,KAAK,MAAM,GAE5B;CAEF,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { g as isPlainText, l as isContainedPath } from "./rules-_dou3jRF.js";
2
- import { a as parseJsonText, i as ignoreError, n as UNKNOWN_GHOST_URL, s as ALGORITHM } from "./manifest-B9vQoSfm.js";
2
+ import { i as ALGORITHM, n as UNKNOWN_GHOST_URL, r as ignoreError } from "./manifest-BO_hJDEK.js";
3
3
  import { FlattenedSign } from "jose";
4
4
  import { z } from "zod";
5
5
  import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from "node:crypto";
@@ -98,6 +98,20 @@ function isValidAppId(value) {
98
98
  */
99
99
  var URL_MAX_LENGTH = 2e3;
100
100
  //#endregion
101
+ //#region ../app-contracts/build/identity/loading.js
102
+ /** The largest manifest Ghost stores, which it keeps in a TEXT column. */
103
+ var MANIFEST_MAX_BYTES = 64 * 1024;
104
+ /**
105
+ * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and
106
+ * the header and signature are well under a kilobyte, so a manifest of the largest size
107
+ * still fits.
108
+ */
109
+ var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(MANIFEST_MAX_BYTES * 4 / 3) + 1024;
110
+ /** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
111
+ function parseJsonText(text) {
112
+ return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
113
+ }
114
+ //#endregion
101
115
  //#region ../app-contracts/build/identity/signed-manifest.js
102
116
  /** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */
103
117
  var SIGNED_MANIFEST_TYPE = "ghost-app-manifest";
@@ -709,6 +723,10 @@ function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {
709
723
  manifestUrl: url.href
710
724
  };
711
725
  }
726
+ /** A manifest's problems as `path: message`, joined by `separator`, as Ghost reports them. */
727
+ function formatManifestErrors(errors, separator) {
728
+ return errors.map(({ path, message }) => path ? `${path}: ${message}` : message).join(separator);
729
+ }
712
730
  function invalid(errors) {
713
731
  return {
714
732
  success: false,
@@ -755,13 +773,6 @@ function parseManifest(input, options) {
755
773
  }
756
774
  //#endregion
757
775
  //#region src/tooling/limits.ts
758
- /** The largest manifest Ghost stores, which it keeps in a TEXT column. */
759
- var MANIFEST_MAX_BYTES = 64 * 1024;
760
- /**
761
- * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and the
762
- * header and signature are well under a kilobyte.
763
- */
764
- var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(MANIFEST_MAX_BYTES * 4 / 3) + 1024;
765
776
  /**
766
777
  * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what
767
778
  * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.
@@ -838,6 +849,10 @@ async function signAppManifest(source, options) {
838
849
  manifest
839
850
  };
840
851
  }
852
+ /** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */
853
+ function formatErrors(errors) {
854
+ return formatManifestErrors(errors, "\n");
855
+ }
841
856
  /** A signed manifest as the CLI and the Vite plugin write it to a file. */
842
857
  function serialiseSigned(signed) {
843
858
  return `${JSON.stringify(signed, null, 2)}\n`;
@@ -864,6 +879,6 @@ async function signProject({ root, mode, env, manifestUrl, manifestFile = MANIFE
864
879
  });
865
880
  }
866
881
  //#endregion
867
- export { isValidAppId as _, signProject as a, KEYS_DIRECTORY as c, generateKey as d, keyFile as f, signingKeySource as g, readSigningKeys as h, signAppManifest as i, KEY_NAMES as l, readBackendKey as m, readManifestSource as n, BACKEND_KEY_VARIABLE as o, publicKeyOf as p, serialiseSigned as r, IDENTITY_KEY_VARIABLE as s, MANIFEST_FILE as t, createKeys as u, isLocalhost as v };
882
+ export { signingKeySource as _, signAppManifest as a, isLocalhost as b, IDENTITY_KEY_VARIABLE as c, createKeys as d, generateKey as f, readSigningKeys as g, readBackendKey as h, serialiseSigned as i, KEYS_DIRECTORY as l, publicKeyOf as m, formatErrors as n, signProject as o, keyFile as p, readManifestSource as r, BACKEND_KEY_VARIABLE as s, MANIFEST_FILE as t, KEY_NAMES as u, parseJsonText as v, isValidAppId as y };
868
883
 
869
- //# sourceMappingURL=sign-Deg9TCUr.js.map
884
+ //# sourceMappingURL=sign-3ysEUyYt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-3ysEUyYt.js","names":[],"sources":["../../../app-contracts/build/manifest/localhost.js","../../../app-contracts/build/manifest/ghost-host.js","../../../app-contracts/build/manifest/id.js","../../../app-contracts/build/manifest/limits.js","../../../app-contracts/build/identity/loading.js","../../../app-contracts/build/identity/signed-manifest.js","../../src/tooling/git.ts","../../src/tooling/keys.ts","../../../app-contracts/build/manifest/icon.js","../../../app-contracts/build/manifest/keys.js","../../../app-contracts/build/manifest/surfaces.js","../../../app-contracts/build/manifest/text.js","../../../app-contracts/build/manifest/url.js","../../../app-contracts/build/manifest/schema.js","../../../app-contracts/build/manifest/parse.js","../../src/tooling/limits.ts","../../src/tooling/sign.ts"],"sourcesContent":["// `URL` has already normalised the host by the time these run: every spelling of an IPv4\n// address is dotted decimal, and an IPv4-mapped IPv6 address is two hex groups.\nconst LOOPBACK_HOSTS = [\n /^localhost$/,\n /\\.localhost$/,\n /^127\\.\\d+\\.\\d+\\.\\d+$/,\n /^0\\.0\\.0\\.0$/,\n /^\\[::1?\\]$/,\n /^\\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\\]$/,\n /^\\[::ffff:0:0\\]$/,\n];\n/**\n * A hostname without its trailing dots, which the URL parser keeps, every one of them:\n * `localhost..` is `localhost`. A loop rather than a regular expression, which would take\n * time quadratic in the number of dots on a hostname with many dots before its end.\n */\nexport function withoutTrailingDots(hostname) {\n let end = hostname.length;\n while (end > 0 && hostname[end - 1] === '.') {\n end -= 1;\n }\n return hostname.slice(0, end);\n}\n/**\n * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.\n * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as\n * `isGhostHost` drops them.\n */\nexport function isLocalhost(hostname) {\n const host = withoutTrailingDots(hostname);\n return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));\n}\n//# sourceMappingURL=localhost.js.map","import { withoutTrailingDots } from './localhost.js';\n/**\n * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any\n * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,\n * whatever a frame's sandbox says. On another port it would be the app's, but browsers send\n * a host's cookies to every port on it, so the app's server would be sent the staff user's\n * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it\n * frames the page, since the site's or Admin's address can change after an app is\n * installed.\n *\n * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and\n * without a trailing dot. A sibling host, such as another subdomain of the site's, is not\n * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as\n * `my-app.localhost` next to `localhost`, or another name for the same machine, such as\n * `127.0.0.1`, which browsers treat as other hosts too.\n *\n * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no\n * Ghost URLs at all. Either way the URL is refused.\n */\nexport function isGhostHost(url, ghostUrls) {\n const host = hostOf(url);\n if (host === null) {\n return true;\n }\n let known = false;\n for (const ghostUrl of ghostUrls) {\n const ghostHost = hostOf(ghostUrl);\n if (ghostHost === null || ghostHost === host) {\n return true;\n }\n known = true;\n }\n return !known;\n}\n/** An http or https URL's host as `isGhostHost` compares it, or null for any other. */\nexport function hostOf(value) {\n let url;\n // Admin runs this, and `URL.parse` is newer than the browsers Admin supports.\n try {\n url = new URL(value);\n }\n catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return null;\n }\n return withoutTrailingDots(url.hostname) || null;\n}\n//# sourceMappingURL=ghost-host.js.map","/** Matches the limit of the index that ties saved cards to an app. */\nexport const APP_ID_MAX_LENGTH = 191;\nconst ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n/**\n * An app ID is reverse-domain style: at least two dot-separated segments of lowercase\n * letters, digits and hyphens, starting with a letter so that an IP address or a version\n * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than\n * lowercased.\n */\nexport function isValidAppId(value) {\n if (typeof value !== 'string' || value.length > APP_ID_MAX_LENGTH) {\n return false;\n }\n const segments = value.split('.');\n return (segments.length >= 2 &&\n /^[a-z]/.test(value) &&\n segments.every((segment) => ID_SEGMENT.test(segment)));\n}\n//# sourceMappingURL=id.js.map","/**\n * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of\n * them, the manifest's own URL included, so its columns are exactly this wide.\n */\nexport const URL_MAX_LENGTH = 2000;\n//# sourceMappingURL=limits.js.map","// How Ghost reads the signed manifest an app serves. Ghost core reads it by these, and the app\n// SDK signs by them, so a manifest it signs is one Ghost reads.\n/** The largest manifest Ghost stores, which it keeps in a TEXT column. */\nexport const MANIFEST_MAX_BYTES = 64 * 1024;\n/**\n * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and\n * the header and signature are well under a kilobyte, so a manifest of the largest size\n * still fits.\n */\nexport const SIGNED_MANIFEST_MAX_BYTES = Math.ceil((MANIFEST_MAX_BYTES * 4) / 3) + 1024;\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text) {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n//# sourceMappingURL=loading.js.map","import { FlattenedSign, flattenedVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeText } from './keys.js';\n/** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */\nexport const SIGNED_MANIFEST_TYPE = 'ghost-app-manifest';\nconst SignedManifestShape = z.strictObject({\n protected: z.string(),\n payload: z.string(),\n signature: z.string(),\n});\nconst ProtectedHeader = z.strictObject({\n alg: z.literal(ALGORITHM),\n typ: z.literal(SIGNED_MANIFEST_TYPE),\n});\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE });\n/**\n * Signs a manifest with an app's identity key. A string is signed as the exact text it is;\n * anything else is signed as its JSON.\n */\nexport async function signManifest(manifest, identityKey) {\n const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest);\n const signed = await new FlattenedSign(new TextEncoder().encode(text))\n .setProtectedHeader({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE })\n .sign(identityKey);\n return { protected: signed.protected, payload: signed.payload, signature: signed.signature };\n}\n/**\n * Reads the manifest out of a signed manifest, without verifying it. The key to verify it\n * with is named inside the manifest, so the manifest has to be read and checked first;\n * nothing in it may be used until `verifySignedManifest` has passed.\n */\nexport function readSignedManifest(body) {\n const shape = SignedManifestShape.safeParse(body);\n if (!shape.success) {\n return {\n success: false,\n error: 'Expected a signed manifest: flattened JWS JSON with protected, payload and signature',\n };\n }\n const signed = shape.data;\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n const payload = decodeText(signed.payload);\n if (payload === undefined) {\n return { success: false, error: 'Expected a payload of UTF-8 text in base64url' };\n }\n return { success: true, signed, payload };\n}\n/**\n * Checks a signed manifest was signed with the identity key the manifest names, under\n * exactly the protected header `readSignedManifest` accepts.\n */\nexport async function verifySignedManifest(signed, identityKey) {\n let key;\n try {\n key = await importJWK(identityKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'identity_key is not a usable Ed25519 key' };\n }\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n try {\n await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });\n }\n catch {\n return { success: false, error: 'The signature was not made with identity_key' };\n }\n return { success: true };\n}\n//# sourceMappingURL=signed-manifest.js.map","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { ignoreError } from '../shared/ignore.ts';\n\nexport type IgnoredResult = { ignored: true } | { ignored: false; reason: string };\n\nfunction git(args: string[], cwd: string, input?: string) {\n return new Promise<{ code: number | string | null; stdout: string; stderr: string }>((done) => {\n const child = execFile('git', args, { cwd }, (error, stdout, stderr) => {\n done({ code: error ? ((error as { code?: number | string }).code ?? 1) : 0, stdout, stderr });\n });\n // A git that couldn't start has no stdin to write to; its error arrives above.\n child.stdin?.on('error', ignoreError);\n child.stdin?.end(input);\n });\n}\n\nfunction insideRepository(directory: string): boolean {\n for (let current = resolve(directory); ; current = dirname(current)) {\n if (existsSync(join(current, '.git'))) {\n return true;\n }\n if (dirname(current) === current) {\n return false;\n }\n }\n}\n\n/**\n * The directory itself, or the nearest one above it that exists, to run git in: a project's\n * directory may not exist before its keys are written, and git can't start in one that doesn't.\n */\nfunction existingDirectory(directory: string): string {\n let current = resolve(directory);\n while (!existsSync(current) && dirname(current) !== current) {\n current = dirname(current);\n }\n return current;\n}\n\n/**\n * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by\n * accident. A file outside any repository counts as ignored.\n */\nexport async function isGitIgnored(\n root: string,\n files: string | readonly string[],\n): Promise<IgnoredResult> {\n // git can't start in a directory that doesn't exist, and a project's may not exist yet.\n const cwd = existingDirectory(root);\n const paths = (typeof files === 'string' ? [files] : files).map((file) => ({\n // As the developer named it, for messages, and as git is asked about it, from `cwd`.\n shown: relative(root, resolve(root, file)),\n asked: relative(cwd, resolve(root, file)),\n }));\n const named = `${paths.map(({ shown }) => shown).join(' and ')} ${paths.length > 1 ? 'are' : 'is'}`;\n\n const repository = await findRepository(cwd, named);\n if (repository !== 'inside') {\n return repository === 'outside' ? { ignored: true } : repository;\n }\n return askWhichAreIgnored(cwd, paths, named);\n}\n\n/** Whether `cwd` is in a repository, or why git can't say when it seems to be. */\nasync function findRepository(\n cwd: string,\n named: string,\n): Promise<'inside' | 'outside' | { ignored: false; reason: string }> {\n // Read from what git exits with, never from what it says, which is in the developer's\n // language. A `.git` that git can't read is still a repository, so it isn't taken as outside.\n const inside = await git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (inside.code === 0) {\n return 'inside';\n }\n if (!insideRepository(cwd)) {\n return 'outside';\n }\n return {\n ignored: false,\n reason:\n inside.code === 'ENOENT'\n ? `git isn't installed, so it can't check ${named} ignored`\n : `git couldn't read the repository: ${inside.stderr.trim()}`,\n };\n}\n\nasync function askWhichAreIgnored(\n cwd: string,\n paths: { shown: string; asked: string }[],\n named: string,\n): Promise<IgnoredResult> {\n // One call for every path. It lists the ones it ignores, and exits with 1 when it ignores none.\n // Paths go in and out separated by NUL, as git would otherwise quote one with any byte outside\n // ASCII. A file git tracks isn't ignored, even if a `.gitignore` names it.\n const { code, stdout, stderr } = await git(\n ['check-ignore', '--stdin', '-z'],\n cwd,\n paths.map(({ asked }) => `${asked}\\0`).join(''),\n );\n if (code !== 0 && code !== 1) {\n return { ignored: false, reason: `git couldn't check ${named} ignored: ${stderr.trim()}` };\n }\n const ignored = new Set(stdout.split('\\0'));\n const notIgnored = paths.find(({ asked }) => !ignored.has(asked));\n return notIgnored\n ? { ignored: false, reason: `git doesn't ignore ${notIgnored.shown}` }\n : { ignored: true };\n}\n","import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nimport { isGitIgnored } from './git.ts';\n\n/**\n * Which keys to use. Development and production have separate identity keys, so an app\n * installed from the developer's machine is a different app from the deployed one.\n */\nexport type Mode = 'development' | 'production';\n\n/** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */\nexport const KEYS_DIRECTORY = '.ghost-app';\n\n/**\n * - `identity`: signs the manifest. It says who made the app, so it stays with the developer\n * (or their CI) and never reaches the backend or a bundle.\n * - `backend`: answers Ghost's challenge, so the backend holds it.\n */\nexport type KeyName = 'identity' | 'backend';\n\nexport const KEY_NAMES: readonly KeyName[] = ['identity', 'backend'];\n\n/** A private Ed25519 key as a JWK. */\nexport interface PrivateKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n d: string;\n}\n\n/** A public Ed25519 key as a JWK, as a manifest names it. */\nexport interface PublicKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n}\n\n/** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */\nexport const IDENTITY_KEY_VARIABLE = 'GHOST_APP_IDENTITY_KEY';\n\n/**\n * The backend key, as the backend reads it, and as CI may provide it to sign a production\n * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.\n */\nexport const BACKEND_KEY_VARIABLE = 'GHOST_APP_BACKEND_KEY';\n\nexport interface KeyOptions {\n /** The project's directory, which holds `.ghost-app/`. */\n root: string;\n mode: Mode;\n}\n\n/** The file a key is kept in, relative to the project. */\nexport function keyFile(mode: Mode, name: KeyName): string {\n return join(KEYS_DIRECTORY, mode, `${name}.json`);\n}\n\n/** A new private Ed25519 key. */\nexport function generateKey(): PrivateKeyJwk {\n const { x, d } = generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' });\n return { kty: 'OKP', crv: 'Ed25519', x: x!, d: d! };\n}\n\n/** A key's public half, with only `kty`, `crv` and `x`. */\nexport function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk {\n return { kty: 'OKP', crv: 'Ed25519', x: key.x };\n}\n\n/**\n * Reads a private key from JSON. `source` names where it came from, for the error: the key\n * itself is never in one.\n */\nexport function readKey(text: string, source: string): PrivateKeyJwk {\n const key = readAnyKey(text, source);\n if (!('d' in key)) {\n throw new Error(`${source} is a public key; expected the private key, with d`);\n }\n return key;\n}\n\n/** Reads a key from JSON, private or public. */\nfunction readAnyKey(text: string, source: string): PrivateKeyJwk | PublicKeyJwk {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new Error(`${source} isn't a key: it isn't JSON`);\n }\n if (!isEd25519(value)) {\n throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\" and x`);\n }\n const { d } = value as { d?: unknown };\n if (d === undefined) {\n return publicKeyOf(value);\n }\n // A key with a private part that doesn't read isn't a public key either.\n if (typeof d !== 'string') {\n throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);\n }\n // A JWK carries both halves, so a hand-edited or pasted one could pair a private half with\n // someone else's public half, and sign for a key the manifest doesn't name.\n if (publicHalfOf(d, source) !== value.x) {\n throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);\n }\n return { kty: 'OKP', crv: 'Ed25519', x: value.x, d } satisfies PrivateKeyJwk;\n}\n\nfunction isEd25519(value: unknown): value is { kty: 'OKP'; crv: 'Ed25519'; x: string } {\n const { kty, crv, x } = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >;\n return kty === 'OKP' && crv === 'Ed25519' && typeof x === 'string';\n}\n\n// What PKCS#8 puts before an Ed25519 private key's 32 bytes.\nconst ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');\n\n/**\n * The public half of a private half, as `x`. Derived from `d` alone, as Node 24.22 and later\n * refuse a JWK whose halves don't match while earlier versions take its `x` as given, so a\n * mismatch is reported the same way on any version.\n */\nfunction publicHalfOf(d: string, source: string): string | undefined {\n const bytes = Buffer.from(d, 'base64url');\n if (bytes.length !== 32) {\n throw new Error(`${source} isn't a usable Ed25519 key`);\n }\n const key = createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, bytes]),\n format: 'der',\n type: 'pkcs8',\n });\n return createPublicKey(key).export({ format: 'jwk' }).x;\n}\n\nasync function readKeyFile(root: string, mode: Mode, name: KeyName): Promise<PrivateKeyJwk> {\n const file = keyFile(mode, name);\n let text: string;\n try {\n text = await readFile(join(root, file), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n throw new Error(missingKeyMessage(mode, name, file), { cause: error });\n }\n return readKey(text, file);\n}\n\n/** Says how to create a missing key, as nothing that reads keys creates one. */\nfunction missingKeyMessage(mode: Mode, name: KeyName, file: string): string {\n if (mode === 'development') {\n return `There's no development ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys\\`.`;\n }\n // In production, CI may provide the key as a variable instead.\n return `There's no production ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys --production\\`, or set ${variableFor(name)}.`;\n}\n\nconst variableFor = (name: KeyName) =>\n name === 'identity' ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;\n\nexport interface CreateKeysResult {\n /** The keys this call created. */\n created: KeyName[];\n /** The keys that already existed, which are never replaced. */\n kept: KeyName[];\n}\n\n/**\n * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only\n * their owner can read, and keeps any that exist.\n */\nexport async function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult> {\n // Each key is written whole to a temporary file beside it first, then linked to its name.\n const keys = KEY_NAMES.map((name) => {\n const file = keyFile(mode, name);\n const pending = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);\n return { name, file, pending };\n });\n // So a private key can't be committed by accident, git must ignore every file a key is\n // written to, the temporary ones included.\n await refuseUnlessGitIgnores(root, [\n ...keys.map(({ file }) => file),\n ...keys.map(({ pending }) => pending),\n ]);\n await mkdir(join(root, KEYS_DIRECTORY, mode), { recursive: true, mode: 0o700 });\n const result: CreateKeysResult = { created: [], kept: [] };\n for (const { name, file, pending } of keys) {\n // An existing key is kept: a new identity key would make the app a different app on every\n // site that installed it.\n const created = await publishKey(join(root, file), join(root, pending));\n result[created ? 'created' : 'kept'].push(name);\n }\n return result;\n}\n\nasync function refuseUnlessGitIgnores(root: string, files: string[]) {\n const ignored = await isGitIgnored(root, files);\n if (!ignored.ignored) {\n throw new Error(\n `Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`,\n );\n }\n}\n\n/** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */\nasync function publishKey(file: string, pending: string): Promise<boolean> {\n try {\n await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\\n`, {\n flag: 'wx',\n // Only for its owner on macOS and Linux. Windows ignores the mode, and the key gets the\n // folder's inherited permissions, which the README tells developers to keep private.\n mode: 0o600,\n });\n // A link fails if the name is taken, so a key is never replaced, even by a concurrent run,\n // and an interrupted write never leaves part of a key where a key belongs.\n await link(pending, file);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n // Kept, but only for its owner, as a key written by hand or copied in may not be.\n if (process.platform !== 'win32' && ((await stat(file)).mode & 0o077) !== 0) {\n await chmod(file, 0o600);\n }\n return false;\n } finally {\n await rm(pending, { force: true });\n }\n}\n\nexport interface SigningKeys {\n identityKey: PrivateKeyJwk;\n /** The backend key's public half: all signing needs. */\n backendKey: PublicKeyJwk;\n}\n\nexport interface ReadKeysOptions extends KeyOptions {\n /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to\n * anything but blanks, or else the key's file.\n */\nexport function signingKeySource(\n mode: Mode,\n name: KeyName,\n env: Record<string, string | undefined> = process.env,\n): string {\n const variable = variableFor(name);\n return mode === 'production' && env[variable]?.trim() ? variable : keyFile(mode, name);\n}\n\n/**\n * The keys to sign a mode's manifest with, from the key files, or in production from\n * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.\n */\nexport async function readSigningKeys({\n root,\n mode,\n env = process.env,\n}: ReadKeysOptions): Promise<SigningKeys> {\n const fromVariable = (name: KeyName) =>\n signingKeySource(mode, name, env) === variableFor(name)\n ? env[variableFor(name)]!.trim()\n : undefined;\n\n const identityText = fromVariable('identity');\n const identityKey = identityText\n ? await sameAsFile(root, mode, 'identity', readKey(identityText, IDENTITY_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'identity');\n\n // CI may provide only the backend key's public half, as signing needs nothing more.\n const backendText = fromVariable('backend');\n const backendKey = publicKeyOf(\n backendText\n ? await sameAsFile(root, mode, 'backend', readAnyKey(backendText, BACKEND_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'backend'),\n );\n\n if (identityKey.x === backendKey.x) {\n throw new Error('The identity key and the backend key are the same key; they must be two keys');\n }\n return { identityKey, backendKey };\n}\n\n/**\n * A key from a variable, after checking it's the same key as the file, where there's one. A\n * variable left set, such as a development key exported for every shell, would otherwise win over\n * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every\n * site.\n */\nasync function sameAsFile<Key extends PublicKeyJwk>(\n root: string,\n mode: Mode,\n name: KeyName,\n key: Key,\n): Promise<Key> {\n const file = keyFile(mode, name);\n if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {\n const variable = variableFor(name);\n throw new Error(\n `${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`,\n );\n }\n return key;\n}\n\n/** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */\nexport function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk> {\n return readKeyFile(root, mode, 'backend');\n}\n","import { z } from 'zod';\nconst ICON_NAME_MAX_LENGTH = 64;\nconst ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst EITHER = 'Expected an icon with either a name or a url';\n/**\n * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app\n * serves. Ghost keeps a copy of the image with each manifest version it stores, and only\n * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;\n * Admin falls back to a default icon.\n */\nexport function iconField(url) {\n return (z\n .strictObject({\n name: z\n .string('Expected an icon name')\n .max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`)\n .regex(ICON_NAME, 'Expected an icon name such as audio-lines')\n .optional(),\n url: url().optional(),\n }, EITHER)\n .refine(({ name, url: iconUrl }) => (name === undefined) !== (iconUrl === undefined), EITHER)\n // Only the type narrows: the value already is one or the other. A transform would\n // narrow it too, but one-way, and a stored manifest has to encode back through here.\n .pipe(z.custom()));\n}\n//# sourceMappingURL=icon.js.map","import { z } from 'zod';\n// 32 bytes in base64url without padding. The last character carries the final 4 bits and\n// 2 zero bits, so only 16 of the 64 characters can end it, which keeps the spelling of a key\n// unique.\nconst ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\nconst EXPECTED = 'Expected a public Ed25519 key as a JWK with kty, crv and x';\nconst PRIVATE = 'Expected a public key, but this includes its private part (d)';\n/**\n * A key a manifest names. A manifest is public, so a key that includes its private part\n * is refused with a message of its own: it has to be replaced, not just removed. Other\n * members are refused by name, as key tools often add some, such as `kid` or `alg`.\n */\nexport const publicKeyField = z.strictObject({\n kty: z.literal('OKP', EXPECTED),\n crv: z.literal('Ed25519', EXPECTED),\n x: z.string(EXPECTED).regex(ED25519_X, 'Expected 32 bytes in base64url, without padding'),\n}, {\n error: (issue) => {\n if (issue.code !== 'unrecognized_keys') {\n return EXPECTED;\n }\n return issue.keys.includes('d')\n ? PRIVATE\n : `Expected only kty, crv and x; remove ${issue.keys.join(', ')}`;\n },\n});\n//# sourceMappingURL=keys.js.map","import { z } from 'zod';\n/**\n * What an app asks for: the places in Ghost it wants to appear. Each surface type is one\n * entry in a union, so a new one is added here and nowhere else.\n */\nexport function surfacesField(url) {\n const adminPage = z.strictObject({\n type: z.literal('admin_page'),\n url: url(),\n });\n const surfaceTypes = [adminPage];\n const surface = z.discriminatedUnion('type', surfaceTypes, {\n error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(', ')}`,\n });\n return z\n .array(surface, 'Expected a list of surfaces')\n .min(1, 'Expected at least one surface')\n .superRefine((surfaces, ctx) => {\n const seen = new Set();\n surfaces.forEach((entry, index) => {\n if (seen.has(entry.type)) {\n ctx.addIssue({\n code: 'custom',\n message: `Expected at most one ${entry.type} surface`,\n path: [index],\n });\n }\n seen.add(entry.type);\n });\n });\n}\n//# sourceMappingURL=surfaces.js.map","import { z } from 'zod';\nimport { isPlainText } from '../plain-text.js';\n// A character that shows something on its own: a letter, digit, punctuation or symbol, but not\n// the blank Braille pattern or one Unicode says to draw as nothing, such as a joiner or a Hangul\n// filler. Whitespace and marks aren't any of those.\nconst VISIBLE_CHARACTER = new RegExp('(?![\\\\u2800\\\\p{Default_Ignorable_Code_Point}])[\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}]', 'u');\nconst shows = (text) => VISIBLE_CHARACTER.test(text);\n// Shows nothing, and holds nothing plain text refuses other than whitespace, so trimming never\n// takes off a character, such as one that reorders text, that should get the text refused.\nconst blank = (character) => !shows(character) && isPlainText(character.replace(/\\s/gu, ''));\n// Made on first use, so loading the contract doesn't set one up.\nlet graphemes;\n/**\n * Takes off each end the characters, as a reader sees them, that show nothing: a space with a\n * mark on it goes, an emoji with its variation selector stays, and so does anything invisible\n * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no\n * more than its length.\n */\nfunction trimEdges(value) {\n graphemes ??= new Intl.Segmenter();\n const characters = graphemes.segment(value);\n let start = value.length;\n for (const { segment, index } of characters) {\n if (!blank(segment)) {\n start = index;\n break;\n }\n }\n let end = value.length;\n while (end > start) {\n const { segment, index } = characters.containing(end - 1);\n if (!blank(segment)) {\n break;\n }\n end = index;\n }\n return value.slice(start, end);\n}\n/**\n * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and\n * text with nothing visible left, such as a name of Hangul fillers, is refused.\n */\nexport function plainText(maxLength) {\n return (z\n .string('Expected text')\n // Whitespace first, as a character that joins onto a space, such as a skin tone, would keep it.\n .trim()\n .overwrite(trimEdges)\n .refine(shows, 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line'));\n}\n// Any letter, digit, punctuation or symbol, fillers included: the rule manifests were stored under\n// before blank names were refused.\nconst ANY_CHARACTER = /[\\p{L}\\p{N}\\p{P}\\p{S}]/u;\n/**\n * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before\n * blank names were refused still reads, and the app can still be listed and uninstalled.\n */\nexport function storedText(maxLength) {\n return z\n .string('Expected text')\n .trim()\n .refine((value) => ANY_CHARACTER.test(value), 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line');\n}\n//# sourceMappingURL=text.js.map","import { z } from 'zod';\nimport { isContainedPath } from '../bridge/rules.js';\nimport { URL_MAX_LENGTH } from './limits.js';\nimport { isLocalhost } from './localhost.js';\nexport const FRAGMENT_PROBLEM = 'Expected a URL without a fragment';\n/**\n * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`\n * hides. A fragment never reaches the server, so a manifest address with one is a mistake or\n * a second spelling of the same address.\n */\nexport const hasFragment = (address) => address.includes('#');\n/**\n * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would\n * use. The length is measured on the parsed URL for the same reason, as that is what is\n * stored and checked again later.\n */\nexport function checkResolvedUrl(url, allowLocalhost) {\n if (url.href.length > URL_MAX_LENGTH) {\n return `Expected at most ${URL_MAX_LENGTH} characters`;\n }\n if (url.username || url.password) {\n return 'Expected a URL without a username or password';\n }\n if (isLocalhost(url.hostname)) {\n if (!allowLocalhost) {\n return 'Expected a public address; localhost is only allowed when Ghost runs in development';\n }\n return url.protocol === 'https:' || url.protocol === 'http:'\n ? null\n : 'Expected an http or https URL';\n }\n return url.protocol === 'https:' ? null : 'Expected an https URL';\n}\nconst ROUTE_PROBLEM = 'Expected a URL that resolves to a path starting with a single /, with no \\\\ in its query or fragment';\nconst PATH_PROBLEM = 'Expected a path on the manifest’s own origin, such as /admin';\n// Two, so a reference that names one of them still names a host other than the other's.\nconst PLACEHOLDER_HOSTS = ['manifest-a.invalid', 'manifest-b.invalid'];\n/** Whether a reference names a host, in any of the URL parser's spellings of one. */\nconst namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);\nfunction isManifestItself(url, base) {\n return url.pathname === new URL(base).pathname;\n}\n/**\n * A URL in the manifest. What Ghost loads is written as a path, resolved against the\n * address the manifest was fetched from, so an app is one origin: the one Ghost fetches\n * the manifest from and challenges is the one every surface runs on. The manifest names\n * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they\n * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.\n *\n * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and\n * may be anywhere, the publisher's own site included.\n *\n * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.\n * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.\n * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which\n * names a host, and a `\\` in the query or fragment is left as it is. Only the page is opened\n * as a route, but every URL Ghost loads is held to the one rule.\n */\nexport function urlField({ allowLocalhost, base }, linkOnly = false) {\n if (linkOnly) {\n return z.string('Expected an absolute URL').transform((value, ctx) => {\n const url = URL.parse(value);\n const problem = url ? checkResolvedUrl(url, allowLocalhost) : 'Expected an absolute URL';\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n return url.href;\n });\n }\n const origin = new URL(base).origin;\n return z.string(PATH_PROBLEM).transform((value, ctx) => {\n // A path, or a path-relative reference. A URL with a scheme, or a `//host` one, names\n // its own origin, which the manifest's would then not be, even when it's the same one\n // today. An empty one, or one that's only a query or fragment, would be the manifest\n // itself.\n const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);\n if (!url || url.origin !== origin || isManifestItself(url, base)) {\n ctx.addIssue({ code: 'custom', message: PATH_PROBLEM });\n return z.NEVER;\n }\n const problem = checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {\n ctx.addIssue({ code: 'custom', message: ROUTE_PROBLEM });\n return z.NEVER;\n }\n return url.href;\n });\n}\n/**\n * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and\n * already checked. Nothing is resolved or checked again, so a manifest accepted before the\n * site's URL changed still reads back.\n */\nexport const absoluteUrl = () => z.url('Expected an absolute URL');\n//# sourceMappingURL=url.js.map","import { z } from 'zod';\nimport { iconField } from './icon.js';\nimport { APP_ID_MAX_LENGTH, isValidAppId } from './id.js';\nimport { publicKeyField } from './keys.js';\nimport { isLocalhost } from './localhost.js';\nimport { surfacesField } from './surfaces.js';\nimport { plainText, storedText } from './text.js';\nimport { absoluteUrl, FRAGMENT_PROBLEM, hasFragment, urlField, } from './url.js';\nconst NAME_MAX_LENGTH = 50;\nconst DESCRIPTION_MAX_LENGTH = 200;\nconst AUTHOR_NAME_MAX_LENGTH = 50;\nconst HEX_COLOR = /^#[0-9a-f]{6}$/i;\nconst KEY_FIELDS = new Set(['identity_key', 'backend_key']);\nconst URL_FIELDS = new Set([\n 'author',\n 'icon',\n 'surfaces',\n 'manifest_url',\n 'development',\n]);\n/** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */\nconst parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));\n/**\n * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot\n * claim something Ghost has not designed, and adding a field is always a deliberate change\n * here.\n *\n * Defined once, with the URL and text rules left open. What a valid URL is depends on whether\n * the manifest is being parsed, when where Ghost is served from matters, or read back after it\n * was, when it doesn't. Text is held to today's rules when parsed, and read back under the\n * rules it was stored under.\n */\nfunction manifestShape(url, text) {\n return (z\n .strictObject({\n id: z.custom(isValidAppId, {\n error: `Expected a lowercase reverse-domain ID such as com.example.app, at most ${APP_ID_MAX_LENGTH} characters`,\n }),\n name: text(NAME_MAX_LENGTH),\n description: text(DESCRIPTION_MAX_LENGTH),\n author: z.strictObject({\n name: text(AUTHOR_NAME_MAX_LENGTH),\n // Only ever linked to, so it may point at the publisher's own site.\n url: url(true),\n }, 'Expected an author with a name and a url'),\n accent_color: z\n .string('Expected a hex colour such as #ff5500')\n .regex(HEX_COLOR, 'Expected a hex colour such as #ff5500')\n .toLowerCase(),\n icon: iconField(url),\n surfaces: surfacesField(url),\n // Where the signed manifest is served from: the app's one origin, which every path\n // in it resolves against. Ghost fetches it server-side and never loads it as a page.\n manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),\n identity_key: publicKeyField,\n backend_key: publicKeyField,\n // Lets Admin label a development build. Production sites may run one to test it.\n development: z.boolean('Expected true or false'),\n })\n // A backend holds its key online. If it also signed manifests, whoever took over the\n // backend could publish any manifest as the app.\n .refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {\n message: 'Expected a different key from identity_key',\n path: ['backend_key'],\n // Only once both keys are known to be keys. An issue without a path is about the\n // manifest as a whole, which may not be an object at all.\n when: parsedFields(KEY_FIELDS),\n })\n // An app on the developer's machine is always labelled as a development build.\n .refine((manifest) => manifest.development ||\n ![\n manifest.author.url,\n 'url' in manifest.icon ? manifest.icon.url : undefined,\n ...manifest.surfaces.map((surface) => surface.url),\n manifest.manifest_url,\n ].some((address) => address !== undefined && isLocalhost(new URL(address).hostname)), {\n message: 'Expected true, as the app is on localhost',\n path: ['development'],\n when: parsedFields(URL_FIELDS),\n }));\n}\n/** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */\nexport function manifestSchema(rules) {\n return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);\n}\n/**\n * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to\n * resolve or check. This is the schema to read a stored manifest with, as it holds\n * whatever the site's URL has become since, and it encodes a manifest back to the same\n * shape, so what is stored is what will be read.\n */\nexport const AppManifestSchema = manifestShape(absoluteUrl, storedText);\n//# sourceMappingURL=schema.js.map","import { hostOf, isGhostHost } from './ghost-host.js';\nimport { isLocalhost } from './localhost.js';\nimport { manifestSchema } from './schema.js';\nimport { checkResolvedUrl, FRAGMENT_PROBLEM, hasFragment } from './url.js';\nfunction formatPath(path) {\n return path.reduce((result, part) => {\n if (typeof part === 'number') {\n return `${result}[${part}]`;\n }\n return result ? `${result}.${String(part)}` : String(part);\n }, '');\n}\nconst GHOST_URLS_PROBLEM = 'Expected the URLs Ghost itself is served from';\nconst ON_GHOST_HOST = 'Expected the manifest on a host other than the one Ghost itself is served from, on any port, as browsers send Ghost’s cookies to every port on its host';\nconst ON_GHOST_HOST_LOCALLY = `${ON_GHOST_HOST}. To run the app on this machine too, serve it from a name of its own under .localhost, such as my-app.localhost`;\n/**\n * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most\n * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`\n * is a host of its own, which browsers send to the machine itself, and so does Ghost in\n * development, whatever the system's resolver knows.\n */\nfunction onGhostHost(url) {\n return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;\n}\n/**\n * Reads the address a manifest is to be read from, by the same rules as the URLs inside\n * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first\n * request never goes to an address Ghost would refuse (plain HTTP, one carrying\n * credentials, or one on Ghost's host). It cannot judge where that address redirects,\n * which is for whatever fetches it to limit.\n *\n * The address it hands back is the one to store, to compare with a later one, and that the\n * manifest must name as its `manifest_url`. The URL parser settles most differences in\n * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a\n * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.\n */\nexport function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {\n if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) {\n return { success: false, error: GHOST_URLS_PROBLEM };\n }\n const url = URL.parse(input);\n if (!url) {\n return { success: false, error: 'Expected the manifest at a URL' };\n }\n const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n return { success: false, error: `${problem} for the manifest itself` };\n }\n if (isGhostHost(url, ghostUrls)) {\n return { success: false, error: onGhostHost(url) };\n }\n return { success: true, manifestUrl: url.href };\n}\n/** A manifest's problems as `path: message`, joined by `separator`, as Ghost reports them. */\nexport function formatManifestErrors(errors, separator) {\n return errors\n .map(({ path, message }) => (path ? `${path}: ${message}` : message))\n .join(separator);\n}\nfunction invalid(errors) {\n return { success: false, reason: 'invalid', errors };\n}\n/**\n * Validates a manifest, and checks it names the address it was fetched from as its\n * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the\n * manifest to its address as well as to every URL in it.\n *\n * Returns either the manifest, or every problem found. It does not fetch anything and it\n * never throws. Without the URLs Ghost is served from it rejects every manifest, since the\n * rule that keeps apps off Ghost's hosts could not be checked.\n */\nexport function parseManifest(input, options) {\n const allowLocalhost = options.allowLocalhost ?? false;\n const address = parseManifestUrl(options.manifestUrl, options);\n if (!address.success) {\n return invalid([{ path: '', message: address.error }]);\n }\n const result = manifestSchema({ allowLocalhost, base: address.manifestUrl }).safeParse(input);\n if (!result.success) {\n return invalid(result.error.issues.map((issue) => ({\n path: formatPath(issue.path),\n message: issue.message,\n })));\n }\n if (result.data.manifest_url !== address.manifestUrl) {\n return {\n success: false,\n reason: 'manifest_url_mismatch',\n errors: [\n {\n path: 'manifest_url',\n message: `Expected ${address.manifestUrl}, the address the manifest was read from`,\n },\n ],\n };\n }\n return { success: true, manifest: result.data };\n}\n//# sourceMappingURL=parse.js.map","import { MANIFEST_MAX_BYTES, SIGNED_MANIFEST_MAX_BYTES } from '@tryghost/app-contracts/identity';\nimport { AppManifestSchema, type AppManifest } from '@tryghost/app-contracts/manifest';\nimport { z } from 'zod';\n\n/**\n * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what\n * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.\n */\nexport function storedSize(manifest: AppManifest): number {\n return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;\n}\n\nexport const signedTooLargeMessage = () =>\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;\n\nexport const tooLargeMessage = () =>\n `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport {\n MANIFEST_MAX_BYTES,\n SIGNED_MANIFEST_MAX_BYTES,\n parseJsonText,\n signManifest,\n} from '@tryghost/app-contracts/identity';\nimport {\n formatManifestErrors,\n parseManifest,\n parseManifestUrl,\n} from '@tryghost/app-contracts/manifest';\n\nimport {\n publicKeyOf,\n readKey,\n readSigningKeys,\n type PrivateKeyJwk,\n type PublicKeyJwk,\n type ReadKeysOptions,\n} from './keys.ts';\nimport { UNKNOWN_GHOST_URL } from '../shared/manifest.ts';\nimport { signedTooLargeMessage, storedSize, tooLargeMessage } from './limits.ts';\nimport type { ManifestError, SignedManifest } from './types.ts';\n\n/** The readable manifest a project keeps, which the tooling signs. */\nexport const MANIFEST_FILE = 'ghost-app.json';\n\n/** The fields the tooling adds, which `ghost-app.json` mustn't set. */\nconst ADDED_FIELDS = ['manifest_url', 'identity_key', 'backend_key', 'development'] as const;\n\nexport interface SignOptions {\n /** The address the signed manifest will be served from, which it names as its own. */\n manifestUrl: string;\n identityKey: PrivateKeyJwk;\n /** Only its public half goes in the manifest. */\n backendKey: PrivateKeyJwk | PublicKeyJwk;\n /** Whether this is a development build, as it must be when any URL is on localhost. */\n development: boolean;\n}\n\nexport type SignResult =\n | {\n success: true;\n signed: SignedManifest;\n /** The manifest as signed, with the fields the tooling added. */\n manifest: Record<string, unknown>;\n }\n | {\n success: false;\n /**\n * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or\n * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost stores.\n */\n code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';\n errors: ManifestError[];\n };\n\ntype Refusal = Extract<SignResult, { success: false }>;\n\nconst refuse = (code: Refusal['code'], message: string, path = ''): Refusal => ({\n success: false,\n code,\n errors: [{ path, message }],\n});\n\n/**\n * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it\n * with the identity key, unless Ghost would refuse it.\n */\nexport async function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult> {\n // A JWK carries both halves, so one passed in, rather than read from a file, could pair a\n // private half with another key's public half. The manifest would name a key that didn't sign\n // it, or one the backend can't answer for, and Ghost would refuse it. That's the caller's\n // mistake, so it throws.\n readKey(JSON.stringify(options.identityKey), 'identityKey');\n if ('d' in options.backendKey) {\n readKey(JSON.stringify(options.backendKey), 'backendKey');\n }\n // Ghost's own hosts are the one rule only a site knows, so a name no site has stands in.\n const address = parseManifestUrl(options.manifestUrl, {\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!address.success) {\n return refuse('APP_MANIFEST_URL_INVALID', address.error);\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return refuse('APP_MANIFEST_INVALID', 'Expected the manifest as a JSON object');\n }\n // The fields signing adds can't come from the file, or the file could name other keys.\n const added = ADDED_FIELDS.filter((field) => field in source);\n if (added.length > 0) {\n return {\n success: false,\n code: 'APP_MANIFEST_INVALID',\n errors: added.map((field) => ({\n path: field,\n message: `Leave ${field} out: it's added when the manifest is signed`,\n })),\n };\n }\n\n const manifest = {\n ...source,\n manifest_url: address.manifestUrl,\n identity_key: publicKeyOf(options.identityKey),\n backend_key: publicKeyOf(options.backendKey),\n development: options.development,\n };\n // Checked by the rules Ghost applies, so a manifest Ghost would refuse is never signed, and\n // the result lists every problem by the path to its field.\n const parsed = parseManifest(manifest, {\n manifestUrl: address.manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!parsed.success) {\n // A mismatch can't happen, as the manifest URL was just set; any failure is invalid.\n return { success: false, code: 'APP_MANIFEST_INVALID', errors: parsed.errors };\n }\n if (storedSize(parsed.manifest) > MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', tooLargeMessage());\n }\n\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // Ghost limits the signed manifest it fetches too, and the payload keeps whatever the file had,\n // such as text Ghost trims, so a manifest Ghost stores can still be too large to fetch.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', signedTooLargeMessage());\n }\n return { success: true, signed, manifest };\n}\n\n/** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */\nexport function formatErrors(errors: readonly ManifestError[]): string {\n return formatManifestErrors(errors, '\\n');\n}\n\n/** A signed manifest as the CLI and the Vite plugin write it to a file. */\nexport function serialiseSigned(signed: SignedManifest): string {\n return `${JSON.stringify(signed, null, 2)}\\n`;\n}\n\n/** Reads `ghost-app.json`, or another readable manifest, as JSON. */\nexport async function readManifestSource(file: string): Promise<unknown> {\n const text = await readFile(file, 'utf8');\n try {\n return parseJsonText(text);\n } catch (error) {\n throw new Error(`${file} isn't JSON: ${(error as Error).message}`, { cause: error });\n }\n}\n\nexport interface SignProjectOptions extends ReadKeysOptions {\n manifestUrl: string;\n /** The readable manifest, relative to `root`. `ghost-app.json` by default. */\n manifestFile?: string;\n}\n\n/** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */\nexport async function signProject({\n root,\n mode,\n env,\n manifestUrl,\n manifestFile = MANIFEST_FILE,\n}: SignProjectOptions): Promise<SignResult> {\n // Resolved, so an absolute path is taken as it is.\n const source = await readManifestSource(resolve(root, manifestFile));\n // Keys are read, never created: a missing one throws with how to create it.\n const keys = await readSigningKeys({ root, mode, env });\n return signAppManifest(source, { manifestUrl, ...keys, development: mode === 'development' });\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAM,iBAAiB;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;AAMA,SAAgB,oBAAoB,UAAU;CAC1C,IAAI,MAAM,SAAS;CACnB,OAAO,MAAM,KAAK,SAAS,MAAM,OAAO,KACpC,OAAO;CAEX,OAAO,SAAS,MAAM,GAAG,GAAG;AAChC;;;;;;AAMA,SAAgB,YAAY,UAAU;CAClC,MAAM,OAAO,oBAAoB,QAAQ;CACzC,OAAO,eAAe,MAAM,YAAY,QAAQ,KAAK,IAAI,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;ACZA,SAAgB,YAAY,KAAK,WAAW;CACxC,MAAM,OAAO,OAAO,GAAG;CACvB,IAAI,SAAS,MACT,OAAO;CAEX,IAAI,QAAQ;CACZ,KAAK,MAAM,YAAY,WAAW;EAC9B,MAAM,YAAY,OAAO,QAAQ;EACjC,IAAI,cAAc,QAAQ,cAAc,MACpC,OAAO;EAEX,QAAQ;CACZ;CACA,OAAO,CAAC;AACZ;;AAEA,SAAgB,OAAO,OAAO;CAC1B,IAAI;CAEJ,IAAI;EACA,MAAM,IAAI,IAAI,KAAK;CACvB,QACM;EACF,OAAO;CACX;CACA,IAAI,IAAI,aAAa,WAAW,IAAI,aAAa,UAC7C,OAAO;CAEX,OAAO,oBAAoB,IAAI,QAAQ,KAAK;AAChD;AC9CA,IAAM,aAAa;;;;;;;AAOnB,SAAgB,aAAa,OAAO;CAChC,IAAI,OAAO,UAAU,YAAY,MAAM,SAAA,KACnC,OAAO;CAEX,MAAM,WAAW,MAAM,MAAM,GAAG;CAChC,OAAQ,SAAS,UAAU,KACvB,SAAS,KAAK,KAAK,KACnB,SAAS,OAAO,YAAY,WAAW,KAAK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AAO,cAAc,IAAI;CAC3B,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,KAAK,eAAgB,MAAgB,WAAW,EAAE,OAAO,MAAM,CAAC;CACrF;AACF;;AASA,eAAsB,YAAY,EAChC,MACA,MACA,KACA,aACA,eAAe,iBAC2B;CAK1C,OAAO,gBAAgB,MAHF,mBAAmB,QAAQ,MAAM,YAAY,CAAC,GAGpC;EAAE;EAAa,GAAG,MAD9B,gBAAgB;GAAE;GAAM;GAAM;EAAI,CAAC;EACC,aAAa,SAAS;CAAc,CAAC;AAC9F"}
package/build/index.js CHANGED
@@ -490,7 +490,7 @@ var Channel = class {
490
490
  * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
491
491
  * and doesn't read package.json.
492
492
  */
493
- var SDK_VERSION = "0.1.0-alpha.10";
493
+ var SDK_VERSION = "0.1.0-alpha.11";
494
494
  //#endregion
495
495
  //#region src/connect.ts
496
496
  /**
@@ -1,4 +1,4 @@
1
- import { i as formatErrors, n as ManifestError, r as SignedManifest } from "./chunks/manifest-DFLCKcwH.js";
1
+ import { n as ManifestError, r as SignedManifest } from "./chunks/manifest-CYA0krtI.js";
2
2
  //#region src/tooling/keys.d.ts
3
3
  /**
4
4
  * Which keys to use. Development and production have separate identity keys, so an app
@@ -135,6 +135,8 @@ type SignResult = {
135
135
  * with the identity key, unless Ghost would refuse it.
136
136
  */
137
137
  declare function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult>;
138
+ /** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */
139
+ declare function formatErrors(errors: readonly ManifestError[]): string;
138
140
  /** Reads `ghost-app.json`, or another readable manifest, as JSON. */
139
141
  declare function readManifestSource(file: string): Promise<unknown>;
140
142
  interface SignProjectOptions extends ReadKeysOptions {
package/build/tooling.js CHANGED
@@ -1,3 +1,2 @@
1
- import { a as signProject, c as KEYS_DIRECTORY, d as generateKey, f as keyFile, h as readSigningKeys, i as signAppManifest, m as readBackendKey, n as readManifestSource, o as BACKEND_KEY_VARIABLE, p as publicKeyOf, s as IDENTITY_KEY_VARIABLE, t as MANIFEST_FILE, u as createKeys } from "./chunks/sign-Deg9TCUr.js";
2
- import { r as formatErrors } from "./chunks/manifest-B9vQoSfm.js";
1
+ import { a as signAppManifest, c as IDENTITY_KEY_VARIABLE, d as createKeys, f as generateKey, g as readSigningKeys, h as readBackendKey, l as KEYS_DIRECTORY, m as publicKeyOf, n as formatErrors, o as signProject, p as keyFile, r as readManifestSource, s as BACKEND_KEY_VARIABLE, t as MANIFEST_FILE } from "./chunks/sign-3ysEUyYt.js";
3
2
  export { BACKEND_KEY_VARIABLE, IDENTITY_KEY_VARIABLE, KEYS_DIRECTORY, MANIFEST_FILE, createKeys, formatErrors, generateKey, keyFile, publicKeyOf, readBackendKey, readManifestSource, readSigningKeys, signAppManifest, signProject };
package/build/vite.js CHANGED
@@ -1,5 +1,6 @@
1
- import { _ as isValidAppId, a as signProject, c as KEYS_DIRECTORY, f as keyFile, g as signingKeySource, m as readBackendKey, o as BACKEND_KEY_VARIABLE, r as serialiseSigned, s as IDENTITY_KEY_VARIABLE, u as createKeys, v as isLocalhost } from "./chunks/sign-Deg9TCUr.js";
2
- import { a as parseJsonText, o as parseOrigin, r as formatErrors, t as MANIFEST_PATH } from "./chunks/manifest-B9vQoSfm.js";
1
+ import { _ as signingKeySource, b as isLocalhost, c as IDENTITY_KEY_VARIABLE, d as createKeys, h as readBackendKey, i as serialiseSigned, l as KEYS_DIRECTORY, n as formatErrors, o as signProject, p as keyFile, s as BACKEND_KEY_VARIABLE, v as parseJsonText, y as isValidAppId } from "./chunks/sign-3ysEUyYt.js";
2
+ import { t as MANIFEST_PATH } from "./chunks/manifest-BO_hJDEK.js";
3
+ import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
3
4
  import { existsSync, readFileSync } from "node:fs";
4
5
  import { appendFile, readFile } from "node:fs/promises";
5
6
  import { join, resolve } from "node:path";
package/build/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH, formatErrors } from '../shared/manifest.ts';\nimport { parseJsonText, parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CAAC;CAAoB;CAAc;CAAQ;AAAQ;;;ACZvE,IAAM,mBAAmB;CAAC;CAAiB;CAAkB;AAAe;AAE5E,IAAM,WAAW;;;;;;AAOjB,eAAsB,qBACpB,MACkE;CAClE,MAAM,SAAS,SAAiB,WAAW,KAAK,MAAM,IAAI,CAAC;CAC3D,IAAI,CAAC,iBAAiB,KAAK,KAAK,GAC9B;CAEF,MAAM,MAAM,MAAM,eAAe;EAAE;EAAM,MAAM;CAAc,CAAC;CAG9D,MAAM,OAAO,MAAM,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,cAAc,MAAM,CAAC,CAAC,OAAO,KAAK;CAC/E,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;EACvB,OAAO,MAAM,SAAS,KAAK,MAAM,IAAI,GAAG,MAAM;EAC9C,IAAI,KAAK,SAAA,uBAA6B,GAEpC,OAAO,KAAK,SAAS,IAAI,CAAC,IACtB,KAAA,IACA;GACE,OAAO;GACP,SAAS,GAAG,KAAK,SAAS,qBAAqB,yBAAyB,QAAQ,eAAe,SAAS,EAAE,sHAAsH,KAAK;EACvO;CAER;CACA,IAAI,KAAK,SAAS,KAAK,KAAK,OAAO,UACjC,OAAO;EACL,OAAO;EACP,SAAS,kBAAkB,KAAK,KAAK,OAAO,EAAE,mBAAmB,SAAS,WAAW,qBAAqB;CAC5G;CAGF,MAAM,OAAO,GAAG,qBAAqB,IAAI,KAAK,UAAU,GAAG,EAAE;CAC7D,MAAM,WAAW,KAAK,MAAM,QAAQ,GAAG,GAAG,QAAQ,CAAC,KAAK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,GAC/F;GAEF,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,cAAc,MAAM,CAAC;IAC/B,QAAQ,gBAAgB,OAAO,MAAM;GACvC,CAAC;GACD,OAAO,OAAO,KACZ,wCAAwC,YAAY,QAAQ,iBAAiB,cAAc,UAAU,GACvG;EACF;CACF;AACF"}
1
+ {"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport { parseJsonText } from '@tryghost/app-contracts/identity';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH } from '../shared/manifest.ts';\nimport { parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, formatErrors, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CAAC;CAAoB;CAAc;CAAQ;AAAQ;;;ACZvE,IAAM,mBAAmB;CAAC;CAAiB;CAAkB;AAAe;AAE5E,IAAM,WAAW;;;;;;AAOjB,eAAsB,qBACpB,MACkE;CAClE,MAAM,SAAS,SAAiB,WAAW,KAAK,MAAM,IAAI,CAAC;CAC3D,IAAI,CAAC,iBAAiB,KAAK,KAAK,GAC9B;CAEF,MAAM,MAAM,MAAM,eAAe;EAAE;EAAM,MAAM;CAAc,CAAC;CAG9D,MAAM,OAAO,MAAM,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,cAAc,MAAM,CAAC,CAAC,OAAO,KAAK;CAC/E,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;EACvB,OAAO,MAAM,SAAS,KAAK,MAAM,IAAI,GAAG,MAAM;EAC9C,IAAI,KAAK,SAAA,uBAA6B,GAEpC,OAAO,KAAK,SAAS,IAAI,CAAC,IACtB,KAAA,IACA;GACE,OAAO;GACP,SAAS,GAAG,KAAK,SAAS,qBAAqB,yBAAyB,QAAQ,eAAe,SAAS,EAAE,sHAAsH,KAAK;EACvO;CAER;CACA,IAAI,KAAK,SAAS,KAAK,KAAK,OA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AAC;GACpD,MAAM,SAAS,MAAM,YAAY;IAC/B,MAAM,OAAO;IACb,MAAM;IACN;IACA;GACF,CAAC,CAAC,CAAC,OAAO,UAAmB,KAAK,MAAM,cAAe,MAAgB,SAAS,CAAC;GACjF,IAAI,CAAC,OAAO,SACV,KAAK,MACH,cAAc,aAAa,uBAAuB,YAAY,KAAK,aAAa,OAAO,MAAM,GAC/F;GAEF,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,cAAc,MAAM,CAAC;IAC/B,QAAQ,gBAAgB,OAAO,MAAM;GACvC,CAAC;GACD,OAAO,OAAO,KACZ,wCAAwC,YAAY,QAAQ,iBAAiB,cAAc,UAAU,GACvG;EACF;CACF;AACF"}
package/dist/app-sdk.js CHANGED
@@ -1218,7 +1218,7 @@ var Channel = class {
1218
1218
  * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
1219
1219
  * and doesn't read package.json.
1220
1220
  */
1221
- var SDK_VERSION = "0.1.0-alpha.10";
1221
+ var SDK_VERSION = "0.1.0-alpha.11";
1222
1222
  //#endregion
1223
1223
  //#region src/connect.ts
1224
1224
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/app-sdk",
3
- "version": "0.1.0-alpha.10",
3
+ "version": "0.1.0-alpha.11",
4
4
  "description": "The SDK apps use to talk to Ghost: from their page inside Admin, from their backend, and from their tooling",
5
5
  "license": "MIT",
6
6
  "author": "Ghost Foundation",
@@ -1,43 +0,0 @@
1
- //#region ../app-contracts/build/identity/jws.js
2
- /** The only algorithm either key signs with. */
3
- var ALGORITHM = "Ed25519";
4
- //#endregion
5
- //#region src/shared/parse.ts
6
- var UNSAFE_IN_POLICY = /[\s;,'"*]/;
7
- /**
8
- * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
9
- * `,` into a host, so the origin must also read back as itself, and hold nothing that would end
10
- * a source in a Content-Security-Policy.
11
- */
12
- function parseOrigin(entry) {
13
- const url = URL.parse(entry);
14
- const origin = url?.origin;
15
- 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;
16
- return origin;
17
- }
18
- /** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
19
- function parseJsonText(text) {
20
- return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
21
- }
22
- //#endregion
23
- //#region src/shared/ignore.ts
24
- /** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
25
- var ignoreError = () => void 0;
26
- //#endregion
27
- //#region src/shared/manifest.ts
28
- /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
29
- var MANIFEST_PATH = "/ghost-app.json";
30
- /**
31
- * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but
32
- * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost
33
- * applies them.
34
- */
35
- var UNKNOWN_GHOST_URL = "https://ghost.invalid/";
36
- /** A manifest's problems, one per line, as `path: message`. */
37
- function formatErrors(errors) {
38
- return errors.map(({ path, message }) => path ? `${path}: ${message}` : message).join("\n");
39
- }
40
- //#endregion
41
- export { parseJsonText as a, ignoreError as i, UNKNOWN_GHOST_URL as n, parseOrigin as o, formatErrors as r, ALGORITHM as s, MANIFEST_PATH as t };
42
-
43
- //# sourceMappingURL=manifest-B9vQoSfm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"manifest-B9vQoSfm.js","names":[],"sources":["../../../app-contracts/build/identity/jws.js","../../src/shared/parse.ts","../../src/shared/ignore.ts","../../src/shared/manifest.ts"],"sourcesContent":["import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text: string): unknown {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n\n/** One problem with a manifest. */\nexport interface ManifestError {\n /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */\n path: string;\n message: string;\n}\n\n/**\n * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but\n * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost\n * applies them.\n */\nexport const UNKNOWN_GHOST_URL = 'https://ghost.invalid/';\n\n/** A manifest's problems, one per line, as `path: message`. */\nexport function formatErrors(errors: readonly ManifestError[]): string {\n return errors.map(({ path, message }) => (path ? `${path}: ${message}` : message)).join('\\n');\n}\n"],"mappings":";;AAEA,IAAa,YAAY;;;ACDzB,IAAM,mBAAmB;;;;;;AAOzB,SAAgB,YAAY,OAAmC;CAC7D,MAAM,MAAM,IAAI,MAAM,KAAK;CAC3B,MAAM,SAAS,KAAK;CACpB,IACE,CAAC,OACD,CAAC,UACA,IAAI,aAAa,YAAY,IAAI,aAAa,WAC/C,IAAI,SAAS,GAAG,OAAO,MACvB,IAAI,MAAM,MAAM,CAAC,EAAE,WAAW,UAC9B,iBAAiB,KAAK,KAAK,KAC3B,iBAAiB,KAAK,MAAM,GAE5B;CAEF,OAAO;AACT;;AAGA,SAAgB,cAAc,MAAuB;CACnD,OAAO,KAAK,MAAM,KAAK,WAAW,CAAC,MAAM,QAAS,KAAK,MAAM,CAAC,IAAI,IAAI;AACxE;;;;AC3BA,IAAa,oBAA+B,KAAA;;;;ACG5C,IAAa,gBAAgB;;;;;;AAqB7B,IAAa,oBAAoB;;AAGjC,SAAgB,aAAa,QAA0C;CACrE,OAAO,OAAO,KAAK,EAAE,MAAM,cAAe,OAAO,GAAG,KAAK,IAAI,YAAY,OAAQ,CAAC,CAAC,KAAK,IAAI;AAC9F"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sign-Deg9TCUr.js","names":[],"sources":["../../../app-contracts/build/manifest/localhost.js","../../../app-contracts/build/manifest/ghost-host.js","../../../app-contracts/build/manifest/id.js","../../../app-contracts/build/manifest/limits.js","../../../app-contracts/build/identity/signed-manifest.js","../../src/tooling/git.ts","../../src/tooling/keys.ts","../../../app-contracts/build/manifest/icon.js","../../../app-contracts/build/manifest/keys.js","../../../app-contracts/build/manifest/surfaces.js","../../../app-contracts/build/manifest/text.js","../../../app-contracts/build/manifest/url.js","../../../app-contracts/build/manifest/schema.js","../../../app-contracts/build/manifest/parse.js","../../src/tooling/limits.ts","../../src/tooling/sign.ts"],"sourcesContent":["// `URL` has already normalised the host by the time these run: every spelling of an IPv4\n// address is dotted decimal, and an IPv4-mapped IPv6 address is two hex groups.\nconst LOOPBACK_HOSTS = [\n /^localhost$/,\n /\\.localhost$/,\n /^127\\.\\d+\\.\\d+\\.\\d+$/,\n /^0\\.0\\.0\\.0$/,\n /^\\[::1?\\]$/,\n /^\\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\\]$/,\n /^\\[::ffff:0:0\\]$/,\n];\n/**\n * A hostname without its trailing dots, which the URL parser keeps, every one of them:\n * `localhost..` is `localhost`. A loop rather than a regular expression, which would take\n * time quadratic in the number of dots on a hostname with many dots before its end.\n */\nexport function withoutTrailingDots(hostname) {\n let end = hostname.length;\n while (end > 0 && hostname[end - 1] === '.') {\n end -= 1;\n }\n return hostname.slice(0, end);\n}\n/**\n * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.\n * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as\n * `isGhostHost` drops them.\n */\nexport function isLocalhost(hostname) {\n const host = withoutTrailingDots(hostname);\n return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));\n}\n//# sourceMappingURL=localhost.js.map","import { withoutTrailingDots } from './localhost.js';\n/**\n * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any\n * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,\n * whatever a frame's sandbox says. On another port it would be the app's, but browsers send\n * a host's cookies to every port on it, so the app's server would be sent the staff user's\n * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it\n * frames the page, since the site's or Admin's address can change after an app is\n * installed.\n *\n * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and\n * without a trailing dot. A sibling host, such as another subdomain of the site's, is not\n * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as\n * `my-app.localhost` next to `localhost`, or another name for the same machine, such as\n * `127.0.0.1`, which browsers treat as other hosts too.\n *\n * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no\n * Ghost URLs at all. Either way the URL is refused.\n */\nexport function isGhostHost(url, ghostUrls) {\n const host = hostOf(url);\n if (host === null) {\n return true;\n }\n let known = false;\n for (const ghostUrl of ghostUrls) {\n const ghostHost = hostOf(ghostUrl);\n if (ghostHost === null || ghostHost === host) {\n return true;\n }\n known = true;\n }\n return !known;\n}\n/** An http or https URL's host as `isGhostHost` compares it, or null for any other. */\nexport function hostOf(value) {\n let url;\n // Admin runs this, and `URL.parse` is newer than the browsers Admin supports.\n try {\n url = new URL(value);\n }\n catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return null;\n }\n return withoutTrailingDots(url.hostname) || null;\n}\n//# sourceMappingURL=ghost-host.js.map","/** Matches the limit of the index that ties saved cards to an app. */\nexport const APP_ID_MAX_LENGTH = 191;\nconst ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n/**\n * An app ID is reverse-domain style: at least two dot-separated segments of lowercase\n * letters, digits and hyphens, starting with a letter so that an IP address or a version\n * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than\n * lowercased.\n */\nexport function isValidAppId(value) {\n if (typeof value !== 'string' || value.length > APP_ID_MAX_LENGTH) {\n return false;\n }\n const segments = value.split('.');\n return (segments.length >= 2 &&\n /^[a-z]/.test(value) &&\n segments.every((segment) => ID_SEGMENT.test(segment)));\n}\n//# sourceMappingURL=id.js.map","/**\n * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of\n * them, the manifest's own URL included, so its columns are exactly this wide.\n */\nexport const URL_MAX_LENGTH = 2000;\n//# sourceMappingURL=limits.js.map","import { FlattenedSign, flattenedVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeText } from './keys.js';\n/** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */\nexport const SIGNED_MANIFEST_TYPE = 'ghost-app-manifest';\nconst SignedManifestShape = z.strictObject({\n protected: z.string(),\n payload: z.string(),\n signature: z.string(),\n});\nconst ProtectedHeader = z.strictObject({\n alg: z.literal(ALGORITHM),\n typ: z.literal(SIGNED_MANIFEST_TYPE),\n});\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE });\n/**\n * Signs a manifest with an app's identity key. A string is signed as the exact text it is;\n * anything else is signed as its JSON.\n */\nexport async function signManifest(manifest, identityKey) {\n const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest);\n const signed = await new FlattenedSign(new TextEncoder().encode(text))\n .setProtectedHeader({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE })\n .sign(identityKey);\n return { protected: signed.protected, payload: signed.payload, signature: signed.signature };\n}\n/**\n * Reads the manifest out of a signed manifest, without verifying it. The key to verify it\n * with is named inside the manifest, so the manifest has to be read and checked first;\n * nothing in it may be used until `verifySignedManifest` has passed.\n */\nexport function readSignedManifest(body) {\n const shape = SignedManifestShape.safeParse(body);\n if (!shape.success) {\n return {\n success: false,\n error: 'Expected a signed manifest: flattened JWS JSON with protected, payload and signature',\n };\n }\n const signed = shape.data;\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n const payload = decodeText(signed.payload);\n if (payload === undefined) {\n return { success: false, error: 'Expected a payload of UTF-8 text in base64url' };\n }\n return { success: true, signed, payload };\n}\n/**\n * Checks a signed manifest was signed with the identity key the manifest names, under\n * exactly the protected header `readSignedManifest` accepts.\n */\nexport async function verifySignedManifest(signed, identityKey) {\n let key;\n try {\n key = await importJWK(identityKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'identity_key is not a usable Ed25519 key' };\n }\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n try {\n await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });\n }\n catch {\n return { success: false, error: 'The signature was not made with identity_key' };\n }\n return { success: true };\n}\n//# sourceMappingURL=signed-manifest.js.map","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { ignoreError } from '../shared/ignore.ts';\n\nexport type IgnoredResult = { ignored: true } | { ignored: false; reason: string };\n\nfunction git(args: string[], cwd: string, input?: string) {\n return new Promise<{ code: number | string | null; stdout: string; stderr: string }>((done) => {\n const child = execFile('git', args, { cwd }, (error, stdout, stderr) => {\n done({ code: error ? ((error as { code?: number | string }).code ?? 1) : 0, stdout, stderr });\n });\n // A git that couldn't start has no stdin to write to; its error arrives above.\n child.stdin?.on('error', ignoreError);\n child.stdin?.end(input);\n });\n}\n\nfunction insideRepository(directory: string): boolean {\n for (let current = resolve(directory); ; current = dirname(current)) {\n if (existsSync(join(current, '.git'))) {\n return true;\n }\n if (dirname(current) === current) {\n return false;\n }\n }\n}\n\n/**\n * The directory itself, or the nearest one above it that exists, to run git in: a project's\n * directory may not exist before its keys are written, and git can't start in one that doesn't.\n */\nfunction existingDirectory(directory: string): string {\n let current = resolve(directory);\n while (!existsSync(current) && dirname(current) !== current) {\n current = dirname(current);\n }\n return current;\n}\n\n/**\n * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by\n * accident. A file outside any repository counts as ignored.\n */\nexport async function isGitIgnored(\n root: string,\n files: string | readonly string[],\n): Promise<IgnoredResult> {\n // git can't start in a directory that doesn't exist, and a project's may not exist yet.\n const cwd = existingDirectory(root);\n const paths = (typeof files === 'string' ? [files] : files).map((file) => ({\n // As the developer named it, for messages, and as git is asked about it, from `cwd`.\n shown: relative(root, resolve(root, file)),\n asked: relative(cwd, resolve(root, file)),\n }));\n const named = `${paths.map(({ shown }) => shown).join(' and ')} ${paths.length > 1 ? 'are' : 'is'}`;\n\n const repository = await findRepository(cwd, named);\n if (repository !== 'inside') {\n return repository === 'outside' ? { ignored: true } : repository;\n }\n return askWhichAreIgnored(cwd, paths, named);\n}\n\n/** Whether `cwd` is in a repository, or why git can't say when it seems to be. */\nasync function findRepository(\n cwd: string,\n named: string,\n): Promise<'inside' | 'outside' | { ignored: false; reason: string }> {\n // Read from what git exits with, never from what it says, which is in the developer's\n // language. A `.git` that git can't read is still a repository, so it isn't taken as outside.\n const inside = await git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (inside.code === 0) {\n return 'inside';\n }\n if (!insideRepository(cwd)) {\n return 'outside';\n }\n return {\n ignored: false,\n reason:\n inside.code === 'ENOENT'\n ? `git isn't installed, so it can't check ${named} ignored`\n : `git couldn't read the repository: ${inside.stderr.trim()}`,\n };\n}\n\nasync function askWhichAreIgnored(\n cwd: string,\n paths: { shown: string; asked: string }[],\n named: string,\n): Promise<IgnoredResult> {\n // One call for every path. It lists the ones it ignores, and exits with 1 when it ignores none.\n // Paths go in and out separated by NUL, as git would otherwise quote one with any byte outside\n // ASCII. A file git tracks isn't ignored, even if a `.gitignore` names it.\n const { code, stdout, stderr } = await git(\n ['check-ignore', '--stdin', '-z'],\n cwd,\n paths.map(({ asked }) => `${asked}\\0`).join(''),\n );\n if (code !== 0 && code !== 1) {\n return { ignored: false, reason: `git couldn't check ${named} ignored: ${stderr.trim()}` };\n }\n const ignored = new Set(stdout.split('\\0'));\n const notIgnored = paths.find(({ asked }) => !ignored.has(asked));\n return notIgnored\n ? { ignored: false, reason: `git doesn't ignore ${notIgnored.shown}` }\n : { ignored: true };\n}\n","import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nimport { isGitIgnored } from './git.ts';\n\n/**\n * Which keys to use. Development and production have separate identity keys, so an app\n * installed from the developer's machine is a different app from the deployed one.\n */\nexport type Mode = 'development' | 'production';\n\n/** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */\nexport const KEYS_DIRECTORY = '.ghost-app';\n\n/**\n * - `identity`: signs the manifest. It says who made the app, so it stays with the developer\n * (or their CI) and never reaches the backend or a bundle.\n * - `backend`: answers Ghost's challenge, so the backend holds it.\n */\nexport type KeyName = 'identity' | 'backend';\n\nexport const KEY_NAMES: readonly KeyName[] = ['identity', 'backend'];\n\n/** A private Ed25519 key as a JWK. */\nexport interface PrivateKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n d: string;\n}\n\n/** A public Ed25519 key as a JWK, as a manifest names it. */\nexport interface PublicKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n}\n\n/** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */\nexport const IDENTITY_KEY_VARIABLE = 'GHOST_APP_IDENTITY_KEY';\n\n/**\n * The backend key, as the backend reads it, and as CI may provide it to sign a production\n * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.\n */\nexport const BACKEND_KEY_VARIABLE = 'GHOST_APP_BACKEND_KEY';\n\nexport interface KeyOptions {\n /** The project's directory, which holds `.ghost-app/`. */\n root: string;\n mode: Mode;\n}\n\n/** The file a key is kept in, relative to the project. */\nexport function keyFile(mode: Mode, name: KeyName): string {\n return join(KEYS_DIRECTORY, mode, `${name}.json`);\n}\n\n/** A new private Ed25519 key. */\nexport function generateKey(): PrivateKeyJwk {\n const { x, d } = generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' });\n return { kty: 'OKP', crv: 'Ed25519', x: x!, d: d! };\n}\n\n/** A key's public half, with only `kty`, `crv` and `x`. */\nexport function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk {\n return { kty: 'OKP', crv: 'Ed25519', x: key.x };\n}\n\n/**\n * Reads a private key from JSON. `source` names where it came from, for the error: the key\n * itself is never in one.\n */\nexport function readKey(text: string, source: string): PrivateKeyJwk {\n const key = readAnyKey(text, source);\n if (!('d' in key)) {\n throw new Error(`${source} is a public key; expected the private key, with d`);\n }\n return key;\n}\n\n/** Reads a key from JSON, private or public. */\nfunction readAnyKey(text: string, source: string): PrivateKeyJwk | PublicKeyJwk {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new Error(`${source} isn't a key: it isn't JSON`);\n }\n if (!isEd25519(value)) {\n throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\" and x`);\n }\n const { d } = value as { d?: unknown };\n if (d === undefined) {\n return publicKeyOf(value);\n }\n // A key with a private part that doesn't read isn't a public key either.\n if (typeof d !== 'string') {\n throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);\n }\n // A JWK carries both halves, so a hand-edited or pasted one could pair a private half with\n // someone else's public half, and sign for a key the manifest doesn't name.\n if (publicHalfOf(d, source) !== value.x) {\n throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);\n }\n return { kty: 'OKP', crv: 'Ed25519', x: value.x, d } satisfies PrivateKeyJwk;\n}\n\nfunction isEd25519(value: unknown): value is { kty: 'OKP'; crv: 'Ed25519'; x: string } {\n const { kty, crv, x } = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >;\n return kty === 'OKP' && crv === 'Ed25519' && typeof x === 'string';\n}\n\n// What PKCS#8 puts before an Ed25519 private key's 32 bytes.\nconst ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');\n\n/**\n * The public half of a private half, as `x`. Derived from `d` alone, as Node 24.22 and later\n * refuse a JWK whose halves don't match while earlier versions take its `x` as given, so a\n * mismatch is reported the same way on any version.\n */\nfunction publicHalfOf(d: string, source: string): string | undefined {\n const bytes = Buffer.from(d, 'base64url');\n if (bytes.length !== 32) {\n throw new Error(`${source} isn't a usable Ed25519 key`);\n }\n const key = createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, bytes]),\n format: 'der',\n type: 'pkcs8',\n });\n return createPublicKey(key).export({ format: 'jwk' }).x;\n}\n\nasync function readKeyFile(root: string, mode: Mode, name: KeyName): Promise<PrivateKeyJwk> {\n const file = keyFile(mode, name);\n let text: string;\n try {\n text = await readFile(join(root, file), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n throw new Error(missingKeyMessage(mode, name, file), { cause: error });\n }\n return readKey(text, file);\n}\n\n/** Says how to create a missing key, as nothing that reads keys creates one. */\nfunction missingKeyMessage(mode: Mode, name: KeyName, file: string): string {\n if (mode === 'development') {\n return `There's no development ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys\\`.`;\n }\n // In production, CI may provide the key as a variable instead.\n return `There's no production ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys --production\\`, or set ${variableFor(name)}.`;\n}\n\nconst variableFor = (name: KeyName) =>\n name === 'identity' ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;\n\nexport interface CreateKeysResult {\n /** The keys this call created. */\n created: KeyName[];\n /** The keys that already existed, which are never replaced. */\n kept: KeyName[];\n}\n\n/**\n * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only\n * their owner can read, and keeps any that exist.\n */\nexport async function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult> {\n // Each key is written whole to a temporary file beside it first, then linked to its name.\n const keys = KEY_NAMES.map((name) => {\n const file = keyFile(mode, name);\n const pending = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);\n return { name, file, pending };\n });\n // So a private key can't be committed by accident, git must ignore every file a key is\n // written to, the temporary ones included.\n await refuseUnlessGitIgnores(root, [\n ...keys.map(({ file }) => file),\n ...keys.map(({ pending }) => pending),\n ]);\n await mkdir(join(root, KEYS_DIRECTORY, mode), { recursive: true, mode: 0o700 });\n const result: CreateKeysResult = { created: [], kept: [] };\n for (const { name, file, pending } of keys) {\n // An existing key is kept: a new identity key would make the app a different app on every\n // site that installed it.\n const created = await publishKey(join(root, file), join(root, pending));\n result[created ? 'created' : 'kept'].push(name);\n }\n return result;\n}\n\nasync function refuseUnlessGitIgnores(root: string, files: string[]) {\n const ignored = await isGitIgnored(root, files);\n if (!ignored.ignored) {\n throw new Error(\n `Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`,\n );\n }\n}\n\n/** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */\nasync function publishKey(file: string, pending: string): Promise<boolean> {\n try {\n await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\\n`, {\n flag: 'wx',\n // Only for its owner on macOS and Linux. Windows ignores the mode, and the key gets the\n // folder's inherited permissions, which the README tells developers to keep private.\n mode: 0o600,\n });\n // A link fails if the name is taken, so a key is never replaced, even by a concurrent run,\n // and an interrupted write never leaves part of a key where a key belongs.\n await link(pending, file);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n // Kept, but only for its owner, as a key written by hand or copied in may not be.\n if (process.platform !== 'win32' && ((await stat(file)).mode & 0o077) !== 0) {\n await chmod(file, 0o600);\n }\n return false;\n } finally {\n await rm(pending, { force: true });\n }\n}\n\nexport interface SigningKeys {\n identityKey: PrivateKeyJwk;\n /** The backend key's public half: all signing needs. */\n backendKey: PublicKeyJwk;\n}\n\nexport interface ReadKeysOptions extends KeyOptions {\n /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to\n * anything but blanks, or else the key's file.\n */\nexport function signingKeySource(\n mode: Mode,\n name: KeyName,\n env: Record<string, string | undefined> = process.env,\n): string {\n const variable = variableFor(name);\n return mode === 'production' && env[variable]?.trim() ? variable : keyFile(mode, name);\n}\n\n/**\n * The keys to sign a mode's manifest with, from the key files, or in production from\n * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.\n */\nexport async function readSigningKeys({\n root,\n mode,\n env = process.env,\n}: ReadKeysOptions): Promise<SigningKeys> {\n const fromVariable = (name: KeyName) =>\n signingKeySource(mode, name, env) === variableFor(name)\n ? env[variableFor(name)]!.trim()\n : undefined;\n\n const identityText = fromVariable('identity');\n const identityKey = identityText\n ? await sameAsFile(root, mode, 'identity', readKey(identityText, IDENTITY_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'identity');\n\n // CI may provide only the backend key's public half, as signing needs nothing more.\n const backendText = fromVariable('backend');\n const backendKey = publicKeyOf(\n backendText\n ? await sameAsFile(root, mode, 'backend', readAnyKey(backendText, BACKEND_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'backend'),\n );\n\n if (identityKey.x === backendKey.x) {\n throw new Error('The identity key and the backend key are the same key; they must be two keys');\n }\n return { identityKey, backendKey };\n}\n\n/**\n * A key from a variable, after checking it's the same key as the file, where there's one. A\n * variable left set, such as a development key exported for every shell, would otherwise win over\n * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every\n * site.\n */\nasync function sameAsFile<Key extends PublicKeyJwk>(\n root: string,\n mode: Mode,\n name: KeyName,\n key: Key,\n): Promise<Key> {\n const file = keyFile(mode, name);\n if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {\n const variable = variableFor(name);\n throw new Error(\n `${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`,\n );\n }\n return key;\n}\n\n/** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */\nexport function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk> {\n return readKeyFile(root, mode, 'backend');\n}\n","import { z } from 'zod';\nconst ICON_NAME_MAX_LENGTH = 64;\nconst ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst EITHER = 'Expected an icon with either a name or a url';\n/**\n * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app\n * serves. Ghost keeps a copy of the image with each manifest version it stores, and only\n * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;\n * Admin falls back to a default icon.\n */\nexport function iconField(url) {\n return (z\n .strictObject({\n name: z\n .string('Expected an icon name')\n .max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`)\n .regex(ICON_NAME, 'Expected an icon name such as audio-lines')\n .optional(),\n url: url().optional(),\n }, EITHER)\n .refine(({ name, url: iconUrl }) => (name === undefined) !== (iconUrl === undefined), EITHER)\n // Only the type narrows: the value already is one or the other. A transform would\n // narrow it too, but one-way, and a stored manifest has to encode back through here.\n .pipe(z.custom()));\n}\n//# sourceMappingURL=icon.js.map","import { z } from 'zod';\n// 32 bytes in base64url without padding. The last character carries the final 4 bits and\n// 2 zero bits, so only 16 of the 64 characters can end it, which keeps the spelling of a key\n// unique.\nconst ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\nconst EXPECTED = 'Expected a public Ed25519 key as a JWK with kty, crv and x';\nconst PRIVATE = 'Expected a public key, but this includes its private part (d)';\n/**\n * A key a manifest names. A manifest is public, so a key that includes its private part\n * is refused with a message of its own: it has to be replaced, not just removed. Other\n * members are refused by name, as key tools often add some, such as `kid` or `alg`.\n */\nexport const publicKeyField = z.strictObject({\n kty: z.literal('OKP', EXPECTED),\n crv: z.literal('Ed25519', EXPECTED),\n x: z.string(EXPECTED).regex(ED25519_X, 'Expected 32 bytes in base64url, without padding'),\n}, {\n error: (issue) => {\n if (issue.code !== 'unrecognized_keys') {\n return EXPECTED;\n }\n return issue.keys.includes('d')\n ? PRIVATE\n : `Expected only kty, crv and x; remove ${issue.keys.join(', ')}`;\n },\n});\n//# sourceMappingURL=keys.js.map","import { z } from 'zod';\n/**\n * What an app asks for: the places in Ghost it wants to appear. Each surface type is one\n * entry in a union, so a new one is added here and nowhere else.\n */\nexport function surfacesField(url) {\n const adminPage = z.strictObject({\n type: z.literal('admin_page'),\n url: url(),\n });\n const surfaceTypes = [adminPage];\n const surface = z.discriminatedUnion('type', surfaceTypes, {\n error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(', ')}`,\n });\n return z\n .array(surface, 'Expected a list of surfaces')\n .min(1, 'Expected at least one surface')\n .superRefine((surfaces, ctx) => {\n const seen = new Set();\n surfaces.forEach((entry, index) => {\n if (seen.has(entry.type)) {\n ctx.addIssue({\n code: 'custom',\n message: `Expected at most one ${entry.type} surface`,\n path: [index],\n });\n }\n seen.add(entry.type);\n });\n });\n}\n//# sourceMappingURL=surfaces.js.map","import { z } from 'zod';\nimport { isPlainText } from '../plain-text.js';\n// A character that shows something on its own: a letter, digit, punctuation or symbol, but not\n// the blank Braille pattern or one Unicode says to draw as nothing, such as a joiner or a Hangul\n// filler. Whitespace and marks aren't any of those.\nconst VISIBLE_CHARACTER = new RegExp('(?![\\\\u2800\\\\p{Default_Ignorable_Code_Point}])[\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}]', 'u');\nconst shows = (text) => VISIBLE_CHARACTER.test(text);\n// Shows nothing, and holds nothing plain text refuses other than whitespace, so trimming never\n// takes off a character, such as one that reorders text, that should get the text refused.\nconst blank = (character) => !shows(character) && isPlainText(character.replace(/\\s/gu, ''));\n// Made on first use, so loading the contract doesn't set one up.\nlet graphemes;\n/**\n * Takes off each end the characters, as a reader sees them, that show nothing: a space with a\n * mark on it goes, an emoji with its variation selector stays, and so does anything invisible\n * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no\n * more than its length.\n */\nfunction trimEdges(value) {\n graphemes ??= new Intl.Segmenter();\n const characters = graphemes.segment(value);\n let start = value.length;\n for (const { segment, index } of characters) {\n if (!blank(segment)) {\n start = index;\n break;\n }\n }\n let end = value.length;\n while (end > start) {\n const { segment, index } = characters.containing(end - 1);\n if (!blank(segment)) {\n break;\n }\n end = index;\n }\n return value.slice(start, end);\n}\n/**\n * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and\n * text with nothing visible left, such as a name of Hangul fillers, is refused.\n */\nexport function plainText(maxLength) {\n return (z\n .string('Expected text')\n // Whitespace first, as a character that joins onto a space, such as a skin tone, would keep it.\n .trim()\n .overwrite(trimEdges)\n .refine(shows, 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line'));\n}\n// Any letter, digit, punctuation or symbol, fillers included: the rule manifests were stored under\n// before blank names were refused.\nconst ANY_CHARACTER = /[\\p{L}\\p{N}\\p{P}\\p{S}]/u;\n/**\n * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before\n * blank names were refused still reads, and the app can still be listed and uninstalled.\n */\nexport function storedText(maxLength) {\n return z\n .string('Expected text')\n .trim()\n .refine((value) => ANY_CHARACTER.test(value), 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line');\n}\n//# sourceMappingURL=text.js.map","import { z } from 'zod';\nimport { isContainedPath } from '../bridge/rules.js';\nimport { URL_MAX_LENGTH } from './limits.js';\nimport { isLocalhost } from './localhost.js';\nexport const FRAGMENT_PROBLEM = 'Expected a URL without a fragment';\n/**\n * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`\n * hides. A fragment never reaches the server, so a manifest address with one is a mistake or\n * a second spelling of the same address.\n */\nexport const hasFragment = (address) => address.includes('#');\n/**\n * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would\n * use. The length is measured on the parsed URL for the same reason, as that is what is\n * stored and checked again later.\n */\nexport function checkResolvedUrl(url, allowLocalhost) {\n if (url.href.length > URL_MAX_LENGTH) {\n return `Expected at most ${URL_MAX_LENGTH} characters`;\n }\n if (url.username || url.password) {\n return 'Expected a URL without a username or password';\n }\n if (isLocalhost(url.hostname)) {\n if (!allowLocalhost) {\n return 'Expected a public address; localhost is only allowed when Ghost runs in development';\n }\n return url.protocol === 'https:' || url.protocol === 'http:'\n ? null\n : 'Expected an http or https URL';\n }\n return url.protocol === 'https:' ? null : 'Expected an https URL';\n}\nconst ROUTE_PROBLEM = 'Expected a URL that resolves to a path starting with a single /, with no \\\\ in its query or fragment';\nconst PATH_PROBLEM = 'Expected a path on the manifest’s own origin, such as /admin';\n// Two, so a reference that names one of them still names a host other than the other's.\nconst PLACEHOLDER_HOSTS = ['manifest-a.invalid', 'manifest-b.invalid'];\n/** Whether a reference names a host, in any of the URL parser's spellings of one. */\nconst namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);\nfunction isManifestItself(url, base) {\n return url.pathname === new URL(base).pathname;\n}\n/**\n * A URL in the manifest. What Ghost loads is written as a path, resolved against the\n * address the manifest was fetched from, so an app is one origin: the one Ghost fetches\n * the manifest from and challenges is the one every surface runs on. The manifest names\n * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they\n * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.\n *\n * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and\n * may be anywhere, the publisher's own site included.\n *\n * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.\n * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.\n * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which\n * names a host, and a `\\` in the query or fragment is left as it is. Only the page is opened\n * as a route, but every URL Ghost loads is held to the one rule.\n */\nexport function urlField({ allowLocalhost, base }, linkOnly = false) {\n if (linkOnly) {\n return z.string('Expected an absolute URL').transform((value, ctx) => {\n const url = URL.parse(value);\n const problem = url ? checkResolvedUrl(url, allowLocalhost) : 'Expected an absolute URL';\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n return url.href;\n });\n }\n const origin = new URL(base).origin;\n return z.string(PATH_PROBLEM).transform((value, ctx) => {\n // A path, or a path-relative reference. A URL with a scheme, or a `//host` one, names\n // its own origin, which the manifest's would then not be, even when it's the same one\n // today. An empty one, or one that's only a query or fragment, would be the manifest\n // itself.\n const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);\n if (!url || url.origin !== origin || isManifestItself(url, base)) {\n ctx.addIssue({ code: 'custom', message: PATH_PROBLEM });\n return z.NEVER;\n }\n const problem = checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {\n ctx.addIssue({ code: 'custom', message: ROUTE_PROBLEM });\n return z.NEVER;\n }\n return url.href;\n });\n}\n/**\n * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and\n * already checked. Nothing is resolved or checked again, so a manifest accepted before the\n * site's URL changed still reads back.\n */\nexport const absoluteUrl = () => z.url('Expected an absolute URL');\n//# sourceMappingURL=url.js.map","import { z } from 'zod';\nimport { iconField } from './icon.js';\nimport { APP_ID_MAX_LENGTH, isValidAppId } from './id.js';\nimport { publicKeyField } from './keys.js';\nimport { isLocalhost } from './localhost.js';\nimport { surfacesField } from './surfaces.js';\nimport { plainText, storedText } from './text.js';\nimport { absoluteUrl, FRAGMENT_PROBLEM, hasFragment, urlField, } from './url.js';\nconst NAME_MAX_LENGTH = 50;\nconst DESCRIPTION_MAX_LENGTH = 200;\nconst AUTHOR_NAME_MAX_LENGTH = 50;\nconst HEX_COLOR = /^#[0-9a-f]{6}$/i;\nconst KEY_FIELDS = new Set(['identity_key', 'backend_key']);\nconst URL_FIELDS = new Set([\n 'author',\n 'icon',\n 'surfaces',\n 'manifest_url',\n 'development',\n]);\n/** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */\nconst parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));\n/**\n * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot\n * claim something Ghost has not designed, and adding a field is always a deliberate change\n * here.\n *\n * Defined once, with the URL and text rules left open. What a valid URL is depends on whether\n * the manifest is being parsed, when where Ghost is served from matters, or read back after it\n * was, when it doesn't. Text is held to today's rules when parsed, and read back under the\n * rules it was stored under.\n */\nfunction manifestShape(url, text) {\n return (z\n .strictObject({\n id: z.custom(isValidAppId, {\n error: `Expected a lowercase reverse-domain ID such as com.example.app, at most ${APP_ID_MAX_LENGTH} characters`,\n }),\n name: text(NAME_MAX_LENGTH),\n description: text(DESCRIPTION_MAX_LENGTH),\n author: z.strictObject({\n name: text(AUTHOR_NAME_MAX_LENGTH),\n // Only ever linked to, so it may point at the publisher's own site.\n url: url(true),\n }, 'Expected an author with a name and a url'),\n accent_color: z\n .string('Expected a hex colour such as #ff5500')\n .regex(HEX_COLOR, 'Expected a hex colour such as #ff5500')\n .toLowerCase(),\n icon: iconField(url),\n surfaces: surfacesField(url),\n // Where the signed manifest is served from: the app's one origin, which every path\n // in it resolves against. Ghost fetches it server-side and never loads it as a page.\n manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),\n identity_key: publicKeyField,\n backend_key: publicKeyField,\n // Lets Admin label a development build. Production sites may run one to test it.\n development: z.boolean('Expected true or false'),\n })\n // A backend holds its key online. If it also signed manifests, whoever took over the\n // backend could publish any manifest as the app.\n .refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {\n message: 'Expected a different key from identity_key',\n path: ['backend_key'],\n // Only once both keys are known to be keys. An issue without a path is about the\n // manifest as a whole, which may not be an object at all.\n when: parsedFields(KEY_FIELDS),\n })\n // An app on the developer's machine is always labelled as a development build.\n .refine((manifest) => manifest.development ||\n ![\n manifest.author.url,\n 'url' in manifest.icon ? manifest.icon.url : undefined,\n ...manifest.surfaces.map((surface) => surface.url),\n manifest.manifest_url,\n ].some((address) => address !== undefined && isLocalhost(new URL(address).hostname)), {\n message: 'Expected true, as the app is on localhost',\n path: ['development'],\n when: parsedFields(URL_FIELDS),\n }));\n}\n/** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */\nexport function manifestSchema(rules) {\n return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);\n}\n/**\n * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to\n * resolve or check. This is the schema to read a stored manifest with, as it holds\n * whatever the site's URL has become since, and it encodes a manifest back to the same\n * shape, so what is stored is what will be read.\n */\nexport const AppManifestSchema = manifestShape(absoluteUrl, storedText);\n//# sourceMappingURL=schema.js.map","import { hostOf, isGhostHost } from './ghost-host.js';\nimport { isLocalhost } from './localhost.js';\nimport { manifestSchema } from './schema.js';\nimport { checkResolvedUrl, FRAGMENT_PROBLEM, hasFragment } from './url.js';\nfunction formatPath(path) {\n return path.reduce((result, part) => {\n if (typeof part === 'number') {\n return `${result}[${part}]`;\n }\n return result ? `${result}.${String(part)}` : String(part);\n }, '');\n}\nconst GHOST_URLS_PROBLEM = 'Expected the URLs Ghost itself is served from';\nconst ON_GHOST_HOST = 'Expected the manifest on a host other than the one Ghost itself is served from, on any port, as browsers send Ghost’s cookies to every port on its host';\nconst ON_GHOST_HOST_LOCALLY = `${ON_GHOST_HOST}. To run the app on this machine too, serve it from a name of its own under .localhost, such as my-app.localhost`;\n/**\n * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most\n * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`\n * is a host of its own, which browsers send to the machine itself, and so does Ghost in\n * development, whatever the system's resolver knows.\n */\nfunction onGhostHost(url) {\n return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;\n}\n/**\n * Reads the address a manifest is to be read from, by the same rules as the URLs inside\n * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first\n * request never goes to an address Ghost would refuse (plain HTTP, one carrying\n * credentials, or one on Ghost's host). It cannot judge where that address redirects,\n * which is for whatever fetches it to limit.\n *\n * The address it hands back is the one to store, to compare with a later one, and that the\n * manifest must name as its `manifest_url`. The URL parser settles most differences in\n * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a\n * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.\n */\nexport function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {\n if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) {\n return { success: false, error: GHOST_URLS_PROBLEM };\n }\n const url = URL.parse(input);\n if (!url) {\n return { success: false, error: 'Expected the manifest at a URL' };\n }\n const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n return { success: false, error: `${problem} for the manifest itself` };\n }\n if (isGhostHost(url, ghostUrls)) {\n return { success: false, error: onGhostHost(url) };\n }\n return { success: true, manifestUrl: url.href };\n}\nfunction invalid(errors) {\n return { success: false, reason: 'invalid', errors };\n}\n/**\n * Validates a manifest, and checks it names the address it was fetched from as its\n * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the\n * manifest to its address as well as to every URL in it.\n *\n * Returns either the manifest, or every problem found. It does not fetch anything and it\n * never throws. Without the URLs Ghost is served from it rejects every manifest, since the\n * rule that keeps apps off Ghost's hosts could not be checked.\n */\nexport function parseManifest(input, options) {\n const allowLocalhost = options.allowLocalhost ?? false;\n const address = parseManifestUrl(options.manifestUrl, options);\n if (!address.success) {\n return invalid([{ path: '', message: address.error }]);\n }\n const result = manifestSchema({ allowLocalhost, base: address.manifestUrl }).safeParse(input);\n if (!result.success) {\n return invalid(result.error.issues.map((issue) => ({\n path: formatPath(issue.path),\n message: issue.message,\n })));\n }\n if (result.data.manifest_url !== address.manifestUrl) {\n return {\n success: false,\n reason: 'manifest_url_mismatch',\n errors: [\n {\n path: 'manifest_url',\n message: `Expected ${address.manifestUrl}, the address the manifest was read from`,\n },\n ],\n };\n }\n return { success: true, manifest: result.data };\n}\n//# sourceMappingURL=parse.js.map","import { AppManifestSchema, type AppManifest } from '@tryghost/app-contracts/manifest';\nimport { z } from 'zod';\n\n// The limits Ghost reads a manifest with, from App Installations in Ghost core, which doesn't\n// export them to apps.\n\n/** The largest manifest Ghost stores, which it keeps in a TEXT column. */\nexport const MANIFEST_MAX_BYTES = 64 * 1024;\n\n/**\n * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and the\n * header and signature are well under a kilobyte.\n */\nexport const SIGNED_MANIFEST_MAX_BYTES = Math.ceil((MANIFEST_MAX_BYTES * 4) / 3) + 1024;\n\n/**\n * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what\n * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.\n */\nexport function storedSize(manifest: AppManifest): number {\n return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;\n}\n\nexport const signedTooLargeMessage = () =>\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;\n\nexport const tooLargeMessage = () =>\n `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport { signManifest } from '@tryghost/app-contracts/identity';\nimport { parseManifest, parseManifestUrl } from '@tryghost/app-contracts/manifest';\n\nimport {\n publicKeyOf,\n readKey,\n readSigningKeys,\n type PrivateKeyJwk,\n type PublicKeyJwk,\n type ReadKeysOptions,\n} from './keys.ts';\nimport { UNKNOWN_GHOST_URL } from '../shared/manifest.ts';\nimport { parseJsonText } from '../shared/parse.ts';\nimport {\n MANIFEST_MAX_BYTES,\n SIGNED_MANIFEST_MAX_BYTES,\n signedTooLargeMessage,\n storedSize,\n tooLargeMessage,\n} from './limits.ts';\nimport type { ManifestError, SignedManifest } from './types.ts';\n\n/** The readable manifest a project keeps, which the tooling signs. */\nexport const MANIFEST_FILE = 'ghost-app.json';\n\n/** The fields the tooling adds, which `ghost-app.json` mustn't set. */\nconst ADDED_FIELDS = ['manifest_url', 'identity_key', 'backend_key', 'development'] as const;\n\nexport interface SignOptions {\n /** The address the signed manifest will be served from, which it names as its own. */\n manifestUrl: string;\n identityKey: PrivateKeyJwk;\n /** Only its public half goes in the manifest. */\n backendKey: PrivateKeyJwk | PublicKeyJwk;\n /** Whether this is a development build, as it must be when any URL is on localhost. */\n development: boolean;\n}\n\nexport type SignResult =\n | {\n success: true;\n signed: SignedManifest;\n /** The manifest as signed, with the fields the tooling added. */\n manifest: Record<string, unknown>;\n }\n | {\n success: false;\n /**\n * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or\n * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost stores.\n */\n code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';\n errors: ManifestError[];\n };\n\ntype Refusal = Extract<SignResult, { success: false }>;\n\nconst refuse = (code: Refusal['code'], message: string, path = ''): Refusal => ({\n success: false,\n code,\n errors: [{ path, message }],\n});\n\n/**\n * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it\n * with the identity key, unless Ghost would refuse it.\n */\nexport async function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult> {\n // A JWK carries both halves, so one passed in, rather than read from a file, could pair a\n // private half with another key's public half. The manifest would name a key that didn't sign\n // it, or one the backend can't answer for, and Ghost would refuse it. That's the caller's\n // mistake, so it throws.\n readKey(JSON.stringify(options.identityKey), 'identityKey');\n if ('d' in options.backendKey) {\n readKey(JSON.stringify(options.backendKey), 'backendKey');\n }\n // Ghost's own hosts are the one rule only a site knows, so a name no site has stands in.\n const address = parseManifestUrl(options.manifestUrl, {\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!address.success) {\n return refuse('APP_MANIFEST_URL_INVALID', address.error);\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return refuse('APP_MANIFEST_INVALID', 'Expected the manifest as a JSON object');\n }\n // The fields signing adds can't come from the file, or the file could name other keys.\n const added = ADDED_FIELDS.filter((field) => field in source);\n if (added.length > 0) {\n return {\n success: false,\n code: 'APP_MANIFEST_INVALID',\n errors: added.map((field) => ({\n path: field,\n message: `Leave ${field} out: it's added when the manifest is signed`,\n })),\n };\n }\n\n const manifest = {\n ...source,\n manifest_url: address.manifestUrl,\n identity_key: publicKeyOf(options.identityKey),\n backend_key: publicKeyOf(options.backendKey),\n development: options.development,\n };\n // Checked by the rules Ghost applies, so a manifest Ghost would refuse is never signed, and\n // the result lists every problem by the path to its field.\n const parsed = parseManifest(manifest, {\n manifestUrl: address.manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!parsed.success) {\n // A mismatch can't happen, as the manifest URL was just set; any failure is invalid.\n return { success: false, code: 'APP_MANIFEST_INVALID', errors: parsed.errors };\n }\n if (storedSize(parsed.manifest) > MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', tooLargeMessage());\n }\n\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // Ghost limits the signed manifest it fetches too, and the payload keeps whatever the file had,\n // such as text Ghost trims, so a manifest Ghost stores can still be too large to fetch.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', signedTooLargeMessage());\n }\n return { success: true, signed, manifest };\n}\n\n/** A signed manifest as the CLI and the Vite plugin write it to a file. */\nexport function serialiseSigned(signed: SignedManifest): string {\n return `${JSON.stringify(signed, null, 2)}\\n`;\n}\n\n/** Reads `ghost-app.json`, or another readable manifest, as JSON. */\nexport async function readManifestSource(file: string): Promise<unknown> {\n const text = await readFile(file, 'utf8');\n try {\n return parseJsonText(text);\n } catch (error) {\n throw new Error(`${file} isn't JSON: ${(error as Error).message}`, { cause: error });\n }\n}\n\nexport interface SignProjectOptions extends ReadKeysOptions {\n manifestUrl: string;\n /** The readable manifest, relative to `root`. `ghost-app.json` by default. */\n manifestFile?: string;\n}\n\n/** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */\nexport async function signProject({\n root,\n mode,\n env,\n manifestUrl,\n manifestFile = MANIFEST_FILE,\n}: SignProjectOptions): Promise<SignResult> {\n // Resolved, so an absolute path is taken as it is.\n const source = await readManifestSource(resolve(root, manifestFile));\n // Keys are read, never created: a missing one throws with how to create it.\n const keys = await readSigningKeys({ root, mode, env });\n return signAppManifest(source, { manifestUrl, ...ke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