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

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.
@@ -0,0 +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,i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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.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/build/bin.js ADDED
@@ -0,0 +1,124 @@
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";
4
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { Command, CommanderError } from "commander";
8
+ //#region src/tooling/paths.ts
9
+ /** Whether `child` is `parent` or anything inside it. Both are absolute. */
10
+ function isWithin(parent, child) {
11
+ const path = relative(parent, child);
12
+ return path === "" || path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
13
+ }
14
+ var realpath = (path) => {
15
+ try {
16
+ return realpathSync.native(path);
17
+ } catch {
18
+ return;
19
+ }
20
+ };
21
+ var MAX_LINKS = 40;
22
+ /**
23
+ * Where writing to `path` really lands: through every link, as far as the path exists, and
24
+ * along a chain of dangling links to where its last one points, as writing follows them all. A
25
+ * path that doesn't exist yet lands in its directory, wherever that really is.
26
+ */
27
+ function canonicalPath(path, links = 0) {
28
+ const existing = realpath(path);
29
+ if (existing) return existing;
30
+ if (links < MAX_LINKS && lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) return canonicalPath(resolve(dirname(path), readlinkSync(path)), links + 1);
31
+ const parent = dirname(path);
32
+ return join(parent === path ? parent : canonicalPath(parent, links), basename(path));
33
+ }
34
+ //#endregion
35
+ //#region src/cli.ts
36
+ var modeOf = (production) => production ? "production" : "development";
37
+ async function keys(root, mode, io) {
38
+ const { created, kept } = await createKeys({
39
+ root,
40
+ mode
41
+ });
42
+ for (const name of created) io.err(`Created ${keyFile(mode, name)}`);
43
+ for (const name of kept) io.err(`Kept ${keyFile(mode, name)}, which already exists`);
44
+ if (mode === "production" && created.includes("identity")) io.err("\nKeep a copy of the production identity key somewhere safe, such as a password manager. Sites that install the app keep its identity key, and an app signed with another key is another app.");
45
+ }
46
+ var MODES = ["development", "production"];
47
+ /** Throws if writing to `written` would overwrite the manifest it's signed from, or a key. */
48
+ function refuseToOverwrite(root, written, manifestFile) {
49
+ const lands = canonicalPath(written);
50
+ if (lands === canonicalPath(resolve(root, manifestFile))) throw new Error(`Refusing to write the signed manifest over ${manifestFile}, which it's signed from`);
51
+ const keysDirectory = join(root, KEYS_DIRECTORY);
52
+ const keyFiles = MODES.flatMap((mode) => KEY_NAMES.map((name) => canonicalPath(join(root, keyFile(mode, name)))));
53
+ if (isWithin(keysDirectory, written) || isWithin(canonicalPath(keysDirectory), lands) || keyFiles.includes(lands)) throw new Error(`Refusing to write the signed manifest into ${KEYS_DIRECTORY}/, which holds the keys`);
54
+ }
55
+ async function sign(root, { url, production, out, manifest }, io) {
56
+ const manifestFile = manifest ?? "ghost-app.json";
57
+ const written = out === void 0 ? void 0 : resolve(root, out);
58
+ if (written) refuseToOverwrite(root, written, manifestFile);
59
+ const result = await signProject({
60
+ root,
61
+ mode: modeOf(production),
62
+ manifestUrl: url,
63
+ manifestFile
64
+ });
65
+ if (!result.success) {
66
+ io.err(`${result.code}: ${manifestFile} can't be signed:\n${formatErrors(result.errors)}`);
67
+ return 1;
68
+ }
69
+ const text = serialiseSigned(result.signed);
70
+ if (written) {
71
+ await mkdir(dirname(written), { recursive: true });
72
+ await writeFile(written, text);
73
+ io.err(`Wrote ${written}, signed for ${String(result.manifest.manifest_url)}`);
74
+ } else io.out(text);
75
+ return 0;
76
+ }
77
+ async function backendKey(root, { production, public: publicHalf, check: checkOnly }, io) {
78
+ const key = await readBackendKey({
79
+ root,
80
+ mode: modeOf(production)
81
+ });
82
+ if (!checkOnly) io.out(JSON.stringify(publicHalf ? publicKeyOf(key) : key));
83
+ }
84
+ /** Runs the CLI with its arguments (without `node` and the script), resolving with the exit code. */
85
+ async function run(args, io) {
86
+ let exitCode = 0;
87
+ const program = new Command("ghost-app").description("Creates an app's keys and signs its manifest.").option("--dir <directory>", "the project's directory", ".").showHelpAfterError().exitOverride().configureOutput({
88
+ writeOut: io.out,
89
+ writeErr: io.err
90
+ });
91
+ const root = () => resolve(program.opts().dir);
92
+ program.command("keys").description("Creates the mode's identity and backend keys in .ghost-app/, keeping any that exist").option("--production", "the production keys instead of the development ones").action(async ({ production }) => {
93
+ await keys(root(), modeOf(production), io);
94
+ });
95
+ program.command("sign").description("Signs ghost-app.json for the address it will be served from").requiredOption("--url <manifest URL>", "the address the signed manifest will be served from").option("--production", "with the production keys instead of the development ones").option("--out <file>", "write it to a file in the project's directory instead of printing it").option("--manifest <file>", "sign another file than ghost-app.json").action(async (options) => {
96
+ exitCode = await sign(root(), options, io);
97
+ });
98
+ program.command("backend-key").description("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").option("--production", "the production key instead of the development one").option("--public", "print only its public half, which is all CI needs to sign").option("--check", "print nothing, and exit 0 only if the key is there and usable").action(async (options) => {
99
+ await backendKey(root(), options, io);
100
+ });
101
+ try {
102
+ await program.parseAsync(args, { from: "user" });
103
+ return exitCode;
104
+ } catch (error) {
105
+ if (error instanceof CommanderError) return error.exitCode === 0 ? 0 : 2;
106
+ io.err(error instanceof Error ? error.message : String(error));
107
+ return 1;
108
+ }
109
+ }
110
+ //#endregion
111
+ //#region src/bin.ts
112
+ var line = (text) => text.endsWith("\n") ? text : `${text}\n`;
113
+ run(process.argv.slice(2), {
114
+ out: (text) => process.stdout.write(line(text)),
115
+ err: (text) => process.stderr.write(line(text))
116
+ }).then((code) => {
117
+ process.exitCode = code;
118
+ }, (error) => {
119
+ process.stderr.write(line(error instanceof Error ? error.message : String(error)));
120
+ process.exitCode = 1;
121
+ });
122
+ //#endregion
123
+
124
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +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,IA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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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,19 @@
1
+ //#region src/shared/manifest.d.ts
2
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
3
+ declare const MANIFEST_PATH = "/ghost-app.json";
4
+ /** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */
5
+ interface SignedManifest {
6
+ protected: string;
7
+ payload: string;
8
+ signature: string;
9
+ }
10
+ /** One problem with a manifest. */
11
+ interface ManifestError {
12
+ /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */
13
+ path: string;
14
+ message: string;
15
+ }
16
+ /** A manifest's problems, one per line, as `path: message`. */
17
+ declare function formatErrors(errors: readonly ManifestError[]): string;
18
+ //#endregion
19
+ export { formatErrors as i, ManifestError as n, SignedManifest as r, MANIFEST_PATH as t };
@@ -0,0 +1,159 @@
1
+ //#region ../app-contracts/build/plain-text.js
2
+ var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
3
+ var PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, "u");
4
+ var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
5
+ /** Whether text is one line of plain text, as a name, a description or a title must be. */
6
+ function isPlainText(value) {
7
+ return PLAIN_TEXT.test(value);
8
+ }
9
+ /** Returns the text with the characters `isPlainText` refuses removed. */
10
+ function toPlainText(value) {
11
+ return value.replace(NOT_PLAIN_TEXT, "");
12
+ }
13
+ //#endregion
14
+ //#region ../app-contracts/build/bridge/rules.js
15
+ /**
16
+ * The bridge's rules that have no dependencies. The root entry point exports them so the SDK
17
+ * can use them without zod. The schemas in this folder build on them, so the SDK and Admin
18
+ * read a path or a refusal the same way.
19
+ *
20
+ * What Admin sends the page has no schema, because Admin builds it and never parses it. Its
21
+ * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so
22
+ * the guards only check shape and path containment. They turn a mismatch into a clear error
23
+ * rather than `undefined` somewhere in the app. Only the schemas check limits.
24
+ */
25
+ /** Posted by the app's page to `window.parent` once the SDK has loaded. */
26
+ var HELLO_MESSAGE_TYPE = "ghost-app:hello";
27
+ /**
28
+ * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long
29
+ * after mounting it, and the SDK waits this long for Admin to start the app unless the app
30
+ * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send
31
+ * its hello.
32
+ */
33
+ var START_TIMEOUT_MS = 1e4;
34
+ /**
35
+ * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK
36
+ * uppercases what apps pass.
37
+ */
38
+ var FETCH_METHODS = [
39
+ "GET",
40
+ "POST",
41
+ "PUT",
42
+ "DELETE"
43
+ ];
44
+ /**
45
+ * Whether a request with this method may carry a body. Expects an uppercase method from
46
+ * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.
47
+ */
48
+ function methodAllowsBody(method) {
49
+ return method !== "GET";
50
+ }
51
+ var RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;
52
+ /**
53
+ * Whether a request header is one that apps may not set, in any case. Admin refuses a request
54
+ * that sets one rather than dropping the header, so the app gets an error instead of wondering
55
+ * why the header never arrived. The browser refuses some of these anyway; they are listed here
56
+ * so that none of them relies on the browser.
57
+ */
58
+ function isReservedRequestHeader(name) {
59
+ return RESERVED_REQUEST_HEADER.test(name);
60
+ }
61
+ /**
62
+ * The messages Admin and the SDK use when they refuse an argument for the same reason, so an
63
+ * app gets the same message whichever side catches the problem. The SDK checks only for obvious
64
+ * mistakes, before anything crosses the channel; Admin's schemas check everything again.
65
+ */
66
+ var ARGUMENT_MESSAGES = {
67
+ fetchPath: "Expected an Admin API path such as /posts/, not a URL",
68
+ fetchMethod: `Expected a method of: ${FETCH_METHODS.join(", ")}`,
69
+ fetchBody: "Expected no body on a GET request",
70
+ reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,
71
+ jsonBody: "Expected the body as JSON text",
72
+ appPath: "Expected a path within the app, starting with a single /",
73
+ pathMove: "Expected a move of push or replace",
74
+ place: "Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }"
75
+ };
76
+ /**
77
+ * The codes a refused call carries across the channel. The structured clone that carries an
78
+ * error keeps only its message, so the refusing side puts the code at the start of the
79
+ * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes
80
+ * are only ever added: an SDK that doesn't know a code treats the whole message as a generic
81
+ * refusal.
82
+ *
83
+ * The host codes, which Admin refuses the page's calls with:
84
+ *
85
+ * - `session_ended`: the session is over; the page is about to be replaced.
86
+ * - `invalid_argument`: an argument Admin does not take.
87
+ * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one
88
+ * the Admin API only responds to with a redirect, such as a path without its trailing `/`.
89
+ * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.
90
+ * - `network_error`: Admin could not reach its own API.
91
+ * - `rejected`: anything else; the detail says why.
92
+ */
93
+ var HOST_ERROR_CODES = [
94
+ "session_ended",
95
+ "invalid_argument",
96
+ "invalid_path",
97
+ "blocked",
98
+ "network_error",
99
+ "rejected"
100
+ ];
101
+ [...HOST_ERROR_CODES];
102
+ var CODED_MESSAGE = /^([a-z_]+): ([\s\S]*)$/;
103
+ /**
104
+ * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass
105
+ * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.
106
+ */
107
+ function encodeBridgeError(code, detail) {
108
+ return `${code}: ${detail}`;
109
+ }
110
+ /**
111
+ * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the
112
+ * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for
113
+ * one from the page. Returns `undefined` for a message that doesn't start with one of them.
114
+ */
115
+ function decodeBridgeError(message, codes) {
116
+ const [, code = "", detail = ""] = CODED_MESSAGE.exec(message) ?? [];
117
+ return codes.includes(code) ? {
118
+ code,
119
+ detail
120
+ } : void 0;
121
+ }
122
+ var THEME_MODES = ["light", "dark"];
123
+ var CONTROL_CHARACTER = /\p{Cc}/u;
124
+ /**
125
+ * Whether a value is a path that stays within the base it is resolved against, rather than
126
+ * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as
127
+ * `//host`. It must not contain `\`, which URL parsers read as `/`, or any control character.
128
+ */
129
+ function isContainedPath(value) {
130
+ return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
131
+ }
132
+ /** An object, or an array: anything whose fields can be read. */
133
+ function isRecord(value) {
134
+ return typeof value === "object" && value !== null;
135
+ }
136
+ function hasStrings(value, keys) {
137
+ return isRecord(value) && keys.every((key) => typeof value[key] === "string");
138
+ }
139
+ function isTheme(value) {
140
+ return hasStrings(value, ["accent_color"]) && THEME_MODES.includes(value.mode);
141
+ }
142
+ function isStartContext(value) {
143
+ return isRecord(value) && hasStrings(value.site, [
144
+ "url",
145
+ "title",
146
+ "timezone",
147
+ "locale"
148
+ ]) && hasStrings(value.user, ["id", "role"]) && isTheme(value.theme) && isRecord(value.session) && Number.isSafeInteger(value.session.revision) && value.session.revision >= 0 && isContainedPath(value.path);
149
+ }
150
+ function isConnectMessage(value) {
151
+ return isRecord(value) && value.type === "ghost-app:connect" && Array.isArray(value.exports) && value.exports.every((name) => typeof name === "string");
152
+ }
153
+ function isFetchResponse(value) {
154
+ return isRecord(value) && Number.isSafeInteger(value.status) && value.status >= 200 && value.status <= 599 && typeof value.statusText === "string" && isRecord(value.headers) && !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string") && typeof value.body === "string";
155
+ }
156
+ //#endregion
157
+ export { toPlainText as _, START_TIMEOUT_MS as a, isConnectMessage as c, isRecord as d, isReservedRequestHeader as f, isPlainText as g, methodAllowsBody as h, HOST_ERROR_CODES as i, isContainedPath as l, isTheme as m, FETCH_METHODS as n, decodeBridgeError as o, isStartContext as p, HELLO_MESSAGE_TYPE as r, encodeBridgeError as s, ARGUMENT_MESSAGES as t, isFetchResponse as u };
158
+
159
+ //# sourceMappingURL=rules-_dou3jRF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules-_dou3jRF.js","names":[],"sources":["../../../app-contracts/build/plain-text.js","../../../app-contracts/build/bridge/rules.js"],"sourcesContent":["// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so `..` can never climb above its root.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. Even then, the result may not be: resolving `.` and `..` can leave `//` at the\n * start, so `/.//host` becomes `//host`, which resolves to another site. Check the result with\n * `isContainedPath` before resolving it against anything. `AppPathSchema` does both and returns\n * this form.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map"],"mappings":";AAMA,IAAM,UAAU;AAChB,IAAM,aAAa,IAAI,OAAO,KAAK,QAAQ,MAAM,GAAG;AACpD,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI;;AAEvD,SAAgB,YAAY,OAAO;CAC/B,OAAO,WAAW,KAAK,KAAK;AAChC;;AAEA,SAAgB,YAAY,OAAO;CAC/B,OAAO,MAAM,QAAQ,gBAAgB,EAAE;AAC3C;;;;;;;;;;;;;;ACLA,IAAa,qBAAqB;;;;;;;AASlC,IAAa,mBAAmB;;;;;AAOhC,IAAa,gBAAgB;CAAC;CAAO;CAAQ;CAAO;AAAQ;;;;;AAK5D,SAAgB,iBAAiB,QAAQ;CACrC,OAAO,WAAW;AACtB;AAOA,IAAM,0BAA0B;;;;;;;AAOhC,SAAgB,wBAAwB,MAAM;CAC1C,OAAO,wBAAwB,KAAK,IAAI;AAC5C;;;;;;AAMA,IA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