@tryghost/app-sdk 0.1.0-alpha.12 → 0.1.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
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";
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-50Ayvddb.js";
3
3
  import { lstatSync, readlinkSync, realpathSync } from "node:fs";
4
4
  import { mkdir, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -97,16 +97,12 @@ function isValidAppId(value) {
97
97
  * them, the manifest's own URL included, so its columns are exactly this wide.
98
98
  */
99
99
  var URL_MAX_LENGTH = 2e3;
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
100
  /**
105
101
  * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and
106
102
  * the header and signature are well under a kilobyte, so a manifest of the largest size
107
103
  * still fits.
108
104
  */
109
- var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(MANIFEST_MAX_BYTES * 4 / 3) + 1024;
105
+ var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(64 * 1024 * 4 / 3) + 1024;
110
106
  /** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
111
107
  function parseJsonText(text) {
112
108
  return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
@@ -660,13 +656,7 @@ function manifestShape(url, text) {
660
656
  function manifestSchema(rules) {
661
657
  return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);
662
658
  }
663
- /**
664
- * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to
665
- * resolve or check. This is the schema to read a stored manifest with, as it holds
666
- * whatever the site's URL has become since, and it encodes a manifest back to the same
667
- * shape, so what is stored is what will be read.
668
- */
669
- var AppManifestSchema = manifestShape(absoluteUrl, storedText);
659
+ manifestShape(absoluteUrl, storedText);
670
660
  //#endregion
671
661
  //#region ../app-contracts/build/manifest/parse.js
672
662
  function formatPath(path) {
@@ -772,17 +762,6 @@ function parseManifest(input, options) {
772
762
  };
773
763
  }
774
764
  //#endregion
775
- //#region src/tooling/limits.ts
776
- /**
777
- * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what
778
- * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.
779
- */
780
- function storedSize(manifest) {
781
- return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;
782
- }
783
- var signedTooLargeMessage = () => `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;
784
- var tooLargeMessage = () => `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;
785
- //#endregion
786
765
  //#region src/tooling/sign.ts
787
766
  /** The readable manifest a project keeps, which the tooling signs. */
788
767
  var MANIFEST_FILE = "ghost-app.json";
@@ -840,9 +819,8 @@ async function signAppManifest(source, options) {
840
819
  code: "APP_MANIFEST_INVALID",
841
820
  errors: parsed.errors
842
821
  };
843
- if (storedSize(parsed.manifest) > 65536) return refuse("APP_MANIFEST_TOO_LARGE", tooLargeMessage());
844
822
  const signed = await signManifest(JSON.stringify(manifest), options.identityKey);
845
- if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) return refuse("APP_MANIFEST_TOO_LARGE", signedTooLargeMessage());
823
+ if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) return refuse("APP_MANIFEST_TOO_LARGE", `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB`);
846
824
  return {
847
825
  success: true,
848
826
  signed,
@@ -881,4 +859,4 @@ async function signProject({ root, mode, env, manifestUrl, manifestFile = MANIFE
881
859
  //#endregion
882
860
  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 };
883
861
 
884
- //# sourceMappingURL=sign-3ysEUyYt.js.map
862
+ //# sourceMappingURL=sign-50Ayvddb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-50Ayvddb.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/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 { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport {\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 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 fetches.\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\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // A valid manifest is far smaller than Ghost stores, but the payload keeps whatever the file\n // had, such as text Ghost trims, so it can still be larger than Ghost fetches.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse(\n 'APP_MANIFEST_TOO_LARGE',\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB`,\n );\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,Q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AM,CAAC,CAAC,CAAC,aAAa,2BACjE,OAAO,OACL,0BACA,yCAAyC,KAAK,MAAM,4BAA4B,IAAI,EAAE,IACxF;CAEF,OAAO;EAAE,SAAS;EAAM;EAAQ;CAAS;AAC3C;;AAGA,SAAgB,aAAa,QAA0C;CACrE,OAAO,qBAAqB,QAAQ,IAAI;AAC1C;;AAGA,SAAgB,gBAAgB,QAAgC;CAC9D,OAAO,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE;AAC5C;;AAGA,eAAsB,mBAAmB,MAAgC;CACvE,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM;CACxC,IAAI;EACF,OAAO,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.12";
493
+ var SDK_VERSION = "0.1.0-alpha.13";
494
494
  //#endregion
495
495
  //#region src/connect.ts
496
496
  /**
@@ -125,7 +125,7 @@ type SignResult = {
125
125
  success: false;
126
126
  /**
127
127
  * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or
128
- * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost stores.
128
+ * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost fetches.
129
129
  */
130
130
  code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';
131
131
  errors: ManifestError[];
package/build/tooling.js CHANGED
@@ -1,2 +1,2 @@
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";
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-50Ayvddb.js";
2
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,4 +1,4 @@
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";
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-50Ayvddb.js";
2
2
  import { t as MANIFEST_PATH } from "./chunks/manifest-BO_hJDEK.js";
3
3
  import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
4
4
  import { existsSync, readFileSync } from "node:fs";
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.12";
1221
+ var SDK_VERSION = "0.1.0-alpha.13";
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.12",
3
+ "version": "0.1.0-alpha.13",
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 +0,0 @@
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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