@tryghost/app-sdk 0.1.0-alpha.2 → 0.1.0-alpha.20

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,898 @@
1
+ import { g as isPlainText, l as isContainedPath } from "./rules-BAEnzs5i.js";
2
+ import { a as ALGORITHM, i as publicHalfOf, n as UNKNOWN_GHOST_URL, r as ignoreError } from "./manifest-DmfZ-0r7.js";
3
+ import { FlattenedSign } from "jose";
4
+ import { z } from "zod";
5
+ import { 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 ../../contracts/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 ../../contracts/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 ../../contracts/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
+ /**
101
+ * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and
102
+ * the header and signature are well under a kilobyte, so a manifest of the largest size
103
+ * still fits.
104
+ */
105
+ var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(64 * 1024 * 4 / 3) + 1024;
106
+ /** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
107
+ function parseJsonText(text) {
108
+ return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
109
+ }
110
+ //#endregion
111
+ //#region ../../contracts/app-contracts/build/identity/signed-manifest.js
112
+ /** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */
113
+ var SIGNED_MANIFEST_TYPE = "ghost-app-manifest";
114
+ z.strictObject({
115
+ protected: z.string(),
116
+ payload: z.string(),
117
+ signature: z.string()
118
+ });
119
+ z.strictObject({
120
+ alg: z.literal(ALGORITHM),
121
+ typ: z.literal(SIGNED_MANIFEST_TYPE)
122
+ });
123
+ JSON.stringify({
124
+ alg: ALGORITHM,
125
+ typ: SIGNED_MANIFEST_TYPE
126
+ });
127
+ /**
128
+ * Signs a manifest with an app's identity key. A string is signed as the exact text it is;
129
+ * anything else is signed as its JSON.
130
+ */
131
+ async function signManifest(manifest, identityKey) {
132
+ const text = typeof manifest === "string" ? manifest : JSON.stringify(manifest);
133
+ const signed = await new FlattenedSign(new TextEncoder().encode(text)).setProtectedHeader({
134
+ alg: ALGORITHM,
135
+ typ: SIGNED_MANIFEST_TYPE
136
+ }).sign(identityKey);
137
+ return {
138
+ protected: signed.protected,
139
+ payload: signed.payload,
140
+ signature: signed.signature
141
+ };
142
+ }
143
+ //#endregion
144
+ //#region src/tooling/git.ts
145
+ function git(args, cwd, input) {
146
+ return new Promise((done) => {
147
+ const child = execFile("git", args, { cwd }, (error, stdout, stderr) => {
148
+ done({
149
+ code: error ? error.code ?? 1 : 0,
150
+ stdout,
151
+ stderr
152
+ });
153
+ });
154
+ child.stdin?.on("error", ignoreError);
155
+ child.stdin?.end(input);
156
+ });
157
+ }
158
+ function insideRepository(directory) {
159
+ for (let current = resolve(directory);; current = dirname(current)) {
160
+ if (existsSync(join(current, ".git"))) return true;
161
+ if (dirname(current) === current) return false;
162
+ }
163
+ }
164
+ /**
165
+ * The directory itself, or the nearest one above it that exists, to run git in: a project's
166
+ * directory may not exist before its keys are written, and git can't start in one that doesn't.
167
+ */
168
+ function existingDirectory(directory) {
169
+ let current = resolve(directory);
170
+ while (!existsSync(current) && dirname(current) !== current) current = dirname(current);
171
+ return current;
172
+ }
173
+ /**
174
+ * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by
175
+ * accident. A file outside any repository counts as ignored.
176
+ */
177
+ async function isGitIgnored(root, files) {
178
+ const cwd = existingDirectory(root);
179
+ const paths = (typeof files === "string" ? [files] : files).map((file) => ({
180
+ shown: relative(root, resolve(root, file)),
181
+ asked: relative(cwd, resolve(root, file))
182
+ }));
183
+ const named = `${paths.map(({ shown }) => shown).join(" and ")} ${paths.length > 1 ? "are" : "is"}`;
184
+ const repository = await findRepository(cwd, named);
185
+ if (repository !== "inside") return repository === "outside" ? { ignored: true } : repository;
186
+ return askWhichAreIgnored(cwd, paths, named);
187
+ }
188
+ /** Whether `cwd` is in a repository, or why git can't say when it seems to be. */
189
+ async function findRepository(cwd, named) {
190
+ const inside = await git(["rev-parse", "--is-inside-work-tree"], cwd);
191
+ if (inside.code === 0) return "inside";
192
+ if (!insideRepository(cwd)) return "outside";
193
+ return {
194
+ ignored: false,
195
+ reason: inside.code === "ENOENT" ? `git isn't installed, so it can't check ${named} ignored` : `git couldn't read the repository: ${inside.stderr.trim()}`
196
+ };
197
+ }
198
+ async function askWhichAreIgnored(cwd, paths, named) {
199
+ const { code, stdout, stderr } = await git([
200
+ "check-ignore",
201
+ "--stdin",
202
+ "-z"
203
+ ], cwd, paths.map(({ asked }) => `${asked}\0`).join(""));
204
+ if (code !== 0 && code !== 1) return {
205
+ ignored: false,
206
+ reason: `git couldn't check ${named} ignored: ${stderr.trim()}`
207
+ };
208
+ const ignored = new Set(stdout.split("\0"));
209
+ const notIgnored = paths.find(({ asked }) => !ignored.has(asked));
210
+ return notIgnored ? {
211
+ ignored: false,
212
+ reason: `git doesn't ignore ${notIgnored.shown}`
213
+ } : { ignored: true };
214
+ }
215
+ //#endregion
216
+ //#region src/tooling/keys.ts
217
+ /** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */
218
+ var KEYS_DIRECTORY = ".ghost-app";
219
+ var KEY_NAMES = ["identity", "backend"];
220
+ /** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */
221
+ var IDENTITY_KEY_VARIABLE = "GHOST_APP_IDENTITY_KEY";
222
+ /**
223
+ * The backend key, as the backend reads it, and as CI may provide it to sign a production
224
+ * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.
225
+ */
226
+ var BACKEND_KEY_VARIABLE = "GHOST_APP_BACKEND_KEY";
227
+ /** The file a key is kept in, relative to the project. */
228
+ function keyFile(mode, name) {
229
+ return join(KEYS_DIRECTORY, mode, `${name}.json`);
230
+ }
231
+ /** A new private Ed25519 key. */
232
+ function generateKey() {
233
+ const { x, d } = generateKeyPairSync("ed25519").privateKey.export({ format: "jwk" });
234
+ return {
235
+ kty: "OKP",
236
+ crv: "Ed25519",
237
+ x,
238
+ d
239
+ };
240
+ }
241
+ /** A key's public half, with only `kty`, `crv` and `x`. */
242
+ function publicKeyOf(key) {
243
+ return {
244
+ kty: "OKP",
245
+ crv: "Ed25519",
246
+ x: key.x
247
+ };
248
+ }
249
+ /**
250
+ * Reads a private key from JSON. `source` names where it came from, for the error: the key
251
+ * itself is never in one.
252
+ */
253
+ async function readKey(text, source) {
254
+ const key = await readAnyKey(text, source);
255
+ if (!("d" in key)) throw new Error(`${source} is a public key; expected the private key, with d`);
256
+ return key;
257
+ }
258
+ /** Reads a key from JSON, private or public. */
259
+ async function readAnyKey(text, source) {
260
+ let value;
261
+ try {
262
+ value = JSON.parse(text);
263
+ } catch {
264
+ throw new Error(`${source} isn't a key: it isn't JSON`);
265
+ }
266
+ if (!isEd25519(value)) throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty "OKP", crv "Ed25519" and x`);
267
+ const { d } = value;
268
+ if (d === void 0) return publicKeyOf(value);
269
+ if (typeof d !== "string") throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);
270
+ const bytes = Buffer.from(d, "base64url");
271
+ if (bytes.length !== 32) throw new Error(`${source} isn't a usable Ed25519 key`);
272
+ if (await publicHalfOf(bytes) !== value.x) throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);
273
+ return {
274
+ kty: "OKP",
275
+ crv: "Ed25519",
276
+ x: value.x,
277
+ d
278
+ };
279
+ }
280
+ function isEd25519(value) {
281
+ const { kty, crv, x } = typeof value === "object" && value !== null ? value : {};
282
+ return kty === "OKP" && crv === "Ed25519" && typeof x === "string";
283
+ }
284
+ async function readKeyFile(root, mode, name) {
285
+ const file = keyFile(mode, name);
286
+ let text;
287
+ try {
288
+ text = await readFile(join(root, file), "utf8");
289
+ } catch (error) {
290
+ if (error.code !== "ENOENT") throw error;
291
+ throw new Error(missingKeyMessage(mode, name, file), { cause: error });
292
+ }
293
+ return readKey(text, file);
294
+ }
295
+ /** Says how to create a missing key, as nothing that reads keys creates one. */
296
+ function missingKeyMessage(mode, name, file) {
297
+ if (mode === "development") return `There's no development ${name} key: ${file} doesn't exist. Create one with \`ghost-app keys\`.`;
298
+ return `There's no production ${name} key: ${file} doesn't exist. Create one with \`ghost-app keys --production\`, or set ${variableFor(name)}.`;
299
+ }
300
+ var variableFor = (name) => name === "identity" ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;
301
+ /**
302
+ * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only
303
+ * their owner can read, and keeps any that exist.
304
+ */
305
+ async function createKeys({ root, mode }) {
306
+ const keys = KEY_NAMES.map((name) => {
307
+ const file = keyFile(mode, name);
308
+ return {
309
+ name,
310
+ file,
311
+ pending: join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`)
312
+ };
313
+ });
314
+ await refuseUnlessGitIgnores(root, [...keys.map(({ file }) => file), ...keys.map(({ pending }) => pending)]);
315
+ await mkdir(join(root, KEYS_DIRECTORY, mode), {
316
+ recursive: true,
317
+ mode: 448
318
+ });
319
+ const result = {
320
+ created: [],
321
+ kept: []
322
+ };
323
+ for (const { name, file, pending } of keys) result[await publishKey(join(root, file), join(root, pending)) ? "created" : "kept"].push(name);
324
+ return result;
325
+ }
326
+ async function refuseUnlessGitIgnores(root, files) {
327
+ const ignored = await isGitIgnored(root, files);
328
+ if (!ignored.ignored) throw new Error(`Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`);
329
+ }
330
+ /** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */
331
+ async function publishKey(file, pending) {
332
+ try {
333
+ await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\n`, {
334
+ flag: "wx",
335
+ mode: 384
336
+ });
337
+ await link(pending, file);
338
+ return true;
339
+ } catch (error) {
340
+ if (error.code !== "EEXIST") throw error;
341
+ if (process.platform !== "win32" && ((await stat(file)).mode & 63) !== 0) await chmod(file, 384);
342
+ return false;
343
+ } finally {
344
+ await rm(pending, { force: true });
345
+ }
346
+ }
347
+ /**
348
+ * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to
349
+ * anything but blanks, or else the key's file.
350
+ */
351
+ function signingKeySource(mode, name, env = process.env) {
352
+ const variable = variableFor(name);
353
+ return mode === "production" && env[variable]?.trim() ? variable : keyFile(mode, name);
354
+ }
355
+ /**
356
+ * The keys to sign a mode's manifest with, from the key files, or in production from
357
+ * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.
358
+ */
359
+ async function readSigningKeys({ root, mode, env = process.env }) {
360
+ const fromVariable = (name) => signingKeySource(mode, name, env) === variableFor(name) ? env[variableFor(name)].trim() : void 0;
361
+ const identityText = fromVariable("identity");
362
+ const identityKey = identityText ? await sameAsFile(root, mode, "identity", await readKey(identityText, IDENTITY_KEY_VARIABLE)) : await readKeyFile(root, mode, "identity");
363
+ const backendText = fromVariable("backend");
364
+ const backendKey = publicKeyOf(backendText ? await sameAsFile(root, mode, "backend", await readAnyKey(backendText, BACKEND_KEY_VARIABLE)) : await readKeyFile(root, mode, "backend"));
365
+ if (identityKey.x === backendKey.x) throw new Error("The identity key and the backend key are the same key; they must be two keys");
366
+ return {
367
+ identityKey,
368
+ backendKey
369
+ };
370
+ }
371
+ /**
372
+ * A key from a variable, after checking it's the same key as the file, where there's one. A
373
+ * variable left set, such as a development key exported for every shell, would otherwise win over
374
+ * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every
375
+ * site.
376
+ */
377
+ async function sameAsFile(root, mode, name, key) {
378
+ const file = keyFile(mode, name);
379
+ if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {
380
+ const variable = variableFor(name);
381
+ 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.`);
382
+ }
383
+ return key;
384
+ }
385
+ /** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */
386
+ function readBackendKey({ root, mode }) {
387
+ return readKeyFile(root, mode, "backend");
388
+ }
389
+ //#endregion
390
+ //#region ../../contracts/app-contracts/build/manifest/icon.js
391
+ var ICON_NAME_MAX_LENGTH = 64;
392
+ var ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
393
+ var EITHER = "Expected an icon with either a name or a url";
394
+ /**
395
+ * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app
396
+ * serves. Ghost keeps a copy of the image with each manifest version it stores, and only
397
+ * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;
398
+ * Admin falls back to a default icon.
399
+ */
400
+ function iconField(url) {
401
+ return z.strictObject({
402
+ 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(),
403
+ url: url().optional()
404
+ }, EITHER).refine(({ name, url: iconUrl }) => name === void 0 !== (iconUrl === void 0), EITHER).pipe(z.custom());
405
+ }
406
+ //#endregion
407
+ //#region ../../contracts/app-contracts/build/manifest/keys.js
408
+ var ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
409
+ var EXPECTED = "Expected a public Ed25519 key as a JWK with kty, crv and x";
410
+ var PRIVATE = "Expected a public key, but this includes its private part (d)";
411
+ /**
412
+ * A key a manifest names. A manifest is public, so a key that includes its private part
413
+ * is refused with a message of its own: it has to be replaced, not just removed. Other
414
+ * members are refused by name, as key tools often add some, such as `kid` or `alg`.
415
+ */
416
+ var publicKeyField = z.strictObject({
417
+ kty: z.literal("OKP", EXPECTED),
418
+ crv: z.literal("Ed25519", EXPECTED),
419
+ x: z.string(EXPECTED).regex(ED25519_X, "Expected 32 bytes in base64url, without padding")
420
+ }, { error: (issue) => {
421
+ if (issue.code !== "unrecognized_keys") return EXPECTED;
422
+ return issue.keys.includes("d") ? PRIVATE : `Expected only kty, crv and x; remove ${issue.keys.join(", ")}`;
423
+ } });
424
+ //#endregion
425
+ //#region ../../contracts/app-contracts/build/manifest/surfaces.js
426
+ /**
427
+ * What an app asks for: the places in Ghost it wants to appear. Each surface type is one
428
+ * entry in a union, so a new one is added here and nowhere else.
429
+ */
430
+ function surfacesField(url) {
431
+ const surfaceTypes = [z.strictObject({
432
+ type: z.literal("admin_page"),
433
+ url: url()
434
+ })];
435
+ const surface = z.discriminatedUnion("type", surfaceTypes, { error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(", ")}` });
436
+ return z.array(surface, "Expected a list of surfaces").min(1, "Expected at least one surface").superRefine((surfaces, ctx) => {
437
+ const seen = /* @__PURE__ */ new Set();
438
+ surfaces.forEach((entry, index) => {
439
+ if (seen.has(entry.type)) ctx.addIssue({
440
+ code: "custom",
441
+ message: `Expected at most one ${entry.type} surface`,
442
+ path: [index]
443
+ });
444
+ seen.add(entry.type);
445
+ });
446
+ });
447
+ }
448
+ //#endregion
449
+ //#region ../../contracts/app-contracts/build/manifest/text.js
450
+ var VISIBLE_CHARACTER = /* @__PURE__ */ new RegExp("(?![\\u2800\\p{Default_Ignorable_Code_Point}])[\\p{L}\\p{N}\\p{P}\\p{S}]", "u");
451
+ var shows = (text) => VISIBLE_CHARACTER.test(text);
452
+ var blank = (character) => !shows(character) && isPlainText(character.replace(/\s/gu, ""));
453
+ var graphemes;
454
+ /**
455
+ * Takes off each end the characters, as a reader sees them, that show nothing: a space with a
456
+ * mark on it goes, an emoji with its variation selector stays, and so does anything invisible
457
+ * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no
458
+ * more than its length.
459
+ */
460
+ function trimEdges(value) {
461
+ graphemes ??= new Intl.Segmenter();
462
+ const characters = graphemes.segment(value);
463
+ let start = value.length;
464
+ for (const { segment, index } of characters) if (!blank(segment)) {
465
+ start = index;
466
+ break;
467
+ }
468
+ let end = value.length;
469
+ while (end > start) {
470
+ const { segment, index } = characters.containing(end - 1);
471
+ if (!blank(segment)) break;
472
+ end = index;
473
+ }
474
+ return value.slice(start, end);
475
+ }
476
+ /**
477
+ * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and
478
+ * text with nothing visible left, such as a name of Hangul fillers, is refused.
479
+ */
480
+ function plainText(maxLength) {
481
+ 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");
482
+ }
483
+ var ANY_CHARACTER = /[\p{L}\p{N}\p{P}\p{S}]/u;
484
+ /**
485
+ * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before
486
+ * blank names were refused still reads, and the app can still be listed and uninstalled.
487
+ */
488
+ function storedText(maxLength) {
489
+ 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");
490
+ }
491
+ //#endregion
492
+ //#region ../../contracts/app-contracts/build/manifest/url.js
493
+ var FRAGMENT_PROBLEM = "Expected a URL without a fragment";
494
+ /**
495
+ * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`
496
+ * hides. A fragment never reaches the server, so a manifest address with one is a mistake or
497
+ * a second spelling of the same address.
498
+ */
499
+ var hasFragment = (address) => address.includes("#");
500
+ /**
501
+ * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would
502
+ * use. The length is measured on the parsed URL for the same reason, as that is what is
503
+ * stored and checked again later.
504
+ */
505
+ function checkResolvedUrl(url, allowLocalhost) {
506
+ if (url.href.length > 2e3) return `Expected at most ${URL_MAX_LENGTH} characters`;
507
+ if (url.username || url.password) return "Expected a URL without a username or password";
508
+ if (isLocalhost(url.hostname)) {
509
+ if (!allowLocalhost) return "Expected a public address; localhost is only allowed when Ghost runs in development";
510
+ return url.protocol === "https:" || url.protocol === "http:" ? null : "Expected an http or https URL";
511
+ }
512
+ return url.protocol === "https:" ? null : "Expected an https URL";
513
+ }
514
+ var ROUTE_PROBLEM = "Expected a URL that resolves to a path starting with a single /, with no \\ in its query or fragment";
515
+ var PATH_PROBLEM = "Expected a path on the manifest’s own origin, such as /admin";
516
+ var PLACEHOLDER_HOSTS = ["manifest-a.invalid", "manifest-b.invalid"];
517
+ /** Whether a reference names a host, in any of the URL parser's spellings of one. */
518
+ var namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);
519
+ function isManifestItself(url, base) {
520
+ return url.pathname === new URL(base).pathname;
521
+ }
522
+ /**
523
+ * A URL in the manifest. What Ghost loads is written as a path, resolved against the
524
+ * address the manifest was fetched from, so an app is one origin: the one Ghost fetches
525
+ * the manifest from and challenges is the one every surface runs on. The manifest names
526
+ * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they
527
+ * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.
528
+ *
529
+ * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and
530
+ * may be anywhere, the publisher's own site included.
531
+ *
532
+ * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.
533
+ * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.
534
+ * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which
535
+ * names a host, and a `\` in the query or fragment is left as it is. Only the page is opened
536
+ * as a route, but every URL Ghost loads is held to the one rule.
537
+ */
538
+ function urlField({ allowLocalhost, base }, linkOnly = false) {
539
+ if (linkOnly) return z.string("Expected an absolute URL").transform((value, ctx) => {
540
+ const url = URL.parse(value);
541
+ const problem = url ? checkResolvedUrl(url, allowLocalhost) : "Expected an absolute URL";
542
+ if (problem) {
543
+ ctx.addIssue({
544
+ code: "custom",
545
+ message: problem
546
+ });
547
+ return z.NEVER;
548
+ }
549
+ return url.href;
550
+ });
551
+ const origin = new URL(base).origin;
552
+ return z.string(PATH_PROBLEM).transform((value, ctx) => {
553
+ const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);
554
+ if (!url || url.origin !== origin || isManifestItself(url, base)) {
555
+ ctx.addIssue({
556
+ code: "custom",
557
+ message: PATH_PROBLEM
558
+ });
559
+ return z.NEVER;
560
+ }
561
+ const problem = checkResolvedUrl(url, allowLocalhost);
562
+ if (problem) {
563
+ ctx.addIssue({
564
+ code: "custom",
565
+ message: problem
566
+ });
567
+ return z.NEVER;
568
+ }
569
+ if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {
570
+ ctx.addIssue({
571
+ code: "custom",
572
+ message: ROUTE_PROBLEM
573
+ });
574
+ return z.NEVER;
575
+ }
576
+ return url.href;
577
+ });
578
+ }
579
+ var MAILTO_PROBLEM = "Expected a mailto: link to one email address";
580
+ var EMAIL_PART = String.raw`[^\s\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\u2800@,;:<>()[\]\\"?#%/]+`;
581
+ var EMAIL_ADDRESS = new RegExp(String.raw`^${EMAIL_PART}@${EMAIL_PART}\.${EMAIL_PART}$`, "u");
582
+ /**
583
+ * Everything after a `mailto:` link's scheme, decoded as a mail client decodes it. That's the
584
+ * whole recipient list, query and fragment included: a mail client doesn't read `//` as an
585
+ * authority, so the URL's `pathname` alone can miss a recipient.
586
+ */
587
+ function mailtoRecipients(link) {
588
+ try {
589
+ return decodeURIComponent(link.href.slice(7));
590
+ } catch {
591
+ return null;
592
+ }
593
+ }
594
+ /**
595
+ * A link to an app's developer: a URL as `url(true)` holds it, or a `mailto:` link to one email
596
+ * address. Ghost only ever links to it. A `mailto:` link takes no query or fragment, not even an
597
+ * empty one, so it can't prefill a message or add recipients. The address is checked as a mail
598
+ * client decodes it, so an escaped `,` can't add a second one.
599
+ */
600
+ function contactField(url) {
601
+ const web = url(true);
602
+ return z.string("Expected an absolute URL").transform((value, ctx) => {
603
+ const link = URL.parse(value);
604
+ if (link?.protocol !== "mailto:") {
605
+ const result = web.safeParse(value);
606
+ if (!result.success) {
607
+ for (const issue of result.error.issues) ctx.addIssue({
608
+ code: "custom",
609
+ message: issue.message
610
+ });
611
+ return z.NEVER;
612
+ }
613
+ return result.data;
614
+ }
615
+ const recipients = mailtoRecipients(link);
616
+ if (!recipients || link.href.length > 2e3 || !EMAIL_ADDRESS.test(recipients)) {
617
+ ctx.addIssue({
618
+ code: "custom",
619
+ message: MAILTO_PROBLEM
620
+ });
621
+ return z.NEVER;
622
+ }
623
+ return link.href;
624
+ });
625
+ }
626
+ /**
627
+ * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and
628
+ * already checked. Nothing is resolved or checked again, so a manifest accepted before the
629
+ * site's URL changed still reads back.
630
+ */
631
+ var absoluteUrl = () => z.url("Expected an absolute URL");
632
+ //#endregion
633
+ //#region ../../contracts/app-contracts/build/manifest/schema.js
634
+ var NAME_MAX_LENGTH = 50;
635
+ var DESCRIPTION_MAX_LENGTH = 200;
636
+ var AUTHOR_NAME_MAX_LENGTH = 50;
637
+ var HEX_COLOR = /^#[0-9a-f]{6}$/i;
638
+ var KEY_FIELDS = /* @__PURE__ */ new Set(["identity_key", "backend_key"]);
639
+ var URL_FIELDS = /* @__PURE__ */ new Set([
640
+ "author",
641
+ "icon",
642
+ "surfaces",
643
+ "manifest_url",
644
+ "development"
645
+ ]);
646
+ /** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */
647
+ var parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));
648
+ /**
649
+ * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot
650
+ * claim something Ghost has not designed, and adding a field is always a deliberate change
651
+ * here.
652
+ *
653
+ * Defined once, with the URL and text rules left open. What a valid URL is depends on whether
654
+ * the manifest is being parsed, when where Ghost is served from matters, or read back after it
655
+ * was, when it doesn't. Text is held to today's rules when parsed, and read back under the
656
+ * rules it was stored under. The author's link is held to its own rule when parsed, which
657
+ * allows a mailto: link, and read back as any absolute URL.
658
+ */
659
+ function manifestShape(url, text, contact) {
660
+ return z.strictObject({
661
+ id: z.custom(isValidAppId, { error: `Expected a lowercase reverse-domain ID such as com.example.app, at most 191 characters` }),
662
+ name: text(NAME_MAX_LENGTH),
663
+ description: text(DESCRIPTION_MAX_LENGTH),
664
+ author: z.strictObject({
665
+ name: text(AUTHOR_NAME_MAX_LENGTH),
666
+ url: contact()
667
+ }, "Expected an author with a name and a url"),
668
+ accent_color: z.string("Expected a hex colour such as #ff5500").regex(HEX_COLOR, "Expected a hex colour such as #ff5500").toLowerCase(),
669
+ icon: iconField(url),
670
+ surfaces: surfacesField(url),
671
+ manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),
672
+ identity_key: publicKeyField,
673
+ backend_key: publicKeyField,
674
+ development: z.boolean("Expected true or false")
675
+ }).refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {
676
+ message: "Expected a different key from identity_key",
677
+ path: ["backend_key"],
678
+ when: parsedFields(KEY_FIELDS)
679
+ }).refine((manifest) => manifest.development || ![
680
+ manifest.author.url,
681
+ "url" in manifest.icon ? manifest.icon.url : void 0,
682
+ ...manifest.surfaces.map((surface) => surface.url),
683
+ manifest.manifest_url
684
+ ].some((address) => address !== void 0 && isLocalhost(new URL(address).hostname)), {
685
+ message: "Expected true, as the app is on localhost",
686
+ path: ["development"],
687
+ when: parsedFields(URL_FIELDS)
688
+ });
689
+ }
690
+ /** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */
691
+ function manifestSchema(rules) {
692
+ const url = (linkOnly) => urlField(rules, linkOnly);
693
+ return manifestShape(url, plainText, () => contactField(url));
694
+ }
695
+ manifestShape(absoluteUrl, storedText, absoluteUrl);
696
+ //#endregion
697
+ //#region ../../contracts/app-contracts/build/manifest/parse.js
698
+ function formatPath(path) {
699
+ return path.reduce((result, part) => {
700
+ if (typeof part === "number") return `${result}[${part}]`;
701
+ return result ? `${result}.${String(part)}` : String(part);
702
+ }, "");
703
+ }
704
+ var GHOST_URLS_PROBLEM = "Expected the URLs Ghost itself is served from";
705
+ 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";
706
+ 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`;
707
+ /**
708
+ * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most
709
+ * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`
710
+ * is a host of its own, which browsers send to the machine itself, and so does Ghost in
711
+ * development, whatever the system's resolver knows.
712
+ */
713
+ function onGhostHost(url) {
714
+ return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;
715
+ }
716
+ /**
717
+ * Reads the address a manifest is to be read from, by the same rules as the URLs inside
718
+ * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first
719
+ * request never goes to an address Ghost would refuse (plain HTTP, one carrying
720
+ * credentials, or one on Ghost's host). It cannot judge where that address redirects,
721
+ * which is for whatever fetches it to limit.
722
+ *
723
+ * The address it hands back is the one to store, to compare with a later one, and that the
724
+ * manifest must name as its `manifest_url`. The URL parser settles most differences in
725
+ * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a
726
+ * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.
727
+ */
728
+ function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {
729
+ if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) return {
730
+ success: false,
731
+ error: GHOST_URLS_PROBLEM
732
+ };
733
+ const url = URL.parse(input);
734
+ if (!url) return {
735
+ success: false,
736
+ error: "Expected the manifest at a URL"
737
+ };
738
+ const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);
739
+ if (problem) return {
740
+ success: false,
741
+ error: `${problem} for the manifest itself`
742
+ };
743
+ if (isGhostHost(url, ghostUrls)) return {
744
+ success: false,
745
+ error: onGhostHost(url)
746
+ };
747
+ return {
748
+ success: true,
749
+ manifestUrl: url.href
750
+ };
751
+ }
752
+ /** A manifest's problems as `path: message`, joined by `separator`, as Ghost reports them. */
753
+ function formatManifestErrors(errors, separator) {
754
+ return errors.map(({ path, message }) => path ? `${path}: ${message}` : message).join(separator);
755
+ }
756
+ function invalid(errors) {
757
+ return {
758
+ success: false,
759
+ reason: "invalid",
760
+ errors
761
+ };
762
+ }
763
+ /**
764
+ * Validates a manifest, and checks it names the address it was fetched from as its
765
+ * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the
766
+ * manifest to its address as well as to every URL in it.
767
+ *
768
+ * Returns either the manifest, or every problem found. It does not fetch anything and it
769
+ * never throws. Without the URLs Ghost is served from it rejects every manifest, since the
770
+ * rule that keeps apps off Ghost's hosts could not be checked.
771
+ */
772
+ function parseManifest(input, options) {
773
+ const allowLocalhost = options.allowLocalhost ?? false;
774
+ const address = parseManifestUrl(options.manifestUrl, options);
775
+ if (!address.success) return invalid([{
776
+ path: "",
777
+ message: address.error
778
+ }]);
779
+ const result = manifestSchema({
780
+ allowLocalhost,
781
+ base: address.manifestUrl
782
+ }).safeParse(input);
783
+ if (!result.success) return invalid(result.error.issues.map((issue) => ({
784
+ path: formatPath(issue.path),
785
+ message: issue.message
786
+ })));
787
+ if (result.data.manifest_url !== address.manifestUrl) return {
788
+ success: false,
789
+ reason: "manifest_url_mismatch",
790
+ errors: [{
791
+ path: "manifest_url",
792
+ message: `Expected ${address.manifestUrl}, the address the manifest was read from`
793
+ }]
794
+ };
795
+ return {
796
+ success: true,
797
+ manifest: result.data
798
+ };
799
+ }
800
+ //#endregion
801
+ //#region src/tooling/sign.ts
802
+ /** The readable manifest a project keeps, which the tooling signs. */
803
+ var MANIFEST_FILE = "ghost-app.json";
804
+ /** The fields the tooling adds, which `ghost-app.json` mustn't set. */
805
+ var ADDED_FIELDS = [
806
+ "manifest_url",
807
+ "identity_key",
808
+ "backend_key",
809
+ "development"
810
+ ];
811
+ var refuse = (code, message, path = "") => ({
812
+ success: false,
813
+ code,
814
+ errors: [{
815
+ path,
816
+ message
817
+ }]
818
+ });
819
+ /**
820
+ * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it
821
+ * with the identity key, unless Ghost would refuse it.
822
+ */
823
+ async function signAppManifest(source, options) {
824
+ await readKey(JSON.stringify(options.identityKey), "identityKey");
825
+ if ("d" in options.backendKey) await readKey(JSON.stringify(options.backendKey), "backendKey");
826
+ const address = parseManifestUrl(options.manifestUrl, {
827
+ ghostUrls: [UNKNOWN_GHOST_URL],
828
+ allowLocalhost: true
829
+ });
830
+ if (!address.success) return refuse("APP_MANIFEST_URL_INVALID", address.error);
831
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return refuse("APP_MANIFEST_INVALID", "Expected the manifest as a JSON object");
832
+ const added = ADDED_FIELDS.filter((field) => field in source);
833
+ if (added.length > 0) return {
834
+ success: false,
835
+ code: "APP_MANIFEST_INVALID",
836
+ errors: added.map((field) => ({
837
+ path: field,
838
+ message: `Leave ${field} out: it's added when the manifest is signed`
839
+ }))
840
+ };
841
+ const manifest = {
842
+ ...source,
843
+ manifest_url: address.manifestUrl,
844
+ identity_key: publicKeyOf(options.identityKey),
845
+ backend_key: publicKeyOf(options.backendKey),
846
+ development: options.development
847
+ };
848
+ const parsed = parseManifest(manifest, {
849
+ manifestUrl: address.manifestUrl,
850
+ ghostUrls: [UNKNOWN_GHOST_URL],
851
+ allowLocalhost: true
852
+ });
853
+ if (!parsed.success) return {
854
+ success: false,
855
+ code: "APP_MANIFEST_INVALID",
856
+ errors: parsed.errors
857
+ };
858
+ const signed = await signManifest(JSON.stringify(manifest), options.identityKey);
859
+ if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) return refuse("APP_MANIFEST_TOO_LARGE", `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB`);
860
+ return {
861
+ success: true,
862
+ signed,
863
+ manifest
864
+ };
865
+ }
866
+ /** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */
867
+ function formatErrors(errors) {
868
+ return formatManifestErrors(errors, "\n");
869
+ }
870
+ /** A signed manifest as the CLI and the Vite plugin write it to a file. */
871
+ function serialiseSigned(signed) {
872
+ return `${JSON.stringify(signed, null, 2)}\n`;
873
+ }
874
+ /** Reads `ghost-app.json`, or another readable manifest, as JSON. */
875
+ async function readManifestSource(file) {
876
+ const text = await readFile(file, "utf8");
877
+ try {
878
+ return parseJsonText(text);
879
+ } catch (error) {
880
+ throw new Error(`${file} isn't JSON: ${error.message}`, { cause: error });
881
+ }
882
+ }
883
+ /** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */
884
+ async function signProject({ root, mode, env, manifestUrl, manifestFile = MANIFEST_FILE }) {
885
+ return signAppManifest(await readManifestSource(resolve(root, manifestFile)), {
886
+ manifestUrl,
887
+ ...await readSigningKeys({
888
+ root,
889
+ mode,
890
+ env
891
+ }),
892
+ development: mode === "development"
893
+ });
894
+ }
895
+ //#endregion
896
+ export { signingKeySource as _, signAppManifest as a, isLocalhost as b, IDENTITY_KEY_VARIABLE as c, createKeys as d, generateKey as f, readSigningKeys as g, readBackendKey as h, serialiseSigned as i, KEYS_DIRECTORY as l, publicKeyOf as m, formatErrors as n, signProject as o, keyFile as p, readManifestSource as r, BACKEND_KEY_VARIABLE as s, MANIFEST_FILE as t, KEY_NAMES as u, parseJsonText as v, isValidAppId as y };
897
+
898
+ //# sourceMappingURL=sign-B1y31TLX.js.map