@tryghost/app-sdk 0.1.0-alpha.6 → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1130 @@
1
+ import { g as isPlainText, l as isContainedPath } from "./rules-_dou3jRF.js";
2
+ import { a as ignoreError, d as createChallenge, f as verifyChallengeAnswer, h as decodeText, i as readBytes, m as readExactHeader, n as UNKNOWN_GHOST_URL, o as parseJsonText, p as ALGORITHM, r as formatErrors, u as challengeUrl } from "./manifest-DX1GTozy.js";
3
+ import { FlattenedSign, flattenedVerify, importJWK } from "jose";
4
+ import { z } from "zod";
5
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from "node:crypto";
6
+ import { existsSync } from "node:fs";
7
+ import { chmod, link, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
8
+ import { basename, dirname, join, relative, resolve } from "node:path";
9
+ import { execFile } from "node:child_process";
10
+ //#region ../app-contracts/build/manifest/localhost.js
11
+ var LOOPBACK_HOSTS = [
12
+ /^localhost$/,
13
+ /\.localhost$/,
14
+ /^127\.\d+\.\d+\.\d+$/,
15
+ /^0\.0\.0\.0$/,
16
+ /^\[::1?\]$/,
17
+ /^\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\]$/,
18
+ /^\[::ffff:0:0\]$/
19
+ ];
20
+ /**
21
+ * A hostname without its trailing dots, which the URL parser keeps, every one of them:
22
+ * `localhost..` is `localhost`. A loop rather than a regular expression, which would take
23
+ * time quadratic in the number of dots on a hostname with many dots before its end.
24
+ */
25
+ function withoutTrailingDots(hostname) {
26
+ let end = hostname.length;
27
+ while (end > 0 && hostname[end - 1] === ".") end -= 1;
28
+ return hostname.slice(0, end);
29
+ }
30
+ /**
31
+ * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.
32
+ * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as
33
+ * `isGhostHost` drops them.
34
+ */
35
+ function isLocalhost(hostname) {
36
+ const host = withoutTrailingDots(hostname);
37
+ return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));
38
+ }
39
+ //#endregion
40
+ //#region ../app-contracts/build/manifest/ghost-host.js
41
+ /**
42
+ * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any
43
+ * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,
44
+ * whatever a frame's sandbox says. On another port it would be the app's, but browsers send
45
+ * a host's cookies to every port on it, so the app's server would be sent the staff user's
46
+ * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it
47
+ * frames the page, since the site's or Admin's address can change after an app is
48
+ * installed.
49
+ *
50
+ * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and
51
+ * without a trailing dot. A sibling host, such as another subdomain of the site's, is not
52
+ * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as
53
+ * `my-app.localhost` next to `localhost`, or another name for the same machine, such as
54
+ * `127.0.0.1`, which browsers treat as other hosts too.
55
+ *
56
+ * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no
57
+ * Ghost URLs at all. Either way the URL is refused.
58
+ */
59
+ function isGhostHost(url, ghostUrls) {
60
+ const host = hostOf(url);
61
+ if (host === null) return true;
62
+ let known = false;
63
+ for (const ghostUrl of ghostUrls) {
64
+ const ghostHost = hostOf(ghostUrl);
65
+ if (ghostHost === null || ghostHost === host) return true;
66
+ known = true;
67
+ }
68
+ return !known;
69
+ }
70
+ /** An http or https URL's host as `isGhostHost` compares it, or null for any other. */
71
+ function hostOf(value) {
72
+ let url;
73
+ try {
74
+ url = new URL(value);
75
+ } catch {
76
+ return null;
77
+ }
78
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
79
+ return withoutTrailingDots(url.hostname) || null;
80
+ }
81
+ var ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
82
+ /**
83
+ * An app ID is reverse-domain style: at least two dot-separated segments of lowercase
84
+ * letters, digits and hyphens, starting with a letter so that an IP address or a version
85
+ * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than
86
+ * lowercased.
87
+ */
88
+ function isValidAppId(value) {
89
+ if (typeof value !== "string" || value.length > 191) return false;
90
+ const segments = value.split(".");
91
+ return segments.length >= 2 && /^[a-z]/.test(value) && segments.every((segment) => ID_SEGMENT.test(segment));
92
+ }
93
+ //#endregion
94
+ //#region ../app-contracts/build/manifest/limits.js
95
+ /**
96
+ * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of
97
+ * them, the manifest's own URL included, so its columns are exactly this wide.
98
+ */
99
+ var URL_MAX_LENGTH = 2e3;
100
+ //#endregion
101
+ //#region ../app-contracts/build/identity/signed-manifest.js
102
+ /** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */
103
+ var SIGNED_MANIFEST_TYPE = "ghost-app-manifest";
104
+ var SignedManifestShape = z.strictObject({
105
+ protected: z.string(),
106
+ payload: z.string(),
107
+ signature: z.string()
108
+ });
109
+ var ProtectedHeader = z.strictObject({
110
+ alg: z.literal(ALGORITHM),
111
+ typ: z.literal(SIGNED_MANIFEST_TYPE)
112
+ });
113
+ var EXPECTED_HEADER = JSON.stringify({
114
+ alg: ALGORITHM,
115
+ typ: SIGNED_MANIFEST_TYPE
116
+ });
117
+ /**
118
+ * Signs a manifest with an app's identity key. A string is signed as the exact text it is;
119
+ * anything else is signed as its JSON.
120
+ */
121
+ async function signManifest(manifest, identityKey) {
122
+ const text = typeof manifest === "string" ? manifest : JSON.stringify(manifest);
123
+ const signed = await new FlattenedSign(new TextEncoder().encode(text)).setProtectedHeader({
124
+ alg: ALGORITHM,
125
+ typ: SIGNED_MANIFEST_TYPE
126
+ }).sign(identityKey);
127
+ return {
128
+ protected: signed.protected,
129
+ payload: signed.payload,
130
+ signature: signed.signature
131
+ };
132
+ }
133
+ /**
134
+ * Reads the manifest out of a signed manifest, without verifying it. The key to verify it
135
+ * with is named inside the manifest, so the manifest has to be read and checked first;
136
+ * nothing in it may be used until `verifySignedManifest` has passed.
137
+ */
138
+ function readSignedManifest(body) {
139
+ const shape = SignedManifestShape.safeParse(body);
140
+ if (!shape.success) return {
141
+ success: false,
142
+ error: "Expected a signed manifest: flattened JWS JSON with protected, payload and signature"
143
+ };
144
+ const signed = shape.data;
145
+ if (!readExactHeader(signed.protected, ProtectedHeader)) return {
146
+ success: false,
147
+ error: `Expected a protected header of ${EXPECTED_HEADER}`
148
+ };
149
+ const payload = decodeText(signed.payload);
150
+ if (payload === void 0) return {
151
+ success: false,
152
+ error: "Expected a payload of UTF-8 text in base64url"
153
+ };
154
+ return {
155
+ success: true,
156
+ signed,
157
+ payload
158
+ };
159
+ }
160
+ /**
161
+ * Checks a signed manifest was signed with the identity key the manifest names, under
162
+ * exactly the protected header `readSignedManifest` accepts.
163
+ */
164
+ async function verifySignedManifest(signed, identityKey) {
165
+ let key;
166
+ try {
167
+ key = await importJWK(identityKey, ALGORITHM);
168
+ } catch {
169
+ return {
170
+ success: false,
171
+ error: "identity_key is not a usable Ed25519 key"
172
+ };
173
+ }
174
+ if (!readExactHeader(signed.protected, ProtectedHeader)) return {
175
+ success: false,
176
+ error: `Expected a protected header of ${EXPECTED_HEADER}`
177
+ };
178
+ try {
179
+ await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });
180
+ } catch {
181
+ return {
182
+ success: false,
183
+ error: "The signature was not made with identity_key"
184
+ };
185
+ }
186
+ return { success: true };
187
+ }
188
+ //#endregion
189
+ //#region ../app-contracts/build/manifest/icon.js
190
+ var ICON_NAME_MAX_LENGTH = 64;
191
+ var ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
192
+ var EITHER = "Expected an icon with either a name or a url";
193
+ /**
194
+ * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app
195
+ * serves. Ghost keeps a copy of the image with each manifest version it stores, and only
196
+ * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;
197
+ * Admin falls back to a default icon.
198
+ */
199
+ function iconField(url) {
200
+ return z.strictObject({
201
+ name: z.string("Expected an icon name").max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`).regex(ICON_NAME, "Expected an icon name such as audio-lines").optional(),
202
+ url: url().optional()
203
+ }, EITHER).refine(({ name, url: iconUrl }) => name === void 0 !== (iconUrl === void 0), EITHER).pipe(z.custom());
204
+ }
205
+ //#endregion
206
+ //#region ../app-contracts/build/manifest/keys.js
207
+ var ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
208
+ var EXPECTED = "Expected a public Ed25519 key as a JWK with kty, crv and x";
209
+ var PRIVATE = "Expected a public key, but this includes its private part (d)";
210
+ /**
211
+ * A key a manifest names. A manifest is public, so a key that includes its private part
212
+ * is refused with a message of its own: it has to be replaced, not just removed. Other
213
+ * members are refused by name, as key tools often add some, such as `kid` or `alg`.
214
+ */
215
+ var publicKeyField = z.strictObject({
216
+ kty: z.literal("OKP", EXPECTED),
217
+ crv: z.literal("Ed25519", EXPECTED),
218
+ x: z.string(EXPECTED).regex(ED25519_X, "Expected 32 bytes in base64url, without padding")
219
+ }, { error: (issue) => {
220
+ if (issue.code !== "unrecognized_keys") return EXPECTED;
221
+ return issue.keys.includes("d") ? PRIVATE : `Expected only kty, crv and x; remove ${issue.keys.join(", ")}`;
222
+ } });
223
+ //#endregion
224
+ //#region ../app-contracts/build/manifest/surfaces.js
225
+ /**
226
+ * What an app asks for: the places in Ghost it wants to appear. Each surface type is one
227
+ * entry in a union, so a new one is added here and nowhere else.
228
+ */
229
+ function surfacesField(url) {
230
+ const surfaceTypes = [z.strictObject({
231
+ type: z.literal("admin_page"),
232
+ url: url()
233
+ })];
234
+ const surface = z.discriminatedUnion("type", surfaceTypes, { error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(", ")}` });
235
+ return z.array(surface, "Expected a list of surfaces").min(1, "Expected at least one surface").superRefine((surfaces, ctx) => {
236
+ const seen = /* @__PURE__ */ new Set();
237
+ surfaces.forEach((entry, index) => {
238
+ if (seen.has(entry.type)) ctx.addIssue({
239
+ code: "custom",
240
+ message: `Expected at most one ${entry.type} surface`,
241
+ path: [index]
242
+ });
243
+ seen.add(entry.type);
244
+ });
245
+ });
246
+ }
247
+ //#endregion
248
+ //#region ../app-contracts/build/manifest/text.js
249
+ var VISIBLE_CHARACTER = /* @__PURE__ */ new RegExp("(?![\\u2800\\p{Default_Ignorable_Code_Point}])[\\p{L}\\p{N}\\p{P}\\p{S}]", "u");
250
+ var shows = (text) => VISIBLE_CHARACTER.test(text);
251
+ var blank = (character) => !shows(character) && isPlainText(character.replace(/\s/gu, ""));
252
+ var graphemes;
253
+ /**
254
+ * Takes off each end the characters, as a reader sees them, that show nothing: a space with a
255
+ * mark on it goes, an emoji with its variation selector stays, and so does anything invisible
256
+ * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no
257
+ * more than its length.
258
+ */
259
+ function trimEdges(value) {
260
+ graphemes ??= new Intl.Segmenter();
261
+ const characters = graphemes.segment(value);
262
+ let start = value.length;
263
+ for (const { segment, index } of characters) if (!blank(segment)) {
264
+ start = index;
265
+ break;
266
+ }
267
+ let end = value.length;
268
+ while (end > start) {
269
+ const { segment, index } = characters.containing(end - 1);
270
+ if (!blank(segment)) break;
271
+ end = index;
272
+ }
273
+ return value.slice(start, end);
274
+ }
275
+ /**
276
+ * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and
277
+ * text with nothing visible left, such as a name of Hangul fillers, is refused.
278
+ */
279
+ function plainText(maxLength) {
280
+ return z.string("Expected text").trim().overwrite(trimEdges).refine(shows, "Expected text").max(maxLength, `Expected at most ${maxLength} characters`).refine(isPlainText, "Expected plain text on one line");
281
+ }
282
+ var ANY_CHARACTER = /[\p{L}\p{N}\p{P}\p{S}]/u;
283
+ /**
284
+ * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before
285
+ * blank names were refused still reads, and the app can still be listed and uninstalled.
286
+ */
287
+ function storedText(maxLength) {
288
+ return z.string("Expected text").trim().refine((value) => ANY_CHARACTER.test(value), "Expected text").max(maxLength, `Expected at most ${maxLength} characters`).refine(isPlainText, "Expected plain text on one line");
289
+ }
290
+ //#endregion
291
+ //#region ../app-contracts/build/manifest/url.js
292
+ var FRAGMENT_PROBLEM = "Expected a URL without a fragment";
293
+ /**
294
+ * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`
295
+ * hides. A fragment never reaches the server, so a manifest address with one is a mistake or
296
+ * a second spelling of the same address.
297
+ */
298
+ var hasFragment = (address) => address.includes("#");
299
+ /**
300
+ * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would
301
+ * use. The length is measured on the parsed URL for the same reason, as that is what is
302
+ * stored and checked again later.
303
+ */
304
+ function checkResolvedUrl(url, allowLocalhost) {
305
+ if (url.href.length > 2e3) return `Expected at most ${URL_MAX_LENGTH} characters`;
306
+ if (url.username || url.password) return "Expected a URL without a username or password";
307
+ if (isLocalhost(url.hostname)) {
308
+ if (!allowLocalhost) return "Expected a public address; localhost is only allowed when Ghost runs in development";
309
+ return url.protocol === "https:" || url.protocol === "http:" ? null : "Expected an http or https URL";
310
+ }
311
+ return url.protocol === "https:" ? null : "Expected an https URL";
312
+ }
313
+ var ROUTE_PROBLEM = "Expected a URL that resolves to a path starting with a single /, with no \\ in its query or fragment";
314
+ var PATH_PROBLEM = "Expected a path on the manifest’s own origin, such as /admin";
315
+ var PLACEHOLDER_HOSTS = ["manifest-a.invalid", "manifest-b.invalid"];
316
+ /** Whether a reference names a host, in any of the URL parser's spellings of one. */
317
+ var namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);
318
+ function isManifestItself(url, base) {
319
+ return url.pathname === new URL(base).pathname;
320
+ }
321
+ /**
322
+ * A URL in the manifest. What Ghost loads is written as a path, resolved against the
323
+ * address the manifest was fetched from, so an app is one origin: the one Ghost fetches
324
+ * the manifest from and challenges is the one every surface runs on. The manifest names
325
+ * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they
326
+ * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.
327
+ *
328
+ * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and
329
+ * may be anywhere, the publisher's own site included.
330
+ *
331
+ * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.
332
+ * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.
333
+ * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which
334
+ * names a host, and a `\` in the query or fragment is left as it is. Only the page is opened
335
+ * as a route, but every URL Ghost loads is held to the one rule.
336
+ */
337
+ function urlField({ allowLocalhost, base }, linkOnly = false) {
338
+ if (linkOnly) return z.string("Expected an absolute URL").transform((value, ctx) => {
339
+ const url = URL.parse(value);
340
+ const problem = url ? checkResolvedUrl(url, allowLocalhost) : "Expected an absolute URL";
341
+ if (problem) {
342
+ ctx.addIssue({
343
+ code: "custom",
344
+ message: problem
345
+ });
346
+ return z.NEVER;
347
+ }
348
+ return url.href;
349
+ });
350
+ const origin = new URL(base).origin;
351
+ return z.string(PATH_PROBLEM).transform((value, ctx) => {
352
+ const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);
353
+ if (!url || url.origin !== origin || isManifestItself(url, base)) {
354
+ ctx.addIssue({
355
+ code: "custom",
356
+ message: PATH_PROBLEM
357
+ });
358
+ return z.NEVER;
359
+ }
360
+ const problem = checkResolvedUrl(url, allowLocalhost);
361
+ if (problem) {
362
+ ctx.addIssue({
363
+ code: "custom",
364
+ message: problem
365
+ });
366
+ return z.NEVER;
367
+ }
368
+ if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {
369
+ ctx.addIssue({
370
+ code: "custom",
371
+ message: ROUTE_PROBLEM
372
+ });
373
+ return z.NEVER;
374
+ }
375
+ return url.href;
376
+ });
377
+ }
378
+ /**
379
+ * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and
380
+ * already checked. Nothing is resolved or checked again, so a manifest accepted before the
381
+ * site's URL changed still reads back.
382
+ */
383
+ var absoluteUrl = () => z.url("Expected an absolute URL");
384
+ //#endregion
385
+ //#region ../app-contracts/build/manifest/schema.js
386
+ var NAME_MAX_LENGTH = 50;
387
+ var DESCRIPTION_MAX_LENGTH = 200;
388
+ var AUTHOR_NAME_MAX_LENGTH = 50;
389
+ var HEX_COLOR = /^#[0-9a-f]{6}$/i;
390
+ var KEY_FIELDS = /* @__PURE__ */ new Set(["identity_key", "backend_key"]);
391
+ var URL_FIELDS = /* @__PURE__ */ new Set([
392
+ "author",
393
+ "icon",
394
+ "surfaces",
395
+ "manifest_url",
396
+ "development"
397
+ ]);
398
+ /** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */
399
+ var parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));
400
+ /**
401
+ * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot
402
+ * claim something Ghost has not designed, and adding a field is always a deliberate change
403
+ * here.
404
+ *
405
+ * Defined once, with the URL and text rules left open. What a valid URL is depends on whether
406
+ * the manifest is being parsed, when where Ghost is served from matters, or read back after it
407
+ * was, when it doesn't. Text is held to today's rules when parsed, and read back under the
408
+ * rules it was stored under.
409
+ */
410
+ function manifestShape(url, text) {
411
+ return z.strictObject({
412
+ id: z.custom(isValidAppId, { error: `Expected a lowercase reverse-domain ID such as com.example.app, at most 191 characters` }),
413
+ name: text(NAME_MAX_LENGTH),
414
+ description: text(DESCRIPTION_MAX_LENGTH),
415
+ author: z.strictObject({
416
+ name: text(AUTHOR_NAME_MAX_LENGTH),
417
+ url: url(true)
418
+ }, "Expected an author with a name and a url"),
419
+ accent_color: z.string("Expected a hex colour such as #ff5500").regex(HEX_COLOR, "Expected a hex colour such as #ff5500").toLowerCase(),
420
+ icon: iconField(url),
421
+ surfaces: surfacesField(url),
422
+ manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),
423
+ identity_key: publicKeyField,
424
+ backend_key: publicKeyField,
425
+ development: z.boolean("Expected true or false")
426
+ }).refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {
427
+ message: "Expected a different key from identity_key",
428
+ path: ["backend_key"],
429
+ when: parsedFields(KEY_FIELDS)
430
+ }).refine((manifest) => manifest.development || ![
431
+ manifest.author.url,
432
+ "url" in manifest.icon ? manifest.icon.url : void 0,
433
+ ...manifest.surfaces.map((surface) => surface.url),
434
+ manifest.manifest_url
435
+ ].some((address) => address !== void 0 && isLocalhost(new URL(address).hostname)), {
436
+ message: "Expected true, as the app is on localhost",
437
+ path: ["development"],
438
+ when: parsedFields(URL_FIELDS)
439
+ });
440
+ }
441
+ /** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */
442
+ function manifestSchema(rules) {
443
+ return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);
444
+ }
445
+ /**
446
+ * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to
447
+ * resolve or check. This is the schema to read a stored manifest with, as it holds
448
+ * whatever the site's URL has become since, and it encodes a manifest back to the same
449
+ * shape, so what is stored is what will be read.
450
+ */
451
+ var AppManifestSchema = manifestShape(absoluteUrl, storedText);
452
+ //#endregion
453
+ //#region ../app-contracts/build/manifest/parse.js
454
+ function formatPath(path) {
455
+ return path.reduce((result, part) => {
456
+ if (typeof part === "number") return `${result}[${part}]`;
457
+ return result ? `${result}.${String(part)}` : String(part);
458
+ }, "");
459
+ }
460
+ var GHOST_URLS_PROBLEM = "Expected the URLs Ghost itself is served from";
461
+ var 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";
462
+ var 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`;
463
+ /**
464
+ * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most
465
+ * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`
466
+ * is a host of its own, which browsers send to the machine itself, and so does Ghost in
467
+ * development, whatever the system's resolver knows.
468
+ */
469
+ function onGhostHost(url) {
470
+ return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;
471
+ }
472
+ /**
473
+ * Reads the address a manifest is to be read from, by the same rules as the URLs inside
474
+ * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first
475
+ * request never goes to an address Ghost would refuse (plain HTTP, one carrying
476
+ * credentials, or one on Ghost's host). It cannot judge where that address redirects,
477
+ * which is for whatever fetches it to limit.
478
+ *
479
+ * The address it hands back is the one to store, to compare with a later one, and that the
480
+ * manifest must name as its `manifest_url`. The URL parser settles most differences in
481
+ * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a
482
+ * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.
483
+ */
484
+ function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {
485
+ if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) return {
486
+ success: false,
487
+ error: GHOST_URLS_PROBLEM
488
+ };
489
+ const url = URL.parse(input);
490
+ if (!url) return {
491
+ success: false,
492
+ error: "Expected the manifest at a URL"
493
+ };
494
+ const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);
495
+ if (problem) return {
496
+ success: false,
497
+ error: `${problem} for the manifest itself`
498
+ };
499
+ if (isGhostHost(url, ghostUrls)) return {
500
+ success: false,
501
+ error: onGhostHost(url)
502
+ };
503
+ return {
504
+ success: true,
505
+ manifestUrl: url.href
506
+ };
507
+ }
508
+ function invalid(errors) {
509
+ return {
510
+ success: false,
511
+ reason: "invalid",
512
+ errors
513
+ };
514
+ }
515
+ /**
516
+ * Validates a manifest, and checks it names the address it was fetched from as its
517
+ * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the
518
+ * manifest to its address as well as to every URL in it.
519
+ *
520
+ * Returns either the manifest, or every problem found. It does not fetch anything and it
521
+ * never throws. Without the URLs Ghost is served from it rejects every manifest, since the
522
+ * rule that keeps apps off Ghost's hosts could not be checked.
523
+ */
524
+ function parseManifest(input, options) {
525
+ const allowLocalhost = options.allowLocalhost ?? false;
526
+ const address = parseManifestUrl(options.manifestUrl, options);
527
+ if (!address.success) return invalid([{
528
+ path: "",
529
+ message: address.error
530
+ }]);
531
+ const result = manifestSchema({
532
+ allowLocalhost,
533
+ base: address.manifestUrl
534
+ }).safeParse(input);
535
+ if (!result.success) return invalid(result.error.issues.map((issue) => ({
536
+ path: formatPath(issue.path),
537
+ message: issue.message
538
+ })));
539
+ if (result.data.manifest_url !== address.manifestUrl) return {
540
+ success: false,
541
+ reason: "manifest_url_mismatch",
542
+ errors: [{
543
+ path: "manifest_url",
544
+ message: `Expected ${address.manifestUrl}, the address the manifest was read from`
545
+ }]
546
+ };
547
+ return {
548
+ success: true,
549
+ manifest: result.data
550
+ };
551
+ }
552
+ //#endregion
553
+ //#region src/tooling/limits.ts
554
+ /** How long Ghost waits for each read from an app, redirects and body included. */
555
+ var TIMEOUT_MS = 5e3;
556
+ /** The largest manifest Ghost stores, which it keeps in a TEXT column. */
557
+ var MANIFEST_MAX_BYTES = 64 * 1024;
558
+ /**
559
+ * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and the
560
+ * header and signature are well under a kilobyte.
561
+ */
562
+ var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(MANIFEST_MAX_BYTES * 4 / 3) + 1024;
563
+ /** The largest answer to a challenge Ghost reads. */
564
+ var ANSWER_MAX_BYTES = 4 * 1024;
565
+ /**
566
+ * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what
567
+ * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.
568
+ */
569
+ function storedSize(manifest) {
570
+ return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;
571
+ }
572
+ var signedTooLargeMessage = () => `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;
573
+ var tooLargeMessage = () => `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;
574
+ //#endregion
575
+ //#region src/tooling/check.ts
576
+ var MESSAGES = {
577
+ APP_MANIFEST_URL_INVALID: "The app manifest URL is not valid.",
578
+ APP_MANIFEST_UNREACHABLE: "Could not load the app’s manifest.",
579
+ APP_MANIFEST_REDIRECTED: "The app’s manifest redirects to another host.",
580
+ APP_MANIFEST_TOO_LARGE: `The app’s manifest is larger than ${MANIFEST_MAX_BYTES / 1024} KB.`,
581
+ APP_MANIFEST_NOT_JSON: "The app’s manifest is not JSON.",
582
+ APP_MANIFEST_UNSIGNED: "The app’s manifest is not signed.",
583
+ APP_MANIFEST_URL_MISMATCH: "The app’s manifest is for another address.",
584
+ APP_MANIFEST_INVALID: "The app manifest is not valid.",
585
+ APP_MANIFEST_SIGNATURE_INVALID: "The app’s manifest signature is not valid.",
586
+ APP_CHALLENGE_UNREACHABLE: "Could not reach the app to confirm it comes from its developer.",
587
+ APP_CHALLENGE_FAILED: "Ghost couldn’t confirm the app comes from its developer."
588
+ };
589
+ /** Thrown by any step, and turned into a failed `CheckResult` by `checkApp`. */
590
+ var Failure = class extends Error {
591
+ code;
592
+ detail;
593
+ errors;
594
+ constructor(code, detail, errors) {
595
+ super(MESSAGES[code]);
596
+ this.code = code;
597
+ this.detail = detail;
598
+ this.errors = errors;
599
+ }
600
+ };
601
+ /**
602
+ * Checks an app as Ghost does before installing it, and resolves with the code Ghost would
603
+ * refuse it with, or the manifest Ghost would install.
604
+ */
605
+ async function checkApp(manifestUrl, { fetch: fetchFn = globalThis.fetch } = {}) {
606
+ try {
607
+ return await runChecks(manifestUrl, fetchFn);
608
+ } catch (error) {
609
+ if (!(error instanceof Failure)) throw error;
610
+ return {
611
+ success: false,
612
+ code: error.code,
613
+ message: error.message,
614
+ detail: error.detail,
615
+ ...error.errors ? { errors: error.errors } : {}
616
+ };
617
+ }
618
+ }
619
+ async function runChecks(input, fetchFn) {
620
+ const manifestUrl = readManifestUrl(input);
621
+ const signed = readSigned(await fetchManifest(manifestUrl, fetchFn), manifestUrl);
622
+ const manifest = parse(signed.payload, manifestUrl);
623
+ await verifySignature(signed.signed, manifest);
624
+ checkStoredSize(manifest, manifestUrl);
625
+ await challenge(new URL(manifestUrl).origin, manifest.backend_key, fetchFn);
626
+ return {
627
+ success: true,
628
+ manifestUrl,
629
+ manifest
630
+ };
631
+ }
632
+ function readManifestUrl(input) {
633
+ const address = parseManifestUrl(input, {
634
+ ghostUrls: [UNKNOWN_GHOST_URL],
635
+ allowLocalhost: true
636
+ });
637
+ if (!address.success) throw new Failure("APP_MANIFEST_URL_INVALID", address.error);
638
+ return address.manifestUrl;
639
+ }
640
+ /** The signed manifest's bytes, following redirects on the same host, as Ghost does. */
641
+ async function fetchManifest(manifestUrl, fetchFn) {
642
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
643
+ let current = new URL(manifestUrl);
644
+ for (let redirects = 0;; redirects++) {
645
+ const answer = await fetchOnce(fetchFn, current, {
646
+ init: {
647
+ headers: { accept: "application/json" },
648
+ signal
649
+ },
650
+ maxBytes: SIGNED_MANIFEST_MAX_BYTES,
651
+ code: "APP_MANIFEST_UNREACHABLE",
652
+ wantsBody: isSuccess
653
+ });
654
+ if (REDIRECT_STATUSES.has(answer.status) && answer.location !== null) {
655
+ current = followRedirect(manifestUrl, current, answer.status, answer.location, redirects);
656
+ continue;
657
+ }
658
+ if (!isSuccess(answer.status)) throw new Failure("APP_MANIFEST_UNREACHABLE", `${current.href} answered with HTTP ${answer.status}`);
659
+ if (!answer.body) throw new Failure("APP_MANIFEST_TOO_LARGE", manifestUrl);
660
+ return answer.body;
661
+ }
662
+ }
663
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([
664
+ 301,
665
+ 302,
666
+ 303,
667
+ 307,
668
+ 308
669
+ ]);
670
+ /** The URL a redirect leads to, if Ghost would follow it. */
671
+ function followRedirect(manifestUrl, current, status, location, redirects) {
672
+ const target = URL.parse(Buffer.from(location, "binary").toString("utf8"), current);
673
+ if (!target) throw new Failure("APP_MANIFEST_UNREACHABLE", `${manifestUrl} answered with HTTP ${status} and a Location that is not a URL`);
674
+ if (!staysOnHost(current, target)) throw new Failure("APP_MANIFEST_REDIRECTED", `${manifestUrl} redirects to ${target.host}`);
675
+ if (redirects === 3) throw new Failure("APP_MANIFEST_UNREACHABLE", `${manifestUrl} redirects more than 3 times`);
676
+ target.username = "";
677
+ target.password = "";
678
+ return target;
679
+ }
680
+ /** Ghost follows a redirect on the same origin, or from HTTP to HTTPS on the same host. */
681
+ function staysOnHost(from, to) {
682
+ if (to.origin === from.origin) return true;
683
+ return from.protocol === "http:" && to.protocol === "https:" && to.hostname === from.hostname && from.port === "" && to.port === "";
684
+ }
685
+ function readSigned(body, manifestUrl) {
686
+ const signed = readSignedManifest(parseJson(decode(body), manifestUrl));
687
+ if (!signed.success) throw new Failure("APP_MANIFEST_UNSIGNED", signed.error);
688
+ return signed;
689
+ }
690
+ function parse(payload, manifestUrl) {
691
+ const parsed = parseManifest(parseJson(payload, manifestUrl), {
692
+ manifestUrl,
693
+ ghostUrls: [UNKNOWN_GHOST_URL],
694
+ allowLocalhost: true
695
+ });
696
+ if (parsed.success) return parsed.manifest;
697
+ const detail = formatErrors(parsed.errors, "; ");
698
+ if (parsed.reason === "manifest_url_mismatch") throw new Failure("APP_MANIFEST_URL_MISMATCH", detail);
699
+ throw new Failure("APP_MANIFEST_INVALID", detail, parsed.errors);
700
+ }
701
+ async function verifySignature(signed, manifest) {
702
+ const verified = await verifySignedManifest(signed, manifest.identity_key);
703
+ if (!verified.success) throw new Failure("APP_MANIFEST_SIGNATURE_INVALID", verified.error);
704
+ }
705
+ function checkStoredSize(manifest, manifestUrl) {
706
+ if (storedSize(manifest) > 65536) throw new Failure("APP_MANIFEST_TOO_LARGE", `${manifestUrl}: ${tooLargeMessage()}`);
707
+ }
708
+ /** Sends Ghost's challenge to the app's origin, and verifies the answer with the backend key. */
709
+ async function challenge(origin, backendKey, fetchFn) {
710
+ const sent = createChallenge(origin);
711
+ const answer = await fetchOnce(fetchFn, challengeUrl(origin), {
712
+ init: {
713
+ method: "POST",
714
+ body: sent,
715
+ headers: {
716
+ accept: "application/json",
717
+ "content-type": "application/json"
718
+ },
719
+ signal: AbortSignal.timeout(TIMEOUT_MS)
720
+ },
721
+ maxBytes: ANSWER_MAX_BYTES,
722
+ code: "APP_CHALLENGE_UNREACHABLE",
723
+ wantsBody: () => true
724
+ });
725
+ const text = answer.body && decode(answer.body);
726
+ if (!isSuccess(answer.status)) throw new Failure("APP_CHALLENGE_UNREACHABLE", describeRefusal(origin, answer.status, text));
727
+ if (text === void 0) throw new Failure("APP_CHALLENGE_FAILED", `${origin}: The answer is larger than ${ANSWER_MAX_BYTES / 1024} KB`);
728
+ const verified = await verifyChallengeAnswer(sent, text, backendKey);
729
+ if (!verified.success) throw new Failure("APP_CHALLENGE_FAILED", `${origin}: ${verified.error}`);
730
+ }
731
+ function describeRefusal(origin, status, text) {
732
+ return `${origin} answered the challenge with HTTP ${status}${isRedirect(status) ? " (Ghost follows no redirect for a challenge)" : ""}${text && text.length < 500 ? `: ${text.trim()}` : ""}`;
733
+ }
734
+ /** Requests a URL as Ghost does, following no redirect, and reads the body only if it's wanted. */
735
+ async function fetchOnce(fetchFn, url, { init, maxBytes, code, wantsBody }) {
736
+ try {
737
+ const response = await fetchFn(url, {
738
+ ...init,
739
+ redirect: "manual"
740
+ });
741
+ const answer = {
742
+ status: response.status,
743
+ location: response.headers.get("location")
744
+ };
745
+ if (!wantsBody(response.status)) {
746
+ response.body?.cancel().catch(ignoreError);
747
+ return {
748
+ ...answer,
749
+ body: void 0
750
+ };
751
+ }
752
+ return {
753
+ ...answer,
754
+ body: await readBytes(response, maxBytes)
755
+ };
756
+ } catch (error) {
757
+ throw new Failure(code, `${String(url)}: ${describeFetchError(error)}`);
758
+ }
759
+ }
760
+ /** A failed fetch's message, with the reason Node hides in its `cause`, such as ECONNREFUSED. */
761
+ function describeFetchError(error) {
762
+ const { message, cause } = typeof error === "object" && error !== null ? error : {};
763
+ const reason = cause?.code ?? cause?.message;
764
+ return reason ? `${message} (${reason})` : String(message ?? error);
765
+ }
766
+ function parseJson(text, manifestUrl) {
767
+ try {
768
+ return parseJsonText(text);
769
+ } catch {
770
+ throw new Failure("APP_MANIFEST_NOT_JSON", manifestUrl);
771
+ }
772
+ }
773
+ var decode = (bytes) => new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
774
+ var isRedirect = (status) => status >= 300 && status < 400;
775
+ var isSuccess = (status) => status >= 200 && status < 300;
776
+ //#endregion
777
+ //#region src/tooling/git.ts
778
+ function git(args, cwd, input) {
779
+ return new Promise((done) => {
780
+ const child = execFile("git", args, { cwd }, (error, stdout, stderr) => {
781
+ done({
782
+ code: error ? error.code ?? 1 : 0,
783
+ stdout,
784
+ stderr
785
+ });
786
+ });
787
+ child.stdin?.on("error", ignoreError);
788
+ child.stdin?.end(input);
789
+ });
790
+ }
791
+ function insideRepository(directory) {
792
+ for (let current = resolve(directory);; current = dirname(current)) {
793
+ if (existsSync(join(current, ".git"))) return true;
794
+ if (dirname(current) === current) return false;
795
+ }
796
+ }
797
+ /**
798
+ * The directory itself, or the nearest one above it that exists, to run git in: a project's
799
+ * directory may not exist before its keys are written, and git can't start in one that doesn't.
800
+ */
801
+ function existingDirectory(directory) {
802
+ let current = resolve(directory);
803
+ while (!existsSync(current) && dirname(current) !== current) current = dirname(current);
804
+ return current;
805
+ }
806
+ /**
807
+ * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by
808
+ * accident. A file outside any repository counts as ignored.
809
+ */
810
+ async function isGitIgnored(root, files) {
811
+ const cwd = existingDirectory(root);
812
+ const paths = (typeof files === "string" ? [files] : files).map((file) => ({
813
+ shown: relative(root, resolve(root, file)),
814
+ asked: relative(cwd, resolve(root, file))
815
+ }));
816
+ const named = `${paths.map(({ shown }) => shown).join(" and ")} ${paths.length > 1 ? "are" : "is"}`;
817
+ const repository = await findRepository(cwd, named);
818
+ if (repository !== "inside") return repository === "outside" ? { ignored: true } : repository;
819
+ return askWhichAreIgnored(cwd, paths, named);
820
+ }
821
+ /** Whether `cwd` is in a repository, or why git can't say when it seems to be. */
822
+ async function findRepository(cwd, named) {
823
+ const inside = await git(["rev-parse", "--is-inside-work-tree"], cwd);
824
+ if (inside.code === 0) return "inside";
825
+ if (!insideRepository(cwd)) return "outside";
826
+ return {
827
+ ignored: false,
828
+ reason: inside.code === "ENOENT" ? `git isn't installed, so it can't check ${named} ignored` : `git couldn't read the repository: ${inside.stderr.trim()}`
829
+ };
830
+ }
831
+ async function askWhichAreIgnored(cwd, paths, named) {
832
+ const { code, stdout, stderr } = await git([
833
+ "check-ignore",
834
+ "--stdin",
835
+ "-z"
836
+ ], cwd, paths.map(({ asked }) => `${asked}\0`).join(""));
837
+ if (code !== 0 && code !== 1) return {
838
+ ignored: false,
839
+ reason: `git couldn't check ${named} ignored: ${stderr.trim()}`
840
+ };
841
+ const ignored = new Set(stdout.split("\0"));
842
+ const notIgnored = paths.find(({ asked }) => !ignored.has(asked));
843
+ return notIgnored ? {
844
+ ignored: false,
845
+ reason: `git doesn't ignore ${notIgnored.shown}`
846
+ } : { ignored: true };
847
+ }
848
+ //#endregion
849
+ //#region src/tooling/keys.ts
850
+ /** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */
851
+ var KEYS_DIRECTORY = ".ghost-app";
852
+ var KEY_NAMES = ["identity", "backend"];
853
+ /** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */
854
+ var IDENTITY_KEY_VARIABLE = "GHOST_APP_IDENTITY_KEY";
855
+ /**
856
+ * The backend key, as the backend reads it, and as CI may provide it to sign a production
857
+ * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.
858
+ */
859
+ var BACKEND_KEY_VARIABLE = "GHOST_APP_BACKEND_KEY";
860
+ /** The file a key is kept in, relative to the project. */
861
+ function keyFile(mode, name) {
862
+ return join(KEYS_DIRECTORY, mode, `${name}.json`);
863
+ }
864
+ /** A new private Ed25519 key. */
865
+ function generateKey() {
866
+ const { x, d } = generateKeyPairSync("ed25519").privateKey.export({ format: "jwk" });
867
+ return {
868
+ kty: "OKP",
869
+ crv: "Ed25519",
870
+ x,
871
+ d
872
+ };
873
+ }
874
+ /** A key's public half, with only `kty`, `crv` and `x`. */
875
+ function publicKeyOf(key) {
876
+ return {
877
+ kty: "OKP",
878
+ crv: "Ed25519",
879
+ x: key.x
880
+ };
881
+ }
882
+ /**
883
+ * Reads a private key from JSON. `source` names where it came from, for the error: the key
884
+ * itself is never in one.
885
+ */
886
+ function readKey(text, source) {
887
+ const key = readAnyKey(text, source);
888
+ if (!("d" in key)) throw new Error(`${source} is a public key; expected the private key, with d`);
889
+ return key;
890
+ }
891
+ /** Reads a key from JSON, private or public. */
892
+ function readAnyKey(text, source) {
893
+ let value;
894
+ try {
895
+ value = JSON.parse(text);
896
+ } catch {
897
+ throw new Error(`${source} isn't a key: it isn't JSON`);
898
+ }
899
+ if (!isEd25519(value)) throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty "OKP", crv "Ed25519" and x`);
900
+ const { d } = value;
901
+ if (d === void 0) return publicKeyOf(value);
902
+ if (typeof d !== "string") throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);
903
+ if (publicHalfOf(d, source) !== value.x) throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);
904
+ return {
905
+ kty: "OKP",
906
+ crv: "Ed25519",
907
+ x: value.x,
908
+ d
909
+ };
910
+ }
911
+ function isEd25519(value) {
912
+ const { kty, crv, x } = typeof value === "object" && value !== null ? value : {};
913
+ return kty === "OKP" && crv === "Ed25519" && typeof x === "string";
914
+ }
915
+ var ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
916
+ /**
917
+ * The public half of a private half, as `x`. Derived from `d` alone, as Node 24.22 and later
918
+ * refuse a JWK whose halves don't match while earlier versions take its `x` as given, so a
919
+ * mismatch is reported the same way on any version.
920
+ */
921
+ function publicHalfOf(d, source) {
922
+ const bytes = Buffer.from(d, "base64url");
923
+ if (bytes.length !== 32) throw new Error(`${source} isn't a usable Ed25519 key`);
924
+ return createPublicKey(createPrivateKey({
925
+ key: Buffer.concat([ED25519_PKCS8_PREFIX, bytes]),
926
+ format: "der",
927
+ type: "pkcs8"
928
+ })).export({ format: "jwk" }).x;
929
+ }
930
+ async function readKeyFile(root, mode, name) {
931
+ const file = keyFile(mode, name);
932
+ let text;
933
+ try {
934
+ text = await readFile(join(root, file), "utf8");
935
+ } catch (error) {
936
+ if (error.code !== "ENOENT") throw error;
937
+ throw new Error(missingKeyMessage(mode, name, file), { cause: error });
938
+ }
939
+ return readKey(text, file);
940
+ }
941
+ /** Says how to create a missing key, as nothing that reads keys creates one. */
942
+ function missingKeyMessage(mode, name, file) {
943
+ if (mode === "development") return `There's no development ${name} key: ${file} doesn't exist. Create one with \`ghost-app keys\`.`;
944
+ return `There's no production ${name} key: ${file} doesn't exist. Create one with \`ghost-app keys --production\`, or set ${variableFor(name)}.`;
945
+ }
946
+ var variableFor = (name) => name === "identity" ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;
947
+ /**
948
+ * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only
949
+ * their owner can read, and keeps any that exist.
950
+ */
951
+ async function createKeys({ root, mode }) {
952
+ const keys = KEY_NAMES.map((name) => {
953
+ const file = keyFile(mode, name);
954
+ return {
955
+ name,
956
+ file,
957
+ pending: join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`)
958
+ };
959
+ });
960
+ await refuseUnlessGitIgnores(root, [...keys.map(({ file }) => file), ...keys.map(({ pending }) => pending)]);
961
+ await mkdir(join(root, KEYS_DIRECTORY, mode), {
962
+ recursive: true,
963
+ mode: 448
964
+ });
965
+ const result = {
966
+ created: [],
967
+ kept: []
968
+ };
969
+ for (const { name, file, pending } of keys) result[await publishKey(join(root, file), join(root, pending)) ? "created" : "kept"].push(name);
970
+ return result;
971
+ }
972
+ async function refuseUnlessGitIgnores(root, files) {
973
+ const ignored = await isGitIgnored(root, files);
974
+ if (!ignored.ignored) throw new Error(`Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`);
975
+ }
976
+ /** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */
977
+ async function publishKey(file, pending) {
978
+ try {
979
+ await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\n`, {
980
+ flag: "wx",
981
+ mode: 384
982
+ });
983
+ await link(pending, file);
984
+ return true;
985
+ } catch (error) {
986
+ if (error.code !== "EEXIST") throw error;
987
+ if (process.platform !== "win32" && ((await stat(file)).mode & 63) !== 0) await chmod(file, 384);
988
+ return false;
989
+ } finally {
990
+ await rm(pending, { force: true });
991
+ }
992
+ }
993
+ /**
994
+ * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to
995
+ * anything but blanks, or else the key's file.
996
+ */
997
+ function signingKeySource(mode, name, env = process.env) {
998
+ const variable = variableFor(name);
999
+ return mode === "production" && env[variable]?.trim() ? variable : keyFile(mode, name);
1000
+ }
1001
+ /**
1002
+ * The keys to sign a mode's manifest with, from the key files, or in production from
1003
+ * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.
1004
+ */
1005
+ async function readSigningKeys({ root, mode, env = process.env }) {
1006
+ const fromVariable = (name) => signingKeySource(mode, name, env) === variableFor(name) ? env[variableFor(name)].trim() : void 0;
1007
+ const identityText = fromVariable("identity");
1008
+ const identityKey = identityText ? await sameAsFile(root, mode, "identity", readKey(identityText, IDENTITY_KEY_VARIABLE)) : await readKeyFile(root, mode, "identity");
1009
+ const backendText = fromVariable("backend");
1010
+ const backendKey = publicKeyOf(backendText ? await sameAsFile(root, mode, "backend", readAnyKey(backendText, BACKEND_KEY_VARIABLE)) : await readKeyFile(root, mode, "backend"));
1011
+ if (identityKey.x === backendKey.x) throw new Error("The identity key and the backend key are the same key; they must be two keys");
1012
+ return {
1013
+ identityKey,
1014
+ backendKey
1015
+ };
1016
+ }
1017
+ /**
1018
+ * A key from a variable, after checking it's the same key as the file, where there's one. A
1019
+ * variable left set, such as a development key exported for every shell, would otherwise win over
1020
+ * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every
1021
+ * site.
1022
+ */
1023
+ async function sameAsFile(root, mode, name, key) {
1024
+ const file = keyFile(mode, name);
1025
+ if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {
1026
+ const variable = variableFor(name);
1027
+ throw new Error(`${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`);
1028
+ }
1029
+ return key;
1030
+ }
1031
+ /** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */
1032
+ function readBackendKey({ root, mode }) {
1033
+ return readKeyFile(root, mode, "backend");
1034
+ }
1035
+ //#endregion
1036
+ //#region src/tooling/sign.ts
1037
+ /** The readable manifest a project keeps, which the tooling signs. */
1038
+ var MANIFEST_FILE = "ghost-app.json";
1039
+ /** The fields the tooling adds, which `ghost-app.json` mustn't set. */
1040
+ var ADDED_FIELDS = [
1041
+ "manifest_url",
1042
+ "identity_key",
1043
+ "backend_key",
1044
+ "development"
1045
+ ];
1046
+ var refuse = (code, message, path = "") => ({
1047
+ success: false,
1048
+ code,
1049
+ errors: [{
1050
+ path,
1051
+ message
1052
+ }]
1053
+ });
1054
+ /**
1055
+ * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it
1056
+ * with the identity key, unless Ghost would refuse it.
1057
+ */
1058
+ async function signAppManifest(source, options) {
1059
+ readKey(JSON.stringify(options.identityKey), "identityKey");
1060
+ if ("d" in options.backendKey) readKey(JSON.stringify(options.backendKey), "backendKey");
1061
+ const address = parseManifestUrl(options.manifestUrl, {
1062
+ ghostUrls: [UNKNOWN_GHOST_URL],
1063
+ allowLocalhost: true
1064
+ });
1065
+ if (!address.success) return refuse("APP_MANIFEST_URL_INVALID", address.error);
1066
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return refuse("APP_MANIFEST_INVALID", "Expected the manifest as a JSON object");
1067
+ const added = ADDED_FIELDS.filter((field) => field in source);
1068
+ if (added.length > 0) return {
1069
+ success: false,
1070
+ code: "APP_MANIFEST_INVALID",
1071
+ errors: added.map((field) => ({
1072
+ path: field,
1073
+ message: `Leave ${field} out: it's added when the manifest is signed`
1074
+ }))
1075
+ };
1076
+ const manifest = {
1077
+ ...source,
1078
+ manifest_url: address.manifestUrl,
1079
+ identity_key: publicKeyOf(options.identityKey),
1080
+ backend_key: publicKeyOf(options.backendKey),
1081
+ development: options.development
1082
+ };
1083
+ const parsed = parseManifest(manifest, {
1084
+ manifestUrl: address.manifestUrl,
1085
+ ghostUrls: [UNKNOWN_GHOST_URL],
1086
+ allowLocalhost: true
1087
+ });
1088
+ if (!parsed.success) return {
1089
+ success: false,
1090
+ code: "APP_MANIFEST_INVALID",
1091
+ errors: parsed.errors
1092
+ };
1093
+ if (storedSize(parsed.manifest) > 65536) return refuse("APP_MANIFEST_TOO_LARGE", tooLargeMessage());
1094
+ const signed = await signManifest(JSON.stringify(manifest), options.identityKey);
1095
+ if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) return refuse("APP_MANIFEST_TOO_LARGE", signedTooLargeMessage());
1096
+ return {
1097
+ success: true,
1098
+ signed,
1099
+ manifest
1100
+ };
1101
+ }
1102
+ /** A signed manifest as the CLI and the Vite plugin write it to a file. */
1103
+ function serialiseSigned(signed) {
1104
+ return `${JSON.stringify(signed, null, 2)}\n`;
1105
+ }
1106
+ /** Reads `ghost-app.json`, or another readable manifest, as JSON. */
1107
+ async function readManifestSource(file) {
1108
+ const text = await readFile(file, "utf8");
1109
+ try {
1110
+ return parseJsonText(text);
1111
+ } catch (error) {
1112
+ throw new Error(`${file} isn't JSON: ${error.message}`, { cause: error });
1113
+ }
1114
+ }
1115
+ /** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */
1116
+ async function signProject({ root, mode, env, manifestUrl, manifestFile = MANIFEST_FILE }) {
1117
+ return signAppManifest(await readManifestSource(resolve(root, manifestFile)), {
1118
+ manifestUrl,
1119
+ ...await readSigningKeys({
1120
+ root,
1121
+ mode,
1122
+ env
1123
+ }),
1124
+ development: mode === "development"
1125
+ });
1126
+ }
1127
+ //#endregion
1128
+ export { signProject as a, KEYS_DIRECTORY as c, generateKey as d, keyFile as f, checkApp as g, readSigningKeys as h, signAppManifest as i, KEY_NAMES as l, readBackendKey as m, readManifestSource as n, BACKEND_KEY_VARIABLE as o, publicKeyOf as p, serialiseSigned as r, IDENTITY_KEY_VARIABLE as s, MANIFEST_FILE as t, createKeys as u };
1129
+
1130
+ //# sourceMappingURL=sign-BhNJAPta.js.map