@tryghost/app-sdk 0.1.0-alpha.8 → 0.1.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -6
- package/build/backend.js +2 -1
- package/build/backend.js.map +1 -1
- package/build/bin.js +3 -2
- package/build/bin.js.map +1 -1
- package/build/chunks/{manifest-DX1GTozy.js → body-CshsXE1J.js} +3 -75
- package/build/chunks/body-CshsXE1J.js.map +1 -0
- package/build/chunks/check-3oU5pDJc.js +208 -0
- package/build/chunks/check-3oU5pDJc.js.map +1 -0
- package/build/chunks/manifest-iOwbzAil.js +77 -0
- package/build/chunks/manifest-iOwbzAil.js.map +1 -0
- package/build/chunks/{sign-BhNJAPta.js → sign-DygdzQYY.js} +3 -205
- package/build/chunks/sign-DygdzQYY.js.map +1 -0
- package/build/index.js +1 -1
- package/build/tooling.js +3 -2
- 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 +1 -1
- package/package.json +13 -1
- package/build/chunks/manifest-DX1GTozy.js.map +0 -1
- package/build/chunks/sign-BhNJAPta.js.map +0 -1
package/build/vite.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { D as isValidAppId, O as isLocalhost, a as signProject, c as KEYS_DIRECTORY, f as keyFile, g as signingKeySource, m as readBackendKey, o as BACKEND_KEY_VARIABLE, r as serialiseSigned, s as IDENTITY_KEY_VARIABLE, u as createKeys } from "./chunks/sign-DygdzQYY.js";
|
|
2
|
+
import { a as parseJsonText, o as parseOrigin, r as formatErrors, t as MANIFEST_PATH } from "./chunks/manifest-iOwbzAil.js";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { appendFile, readFile } from "node:fs/promises";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
//#region src/vite/deny.ts
|
|
7
|
+
var VITE_DEFAULT_DENY = [
|
|
8
|
+
".env",
|
|
9
|
+
".env.*",
|
|
10
|
+
"*.{crt,pem,key,p12,pfx,cer,der}",
|
|
11
|
+
".npmrc",
|
|
12
|
+
".yarnrc.yml",
|
|
13
|
+
"**/.git/**"
|
|
14
|
+
];
|
|
15
|
+
var DENY = [
|
|
16
|
+
"**/.ghost-app/**",
|
|
17
|
+
".dev.vars*",
|
|
18
|
+
".env",
|
|
19
|
+
".env.*"
|
|
20
|
+
];
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/vite/dev-vars.ts
|
|
23
|
+
var WRANGLER_CONFIGS = [
|
|
24
|
+
"wrangler.json",
|
|
25
|
+
"wrangler.jsonc",
|
|
26
|
+
"wrangler.toml"
|
|
27
|
+
];
|
|
28
|
+
var DEV_VARS = ".dev.vars";
|
|
29
|
+
/**
|
|
30
|
+
* Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as
|
|
31
|
+
* `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development
|
|
32
|
+
* as it does in production. Returns what to tell the developer, if anything.
|
|
33
|
+
*/
|
|
34
|
+
async function provideDevBackendKey(root) {
|
|
35
|
+
const there = (file) => existsSync(join(root, file));
|
|
36
|
+
if (!WRANGLER_CONFIGS.some(there)) return;
|
|
37
|
+
const key = await readBackendKey({
|
|
38
|
+
root,
|
|
39
|
+
mode: "development"
|
|
40
|
+
});
|
|
41
|
+
const read = there(DEV_VARS) ? [DEV_VARS] : [".env.local", ".env"].filter(there);
|
|
42
|
+
let last = "";
|
|
43
|
+
for (const file of read) {
|
|
44
|
+
last = await readFile(join(root, file), "utf8");
|
|
45
|
+
if (last.includes("GHOST_APP_BACKEND_KEY")) return last.includes(key.x) ? void 0 : {
|
|
46
|
+
level: "warn",
|
|
47
|
+
message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile("development", "backend")}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (read.length > 0 && read[0] !== DEV_VARS) return {
|
|
51
|
+
level: "warn",
|
|
52
|
+
message: `Wrangler reads ${read.join(" and ")} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \`ghost-app backend-key\`, so the Worker can answer Ghost's challenge.`
|
|
53
|
+
};
|
|
54
|
+
const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\n`;
|
|
55
|
+
await appendFile(join(root, DEV_VARS), `${last && !last.endsWith("\n") ? "\n" : ""}${line}`, { mode: 384 });
|
|
56
|
+
return {
|
|
57
|
+
level: "info",
|
|
58
|
+
message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/vite/index.ts
|
|
63
|
+
/**
|
|
64
|
+
* A Vite plugin that serves and builds an app's signed manifest.
|
|
65
|
+
*
|
|
66
|
+
* ```ts
|
|
67
|
+
* import { cloudflare } from '@cloudflare/vite-plugin';
|
|
68
|
+
* import { ghostApp } from '@tryghost/app-sdk/vite';
|
|
69
|
+
* import { defineConfig } from 'vite';
|
|
70
|
+
*
|
|
71
|
+
* export default defineConfig({ plugins: [ghostApp(), cloudflare()] });
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
function readTunnels(input) {
|
|
75
|
+
return (typeof input === "string" ? input.split(",") : input ?? []).map((entry) => entry.trim()).filter(Boolean).map((entry) => {
|
|
76
|
+
const origin = parseOrigin(entry);
|
|
77
|
+
if (!origin) throw new Error(`ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`);
|
|
78
|
+
return origin;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The name `vite dev` prints the app at, such as `hello-world.localhost` for
|
|
83
|
+
* `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.
|
|
84
|
+
*/
|
|
85
|
+
function devHostname(manifestFile) {
|
|
86
|
+
try {
|
|
87
|
+
const { id } = parseJsonText(readFileSync(manifestFile, "utf8"));
|
|
88
|
+
if (isValidAppId(id)) return `${id.slice(id.lastIndexOf(".") + 1)}.localhost`;
|
|
89
|
+
} catch {}
|
|
90
|
+
return "app.localhost";
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build
|
|
94
|
+
* emits it:
|
|
95
|
+
*
|
|
96
|
+
* - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves
|
|
97
|
+
* `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one
|
|
98
|
+
* of the tunnels it's told about. In a Cloudflare Workers project, it adds the development
|
|
99
|
+
* backend key to `.dev.vars`.
|
|
100
|
+
* - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the
|
|
101
|
+
* client build.
|
|
102
|
+
*
|
|
103
|
+
* List it before `cloudflare()`.
|
|
104
|
+
*/
|
|
105
|
+
function ghostApp(options = {}) {
|
|
106
|
+
const manifestFile = options.manifest ?? "ghost-app.json";
|
|
107
|
+
let tunnels = [];
|
|
108
|
+
let appUrl;
|
|
109
|
+
let ghostUrl;
|
|
110
|
+
let config;
|
|
111
|
+
let pending;
|
|
112
|
+
let dev = false;
|
|
113
|
+
/** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */
|
|
114
|
+
function manifestUrlFor(host) {
|
|
115
|
+
const url = URL.parse(`${config.server.https ? "https" : "http"}://${host ?? ""}`);
|
|
116
|
+
const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);
|
|
117
|
+
if (tunnel) return `${tunnel}${MANIFEST_PATH}`;
|
|
118
|
+
return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : void 0;
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
name: "@tryghost/app-sdk/vite",
|
|
122
|
+
enforce: "pre",
|
|
123
|
+
async config(userConfig, { command, isPreview, mode }) {
|
|
124
|
+
const root = resolve(userConfig.root ?? "");
|
|
125
|
+
const { loadEnv } = await import("vite");
|
|
126
|
+
const env = userConfig.envDir === false ? process.env : loadEnv(mode, resolve(root, userConfig.envDir ?? ""), [
|
|
127
|
+
"GHOST_APP_URL",
|
|
128
|
+
"GHOST_APP_TUNNEL_URL",
|
|
129
|
+
"GHOST_URL"
|
|
130
|
+
]);
|
|
131
|
+
appUrl = env.GHOST_APP_URL?.trim() || void 0;
|
|
132
|
+
ghostUrl = env.GHOST_URL?.trim() || void 0;
|
|
133
|
+
if (command !== "serve" || isPreview) return;
|
|
134
|
+
tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);
|
|
135
|
+
dev = !process.env.VITEST && mode !== "test";
|
|
136
|
+
if (dev) {
|
|
137
|
+
await createKeys({
|
|
138
|
+
root,
|
|
139
|
+
mode: "development"
|
|
140
|
+
});
|
|
141
|
+
pending = await provideDevBackendKey(root);
|
|
142
|
+
}
|
|
143
|
+
return { server: {
|
|
144
|
+
fs: { deny: [...userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY, ...DENY] },
|
|
145
|
+
...tunnels.length > 0 && userConfig.server?.allowedHosts !== true ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) } : {}
|
|
146
|
+
} };
|
|
147
|
+
},
|
|
148
|
+
configResolved(resolved) {
|
|
149
|
+
config = resolved;
|
|
150
|
+
const exposed = [resolved.envPrefix ?? "VITE_"].flat().find((prefix) => [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)));
|
|
151
|
+
if (exposed !== void 0) throw new Error(`ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`);
|
|
152
|
+
if (dev && !resolved.server.fs.strict) throw new Error(`ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`);
|
|
153
|
+
if (pending) config.logger[pending.level](`ghost-app: ${pending.message}`);
|
|
154
|
+
},
|
|
155
|
+
configureServer(server) {
|
|
156
|
+
server.middlewares.use((req, res, next) => {
|
|
157
|
+
if (req.url?.split("?")[0] !== "/ghost-app.json" || !["GET", "HEAD"].includes(req.method)) {
|
|
158
|
+
next();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const host = req.headers.host ?? req.headers[":authority"];
|
|
162
|
+
const manifestUrl = manifestUrlFor(host);
|
|
163
|
+
if (!manifestUrl) {
|
|
164
|
+
const allowed = ["this machine", ...tunnels.map((origin) => new URL(origin).host)];
|
|
165
|
+
res.statusCode = 421;
|
|
166
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
167
|
+
res.end(`The dev server signs ghost-app.json only for ${allowed.join(", ")}, not ${host ?? "a request without a Host"}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\n`);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
signProject({
|
|
171
|
+
root: config.root,
|
|
172
|
+
mode: "development",
|
|
173
|
+
manifestUrl,
|
|
174
|
+
manifestFile
|
|
175
|
+
}).then((result) => {
|
|
176
|
+
if (!result.success) throw new Error(`${manifestFile} can't be signed:\n${formatErrors(result.errors)}`);
|
|
177
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
178
|
+
res.setHeader("cache-control", "no-store");
|
|
179
|
+
res.end(req.method === "HEAD" ? void 0 : serialiseSigned(result.signed));
|
|
180
|
+
}).catch((error) => {
|
|
181
|
+
const message = `ghost-app: ${error.message}`;
|
|
182
|
+
config.logger.error(message, { timestamp: true });
|
|
183
|
+
res.statusCode = 500;
|
|
184
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
185
|
+
res.end(`${message}\n`);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
const printUrls = server.printUrls.bind(server);
|
|
189
|
+
server.printUrls = () => {
|
|
190
|
+
printUrls();
|
|
191
|
+
const address = server.httpServer?.address();
|
|
192
|
+
const port = typeof address === "object" && address ? address.port : void 0;
|
|
193
|
+
const local = `${config.server.https ? "https" : "http"}://${devHostname(resolve(config.root, manifestFile))}:${port}`;
|
|
194
|
+
const ghost = (ghostUrl ?? "http://localhost:2368").replace(/\/+$/, "");
|
|
195
|
+
const lines = [...port ? [local] : [], ...tunnels].flatMap((origin) => [` Ghost app: ${origin}${MANIFEST_PATH}`, ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`]);
|
|
196
|
+
config.logger.info(`\n${lines.join("\n")}\n`);
|
|
197
|
+
};
|
|
198
|
+
},
|
|
199
|
+
async buildStart() {
|
|
200
|
+
if (config.command !== "build" || this.environment.config.consumer !== "client") return;
|
|
201
|
+
if (!appUrl) {
|
|
202
|
+
config.logger.warn(`ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const base = URL.parse(appUrl.endsWith("/") ? appUrl : `${appUrl}/`);
|
|
206
|
+
if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) this.error(`ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`);
|
|
207
|
+
const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;
|
|
208
|
+
this.addWatchFile(resolve(config.root, manifestFile));
|
|
209
|
+
const result = await signProject({
|
|
210
|
+
root: config.root,
|
|
211
|
+
mode: "production",
|
|
212
|
+
manifestUrl,
|
|
213
|
+
manifestFile
|
|
214
|
+
}).catch((error) => this.error(`ghost-app: ${error.message}`));
|
|
215
|
+
if (!result.success) this.error(`ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\n${formatErrors(result.errors)}`);
|
|
216
|
+
this.emitFile({
|
|
217
|
+
type: "asset",
|
|
218
|
+
fileName: MANIFEST_PATH.slice(1),
|
|
219
|
+
source: serialiseSigned(result.signed)
|
|
220
|
+
});
|
|
221
|
+
config.logger.info(`ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource("production", "identity")}`);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
226
|
+
export { ghostApp };
|
|
227
|
+
|
|
228
|
+
//# sourceMappingURL=vite.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH, formatErrors } from '../shared/manifest.ts';\nimport { parseJsonText, parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CAAC;CAAoB;CAAc;CAAQ;AAAQ;;;ACZvE,IAAM,mBAAmB;CAAC;CAAiB;CAAkB;AAAe;AAE5E,IAAM,WAAW;;;;;;AAOjB,eAAsB,qBACpB,MACkE;CAClE,MAAM,SAAS,SAAiB,WAAW,KAAK,MAAM,IAAI,CAAC;CAC3D,IAAI,CAAC,iBAAiB,KAAK,KAAK,GAC9B;CAEF,MAAM,MAAM,MAAM,eAAe;EAAE;EAAM,MAAM;CAAc,CAAC;CAG9D,MAAM,OAAO,MAAM,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,cAAc,MAAM,CAAC,CAAC,OAAO,KAAK;CAC/E,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;EACvB,OAAO,MAAM,SAAS,KAAK,MAAM,IAAI,GAAG,MAAM;EAC9C,IAAI,KAAK,SAAA,uBAA6B,GAEpC,OAAO,KAAK,SAAS,IAAI,CAAC,I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AAK,MAAM,GACjE,KAAK,MACH,mGAAmG,QACrG;GAEF,MAAM,cAAc,IAAI,IAAI,cAAc,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;GAE1D,KAAK,aAAa,QAAQ,OAAO,MAAM,YAAY,CAAC;GACpD,MAAM,SAAS,MAAM,YAAY;IAC/B,MAAM,OAAO;IACb,MAAM;IACN;IACA;GACF,CAAC,CAAC,CAAC,OAAO,UAAmB,KAAK,MAAM,cAAe,MAAgB,SAAS,CAAC;GACjF,IAAI,CAAC,OAAO,SACV,KAAK,MACH,cAAc,aAAa,uBAAuB,YAAY,KAAK,aAAa,OAAO,MAAM,GAC/F;GAEF,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,cAAc,MAAM,CAAC;IAC/B,QAAQ,gBAAgB,OAAO,MAAM;GACvC,CAAC;GACD,OAAO,OAAO,KACZ,wCAAwC,YAAY,QAAQ,iBAAiB,cAAc,UAAU,GACvG;EACF;CACF;AACF"}
|
package/dist/app-sdk.js
CHANGED
|
@@ -1218,7 +1218,7 @@ var Channel = class {
|
|
|
1218
1218
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
1219
1219
|
* and doesn't read package.json.
|
|
1220
1220
|
*/
|
|
1221
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
1221
|
+
var SDK_VERSION = "0.1.0-alpha.9";
|
|
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.
|
|
3
|
+
"version": "0.1.0-alpha.9",
|
|
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",
|
|
@@ -31,6 +31,10 @@
|
|
|
31
31
|
"./tooling": {
|
|
32
32
|
"types": "./build/tooling.d.ts",
|
|
33
33
|
"default": "./build/tooling.js"
|
|
34
|
+
},
|
|
35
|
+
"./vite": {
|
|
36
|
+
"types": "./build/vite.d.ts",
|
|
37
|
+
"default": "./build/vite.js"
|
|
34
38
|
}
|
|
35
39
|
},
|
|
36
40
|
"dependencies": {
|
|
@@ -39,6 +43,14 @@
|
|
|
39
43
|
"jose": "6.2.15",
|
|
40
44
|
"zod": "4.6.7"
|
|
41
45
|
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"vite": ">=6"
|
|
48
|
+
},
|
|
49
|
+
"peerDependenciesMeta": {
|
|
50
|
+
"vite": {
|
|
51
|
+
"optional": true
|
|
52
|
+
}
|
|
53
|
+
},
|
|
42
54
|
"engines": {
|
|
43
55
|
"node": ">=22.12"
|
|
44
56
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"manifest-DX1GTozy.js","names":[],"sources":["../../../app-contracts/build/identity/keys.js","../../../app-contracts/build/identity/jws.js","../../../app-contracts/build/identity/challenge.js","../../src/shared/parse.ts","../../src/shared/ignore.ts","../../src/shared/body.ts","../../src/shared/manifest.ts"],"sourcesContent":["import { base64url, calculateJwkThumbprint } from 'jose';\n/**\n * A key's RFC 7638 thumbprint: the same for a key however its JWK is written, so it is\n * what Ghost stores to recognise a key again.\n */\nexport function thumbprintOf(key) {\n return calculateJwkThumbprint({ kty: key.kty, crv: key.crv, x: key.x }, 'sha256');\n}\nexport function decodeUtf8(bytes) {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\nexport function decodeText(encoded) {\n try {\n return decodeUtf8(base64url.decode(encoded));\n }\n catch {\n return undefined;\n }\n}\nexport function decodeJson(encoded) {\n const text = decodeText(encoded);\n if (text === undefined) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=keys.js.map","import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","import { CompactSign, base64url, compactVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeUtf8 } from './keys.js';\n/** Where on an origin Ghost posts a challenge. */\nexport const CHALLENGE_PATH = '/.well-known/ghost-app/challenge';\n/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */\nexport const CHALLENGE_PURPOSE = 'ghost-app-challenge';\nconst NONCE_BYTES = 32;\nconst ProtectedHeader = z.strictObject({ alg: z.literal(ALGORITHM) });\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM });\nconst ChallengeShape = z.strictObject({\n purpose: z.literal(CHALLENGE_PURPOSE),\n origin: z.string(),\n nonce: z.string(),\n});\nconst ChallengeAnswerShape = z.object({ signature: z.string() });\n/** The URL to post a challenge for an origin to. */\nexport function challengeUrl(origin) {\n return new URL(CHALLENGE_PATH, origin).href;\n}\n/** A fresh challenge for an origin, as the exact text to post and to verify the answer with. */\nexport function createChallenge(origin) {\n const challenge = {\n purpose: CHALLENGE_PURPOSE,\n origin: new URL(origin).origin,\n nonce: base64url.encode(crypto.getRandomValues(new Uint8Array(NONCE_BYTES))),\n };\n return JSON.stringify(challenge);\n}\n/**\n * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is\n * the URL the request arrived at, as the platform reports it (`request.url` on Workers):\n * never one built from `X-Forwarded-Host` or any other header the sender controls. A\n * challenge for any origin but that one is refused, so whoever takes over a name the app\n * used to serve can't relay Ghost's challenge to the real backend to prove it.\n *\n * Ghost can't see this check, so it only helps where the platform routes requests by host,\n * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.\n */\nexport async function answerChallenge(body, { backendKey, requestUrl }) {\n const challenge = ChallengeShape.safeParse(parseJson(body));\n if (!challenge.success) {\n return { success: false, error: 'Expected a challenge of {purpose, origin, nonce}' };\n }\n const arrivedAt = URL.parse(requestUrl)?.origin;\n if (arrivedAt !== challenge.data.origin) {\n return {\n success: false,\n error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? 'an unknown origin'}`,\n };\n }\n const signature = await new CompactSign(new TextEncoder().encode(body))\n .setProtectedHeader({ alg: ALGORITHM })\n .sign(backendKey);\n return { success: true, answer: { signature } };\n}\n/**\n * Checks an origin's answer to a challenge: a signature with the backend key over the\n * exact text Ghost posted, under a protected header of only `alg`. The error only says how\n * the answer fell short.\n */\nexport async function verifyChallengeAnswer(challenge, answer, backendKey) {\n const parsed = ChallengeAnswerShape.safeParse(parseJson(answer));\n if (!parsed.success) {\n return { success: false, error: 'Expected an answer of {\"signature\": \"<compact JWS>\"}' };\n }\n let key;\n try {\n key = await importJWK(backendKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'backend_key is not a usable Ed25519 key' };\n }\n const [header = ''] = parsed.data.signature.split('.');\n if (!readExactHeader(header, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n let payload;\n try {\n ({ payload } = await compactVerify(parsed.data.signature, key, { algorithms: [ALGORITHM] }));\n }\n catch {\n return { success: false, error: 'The signature was not made with backend_key' };\n }\n if (!sameText(payload, challenge)) {\n return { success: false, error: 'The signature is not over the challenge that was sent' };\n }\n return { success: true };\n}\nfunction sameText(bytes, text) {\n try {\n return decodeUtf8(bytes) === text;\n }\n catch {\n return false;\n }\n}\nfunction parseJson(text) {\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=challenge.js.map","// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text: string): unknown {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","import { ignoreError } from './ignore.ts';\n\n/**\n * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It\n * stops reading as soon as the body passes the limit, so a large body is never held whole.\n */\nexport async function readBytes(\n message: Request | Response,\n maxBytes: number,\n): Promise<Uint8Array | undefined> {\n if (Number(message.headers.get('content-length')) > maxBytes) {\n // Too large either way, so a body that refuses to be cancelled changes nothing. Not waited\n // for: one branch of a teed body, as a cloned request's is, cancels only once the other does.\n message.body?.cancel().catch(ignoreError);\n return undefined;\n }\n if (!message.body) {\n return new Uint8Array();\n }\n const reader = message.body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n length += value.byteLength;\n if (length > maxBytes) {\n reader.cancel().catch(ignoreError);\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n\n/** One problem with a manifest. */\nexport interface ManifestError {\n /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */\n path: string;\n message: string;\n}\n\n/**\n * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but\n * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost\n * applies them.\n */\nexport const UNKNOWN_GHOST_URL = 'https://ghost.invalid/';\n\n/** A manifest's problems, one per line, as `path: message`. */\nexport function formatErrors(errors: readonly ManifestError[], separator = '\\n'): string {\n return errors\n .map(({ path, message }) => (path ? `${path}: ${message}` : message))\n .join(separator);\n}\n"],"mappings":";;;AAQA,SAAgB,WAAW,OAAO;CAC9B,OAAO,IAAI,YAAY,SAAS;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AAClF;AACA,SAAgB,WAAW,SAAS;CAChC,IAAI;EACA,OAAO,WAAW,UAAU,OAAO,OAAO,CAAC;CAC/C,QACM;EACF;CACJ;AACJ;AACA,SAAgB,WAAW,SAAS;CAChC,MAAM,OAAO,WAAW,OAAO;CAC/B,IAAI,SAAS,KAAA,GACT;CAEJ,IAAI;EACA,OAAO,KAAK,MAAM,IAAI;CAC1B,QACM;EACF;CACJ;AACJ;;;;AC5BA,IAAa,YAAY;;;;;;AAMzB,SAAgB,gBAAgB,SAAS,OAAO;CAC5C,MAAM,SAAS,MAAM,UAAU,WAAW,OAAO,CAAC;CAClD,OAAO,OAAO,UAAU,OAAO,OAAO,KAAA;AAC1C;;;;ACNA,IAAa,iBAAiB;;AAE9B,IAAa,oBAAoB;AACjC,IAAM,cAAc;AACpB,IAAM,kBAAkB,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,SAAS,EAAE,C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AACxE;;;;AC3BA,IAAa,oBAA+B,KAAA;;;;;;;ACK5C,eAAsB,UACpB,SACA,UACiC;CACjC,IAAI,OAAO,QAAQ,QAAQ,IAAI,gBAAgB,CAAC,IAAI,UAAU;EAG5D,QAAQ,MAAM,OAAO,CAAC,CAAC,MAAM,WAAW;EACxC;CACF;CACA,IAAI,CAAC,QAAQ,MACX,uBAAO,IAAI,WAAW;CAExB,MAAM,SAAS,QAAQ,KAAK,UAAU;CACtC,MAAM,SAAuB,CAAC;CAC9B,IAAI,SAAS;CACb,SAAS;EACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;EAC1C,IAAI,MACF;EAEF,UAAU,MAAM;EAChB,IAAI,SAAS,UAAU;GACrB,OAAO,OAAO,CAAC,CAAC,MAAM,WAAW;GACjC;EACF;EACA,OAAO,KAAK,KAAK;CACnB;CACA,MAAM,QAAQ,IAAI,WAAW,MAAM;CACnC,IAAI,SAAS;CACb,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,IAAI,OAAO,MAAM;EACvB,UAAU,MAAM;CAClB;CACA,OAAO;AACT;;;;ACrCA,IAAa,gBAAgB;;;;;;AAqB7B,IAAa,oBAAoB;;AAGjC,SAAgB,aAAa,QAAkC,YAAY,MAAc;CACvF,OAAO,OACJ,KAAK,EAAE,MAAM,cAAe,OAAO,GAAG,KAAK,IAAI,YAAY,OAAQ,CAAC,CACpE,KAAK,SAAS;AACnB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sign-BhNJAPta.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","../../../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/check.ts","../../src/tooling/git.ts","../../src/tooling/keys.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 { 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 an app with, from App Installations in Ghost core, which doesn't\n// export them to apps.\n\n/** How long Ghost waits for each read from an app, redirects and body included. */\nexport const TIMEOUT_MS = 5000;\n\n/** How many redirects on the same host Ghost follows for a manifest. */\nexport const MAX_REDIRECTS = 3;\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/** The largest answer to a challenge Ghost reads. */\nexport const ANSWER_MAX_BYTES = 4 * 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 {\n challengeUrl,\n createChallenge,\n readSignedManifest,\n verifyChallengeAnswer,\n verifySignedManifest,\n} from '@tryghost/app-contracts/identity';\nimport { parseManifest, parseManifestUrl } from '@tryghost/app-contracts/manifest';\n\nimport { readBytes } from '../shared/body.ts';\nimport { ignoreError } from '../shared/ignore.ts';\nimport { UNKNOWN_GHOST_URL, formatErrors } from '../shared/manifest.ts';\nimport { parseJsonText } from '../shared/parse.ts';\nimport type { PublicKeyJwk } from './keys.ts';\nimport {\n ANSWER_MAX_BYTES,\n MANIFEST_MAX_BYTES,\n MAX_REDIRECTS,\n SIGNED_MANIFEST_MAX_BYTES,\n TIMEOUT_MS,\n storedSize,\n tooLargeMessage,\n} from './limits.ts';\nimport type { AppManifest, ManifestError } from './types.ts';\n\n/** The codes Ghost refuses an app with, which `checkApp` reports the same problems with. */\nexport type CheckCode =\n | 'APP_MANIFEST_URL_INVALID'\n | 'APP_MANIFEST_UNREACHABLE'\n | 'APP_MANIFEST_REDIRECTED'\n | 'APP_MANIFEST_TOO_LARGE'\n | 'APP_MANIFEST_NOT_JSON'\n | 'APP_MANIFEST_UNSIGNED'\n | 'APP_MANIFEST_URL_MISMATCH'\n | 'APP_MANIFEST_INVALID'\n | 'APP_MANIFEST_SIGNATURE_INVALID'\n | 'APP_CHALLENGE_UNREACHABLE'\n | 'APP_CHALLENGE_FAILED';\n\n/** What `checkApp` resolves with: the manifest Ghost would install, or why Ghost would refuse. */\nexport type CheckResult =\n | {\n success: true;\n manifestUrl: string;\n /** The manifest as Ghost parses it, with every path resolved. */\n manifest: AppManifest;\n }\n | {\n success: false;\n code: CheckCode;\n /** Ghost's own message for the code. */\n message: string;\n /** What exactly was wrong. Unlike Ghost, it says why a request failed. */\n detail: string;\n /** For `APP_MANIFEST_INVALID`, each problem by the path to its field. */\n errors?: ManifestError[];\n };\n\nexport interface CheckOptions {\n /** The fetch to make requests with. Node's own, by default. */\n fetch?: typeof fetch;\n}\n\ntype Fetch = typeof fetch;\n\n// Ghost's own message for each code.\nconst MESSAGES: Record<CheckCode, string> = {\n APP_MANIFEST_URL_INVALID: 'The app manifest URL is not valid.',\n APP_MANIFEST_UNREACHABLE: 'Could not load the app’s manifest.',\n APP_MANIFEST_REDIRECTED: 'The app’s manifest redirects to another host.',\n APP_MANIFEST_TOO_LARGE: `The app’s manifest is larger than ${MANIFEST_MAX_BYTES / 1024} KB.`,\n APP_MANIFEST_NOT_JSON: 'The app’s manifest is not JSON.',\n APP_MANIFEST_UNSIGNED: 'The app’s manifest is not signed.',\n APP_MANIFEST_URL_MISMATCH: 'The app’s manifest is for another address.',\n APP_MANIFEST_INVALID: 'The app manifest is not valid.',\n APP_MANIFEST_SIGNATURE_INVALID: 'The app’s manifest signature is not valid.',\n APP_CHALLENGE_UNREACHABLE: 'Could not reach the app to confirm it comes from its developer.',\n APP_CHALLENGE_FAILED: 'Ghost couldn’t confirm the app comes from its developer.',\n};\n\n/** Thrown by any step, and turned into a failed `CheckResult` by `checkApp`. */\nclass Failure extends Error {\n constructor(\n readonly code: CheckCode,\n readonly detail: string,\n readonly errors?: ManifestError[],\n ) {\n super(MESSAGES[code]);\n }\n}\n\n/**\n * Checks an app as Ghost does before installing it, and resolves with the code Ghost would\n * refuse it with, or the manifest Ghost would install.\n */\nexport async function checkApp(\n manifestUrl: string,\n { fetch: fetchFn = globalThis.fetch }: CheckOptions = {},\n): Promise<CheckResult> {\n try {\n return await runChecks(manifestUrl, fetchFn);\n } catch (error) {\n if (!(error instanceof Failure)) {\n throw error;\n }\n return {\n success: false,\n code: error.code,\n message: error.message,\n detail: error.detail,\n ...(error.errors ? { errors: error.errors } : {}),\n };\n }\n}\n\n// The steps run in the order Ghost runs them, so the first failure is the one Ghost would report.\n// Some things only a site knows can't be checked: Ghost's own hosts, the identity key the site\n// installed the app with, and backend keys a newer manifest replaced.\nasync function runChecks(input: string, fetchFn: Fetch): Promise<CheckResult> {\n const manifestUrl = readManifestUrl(input);\n const body = await fetchManifest(manifestUrl, fetchFn);\n const signed = readSigned(body, manifestUrl);\n const manifest = parse(signed.payload, manifestUrl);\n await verifySignature(signed.signed, manifest);\n checkStoredSize(manifest, manifestUrl);\n // Sent even to localhost, which Ghost in development skips, so a backend is checked before\n // it's deployed.\n await challenge(new URL(manifestUrl).origin, manifest.backend_key, fetchFn);\n return { success: true, manifestUrl, manifest };\n}\n\nfunction readManifestUrl(input: string): string {\n // The site's own URL is a name no site has, as only a site knows its own hosts.\n const address = parseManifestUrl(input, { ghostUrls: [UNKNOWN_GHOST_URL], allowLocalhost: true });\n if (!address.success) {\n throw new Failure('APP_MANIFEST_URL_INVALID', address.error);\n }\n return address.manifestUrl;\n}\n\n/** The signed manifest's bytes, following redirects on the same host, as Ghost does. */\nasync function fetchManifest(manifestUrl: string, fetchFn: Fetch): Promise<Uint8Array> {\n // One deadline for the whole read, redirects included, as in Ghost, so a slow app can't stall\n // it several times over.\n const signal = AbortSignal.timeout(TIMEOUT_MS);\n let current = new URL(manifestUrl);\n for (let redirects = 0; ; redirects++) {\n const answer = await fetchOnce(fetchFn, current, {\n init: { headers: { accept: 'application/json' }, signal },\n maxBytes: SIGNED_MANIFEST_MAX_BYTES,\n code: 'APP_MANIFEST_UNREACHABLE',\n // A redirect's or an error's body is dropped unread, as Ghost drops it.\n wantsBody: isSuccess,\n });\n // Ghost's HTTP client follows only these, and treats any other status as an answer.\n if (REDIRECT_STATUSES.has(answer.status) && answer.location !== null) {\n current = followRedirect(manifestUrl, current, answer.status, answer.location, redirects);\n continue;\n }\n if (!isSuccess(answer.status)) {\n throw new Failure(\n 'APP_MANIFEST_UNREACHABLE',\n `${current.href} answered with HTTP ${answer.status}`,\n );\n }\n if (!answer.body) {\n throw new Failure('APP_MANIFEST_TOO_LARGE', manifestUrl);\n }\n return answer.body;\n }\n}\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\n/** The URL a redirect leads to, if Ghost would follow it. */\nfunction followRedirect(\n manifestUrl: string,\n current: URL,\n status: number,\n location: string,\n redirects: number,\n): URL {\n // Headers arrive as latin1, and Ghost reads the Location as UTF-8, as got and browsers do.\n const target = URL.parse(Buffer.from(location, 'binary').toString('utf8'), current);\n if (!target) {\n throw new Failure(\n 'APP_MANIFEST_UNREACHABLE',\n `${manifestUrl} answered with HTTP ${status} and a Location that is not a URL`,\n );\n }\n if (!staysOnHost(current, target)) {\n throw new Failure('APP_MANIFEST_REDIRECTED', `${manifestUrl} redirects to ${target.host}`);\n }\n if (redirects === MAX_REDIRECTS) {\n throw new Failure(\n 'APP_MANIFEST_UNREACHABLE',\n `${manifestUrl} redirects more than ${MAX_REDIRECTS} times`,\n );\n }\n // Ghost drops credentials from a Location, as browsers do, and fetch would refuse them.\n target.username = '';\n target.password = '';\n return target;\n}\n\n/** Ghost follows a redirect on the same origin, or from HTTP to HTTPS on the same host. */\nfunction staysOnHost(from: URL, to: URL): boolean {\n if (to.origin === from.origin) {\n return true;\n }\n return (\n from.protocol === 'http:' &&\n to.protocol === 'https:' &&\n to.hostname === from.hostname &&\n from.port === '' &&\n to.port === ''\n );\n}\n\nfunction readSigned(body: Uint8Array, manifestUrl: string) {\n const signed = readSignedManifest(parseJson(decode(body), manifestUrl));\n if (!signed.success) {\n throw new Failure('APP_MANIFEST_UNSIGNED', signed.error);\n }\n return signed;\n}\n\nfunction parse(payload: string, manifestUrl: string): AppManifest {\n const parsed = parseManifest(parseJson(payload, manifestUrl), {\n manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (parsed.success) {\n return parsed.manifest;\n }\n const detail = formatErrors(parsed.errors, '; ');\n // A manifest signed for another address has its own code, as it's the usual mistake.\n if (parsed.reason === 'manifest_url_mismatch') {\n throw new Failure('APP_MANIFEST_URL_MISMATCH', detail);\n }\n throw new Failure('APP_MANIFEST_INVALID', detail, parsed.errors);\n}\n\nasync function verifySignature(\n signed: Parameters<typeof verifySignedManifest>[0],\n manifest: AppManifest,\n) {\n // With the identity key the manifest names: a site installing the app pins it from here.\n const verified = await verifySignedManifest(signed, manifest.identity_key);\n if (!verified.success) {\n throw new Failure('APP_MANIFEST_SIGNATURE_INVALID', verified.error);\n }\n}\n\nfunction checkStoredSize(manifest: AppManifest, manifestUrl: string) {\n // Ghost measures what it stores, with the paths resolved, after verifying the signature.\n if (storedSize(manifest) > MANIFEST_MAX_BYTES) {\n throw new Failure('APP_MANIFEST_TOO_LARGE', `${manifestUrl}: ${tooLargeMessage()}`);\n }\n}\n\n/** Sends Ghost's challenge to the app's origin, and verifies the answer with the backend key. */\nasync function challenge(origin: string, backendKey: PublicKeyJwk, fetchFn: Fetch) {\n const sent = createChallenge(origin);\n const answer = await fetchOnce(fetchFn, challengeUrl(origin), {\n init: {\n method: 'POST',\n body: sent,\n headers: { accept: 'application/json', 'content-type': 'application/json' },\n signal: AbortSignal.timeout(TIMEOUT_MS),\n },\n maxBytes: ANSWER_MAX_BYTES,\n code: 'APP_CHALLENGE_UNREACHABLE',\n // Read whatever the status, for the backend's explanation of a refusal.\n wantsBody: () => true,\n });\n const text = answer.body && decode(answer.body);\n if (!isSuccess(answer.status)) {\n throw new Failure('APP_CHALLENGE_UNREACHABLE', describeRefusal(origin, answer.status, text));\n }\n if (text === undefined) {\n throw new Failure(\n 'APP_CHALLENGE_FAILED',\n `${origin}: The answer is larger than ${ANSWER_MAX_BYTES / 1024} KB`,\n );\n }\n const verified = await verifyChallengeAnswer(sent, text, backendKey);\n if (!verified.success) {\n throw new Failure('APP_CHALLENGE_FAILED', `${origin}: ${verified.error}`);\n }\n}\n\nfunction describeRefusal(origin: string, status: number, text: string | undefined): string {\n // Ghost sends the challenge to one exact address, so a redirect means the app is set up wrong.\n const redirect = isRedirect(status) ? ' (Ghost follows no redirect for a challenge)' : '';\n // The backend's own explanation, such as handleChallenge's, if it's short enough to show.\n const said = text && text.length < 500 ? `: ${text.trim()}` : '';\n return `${origin} answered the challenge with HTTP ${status}${redirect}${said}`;\n}\n\ninterface Answer {\n status: number;\n location: string | null;\n /** Up to the limit; `undefined` past it, or when it wasn't wanted. */\n body: Uint8Array | undefined;\n}\n\n/** Requests a URL as Ghost does, following no redirect, and reads the body only if it's wanted. */\nasync function fetchOnce(\n fetchFn: Fetch,\n url: URL | string,\n {\n init,\n maxBytes,\n code,\n wantsBody,\n }: {\n init: RequestInit & { signal: AbortSignal };\n maxBytes: number;\n /** The code a failed request, or a body that breaks while it's read, fails with. */\n code: CheckCode;\n wantsBody: (status: number) => boolean;\n },\n): Promise<Answer> {\n try {\n const response = await fetchFn(url, { ...init, redirect: 'manual' });\n const answer = { status: response.status, location: response.headers.get('location') };\n if (!wantsBody(response.status)) {\n // Dropped unread, so a body that stalls or breaks doesn't matter.\n response.body?.cancel().catch(ignoreError);\n return { ...answer, body: undefined };\n }\n return { ...answer, body: await readBytes(response, maxBytes) };\n } catch (error) {\n throw new Failure(code, `${String(url)}: ${describeFetchError(error)}`);\n }\n}\n\n/** A failed fetch's message, with the reason Node hides in its `cause`, such as ECONNREFUSED. */\nfunction describeFetchError(error: unknown): string {\n // A fetch may reject with anything, `null` and `undefined` included.\n const { message, cause } = (typeof error === 'object' && error !== null ? error : {}) as {\n message?: string;\n cause?: { code?: string; message?: string };\n };\n const reason = cause?.code ?? cause?.message;\n return reason ? `${message} (${reason})` : String(message ?? error);\n}\n\nfunction parseJson(text: string, manifestUrl: string): unknown {\n try {\n return parseJsonText(text);\n } catch {\n throw new Failure('APP_MANIFEST_NOT_JSON', manifestUrl);\n }\n}\n\n// Decoded as UTF-8, which is what JSON should use, whatever charset the app names, as in Ghost.\n// Kept with any byte order mark, as Ghost's `Buffer#toString` keeps it: a manifest may start with\n// one, which its JSON parse allows, and an answer to the challenge may not.\nconst decode = (bytes: Uint8Array) => new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes);\n\nconst isRedirect = (status: number) => status >= 300 && status < 400;\nconst isSuccess = (status: number) => status >= 200 && status < 300;\n","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 { 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,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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