@tryghost/app-sdk 0.1.0-alpha.0 → 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +252 -29
- package/build/backend.d.ts +89 -0
- package/build/backend.js +200 -0
- package/build/backend.js.map +1 -0
- package/build/bin.d.ts +1 -0
- package/build/bin.js +124 -0
- package/build/bin.js.map +1 -0
- package/build/chunks/manifest-B9vQoSfm.js +43 -0
- package/build/chunks/manifest-B9vQoSfm.js.map +1 -0
- package/build/chunks/manifest-DFLCKcwH.d.ts +19 -0
- package/build/chunks/rules-_dou3jRF.js +159 -0
- package/build/chunks/rules-_dou3jRF.js.map +1 -0
- package/build/chunks/sign-Deg9TCUr.js +869 -0
- package/build/chunks/sign-Deg9TCUr.js.map +1 -0
- package/build/index.d.ts +19 -5
- package/build/index.js +40 -176
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +148 -0
- package/build/tooling.js +3 -0
- package/build/vite.d.ts +29 -0
- package/build/vite.js +228 -0
- package/build/vite.js.map +1 -0
- package/dist/app-sdk.js +40 -24
- package/dist/app-sdk.js.map +1 -1
- package/package.json +32 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-Deg9TCUr.js","names":[],"sources":["../../../app-contracts/build/manifest/localhost.js","../../../app-contracts/build/manifest/ghost-host.js","../../../app-contracts/build/manifest/id.js","../../../app-contracts/build/manifest/limits.js","../../../app-contracts/build/identity/signed-manifest.js","../../src/tooling/git.ts","../../src/tooling/keys.ts","../../../app-contracts/build/manifest/icon.js","../../../app-contracts/build/manifest/keys.js","../../../app-contracts/build/manifest/surfaces.js","../../../app-contracts/build/manifest/text.js","../../../app-contracts/build/manifest/url.js","../../../app-contracts/build/manifest/schema.js","../../../app-contracts/build/manifest/parse.js","../../src/tooling/limits.ts","../../src/tooling/sign.ts"],"sourcesContent":["// `URL` has already normalised the host by the time these run: every spelling of an IPv4\n// address is dotted decimal, and an IPv4-mapped IPv6 address is two hex groups.\nconst LOOPBACK_HOSTS = [\n /^localhost$/,\n /\\.localhost$/,\n /^127\\.\\d+\\.\\d+\\.\\d+$/,\n /^0\\.0\\.0\\.0$/,\n /^\\[::1?\\]$/,\n /^\\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\\]$/,\n /^\\[::ffff:0:0\\]$/,\n];\n/**\n * A hostname without its trailing dots, which the URL parser keeps, every one of them:\n * `localhost..` is `localhost`. A loop rather than a regular expression, which would take\n * time quadratic in the number of dots on a hostname with many dots before its end.\n */\nexport function withoutTrailingDots(hostname) {\n let end = hostname.length;\n while (end > 0 && hostname[end - 1] === '.') {\n end -= 1;\n }\n return hostname.slice(0, end);\n}\n/**\n * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.\n * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as\n * `isGhostHost` drops them.\n */\nexport function isLocalhost(hostname) {\n const host = withoutTrailingDots(hostname);\n return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));\n}\n//# sourceMappingURL=localhost.js.map","import { withoutTrailingDots } from './localhost.js';\n/**\n * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any\n * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,\n * whatever a frame's sandbox says. On another port it would be the app's, but browsers send\n * a host's cookies to every port on it, so the app's server would be sent the staff user's\n * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it\n * frames the page, since the site's or Admin's address can change after an app is\n * installed.\n *\n * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and\n * without a trailing dot. A sibling host, such as another subdomain of the site's, is not\n * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as\n * `my-app.localhost` next to `localhost`, or another name for the same machine, such as\n * `127.0.0.1`, which browsers treat as other hosts too.\n *\n * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no\n * Ghost URLs at all. Either way the URL is refused.\n */\nexport function isGhostHost(url, ghostUrls) {\n const host = hostOf(url);\n if (host === null) {\n return true;\n }\n let known = false;\n for (const ghostUrl of ghostUrls) {\n const ghostHost = hostOf(ghostUrl);\n if (ghostHost === null || ghostHost === host) {\n return true;\n }\n known = true;\n }\n return !known;\n}\n/** An http or https URL's host as `isGhostHost` compares it, or null for any other. */\nexport function hostOf(value) {\n let url;\n // Admin runs this, and `URL.parse` is newer than the browsers Admin supports.\n try {\n url = new URL(value);\n }\n catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return null;\n }\n return withoutTrailingDots(url.hostname) || null;\n}\n//# sourceMappingURL=ghost-host.js.map","/** Matches the limit of the index that ties saved cards to an app. */\nexport const APP_ID_MAX_LENGTH = 191;\nconst ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n/**\n * An app ID is reverse-domain style: at least two dot-separated segments of lowercase\n * letters, digits and hyphens, starting with a letter so that an IP address or a version\n * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than\n * lowercased.\n */\nexport function isValidAppId(value) {\n if (typeof value !== 'string' || value.length > APP_ID_MAX_LENGTH) {\n return false;\n }\n const segments = value.split('.');\n return (segments.length >= 2 &&\n /^[a-z]/.test(value) &&\n segments.every((segment) => ID_SEGMENT.test(segment)));\n}\n//# sourceMappingURL=id.js.map","/**\n * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of\n * them, the manifest's own URL included, so its columns are exactly this wide.\n */\nexport const URL_MAX_LENGTH = 2000;\n//# sourceMappingURL=limits.js.map","import { FlattenedSign, flattenedVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeText } from './keys.js';\n/** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */\nexport const SIGNED_MANIFEST_TYPE = 'ghost-app-manifest';\nconst SignedManifestShape = z.strictObject({\n protected: z.string(),\n payload: z.string(),\n signature: z.string(),\n});\nconst ProtectedHeader = z.strictObject({\n alg: z.literal(ALGORITHM),\n typ: z.literal(SIGNED_MANIFEST_TYPE),\n});\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE });\n/**\n * Signs a manifest with an app's identity key. A string is signed as the exact text it is;\n * anything else is signed as its JSON.\n */\nexport async function signManifest(manifest, identityKey) {\n const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest);\n const signed = await new FlattenedSign(new TextEncoder().encode(text))\n .setProtectedHeader({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE })\n .sign(identityKey);\n return { protected: signed.protected, payload: signed.payload, signature: signed.signature };\n}\n/**\n * Reads the manifest out of a signed manifest, without verifying it. The key to verify it\n * with is named inside the manifest, so the manifest has to be read and checked first;\n * nothing in it may be used until `verifySignedManifest` has passed.\n */\nexport function readSignedManifest(body) {\n const shape = SignedManifestShape.safeParse(body);\n if (!shape.success) {\n return {\n success: false,\n error: 'Expected a signed manifest: flattened JWS JSON with protected, payload and signature',\n };\n }\n const signed = shape.data;\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n const payload = decodeText(signed.payload);\n if (payload === undefined) {\n return { success: false, error: 'Expected a payload of UTF-8 text in base64url' };\n }\n return { success: true, signed, payload };\n}\n/**\n * Checks a signed manifest was signed with the identity key the manifest names, under\n * exactly the protected header `readSignedManifest` accepts.\n */\nexport async function verifySignedManifest(signed, identityKey) {\n let key;\n try {\n key = await importJWK(identityKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'identity_key is not a usable Ed25519 key' };\n }\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n try {\n await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });\n }\n catch {\n return { success: false, error: 'The signature was not made with identity_key' };\n }\n return { success: true };\n}\n//# sourceMappingURL=signed-manifest.js.map","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { ignoreError } from '../shared/ignore.ts';\n\nexport type IgnoredResult = { ignored: true } | { ignored: false; reason: string };\n\nfunction git(args: string[], cwd: string, input?: string) {\n return new Promise<{ code: number | string | null; stdout: string; stderr: string }>((done) => {\n const child = execFile('git', args, { cwd }, (error, stdout, stderr) => {\n done({ code: error ? ((error as { code?: number | string }).code ?? 1) : 0, stdout, stderr });\n });\n // A git that couldn't start has no stdin to write to; its error arrives above.\n child.stdin?.on('error', ignoreError);\n child.stdin?.end(input);\n });\n}\n\nfunction insideRepository(directory: string): boolean {\n for (let current = resolve(directory); ; current = dirname(current)) {\n if (existsSync(join(current, '.git'))) {\n return true;\n }\n if (dirname(current) === current) {\n return false;\n }\n }\n}\n\n/**\n * The directory itself, or the nearest one above it that exists, to run git in: a project's\n * directory may not exist before its keys are written, and git can't start in one that doesn't.\n */\nfunction existingDirectory(directory: string): string {\n let current = resolve(directory);\n while (!existsSync(current) && dirname(current) !== current) {\n current = dirname(current);\n }\n return current;\n}\n\n/**\n * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by\n * accident. A file outside any repository counts as ignored.\n */\nexport async function isGitIgnored(\n root: string,\n files: string | readonly string[],\n): Promise<IgnoredResult> {\n // git can't start in a directory that doesn't exist, and a project's may not exist yet.\n const cwd = existingDirectory(root);\n const paths = (typeof files === 'string' ? [files] : files).map((file) => ({\n // As the developer named it, for messages, and as git is asked about it, from `cwd`.\n shown: relative(root, resolve(root, file)),\n asked: relative(cwd, resolve(root, file)),\n }));\n const named = `${paths.map(({ shown }) => shown).join(' and ')} ${paths.length > 1 ? 'are' : 'is'}`;\n\n const repository = await findRepository(cwd, named);\n if (repository !== 'inside') {\n return repository === 'outside' ? { ignored: true } : repository;\n }\n return askWhichAreIgnored(cwd, paths, named);\n}\n\n/** Whether `cwd` is in a repository, or why git can't say when it seems to be. */\nasync function findRepository(\n cwd: string,\n named: string,\n): Promise<'inside' | 'outside' | { ignored: false; reason: string }> {\n // Read from what git exits with, never from what it says, which is in the developer's\n // language. A `.git` that git can't read is still a repository, so it isn't taken as outside.\n const inside = await git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (inside.code === 0) {\n return 'inside';\n }\n if (!insideRepository(cwd)) {\n return 'outside';\n }\n return {\n ignored: false,\n reason:\n inside.code === 'ENOENT'\n ? `git isn't installed, so it can't check ${named} ignored`\n : `git couldn't read the repository: ${inside.stderr.trim()}`,\n };\n}\n\nasync function askWhichAreIgnored(\n cwd: string,\n paths: { shown: string; asked: string }[],\n named: string,\n): Promise<IgnoredResult> {\n // One call for every path. It lists the ones it ignores, and exits with 1 when it ignores none.\n // Paths go in and out separated by NUL, as git would otherwise quote one with any byte outside\n // ASCII. A file git tracks isn't ignored, even if a `.gitignore` names it.\n const { code, stdout, stderr } = await git(\n ['check-ignore', '--stdin', '-z'],\n cwd,\n paths.map(({ asked }) => `${asked}\\0`).join(''),\n );\n if (code !== 0 && code !== 1) {\n return { ignored: false, reason: `git couldn't check ${named} ignored: ${stderr.trim()}` };\n }\n const ignored = new Set(stdout.split('\\0'));\n const notIgnored = paths.find(({ asked }) => !ignored.has(asked));\n return notIgnored\n ? { ignored: false, reason: `git doesn't ignore ${notIgnored.shown}` }\n : { ignored: true };\n}\n","import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nimport { isGitIgnored } from './git.ts';\n\n/**\n * Which keys to use. Development and production have separate identity keys, so an app\n * installed from the developer's machine is a different app from the deployed one.\n */\nexport type Mode = 'development' | 'production';\n\n/** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */\nexport const KEYS_DIRECTORY = '.ghost-app';\n\n/**\n * - `identity`: signs the manifest. It says who made the app, so it stays with the developer\n * (or their CI) and never reaches the backend or a bundle.\n * - `backend`: answers Ghost's challenge, so the backend holds it.\n */\nexport type KeyName = 'identity' | 'backend';\n\nexport const KEY_NAMES: readonly KeyName[] = ['identity', 'backend'];\n\n/** A private Ed25519 key as a JWK. */\nexport interface PrivateKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n d: string;\n}\n\n/** A public Ed25519 key as a JWK, as a manifest names it. */\nexport interface PublicKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n}\n\n/** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */\nexport const IDENTITY_KEY_VARIABLE = 'GHOST_APP_IDENTITY_KEY';\n\n/**\n * The backend key, as the backend reads it, and as CI may provide it to sign a production\n * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.\n */\nexport const BACKEND_KEY_VARIABLE = 'GHOST_APP_BACKEND_KEY';\n\nexport interface KeyOptions {\n /** The project's directory, which holds `.ghost-app/`. */\n root: string;\n mode: Mode;\n}\n\n/** The file a key is kept in, relative to the project. */\nexport function keyFile(mode: Mode, name: KeyName): string {\n return join(KEYS_DIRECTORY, mode, `${name}.json`);\n}\n\n/** A new private Ed25519 key. */\nexport function generateKey(): PrivateKeyJwk {\n const { x, d } = generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' });\n return { kty: 'OKP', crv: 'Ed25519', x: x!, d: d! };\n}\n\n/** A key's public half, with only `kty`, `crv` and `x`. */\nexport function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk {\n return { kty: 'OKP', crv: 'Ed25519', x: key.x };\n}\n\n/**\n * Reads a private key from JSON. `source` names where it came from, for the error: the key\n * itself is never in one.\n */\nexport function readKey(text: string, source: string): PrivateKeyJwk {\n const key = readAnyKey(text, source);\n if (!('d' in key)) {\n throw new Error(`${source} is a public key; expected the private key, with d`);\n }\n return key;\n}\n\n/** Reads a key from JSON, private or public. */\nfunction readAnyKey(text: string, source: string): PrivateKeyJwk | PublicKeyJwk {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new Error(`${source} isn't a key: it isn't JSON`);\n }\n if (!isEd25519(value)) {\n throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\" and x`);\n }\n const { d } = value as { d?: unknown };\n if (d === undefined) {\n return publicKeyOf(value);\n }\n // A key with a private part that doesn't read isn't a public key either.\n if (typeof d !== 'string') {\n throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);\n }\n // A JWK carries both halves, so a hand-edited or pasted one could pair a private half with\n // someone else's public half, and sign for a key the manifest doesn't name.\n if (publicHalfOf(d, source) !== value.x) {\n throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);\n }\n return { kty: 'OKP', crv: 'Ed25519', x: value.x, d } satisfies PrivateKeyJwk;\n}\n\nfunction isEd25519(value: unknown): value is { kty: 'OKP'; crv: 'Ed25519'; x: string } {\n const { kty, crv, x } = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >;\n return kty === 'OKP' && crv === 'Ed25519' && typeof x === 'string';\n}\n\n// What PKCS#8 puts before an Ed25519 private key's 32 bytes.\nconst ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');\n\n/**\n * The public half of a private half, as `x`. Derived from `d` alone, as Node 24.22 and later\n * refuse a JWK whose halves don't match while earlier versions take its `x` as given, so a\n * mismatch is reported the same way on any version.\n */\nfunction publicHalfOf(d: string, source: string): string | undefined {\n const bytes = Buffer.from(d, 'base64url');\n if (bytes.length !== 32) {\n throw new Error(`${source} isn't a usable Ed25519 key`);\n }\n const key = createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, bytes]),\n format: 'der',\n type: 'pkcs8',\n });\n return createPublicKey(key).export({ format: 'jwk' }).x;\n}\n\nasync function readKeyFile(root: string, mode: Mode, name: KeyName): Promise<PrivateKeyJwk> {\n const file = keyFile(mode, name);\n let text: string;\n try {\n text = await readFile(join(root, file), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n throw new Error(missingKeyMessage(mode, name, file), { cause: error });\n }\n return readKey(text, file);\n}\n\n/** Says how to create a missing key, as nothing that reads keys creates one. */\nfunction missingKeyMessage(mode: Mode, name: KeyName, file: string): string {\n if (mode === 'development') {\n return `There's no development ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys\\`.`;\n }\n // In production, CI may provide the key as a variable instead.\n return `There's no production ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys --production\\`, or set ${variableFor(name)}.`;\n}\n\nconst variableFor = (name: KeyName) =>\n name === 'identity' ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;\n\nexport interface CreateKeysResult {\n /** The keys this call created. */\n created: KeyName[];\n /** The keys that already existed, which are never replaced. */\n kept: KeyName[];\n}\n\n/**\n * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only\n * their owner can read, and keeps any that exist.\n */\nexport async function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult> {\n // Each key is written whole to a temporary file beside it first, then linked to its name.\n const keys = KEY_NAMES.map((name) => {\n const file = keyFile(mode, name);\n const pending = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);\n return { name, file, pending };\n });\n // So a private key can't be committed by accident, git must ignore every file a key is\n // written to, the temporary ones included.\n await refuseUnlessGitIgnores(root, [\n ...keys.map(({ file }) => file),\n ...keys.map(({ pending }) => pending),\n ]);\n await mkdir(join(root, KEYS_DIRECTORY, mode), { recursive: true, mode: 0o700 });\n const result: CreateKeysResult = { created: [], kept: [] };\n for (const { name, file, pending } of keys) {\n // An existing key is kept: a new identity key would make the app a different app on every\n // site that installed it.\n const created = await publishKey(join(root, file), join(root, pending));\n result[created ? 'created' : 'kept'].push(name);\n }\n return result;\n}\n\nasync function refuseUnlessGitIgnores(root: string, files: string[]) {\n const ignored = await isGitIgnored(root, files);\n if (!ignored.ignored) {\n throw new Error(\n `Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`,\n );\n }\n}\n\n/** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */\nasync function publishKey(file: string, pending: string): Promise<boolean> {\n try {\n await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\\n`, {\n flag: 'wx',\n // Only for its owner on macOS and Linux. Windows ignores the mode, and the key gets the\n // folder's inherited permissions, which the README tells developers to keep private.\n mode: 0o600,\n });\n // A link fails if the name is taken, so a key is never replaced, even by a concurrent run,\n // and an interrupted write never leaves part of a key where a key belongs.\n await link(pending, file);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n // Kept, but only for its owner, as a key written by hand or copied in may not be.\n if (process.platform !== 'win32' && ((await stat(file)).mode & 0o077) !== 0) {\n await chmod(file, 0o600);\n }\n return false;\n } finally {\n await rm(pending, { force: true });\n }\n}\n\nexport interface SigningKeys {\n identityKey: PrivateKeyJwk;\n /** The backend key's public half: all signing needs. */\n backendKey: PublicKeyJwk;\n}\n\nexport interface ReadKeysOptions extends KeyOptions {\n /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to\n * anything but blanks, or else the key's file.\n */\nexport function signingKeySource(\n mode: Mode,\n name: KeyName,\n env: Record<string, string | undefined> = process.env,\n): string {\n const variable = variableFor(name);\n return mode === 'production' && env[variable]?.trim() ? variable : keyFile(mode, name);\n}\n\n/**\n * The keys to sign a mode's manifest with, from the key files, or in production from\n * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.\n */\nexport async function readSigningKeys({\n root,\n mode,\n env = process.env,\n}: ReadKeysOptions): Promise<SigningKeys> {\n const fromVariable = (name: KeyName) =>\n signingKeySource(mode, name, env) === variableFor(name)\n ? env[variableFor(name)]!.trim()\n : undefined;\n\n const identityText = fromVariable('identity');\n const identityKey = identityText\n ? await sameAsFile(root, mode, 'identity', readKey(identityText, IDENTITY_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'identity');\n\n // CI may provide only the backend key's public half, as signing needs nothing more.\n const backendText = fromVariable('backend');\n const backendKey = publicKeyOf(\n backendText\n ? await sameAsFile(root, mode, 'backend', readAnyKey(backendText, BACKEND_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'backend'),\n );\n\n if (identityKey.x === backendKey.x) {\n throw new Error('The identity key and the backend key are the same key; they must be two keys');\n }\n return { identityKey, backendKey };\n}\n\n/**\n * A key from a variable, after checking it's the same key as the file, where there's one. A\n * variable left set, such as a development key exported for every shell, would otherwise win over\n * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every\n * site.\n */\nasync function sameAsFile<Key extends PublicKeyJwk>(\n root: string,\n mode: Mode,\n name: KeyName,\n key: Key,\n): Promise<Key> {\n const file = keyFile(mode, name);\n if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {\n const variable = variableFor(name);\n throw new Error(\n `${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`,\n );\n }\n return key;\n}\n\n/** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */\nexport function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk> {\n return readKeyFile(root, mode, 'backend');\n}\n","import { z } from 'zod';\nconst ICON_NAME_MAX_LENGTH = 64;\nconst ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst EITHER = 'Expected an icon with either a name or a url';\n/**\n * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app\n * serves. Ghost keeps a copy of the image with each manifest version it stores, and only\n * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;\n * Admin falls back to a default icon.\n */\nexport function iconField(url) {\n return (z\n .strictObject({\n name: z\n .string('Expected an icon name')\n .max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`)\n .regex(ICON_NAME, 'Expected an icon name such as audio-lines')\n .optional(),\n url: url().optional(),\n }, EITHER)\n .refine(({ name, url: iconUrl }) => (name === undefined) !== (iconUrl === undefined), EITHER)\n // Only the type narrows: the value already is one or the other. A transform would\n // narrow it too, but one-way, and a stored manifest has to encode back through here.\n .pipe(z.custom()));\n}\n//# sourceMappingURL=icon.js.map","import { z } from 'zod';\n// 32 bytes in base64url without padding. The last character carries the final 4 bits and\n// 2 zero bits, so only 16 of the 64 characters can end it, which keeps the spelling of a key\n// unique.\nconst ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\nconst EXPECTED = 'Expected a public Ed25519 key as a JWK with kty, crv and x';\nconst PRIVATE = 'Expected a public key, but this includes its private part (d)';\n/**\n * A key a manifest names. A manifest is public, so a key that includes its private part\n * is refused with a message of its own: it has to be replaced, not just removed. Other\n * members are refused by name, as key tools often add some, such as `kid` or `alg`.\n */\nexport const publicKeyField = z.strictObject({\n kty: z.literal('OKP', EXPECTED),\n crv: z.literal('Ed25519', EXPECTED),\n x: z.string(EXPECTED).regex(ED25519_X, 'Expected 32 bytes in base64url, without padding'),\n}, {\n error: (issue) => {\n if (issue.code !== 'unrecognized_keys') {\n return EXPECTED;\n }\n return issue.keys.includes('d')\n ? PRIVATE\n : `Expected only kty, crv and x; remove ${issue.keys.join(', ')}`;\n },\n});\n//# sourceMappingURL=keys.js.map","import { z } from 'zod';\n/**\n * What an app asks for: the places in Ghost it wants to appear. Each surface type is one\n * entry in a union, so a new one is added here and nowhere else.\n */\nexport function surfacesField(url) {\n const adminPage = z.strictObject({\n type: z.literal('admin_page'),\n url: url(),\n });\n const surfaceTypes = [adminPage];\n const surface = z.discriminatedUnion('type', surfaceTypes, {\n error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(', ')}`,\n });\n return z\n .array(surface, 'Expected a list of surfaces')\n .min(1, 'Expected at least one surface')\n .superRefine((surfaces, ctx) => {\n const seen = new Set();\n surfaces.forEach((entry, index) => {\n if (seen.has(entry.type)) {\n ctx.addIssue({\n code: 'custom',\n message: `Expected at most one ${entry.type} surface`,\n path: [index],\n });\n }\n seen.add(entry.type);\n });\n });\n}\n//# sourceMappingURL=surfaces.js.map","import { z } from 'zod';\nimport { isPlainText } from '../plain-text.js';\n// A character that shows something on its own: a letter, digit, punctuation or symbol, but not\n// the blank Braille pattern or one Unicode says to draw as nothing, such as a joiner or a Hangul\n// filler. Whitespace and marks aren't any of those.\nconst VISIBLE_CHARACTER = new RegExp('(?![\\\\u2800\\\\p{Default_Ignorable_Code_Point}])[\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}]', 'u');\nconst shows = (text) => VISIBLE_CHARACTER.test(text);\n// Shows nothing, and holds nothing plain text refuses other than whitespace, so trimming never\n// takes off a character, such as one that reorders text, that should get the text refused.\nconst blank = (character) => !shows(character) && isPlainText(character.replace(/\\s/gu, ''));\n// Made on first use, so loading the contract doesn't set one up.\nlet graphemes;\n/**\n * Takes off each end the characters, as a reader sees them, that show nothing: a space with a\n * mark on it goes, an emoji with its variation selector stays, and so does anything invisible\n * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no\n * more than its length.\n */\nfunction trimEdges(value) {\n graphemes ??= new Intl.Segmenter();\n const characters = graphemes.segment(value);\n let start = value.length;\n for (const { segment, index } of characters) {\n if (!blank(segment)) {\n start = index;\n break;\n }\n }\n let end = value.length;\n while (end > start) {\n const { segment, index } = characters.containing(end - 1);\n if (!blank(segment)) {\n break;\n }\n end = index;\n }\n return value.slice(start, end);\n}\n/**\n * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and\n * text with nothing visible left, such as a name of Hangul fillers, is refused.\n */\nexport function plainText(maxLength) {\n return (z\n .string('Expected text')\n // Whitespace first, as a character that joins onto a space, such as a skin tone, would keep it.\n .trim()\n .overwrite(trimEdges)\n .refine(shows, 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line'));\n}\n// Any letter, digit, punctuation or symbol, fillers included: the rule manifests were stored under\n// before blank names were refused.\nconst ANY_CHARACTER = /[\\p{L}\\p{N}\\p{P}\\p{S}]/u;\n/**\n * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before\n * blank names were refused still reads, and the app can still be listed and uninstalled.\n */\nexport function storedText(maxLength) {\n return z\n .string('Expected text')\n .trim()\n .refine((value) => ANY_CHARACTER.test(value), 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line');\n}\n//# sourceMappingURL=text.js.map","import { z } from 'zod';\nimport { isContainedPath } from '../bridge/rules.js';\nimport { URL_MAX_LENGTH } from './limits.js';\nimport { isLocalhost } from './localhost.js';\nexport const FRAGMENT_PROBLEM = 'Expected a URL without a fragment';\n/**\n * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`\n * hides. A fragment never reaches the server, so a manifest address with one is a mistake or\n * a second spelling of the same address.\n */\nexport const hasFragment = (address) => address.includes('#');\n/**\n * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would\n * use. The length is measured on the parsed URL for the same reason, as that is what is\n * stored and checked again later.\n */\nexport function checkResolvedUrl(url, allowLocalhost) {\n if (url.href.length > URL_MAX_LENGTH) {\n return `Expected at most ${URL_MAX_LENGTH} characters`;\n }\n if (url.username || url.password) {\n return 'Expected a URL without a username or password';\n }\n if (isLocalhost(url.hostname)) {\n if (!allowLocalhost) {\n return 'Expected a public address; localhost is only allowed when Ghost runs in development';\n }\n return url.protocol === 'https:' || url.protocol === 'http:'\n ? null\n : 'Expected an http or https URL';\n }\n return url.protocol === 'https:' ? null : 'Expected an https URL';\n}\nconst ROUTE_PROBLEM = 'Expected a URL that resolves to a path starting with a single /, with no \\\\ in its query or fragment';\nconst PATH_PROBLEM = 'Expected a path on the manifest’s own origin, such as /admin';\n// Two, so a reference that names one of them still names a host other than the other's.\nconst PLACEHOLDER_HOSTS = ['manifest-a.invalid', 'manifest-b.invalid'];\n/** Whether a reference names a host, in any of the URL parser's spellings of one. */\nconst namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);\nfunction isManifestItself(url, base) {\n return url.pathname === new URL(base).pathname;\n}\n/**\n * A URL in the manifest. What Ghost loads is written as a path, resolved against the\n * address the manifest was fetched from, so an app is one origin: the one Ghost fetches\n * the manifest from and challenges is the one every surface runs on. The manifest names\n * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they\n * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.\n *\n * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and\n * may be anywhere, the publisher's own site included.\n *\n * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.\n * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.\n * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which\n * names a host, and a `\\` in the query or fragment is left as it is. Only the page is opened\n * as a route, but every URL Ghost loads is held to the one rule.\n */\nexport function urlField({ allowLocalhost, base }, linkOnly = false) {\n if (linkOnly) {\n return z.string('Expected an absolute URL').transform((value, ctx) => {\n const url = URL.parse(value);\n const problem = url ? checkResolvedUrl(url, allowLocalhost) : 'Expected an absolute URL';\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n return url.href;\n });\n }\n const origin = new URL(base).origin;\n return z.string(PATH_PROBLEM).transform((value, ctx) => {\n // A path, or a path-relative reference. A URL with a scheme, or a `//host` one, names\n // its own origin, which the manifest's would then not be, even when it's the same one\n // today. An empty one, or one that's only a query or fragment, would be the manifest\n // itself.\n const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);\n if (!url || url.origin !== origin || isManifestItself(url, base)) {\n ctx.addIssue({ code: 'custom', message: PATH_PROBLEM });\n return z.NEVER;\n }\n const problem = checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {\n ctx.addIssue({ code: 'custom', message: ROUTE_PROBLEM });\n return z.NEVER;\n }\n return url.href;\n });\n}\n/**\n * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and\n * already checked. Nothing is resolved or checked again, so a manifest accepted before the\n * site's URL changed still reads back.\n */\nexport const absoluteUrl = () => z.url('Expected an absolute URL');\n//# sourceMappingURL=url.js.map","import { z } from 'zod';\nimport { iconField } from './icon.js';\nimport { APP_ID_MAX_LENGTH, isValidAppId } from './id.js';\nimport { publicKeyField } from './keys.js';\nimport { isLocalhost } from './localhost.js';\nimport { surfacesField } from './surfaces.js';\nimport { plainText, storedText } from './text.js';\nimport { absoluteUrl, FRAGMENT_PROBLEM, hasFragment, urlField, } from './url.js';\nconst NAME_MAX_LENGTH = 50;\nconst DESCRIPTION_MAX_LENGTH = 200;\nconst AUTHOR_NAME_MAX_LENGTH = 50;\nconst HEX_COLOR = /^#[0-9a-f]{6}$/i;\nconst KEY_FIELDS = new Set(['identity_key', 'backend_key']);\nconst URL_FIELDS = new Set([\n 'author',\n 'icon',\n 'surfaces',\n 'manifest_url',\n 'development',\n]);\n/** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */\nconst parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));\n/**\n * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot\n * claim something Ghost has not designed, and adding a field is always a deliberate change\n * here.\n *\n * Defined once, with the URL and text rules left open. What a valid URL is depends on whether\n * the manifest is being parsed, when where Ghost is served from matters, or read back after it\n * was, when it doesn't. Text is held to today's rules when parsed, and read back under the\n * rules it was stored under.\n */\nfunction manifestShape(url, text) {\n return (z\n .strictObject({\n id: z.custom(isValidAppId, {\n error: `Expected a lowercase reverse-domain ID such as com.example.app, at most ${APP_ID_MAX_LENGTH} characters`,\n }),\n name: text(NAME_MAX_LENGTH),\n description: text(DESCRIPTION_MAX_LENGTH),\n author: z.strictObject({\n name: text(AUTHOR_NAME_MAX_LENGTH),\n // Only ever linked to, so it may point at the publisher's own site.\n url: url(true),\n }, 'Expected an author with a name and a url'),\n accent_color: z\n .string('Expected a hex colour such as #ff5500')\n .regex(HEX_COLOR, 'Expected a hex colour such as #ff5500')\n .toLowerCase(),\n icon: iconField(url),\n surfaces: surfacesField(url),\n // Where the signed manifest is served from: the app's one origin, which every path\n // in it resolves against. Ghost fetches it server-side and never loads it as a page.\n manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),\n identity_key: publicKeyField,\n backend_key: publicKeyField,\n // Lets Admin label a development build. Production sites may run one to test it.\n development: z.boolean('Expected true or false'),\n })\n // A backend holds its key online. If it also signed manifests, whoever took over the\n // backend could publish any manifest as the app.\n .refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {\n message: 'Expected a different key from identity_key',\n path: ['backend_key'],\n // Only once both keys are known to be keys. An issue without a path is about the\n // manifest as a whole, which may not be an object at all.\n when: parsedFields(KEY_FIELDS),\n })\n // An app on the developer's machine is always labelled as a development build.\n .refine((manifest) => manifest.development ||\n ![\n manifest.author.url,\n 'url' in manifest.icon ? manifest.icon.url : undefined,\n ...manifest.surfaces.map((surface) => surface.url),\n manifest.manifest_url,\n ].some((address) => address !== undefined && isLocalhost(new URL(address).hostname)), {\n message: 'Expected true, as the app is on localhost',\n path: ['development'],\n when: parsedFields(URL_FIELDS),\n }));\n}\n/** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */\nexport function manifestSchema(rules) {\n return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);\n}\n/**\n * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to\n * resolve or check. This is the schema to read a stored manifest with, as it holds\n * whatever the site's URL has become since, and it encodes a manifest back to the same\n * shape, so what is stored is what will be read.\n */\nexport const AppManifestSchema = manifestShape(absoluteUrl, storedText);\n//# sourceMappingURL=schema.js.map","import { hostOf, isGhostHost } from './ghost-host.js';\nimport { isLocalhost } from './localhost.js';\nimport { manifestSchema } from './schema.js';\nimport { checkResolvedUrl, FRAGMENT_PROBLEM, hasFragment } from './url.js';\nfunction formatPath(path) {\n return path.reduce((result, part) => {\n if (typeof part === 'number') {\n return `${result}[${part}]`;\n }\n return result ? `${result}.${String(part)}` : String(part);\n }, '');\n}\nconst GHOST_URLS_PROBLEM = 'Expected the URLs Ghost itself is served from';\nconst ON_GHOST_HOST = 'Expected the manifest on a host other than the one Ghost itself is served from, on any port, as browsers send Ghost’s cookies to every port on its host';\nconst ON_GHOST_HOST_LOCALLY = `${ON_GHOST_HOST}. To run the app on this machine too, serve it from a name of its own under .localhost, such as my-app.localhost`;\n/**\n * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most\n * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`\n * is a host of its own, which browsers send to the machine itself, and so does Ghost in\n * development, whatever the system's resolver knows.\n */\nfunction onGhostHost(url) {\n return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;\n}\n/**\n * Reads the address a manifest is to be read from, by the same rules as the URLs inside\n * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first\n * request never goes to an address Ghost would refuse (plain HTTP, one carrying\n * credentials, or one on Ghost's host). It cannot judge where that address redirects,\n * which is for whatever fetches it to limit.\n *\n * The address it hands back is the one to store, to compare with a later one, and that the\n * manifest must name as its `manifest_url`. The URL parser settles most differences in\n * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a\n * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.\n */\nexport function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {\n if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) {\n return { success: false, error: GHOST_URLS_PROBLEM };\n }\n const url = URL.parse(input);\n if (!url) {\n return { success: false, error: 'Expected the manifest at a URL' };\n }\n const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n return { success: false, error: `${problem} for the manifest itself` };\n }\n if (isGhostHost(url, ghostUrls)) {\n return { success: false, error: onGhostHost(url) };\n }\n return { success: true, manifestUrl: url.href };\n}\nfunction invalid(errors) {\n return { success: false, reason: 'invalid', errors };\n}\n/**\n * Validates a manifest, and checks it names the address it was fetched from as its\n * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the\n * manifest to its address as well as to every URL in it.\n *\n * Returns either the manifest, or every problem found. It does not fetch anything and it\n * never throws. Without the URLs Ghost is served from it rejects every manifest, since the\n * rule that keeps apps off Ghost's hosts could not be checked.\n */\nexport function parseManifest(input, options) {\n const allowLocalhost = options.allowLocalhost ?? false;\n const address = parseManifestUrl(options.manifestUrl, options);\n if (!address.success) {\n return invalid([{ path: '', message: address.error }]);\n }\n const result = manifestSchema({ allowLocalhost, base: address.manifestUrl }).safeParse(input);\n if (!result.success) {\n return invalid(result.error.issues.map((issue) => ({\n path: formatPath(issue.path),\n message: issue.message,\n })));\n }\n if (result.data.manifest_url !== address.manifestUrl) {\n return {\n success: false,\n reason: 'manifest_url_mismatch',\n errors: [\n {\n path: 'manifest_url',\n message: `Expected ${address.manifestUrl}, the address the manifest was read from`,\n },\n ],\n };\n }\n return { success: true, manifest: result.data };\n}\n//# sourceMappingURL=parse.js.map","import { AppManifestSchema, type AppManifest } from '@tryghost/app-contracts/manifest';\nimport { z } from 'zod';\n\n// The limits Ghost reads a manifest with, from App Installations in Ghost core, which doesn't\n// export them to apps.\n\n/** The largest manifest Ghost stores, which it keeps in a TEXT column. */\nexport const MANIFEST_MAX_BYTES = 64 * 1024;\n\n/**\n * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and the\n * header and signature are well under a kilobyte.\n */\nexport const SIGNED_MANIFEST_MAX_BYTES = Math.ceil((MANIFEST_MAX_BYTES * 4) / 3) + 1024;\n\n/**\n * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what\n * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.\n */\nexport function storedSize(manifest: AppManifest): number {\n return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;\n}\n\nexport const signedTooLargeMessage = () =>\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;\n\nexport const tooLargeMessage = () =>\n `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport { signManifest } from '@tryghost/app-contracts/identity';\nimport { parseManifest, parseManifestUrl } from '@tryghost/app-contracts/manifest';\n\nimport {\n publicKeyOf,\n readKey,\n readSigningKeys,\n type PrivateKeyJwk,\n type PublicKeyJwk,\n type ReadKeysOptions,\n} from './keys.ts';\nimport { UNKNOWN_GHOST_URL } from '../shared/manifest.ts';\nimport { parseJsonText } from '../shared/parse.ts';\nimport {\n MANIFEST_MAX_BYTES,\n SIGNED_MANIFEST_MAX_BYTES,\n signedTooLargeMessage,\n storedSize,\n tooLargeMessage,\n} from './limits.ts';\nimport type { ManifestError, SignedManifest } from './types.ts';\n\n/** The readable manifest a project keeps, which the tooling signs. */\nexport const MANIFEST_FILE = 'ghost-app.json';\n\n/** The fields the tooling adds, which `ghost-app.json` mustn't set. */\nconst ADDED_FIELDS = ['manifest_url', 'identity_key', 'backend_key', 'development'] as const;\n\nexport interface SignOptions {\n /** The address the signed manifest will be served from, which it names as its own. */\n manifestUrl: string;\n identityKey: PrivateKeyJwk;\n /** Only its public half goes in the manifest. */\n backendKey: PrivateKeyJwk | PublicKeyJwk;\n /** Whether this is a development build, as it must be when any URL is on localhost. */\n development: boolean;\n}\n\nexport type SignResult =\n | {\n success: true;\n signed: SignedManifest;\n /** The manifest as signed, with the fields the tooling added. */\n manifest: Record<string, unknown>;\n }\n | {\n success: false;\n /**\n * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or\n * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost stores.\n */\n code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';\n errors: ManifestError[];\n };\n\ntype Refusal = Extract<SignResult, { success: false }>;\n\nconst refuse = (code: Refusal['code'], message: string, path = ''): Refusal => ({\n success: false,\n code,\n errors: [{ path, message }],\n});\n\n/**\n * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it\n * with the identity key, unless Ghost would refuse it.\n */\nexport async function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult> {\n // A JWK carries both halves, so one passed in, rather than read from a file, could pair a\n // private half with another key's public half. The manifest would name a key that didn't sign\n // it, or one the backend can't answer for, and Ghost would refuse it. That's the caller's\n // mistake, so it throws.\n readKey(JSON.stringify(options.identityKey), 'identityKey');\n if ('d' in options.backendKey) {\n readKey(JSON.stringify(options.backendKey), 'backendKey');\n }\n // Ghost's own hosts are the one rule only a site knows, so a name no site has stands in.\n const address = parseManifestUrl(options.manifestUrl, {\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!address.success) {\n return refuse('APP_MANIFEST_URL_INVALID', address.error);\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return refuse('APP_MANIFEST_INVALID', 'Expected the manifest as a JSON object');\n }\n // The fields signing adds can't come from the file, or the file could name other keys.\n const added = ADDED_FIELDS.filter((field) => field in source);\n if (added.length > 0) {\n return {\n success: false,\n code: 'APP_MANIFEST_INVALID',\n errors: added.map((field) => ({\n path: field,\n message: `Leave ${field} out: it's added when the manifest is signed`,\n })),\n };\n }\n\n const manifest = {\n ...source,\n manifest_url: address.manifestUrl,\n identity_key: publicKeyOf(options.identityKey),\n backend_key: publicKeyOf(options.backendKey),\n development: options.development,\n };\n // Checked by the rules Ghost applies, so a manifest Ghost would refuse is never signed, and\n // the result lists every problem by the path to its field.\n const parsed = parseManifest(manifest, {\n manifestUrl: address.manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!parsed.success) {\n // A mismatch can't happen, as the manifest URL was just set; any failure is invalid.\n return { success: false, code: 'APP_MANIFEST_INVALID', errors: parsed.errors };\n }\n if (storedSize(parsed.manifest) > MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', tooLargeMessage());\n }\n\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // Ghost limits the signed manifest it fetches too, and the payload keeps whatever the file had,\n // such as text Ghost trims, so a manifest Ghost stores can still be too large to fetch.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', signedTooLargeMessage());\n }\n return { success: true, signed, manifest };\n}\n\n/** A signed manifest as the CLI and the Vite plugin write it to a file. */\nexport function serialiseSigned(signed: SignedManifest): string {\n return `${JSON.stringify(signed, null, 2)}\\n`;\n}\n\n/** Reads `ghost-app.json`, or another readable manifest, as JSON. */\nexport async function readManifestSource(file: string): Promise<unknown> {\n const text = await readFile(file, 'utf8');\n try {\n return parseJsonText(text);\n } catch (error) {\n throw new Error(`${file} isn't JSON: ${(error as Error).message}`, { cause: error });\n }\n}\n\nexport interface SignProjectOptions extends ReadKeysOptions {\n manifestUrl: string;\n /** The readable manifest, relative to `root`. `ghost-app.json` by default. */\n manifestFile?: string;\n}\n\n/** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */\nexport async function signProject({\n root,\n mode,\n env,\n manifestUrl,\n manifestFile = MANIFEST_FILE,\n}: SignProjectOptions): Promise<SignResult> {\n // Resolved, so an absolute path is taken as it is.\n const source = await readManifestSource(resolve(root, manifestFile));\n // Keys are read, never created: a missing one throws with how to create it.\n const keys = await readSigningKeys({ root, mode, env });\n return signAppManifest(source, { manifestUrl, ...keys, development: mode === 'development' });\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAM,iBA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AAQ;CACvB;CAGA,MAAM,SAAS,cAAc,UAAU;EACrC,aAAa,QAAQ;EACrB,WAAW,CAAC,iBAAiB;EAC7B,gBAAgB;CAClB,CAAC;CACD,IAAI,CAAC,OAAO,SAEV,OAAO;EAAE,SAAS;EAAO,MAAM;EAAwB,QAAQ,OAAO;CAAO;CAE/E,IAAI,WAAW,OAAO,QAAQ,IAAA,OAC5B,OAAO,OAAO,0BAA0B,gBAAgB,CAAC;CAG3D,MAAM,SAAS,MAAM,aAAa,KAAK,UAAU,QAAQ,GAAG,QAAQ,WAAW;CAG/E,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,gBAAgB,MAAM,CAAC,CAAC,CAAC,aAAa,2BACjE,OAAO,OAAO,0BAA0B,sBAAsB,CAAC;CAEjE,OAAO;EAAE,SAAS;EAAM;EAAQ;CAAS;AAC3C;;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.d.ts
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
declare const BRIDGE_ERROR_CODES: readonly ["session_ended", "invalid_argument", "invalid_path", "blocked", "network_error", "rejected", "invalid_context"];
|
|
4
4
|
type BridgeErrorCode = (typeof BRIDGE_ERROR_CODES)[number];
|
|
5
5
|
declare const THEME_MODES: readonly ['light', 'dark'];
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* The theme Admin is showing, so the page can match it. `mode` is `light` or `dark`, never
|
|
8
|
+
* `system`.
|
|
9
|
+
*/
|
|
7
10
|
type Theme = {
|
|
8
11
|
mode: (typeof THEME_MODES)[number];
|
|
9
12
|
accent_color: string;
|
|
@@ -69,9 +72,12 @@ type Place = {
|
|
|
69
72
|
*
|
|
70
73
|
* - `not_framed`: the page is not framed in Admin, so there is nothing to connect to.
|
|
71
74
|
* - `not_connected`: Admin did not start the app in time.
|
|
72
|
-
* - `duplicate_sdk`: another copy of the SDK in the page has already connected, or tried to
|
|
73
|
-
*
|
|
74
|
-
* - `
|
|
75
|
+
* - `duplicate_sdk`: another copy of the SDK in the page has already connected, or tried to,
|
|
76
|
+
* because the page loads the SDK more than once. Load a single copy for the whole page.
|
|
77
|
+
* - `invalid_context`: Admin started the app with a context this SDK cannot read. Updating the
|
|
78
|
+
* SDK usually fixes it.
|
|
79
|
+
* - `session_ended`: this document has left the app session, usually because the page reloaded
|
|
80
|
+
* or navigated away, or the session has ended. Every call fails after that.
|
|
75
81
|
* - `invalid_argument`: the app passed something that cannot be sent.
|
|
76
82
|
* - `invalid_path`: a path that is not an Admin API path, or not a route within the app; or
|
|
77
83
|
* one the Admin API only redirects, such as a path without its trailing `/`.
|
|
@@ -96,7 +102,7 @@ declare class GhostAppError extends Error {
|
|
|
96
102
|
type Site = Readonly<StartContext['site']>;
|
|
97
103
|
/**
|
|
98
104
|
* Who is using the app, by ID and role. Read anything more, such as their name, through
|
|
99
|
-
*
|
|
105
|
+
* `` ghost.fetch(`/users/?filter=id:${ghost.user.id}`) ``: `/users/:id/` isn't allowed.
|
|
100
106
|
*/
|
|
101
107
|
type User = Readonly<StartContext['user']>;
|
|
102
108
|
/** The session with Admin: the installation's revision when the session started. */
|
|
@@ -111,6 +117,10 @@ type JsonBody = Record<string, unknown> | readonly unknown[];
|
|
|
111
117
|
interface GhostFetchInit {
|
|
112
118
|
/** Any case; sent in uppercase. Defaults to `GET`. */
|
|
113
119
|
method?: string;
|
|
120
|
+
/**
|
|
121
|
+
* Anything `Headers` accepts, except the headers only Admin sets, such as `authorization`,
|
|
122
|
+
* `cookie` and `content-type`, which are refused.
|
|
123
|
+
*/
|
|
114
124
|
headers?: HeadersInit;
|
|
115
125
|
/** Always JSON: text is sent as it is, and an object or array is sent as JSON. */
|
|
116
126
|
body?: string | JsonBody | null;
|
|
@@ -130,11 +140,15 @@ interface GhostPath {
|
|
|
130
140
|
type Unsubscribe = () => void;
|
|
131
141
|
/** The connection to Ghost, once Admin has started the app. */
|
|
132
142
|
interface Ghost {
|
|
143
|
+
/** The site the app is running in: its URL, title, timezone and locale. */
|
|
133
144
|
readonly site: Site;
|
|
145
|
+
/** The staff user using the app, by ID and role. */
|
|
134
146
|
readonly user: User;
|
|
135
147
|
/** The theme Admin shows now. `mode` is always `light` or `dark`. */
|
|
136
148
|
readonly theme: Readonly<Theme>;
|
|
149
|
+
/** The installation's revision when this session started. */
|
|
137
150
|
readonly session: Session;
|
|
151
|
+
/** The app's route, kept in step with Admin's URL. */
|
|
138
152
|
readonly path: GhostPath;
|
|
139
153
|
/** False once the session has ended; every call then rejects with `session_ended`. */
|
|
140
154
|
readonly connected: boolean;
|
package/build/index.js
CHANGED
|
@@ -1,172 +1,5 @@
|
|
|
1
|
+
import { _ as toPlainText, a as START_TIMEOUT_MS, c as isConnectMessage, d as isRecord, f as isReservedRequestHeader, h as methodAllowsBody, i as HOST_ERROR_CODES, l as isContainedPath, m as isTheme, n as FETCH_METHODS, o as decodeBridgeError, p as isStartContext, r as HELLO_MESSAGE_TYPE, s as encodeBridgeError, t as ARGUMENT_MESSAGES, u as isFetchResponse } from "./chunks/rules-_dou3jRF.js";
|
|
1
2
|
import { ThreadMessagePort } from "@quilted/threads";
|
|
2
|
-
//#region ../app-contracts/build/plain-text.js
|
|
3
|
-
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
4
|
-
new RegExp(`^[${ALLOWED}]*$`, "u");
|
|
5
|
-
var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
|
|
6
|
-
/** Returns the text with the characters `isPlainText` refuses removed. */
|
|
7
|
-
function toPlainText(value) {
|
|
8
|
-
return value.replace(NOT_PLAIN_TEXT, "");
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
//#region ../app-contracts/build/bridge/rules.js
|
|
12
|
-
/**
|
|
13
|
-
* The bridge's rules that have no dependencies. The root entry point exports them so the SDK
|
|
14
|
-
* can use them without zod. The schemas in this folder build on them, so the SDK and Admin
|
|
15
|
-
* read a path or a refusal the same way.
|
|
16
|
-
*
|
|
17
|
-
* What Admin sends the page has no schema, because Admin builds it and never parses it. Its
|
|
18
|
-
* types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so
|
|
19
|
-
* the guards only check shape and path containment. They turn a mismatch into a clear error
|
|
20
|
-
* rather than `undefined` somewhere in the app. Only the schemas check limits.
|
|
21
|
-
*/
|
|
22
|
-
/** Posted by the app's page to `window.parent` once the SDK has loaded. */
|
|
23
|
-
var HELLO_MESSAGE_TYPE = "ghost-app:hello";
|
|
24
|
-
/**
|
|
25
|
-
* How long an app's page has to start, in milliseconds. Admin gives up on a frame this long
|
|
26
|
-
* after mounting it, and the SDK waits this long for Admin to start the app unless the app
|
|
27
|
-
* passes its own `timeout`. Long enough for a slow page on a slow connection to load and send
|
|
28
|
-
* its hello.
|
|
29
|
-
*/
|
|
30
|
-
var START_TIMEOUT_MS = 1e4;
|
|
31
|
-
/**
|
|
32
|
-
* The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK
|
|
33
|
-
* uppercases what apps pass.
|
|
34
|
-
*/
|
|
35
|
-
var FETCH_METHODS = [
|
|
36
|
-
"GET",
|
|
37
|
-
"POST",
|
|
38
|
-
"PUT",
|
|
39
|
-
"DELETE"
|
|
40
|
-
];
|
|
41
|
-
/**
|
|
42
|
-
* Whether a request with this method may carry a body. Expects an uppercase method from
|
|
43
|
-
* `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.
|
|
44
|
-
*/
|
|
45
|
-
function methodAllowsBody(method) {
|
|
46
|
-
return method !== "GET";
|
|
47
|
-
}
|
|
48
|
-
var RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;
|
|
49
|
-
/**
|
|
50
|
-
* Whether a request header is one that apps may not set, in any case. Admin refuses a request
|
|
51
|
-
* that sets one rather than dropping the header, so the app gets an error instead of wondering
|
|
52
|
-
* why the header never arrived. The browser refuses some of these anyway; they are listed here
|
|
53
|
-
* so that none of them relies on the browser.
|
|
54
|
-
*/
|
|
55
|
-
function isReservedRequestHeader(name) {
|
|
56
|
-
return RESERVED_REQUEST_HEADER.test(name);
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* The messages Admin and the SDK use when they refuse an argument for the same reason, so an
|
|
60
|
-
* app gets the same message whichever side catches the problem. The SDK checks only for obvious
|
|
61
|
-
* mistakes, before anything crosses the channel; Admin's schemas check everything again.
|
|
62
|
-
*/
|
|
63
|
-
var ARGUMENT_MESSAGES = {
|
|
64
|
-
fetchPath: "Expected an Admin API path such as /posts/, not a URL",
|
|
65
|
-
fetchMethod: `Expected a method of: ${FETCH_METHODS.join(", ")}`,
|
|
66
|
-
fetchBody: "Expected no body on a GET request",
|
|
67
|
-
reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,
|
|
68
|
-
jsonBody: "Expected the body as JSON text",
|
|
69
|
-
appPath: "Expected a path within the app, starting with a single /",
|
|
70
|
-
pathMove: "Expected a move of push or replace",
|
|
71
|
-
place: "Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }"
|
|
72
|
-
};
|
|
73
|
-
/**
|
|
74
|
-
* The codes a refused call carries across the channel. The structured clone that carries an
|
|
75
|
-
* error keeps only its message, so the refusing side puts the code at the start of the
|
|
76
|
-
* message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes
|
|
77
|
-
* are only ever added: an SDK that doesn't know a code treats the whole message as a generic
|
|
78
|
-
* refusal.
|
|
79
|
-
*
|
|
80
|
-
* The host codes, which Admin refuses the page's calls with:
|
|
81
|
-
*
|
|
82
|
-
* - `session_ended`: the session is over; the page is about to be replaced.
|
|
83
|
-
* - `invalid_argument`: an argument Admin does not take.
|
|
84
|
-
* - `invalid_path`: a path that is not an Admin API path or a route within the app, or one
|
|
85
|
-
* the Admin API only responds to with a redirect, such as a path without its trailing `/`.
|
|
86
|
-
* - `blocked`: a request the allowlist doesn't allow, or a write it refuses.
|
|
87
|
-
* - `network_error`: Admin could not reach its own API.
|
|
88
|
-
* - `rejected`: anything else; the detail says why.
|
|
89
|
-
*/
|
|
90
|
-
var HOST_ERROR_CODES = [
|
|
91
|
-
"session_ended",
|
|
92
|
-
"invalid_argument",
|
|
93
|
-
"invalid_path",
|
|
94
|
-
"blocked",
|
|
95
|
-
"network_error",
|
|
96
|
-
"rejected"
|
|
97
|
-
];
|
|
98
|
-
[...HOST_ERROR_CODES];
|
|
99
|
-
var CODED_MESSAGE = /^([a-z_]+): ([\s\S]*)$/;
|
|
100
|
-
/**
|
|
101
|
-
* Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass
|
|
102
|
-
* only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.
|
|
103
|
-
*/
|
|
104
|
-
function encodeBridgeError(code, detail) {
|
|
105
|
-
return `${code}: ${detail}`;
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the
|
|
109
|
-
* other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for
|
|
110
|
-
* one from the page. Returns `undefined` for a message that doesn't start with one of them.
|
|
111
|
-
*/
|
|
112
|
-
function decodeBridgeError(message, codes) {
|
|
113
|
-
const [, code = "", detail = ""] = CODED_MESSAGE.exec(message) ?? [];
|
|
114
|
-
return codes.includes(code) ? {
|
|
115
|
-
code,
|
|
116
|
-
detail
|
|
117
|
-
} : void 0;
|
|
118
|
-
}
|
|
119
|
-
var THEME_MODES = ["light", "dark"];
|
|
120
|
-
var CONTROL_CHARACTER = /\p{Cc}/u;
|
|
121
|
-
/**
|
|
122
|
-
* Whether a value is a path that stays within the base it is resolved against, rather than
|
|
123
|
-
* escaping it. It must start with a single `/`, so it can't carry a scheme or be read as
|
|
124
|
-
* `//host`. It must not contain `\`, which URL parsers read as `/`, or any control character.
|
|
125
|
-
*/
|
|
126
|
-
function isContainedPath(value) {
|
|
127
|
-
return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
|
|
128
|
-
}
|
|
129
|
-
var APP_PATH_BASE = "https://app.invalid";
|
|
130
|
-
/**
|
|
131
|
-
* Returns an app path in the URL parser's normalised form, the one form Admin and the SDK
|
|
132
|
-
* store it in. `.` and `..` are resolved within the app, so a path can never climb out of it.
|
|
133
|
-
* Characters that need escaping are escaped once, so a path the app reported compares equal to
|
|
134
|
-
* the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and
|
|
135
|
-
* `/x/../episodes/1` becomes `/episodes/1`.
|
|
136
|
-
*
|
|
137
|
-
* Expects a path that `isContainedPath` accepts; anything else may not be a path within the
|
|
138
|
-
* app at all. `AppPathSchema` already returns this form, so Admin never calls this directly.
|
|
139
|
-
* The SDK, which doesn't load zod, does.
|
|
140
|
-
*/
|
|
141
|
-
function normaliseAppPath(path) {
|
|
142
|
-
const url = new URL(path, APP_PATH_BASE);
|
|
143
|
-
return `${url.pathname}${url.search}${url.hash}`;
|
|
144
|
-
}
|
|
145
|
-
/** An object, or an array: anything whose fields can be read. */
|
|
146
|
-
function isRecord(value) {
|
|
147
|
-
return typeof value === "object" && value !== null;
|
|
148
|
-
}
|
|
149
|
-
function hasStrings(value, keys) {
|
|
150
|
-
return isRecord(value) && keys.every((key) => typeof value[key] === "string");
|
|
151
|
-
}
|
|
152
|
-
function isTheme(value) {
|
|
153
|
-
return hasStrings(value, ["accent_color"]) && THEME_MODES.includes(value.mode);
|
|
154
|
-
}
|
|
155
|
-
function isStartContext(value) {
|
|
156
|
-
return isRecord(value) && hasStrings(value.site, [
|
|
157
|
-
"url",
|
|
158
|
-
"title",
|
|
159
|
-
"timezone",
|
|
160
|
-
"locale"
|
|
161
|
-
]) && hasStrings(value.user, ["id", "role"]) && isTheme(value.theme) && isRecord(value.session) && Number.isSafeInteger(value.session.revision) && value.session.revision >= 0 && isContainedPath(value.path);
|
|
162
|
-
}
|
|
163
|
-
function isConnectMessage(value) {
|
|
164
|
-
return isRecord(value) && value.type === "ghost-app:connect" && Array.isArray(value.exports) && value.exports.every((name) => typeof name === "string");
|
|
165
|
-
}
|
|
166
|
-
function isFetchResponse(value) {
|
|
167
|
-
return isRecord(value) && Number.isSafeInteger(value.status) && value.status >= 200 && value.status <= 599 && typeof value.statusText === "string" && isRecord(value.headers) && !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string") && typeof value.body === "string";
|
|
168
|
-
}
|
|
169
|
-
//#endregion
|
|
170
3
|
//#region src/errors.ts
|
|
171
4
|
/** The only error type the SDK rejects with, so an app can branch on `code`. */
|
|
172
5
|
var GhostAppError = class extends Error {
|
|
@@ -277,18 +110,43 @@ function toResponse(answer) {
|
|
|
277
110
|
//#endregion
|
|
278
111
|
//#region src/history.ts
|
|
279
112
|
/**
|
|
280
|
-
*
|
|
281
|
-
* stores app paths in.
|
|
113
|
+
* A URL's route: its path, query and fragment. The URL parser has already put them in the
|
|
114
|
+
* normalised form Admin stores app paths in. Resolving them again would read a path that starts
|
|
115
|
+
* with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that
|
|
116
|
+
* route fails `isContainedPath` and is never reported.
|
|
282
117
|
*/
|
|
118
|
+
function routeOf({ pathname, search, hash }) {
|
|
119
|
+
return `${pathname}${search}${hash}`;
|
|
120
|
+
}
|
|
121
|
+
/** The page's route. */
|
|
283
122
|
function currentRoute() {
|
|
284
|
-
|
|
285
|
-
return normaliseAppPath(`${pathname}${search}${hash}`);
|
|
123
|
+
return routeOf(window.location);
|
|
286
124
|
}
|
|
287
125
|
/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */
|
|
288
126
|
function isLink(node) {
|
|
289
127
|
return (node instanceof HTMLAnchorElement || node instanceof SVGElement && node.localName === "a") && node.hasAttribute("href");
|
|
290
128
|
}
|
|
291
129
|
/**
|
|
130
|
+
* Whether a route is one Admin would take. Admin owns the app's address, so the page never
|
|
131
|
+
* moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin
|
|
132
|
+
* link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is
|
|
133
|
+
* dropped, with a warning for the app's developer.
|
|
134
|
+
*/
|
|
135
|
+
function isContained(route) {
|
|
136
|
+
if (isContainedPath(route)) return true;
|
|
137
|
+
console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL
|
|
142
|
+
* parser can't read is left to the browser, which throws as it would without the SDK.
|
|
143
|
+
*/
|
|
144
|
+
function refuses(url) {
|
|
145
|
+
if (url === void 0 || url === null) return false;
|
|
146
|
+
const next = URL.parse(url, window.location.href);
|
|
147
|
+
return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
292
150
|
* Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,
|
|
293
151
|
* and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's
|
|
294
152
|
* entries, which left back steps that did nothing once the app's page opened again, and WebKit
|
|
@@ -301,6 +159,7 @@ function isLink(node) {
|
|
|
301
159
|
* - A click on a link to the app's own origin, which a router hasn't already handled, is reported
|
|
302
160
|
* as a push, and the page then loads the link's address in place of its own entry. A link that
|
|
303
161
|
* opens elsewhere (a `target`, `download`, or a modifier key) is left alone.
|
|
162
|
+
* - Neither is made to a route Admin would refuse, one that isn't contained.
|
|
304
163
|
* - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.
|
|
305
164
|
*
|
|
306
165
|
* Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the
|
|
@@ -321,10 +180,12 @@ function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
|
321
180
|
}
|
|
322
181
|
};
|
|
323
182
|
const push = (data, unused, url) => {
|
|
183
|
+
if (refuses(url)) return;
|
|
324
184
|
replaceState.call(history, data, unused, url);
|
|
325
185
|
report("push");
|
|
326
186
|
};
|
|
327
187
|
const replace = (data, unused, url) => {
|
|
188
|
+
if (refuses(url)) return;
|
|
328
189
|
replaceState.call(history, data, unused, url);
|
|
329
190
|
report("replace");
|
|
330
191
|
};
|
|
@@ -339,7 +200,8 @@ function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
|
339
200
|
if (url.origin !== window.location.origin) return;
|
|
340
201
|
event.preventDefault();
|
|
341
202
|
const go = () => load(url.href);
|
|
342
|
-
const next =
|
|
203
|
+
const next = routeOf(url);
|
|
204
|
+
if (!isContained(next)) return;
|
|
343
205
|
if (next === route) {
|
|
344
206
|
go();
|
|
345
207
|
return;
|
|
@@ -493,8 +355,9 @@ var Channel = class {
|
|
|
493
355
|
};
|
|
494
356
|
this.#theme = Object.freeze({ ...context.theme });
|
|
495
357
|
this.#history = watchHistory((route, move) => this.#moved(route, move));
|
|
496
|
-
|
|
497
|
-
|
|
358
|
+
const route = currentRoute();
|
|
359
|
+
this.#path = context.path;
|
|
360
|
+
if (route !== context.path) this.#moved(route, "replace");
|
|
498
361
|
if (this.#hostExports.has("titleChanged")) this.#stopWatchingTitle = watchTitle((title) => {
|
|
499
362
|
this.#call("titleChanged", title).catch(() => {});
|
|
500
363
|
});
|
|
@@ -518,6 +381,7 @@ var Channel = class {
|
|
|
518
381
|
* for the app, or has refused; a refused move leaves the page where it is.
|
|
519
382
|
*/
|
|
520
383
|
async #moved(route, move) {
|
|
384
|
+
if (!isContainedPath(route)) return;
|
|
521
385
|
this.#path = route;
|
|
522
386
|
this.#moves += 1;
|
|
523
387
|
const thisMove = this.#moves;
|
|
@@ -626,7 +490,7 @@ var Channel = class {
|
|
|
626
490
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
627
491
|
* and doesn't read package.json.
|
|
628
492
|
*/
|
|
629
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
493
|
+
var SDK_VERSION = "0.1.0-alpha.10";
|
|
630
494
|
//#endregion
|
|
631
495
|
//#region src/connect.ts
|
|
632
496
|
/**
|