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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,77 @@
1
+ import { base64url } from "jose";
2
+ //#region ../app-contracts/build/identity/keys.js
3
+ function decodeUtf8(bytes) {
4
+ return new TextDecoder("utf-8", {
5
+ fatal: true,
6
+ ignoreBOM: true
7
+ }).decode(bytes);
8
+ }
9
+ function decodeText(encoded) {
10
+ try {
11
+ return decodeUtf8(base64url.decode(encoded));
12
+ } catch {
13
+ return;
14
+ }
15
+ }
16
+ function decodeJson(encoded) {
17
+ const text = decodeText(encoded);
18
+ if (text === void 0) return;
19
+ try {
20
+ return JSON.parse(text);
21
+ } catch {
22
+ return;
23
+ }
24
+ }
25
+ //#endregion
26
+ //#region ../app-contracts/build/identity/jws.js
27
+ /** The only algorithm either key signs with. */
28
+ var ALGORITHM = "Ed25519";
29
+ /**
30
+ * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any
31
+ * other member could change what the signature covers, as `b64: false` does, or name
32
+ * another key, so the header is checked before the signature and again when verifying.
33
+ */
34
+ function readExactHeader(encoded, shape) {
35
+ const parsed = shape.safeParse(decodeJson(encoded));
36
+ return parsed.success ? parsed.data : void 0;
37
+ }
38
+ //#endregion
39
+ //#region src/shared/parse.ts
40
+ var UNSAFE_IN_POLICY = /[\s;,'"*]/;
41
+ /**
42
+ * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
43
+ * `,` into a host, so the origin must also read back as itself, and hold nothing that would end
44
+ * a source in a Content-Security-Policy.
45
+ */
46
+ function parseOrigin(entry) {
47
+ const url = URL.parse(entry);
48
+ const origin = url?.origin;
49
+ if (!url || !origin || url.protocol !== "https:" && url.protocol !== "http:" || url.href !== `${origin}/` || URL.parse(origin)?.origin !== origin || UNSAFE_IN_POLICY.test(entry) || UNSAFE_IN_POLICY.test(origin)) return;
50
+ return origin;
51
+ }
52
+ /** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
53
+ function parseJsonText(text) {
54
+ return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
55
+ }
56
+ //#endregion
57
+ //#region src/shared/ignore.ts
58
+ /** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
59
+ var ignoreError = () => void 0;
60
+ //#endregion
61
+ //#region src/shared/manifest.ts
62
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
63
+ var MANIFEST_PATH = "/ghost-app.json";
64
+ /**
65
+ * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but
66
+ * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost
67
+ * applies them.
68
+ */
69
+ var UNKNOWN_GHOST_URL = "https://ghost.invalid/";
70
+ /** A manifest's problems, one per line, as `path: message`. */
71
+ function formatErrors(errors, separator = "\n") {
72
+ return errors.map(({ path, message }) => path ? `${path}: ${message}` : message).join(separator);
73
+ }
74
+ //#endregion
75
+ export { parseJsonText as a, readExactHeader as c, ignoreError as i, decodeText as l, UNKNOWN_GHOST_URL as n, parseOrigin as o, formatErrors as r, ALGORITHM as s, MANIFEST_PATH as t, decodeUtf8 as u };
76
+
77
+ //# sourceMappingURL=manifest-iOwbzAil.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest-iOwbzAil.js","names":[],"sources":["../../../app-contracts/build/identity/keys.js","../../../app-contracts/build/identity/jws.js","../../src/shared/parse.ts","../../src/shared/ignore.ts","../../src/shared/manifest.ts"],"sourcesContent":["import { base64url, calculateJwkThumbprint } from 'jose';\n/**\n * A key's RFC 7638 thumbprint: the same for a key however its JWK is written, so it is\n * what Ghost stores to recognise a key again.\n */\nexport function thumbprintOf(key) {\n return calculateJwkThumbprint({ kty: key.kty, crv: key.crv, x: key.x }, 'sha256');\n}\nexport function decodeUtf8(bytes) {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\nexport function decodeText(encoded) {\n try {\n return decodeUtf8(base64url.decode(encoded));\n }\n catch {\n return undefined;\n }\n}\nexport function decodeJson(encoded) {\n const text = decodeText(encoded);\n if (text === undefined) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=keys.js.map","import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text: string): unknown {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n\n/** One problem with a manifest. */\nexport interface ManifestError {\n /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */\n path: string;\n message: string;\n}\n\n/**\n * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but\n * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost\n * applies them.\n */\nexport const UNKNOWN_GHOST_URL = 'https://ghost.invalid/';\n\n/** A manifest's problems, one per line, as `path: message`. */\nexport function formatErrors(errors: readonly ManifestError[], separator = '\\n'): string {\n return errors\n .map(({ path, message }) => (path ? `${path}: ${message}` : message))\n .join(separator);\n}\n"],"mappings":";;AAQA,SAAgB,WAAW,OAAO;CAC9B,OAAO,IAAI,YAAY,SAAS;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AAClF;AACA,SAAgB,WAAW,SAAS;CAChC,IAAI;EACA,OAAO,WAAW,UAAU,OAAO,OAAO,CAAC;CAC/C,QACM;EACF;CACJ;AACJ;AACA,SAAgB,WAAW,SAAS;CAChC,MAAM,OAAO,WAAW,OAAO;CAC/B,IAAI,SAAS,KAAA,GACT;CAEJ,IAAI;EACA,OAAO,KAAK,MAAM,IAAI;CAC1B,QACM;EACF;CACJ;AACJ;;;;AC5BA,IAAa,YAAY;;;;;;AAMzB,SAAgB,gBAAgB,SAAS,OAAO;CAC5C,MAAM,SAAS,MAAM,UAAU,WAAW,OAAO,CAAC;CAClD,OAAO,OAAO,UAAU,OAAO,OAAO,KAAA;AAC1C;;;ACVA,IAAM,mBAAmB;;;;;;AAOzB,SAAgB,YAAY,OAAmC;CAC7D,MAAM,MAAM,IAAI,MAAM,KAAK;CAC3B,MAAM,SAAS,KAAK;CACpB,IACE,CAAC,OACD,CAAC,UACA,IAAI,aAAa,YAAY,IAAI,aAAa,WAC/C,IAAI,SAAS,GAAG,OAAO,MACvB,IAAI,MAAM,MAAM,CAAC,EAAE,WAAW,UAC9B,iBAAiB,KAAK,KAAK,KAC3B,iBAAiB,KAAK,MAAM,GAE5B;CAEF,OAAO;AACT;;AAGA,SAAgB,cAAc,MAAuB;CACnD,OAAO,KAAK,MAAM,KAAK,WAAW,CAAC,MAAM,QAAS,KAAK,MAAM,CAAC,IAAI,IAAI;AACxE;;;;AC3BA,IAAa,oBAA+B,KAAA;;;;ACG5C,IAAa,gBAAgB;;;;;;AAqB7B,IAAa,oBAAoB;;AAGjC,SAAgB,aAAa,QAAkC,YAAY,MAAc;CACvF,OAAO,OACJ,KAAK,EAAE,MAAM,cAAe,OAAO,GAAG,KAAK,IAAI,YAAY,OAAQ,CAAC,CACpE,KAAK,SAAS;AACnB"}
@@ -1,5 +1,5 @@
1
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";
2
+ import { a as parseJsonText, c as readExactHeader, i as ignoreError, l as decodeText, n as UNKNOWN_GHOST_URL, s as ALGORITHM } from "./manifest-iOwbzAil.js";
3
3
  import { FlattenedSign, flattenedVerify, importJWK } from "jose";
4
4
  import { z } from "zod";
5
5
  import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from "node:crypto";
@@ -572,208 +572,6 @@ function storedSize(manifest) {
572
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
573
  var tooLargeMessage = () => `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;
574
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
575
  //#region src/tooling/git.ts
778
576
  function git(args, cwd, input) {
779
577
  return new Promise((done) => {
@@ -1125,6 +923,6 @@ async function signProject({ root, mode, env, manifestUrl, manifestFile = MANIFE
1125
923
  });
1126
924
  }
1127
925
  //#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 };
926
+ export { parseManifest as C, isValidAppId as D, verifySignedManifest as E, isLocalhost as O, tooLargeMessage as S, readSignedManifest as T, ANSWER_MAX_BYTES as _, signProject as a, TIMEOUT_MS as b, KEYS_DIRECTORY as c, generateKey as d, keyFile as f, signingKeySource 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, MANIFEST_MAX_BYTES as v, parseManifestUrl as w, storedSize as x, SIGNED_MANIFEST_MAX_BYTES as y };
1129
927
 
1130
- //# sourceMappingURL=sign-BhNJAPta.js.map
928
+ //# sourceMappingURL=sign-DygdzQYY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-DygdzQYY.js","names":[],"sources":["../../../app-contracts/build/manifest/localhost.js","../../../app-contracts/build/manifest/ghost-host.js","../../../app-contracts/build/manifest/id.js","../../../app-contracts/build/manifest/limits.js","../../../app-contracts/build/identity/signed-manifest.js","../../../app-contracts/build/manifest/icon.js","../../../app-contracts/build/manifest/keys.js","../../../app-contracts/build/manifest/surfaces.js","../../../app-contracts/build/manifest/text.js","../../../app-contracts/build/manifest/url.js","../../../app-contracts/build/manifest/schema.js","../../../app-contracts/build/manifest/parse.js","../../src/tooling/limits.ts","../../src/tooling/git.ts","../../src/tooling/keys.ts","../../src/tooling/sign.ts"],"sourcesContent":["// `URL` has already normalised the host by the time these run: every spelling of an IPv4\n// address is dotted decimal, and an IPv4-mapped IPv6 address is two hex groups.\nconst LOOPBACK_HOSTS = [\n /^localhost$/,\n /\\.localhost$/,\n /^127\\.\\d+\\.\\d+\\.\\d+$/,\n /^0\\.0\\.0\\.0$/,\n /^\\[::1?\\]$/,\n /^\\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\\]$/,\n /^\\[::ffff:0:0\\]$/,\n];\n/**\n * A hostname without its trailing dots, which the URL parser keeps, every one of them:\n * `localhost..` is `localhost`. A loop rather than a regular expression, which would take\n * time quadratic in the number of dots on a hostname with many dots before its end.\n */\nexport function withoutTrailingDots(hostname) {\n let end = hostname.length;\n while (end > 0 && hostname[end - 1] === '.') {\n end -= 1;\n }\n return hostname.slice(0, end);\n}\n/**\n * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.\n * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as\n * `isGhostHost` drops them.\n */\nexport function isLocalhost(hostname) {\n const host = withoutTrailingDots(hostname);\n return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));\n}\n//# sourceMappingURL=localhost.js.map","import { withoutTrailingDots } from './localhost.js';\n/**\n * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any\n * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,\n * whatever a frame's sandbox says. On another port it would be the app's, but browsers send\n * a host's cookies to every port on it, so the app's server would be sent the staff user's\n * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it\n * frames the page, since the site's or Admin's address can change after an app is\n * installed.\n *\n * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and\n * without a trailing dot. A sibling host, such as another subdomain of the site's, is not\n * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as\n * `my-app.localhost` next to `localhost`, or another name for the same machine, such as\n * `127.0.0.1`, which browsers treat as other hosts too.\n *\n * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no\n * Ghost URLs at all. Either way the URL is refused.\n */\nexport function isGhostHost(url, ghostUrls) {\n const host = hostOf(url);\n if (host === null) {\n return true;\n }\n let known = false;\n for (const ghostUrl of ghostUrls) {\n const ghostHost = hostOf(ghostUrl);\n if (ghostHost === null || ghostHost === host) {\n return true;\n }\n known = true;\n }\n return !known;\n}\n/** An http or https URL's host as `isGhostHost` compares it, or null for any other. */\nexport function hostOf(value) {\n let url;\n // Admin runs this, and `URL.parse` is newer than the browsers Admin supports.\n try {\n url = new URL(value);\n }\n catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return null;\n }\n return withoutTrailingDots(url.hostname) || null;\n}\n//# sourceMappingURL=ghost-host.js.map","/** Matches the limit of the index that ties saved cards to an app. */\nexport const APP_ID_MAX_LENGTH = 191;\nconst ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n/**\n * An app ID is reverse-domain style: at least two dot-separated segments of lowercase\n * letters, digits and hyphens, starting with a letter so that an IP address or a version\n * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than\n * lowercased.\n */\nexport function isValidAppId(value) {\n if (typeof value !== 'string' || value.length > APP_ID_MAX_LENGTH) {\n return false;\n }\n const segments = value.split('.');\n return (segments.length >= 2 &&\n /^[a-z]/.test(value) &&\n segments.every((segment) => ID_SEGMENT.test(segment)));\n}\n//# sourceMappingURL=id.js.map","/**\n * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of\n * them, the manifest's own URL included, so its columns are exactly this wide.\n */\nexport const URL_MAX_LENGTH = 2000;\n//# sourceMappingURL=limits.js.map","import { FlattenedSign, flattenedVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeText } from './keys.js';\n/** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */\nexport const SIGNED_MANIFEST_TYPE = 'ghost-app-manifest';\nconst SignedManifestShape = z.strictObject({\n protected: z.string(),\n payload: z.string(),\n signature: z.string(),\n});\nconst ProtectedHeader = z.strictObject({\n alg: z.literal(ALGORITHM),\n typ: z.literal(SIGNED_MANIFEST_TYPE),\n});\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE });\n/**\n * Signs a manifest with an app's identity key. A string is signed as the exact text it is;\n * anything else is signed as its JSON.\n */\nexport async function signManifest(manifest, identityKey) {\n const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest);\n const signed = await new FlattenedSign(new TextEncoder().encode(text))\n .setProtectedHeader({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE })\n .sign(identityKey);\n return { protected: signed.protected, payload: signed.payload, signature: signed.signature };\n}\n/**\n * Reads the manifest out of a signed manifest, without verifying it. The key to verify it\n * with is named inside the manifest, so the manifest has to be read and checked first;\n * nothing in it may be used until `verifySignedManifest` has passed.\n */\nexport function readSignedManifest(body) {\n const shape = SignedManifestShape.safeParse(body);\n if (!shape.success) {\n return {\n success: false,\n error: 'Expected a signed manifest: flattened JWS JSON with protected, payload and signature',\n };\n }\n const signed = shape.data;\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n const payload = decodeText(signed.payload);\n if (payload === undefined) {\n return { success: false, error: 'Expected a payload of UTF-8 text in base64url' };\n }\n return { success: true, signed, payload };\n}\n/**\n * Checks a signed manifest was signed with the identity key the manifest names, under\n * exactly the protected header `readSignedManifest` accepts.\n */\nexport async function verifySignedManifest(signed, identityKey) {\n let key;\n try {\n key = await importJWK(identityKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'identity_key is not a usable Ed25519 key' };\n }\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n try {\n await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });\n }\n catch {\n return { success: false, error: 'The signature was not made with identity_key' };\n }\n return { success: true };\n}\n//# sourceMappingURL=signed-manifest.js.map","import { z } from 'zod';\nconst ICON_NAME_MAX_LENGTH = 64;\nconst ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst EITHER = 'Expected an icon with either a name or a url';\n/**\n * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app\n * serves. Ghost keeps a copy of the image with each manifest version it stores, and only\n * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;\n * Admin falls back to a default icon.\n */\nexport function iconField(url) {\n return (z\n .strictObject({\n name: z\n .string('Expected an icon name')\n .max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`)\n .regex(ICON_NAME, 'Expected an icon name such as audio-lines')\n .optional(),\n url: url().optional(),\n }, EITHER)\n .refine(({ name, url: iconUrl }) => (name === undefined) !== (iconUrl === undefined), EITHER)\n // Only the type narrows: the value already is one or the other. A transform would\n // narrow it too, but one-way, and a stored manifest has to encode back through here.\n .pipe(z.custom()));\n}\n//# sourceMappingURL=icon.js.map","import { z } from 'zod';\n// 32 bytes in base64url without padding. The last character carries the final 4 bits and\n// 2 zero bits, so only 16 of the 64 characters can end it, which keeps the spelling of a key\n// unique.\nconst ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\nconst EXPECTED = 'Expected a public Ed25519 key as a JWK with kty, crv and x';\nconst PRIVATE = 'Expected a public key, but this includes its private part (d)';\n/**\n * A key a manifest names. A manifest is public, so a key that includes its private part\n * is refused with a message of its own: it has to be replaced, not just removed. Other\n * members are refused by name, as key tools often add some, such as `kid` or `alg`.\n */\nexport const publicKeyField = z.strictObject({\n kty: z.literal('OKP', EXPECTED),\n crv: z.literal('Ed25519', EXPECTED),\n x: z.string(EXPECTED).regex(ED25519_X, 'Expected 32 bytes in base64url, without padding'),\n}, {\n error: (issue) => {\n if (issue.code !== 'unrecognized_keys') {\n return EXPECTED;\n }\n return issue.keys.includes('d')\n ? PRIVATE\n : `Expected only kty, crv and x; remove ${issue.keys.join(', ')}`;\n },\n});\n//# sourceMappingURL=keys.js.map","import { z } from 'zod';\n/**\n * What an app asks for: the places in Ghost it wants to appear. Each surface type is one\n * entry in a union, so a new one is added here and nowhere else.\n */\nexport function surfacesField(url) {\n const adminPage = z.strictObject({\n type: z.literal('admin_page'),\n url: url(),\n });\n const surfaceTypes = [adminPage];\n const surface = z.discriminatedUnion('type', surfaceTypes, {\n error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(', ')}`,\n });\n return z\n .array(surface, 'Expected a list of surfaces')\n .min(1, 'Expected at least one surface')\n .superRefine((surfaces, ctx) => {\n const seen = new Set();\n surfaces.forEach((entry, index) => {\n if (seen.has(entry.type)) {\n ctx.addIssue({\n code: 'custom',\n message: `Expected at most one ${entry.type} surface`,\n path: [index],\n });\n }\n seen.add(entry.type);\n });\n });\n}\n//# sourceMappingURL=surfaces.js.map","import { z } from 'zod';\nimport { isPlainText } from '../plain-text.js';\n// A character that shows something on its own: a letter, digit, punctuation or symbol, but not\n// the blank Braille pattern or one Unicode says to draw as nothing, such as a joiner or a Hangul\n// filler. Whitespace and marks aren't any of those.\nconst VISIBLE_CHARACTER = new RegExp('(?![\\\\u2800\\\\p{Default_Ignorable_Code_Point}])[\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}]', 'u');\nconst shows = (text) => VISIBLE_CHARACTER.test(text);\n// Shows nothing, and holds nothing plain text refuses other than whitespace, so trimming never\n// takes off a character, such as one that reorders text, that should get the text refused.\nconst blank = (character) => !shows(character) && isPlainText(character.replace(/\\s/gu, ''));\n// Made on first use, so loading the contract doesn't set one up.\nlet graphemes;\n/**\n * Takes off each end the characters, as a reader sees them, that show nothing: a space with a\n * mark on it goes, an emoji with its variation selector stays, and so does anything invisible\n * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no\n * more than its length.\n */\nfunction trimEdges(value) {\n graphemes ??= new Intl.Segmenter();\n const characters = graphemes.segment(value);\n let start = value.length;\n for (const { segment, index } of characters) {\n if (!blank(segment)) {\n start = index;\n break;\n }\n }\n let end = value.length;\n while (end > start) {\n const { segment, index } = characters.containing(end - 1);\n if (!blank(segment)) {\n break;\n }\n end = index;\n }\n return value.slice(start, end);\n}\n/**\n * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and\n * text with nothing visible left, such as a name of Hangul fillers, is refused.\n */\nexport function plainText(maxLength) {\n return (z\n .string('Expected text')\n // Whitespace first, as a character that joins onto a space, such as a skin tone, would keep it.\n .trim()\n .overwrite(trimEdges)\n .refine(shows, 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line'));\n}\n// Any letter, digit, punctuation or symbol, fillers included: the rule manifests were stored under\n// before blank names were refused.\nconst ANY_CHARACTER = /[\\p{L}\\p{N}\\p{P}\\p{S}]/u;\n/**\n * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before\n * blank names were refused still reads, and the app can still be listed and uninstalled.\n */\nexport function storedText(maxLength) {\n return z\n .string('Expected text')\n .trim()\n .refine((value) => ANY_CHARACTER.test(value), 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line');\n}\n//# sourceMappingURL=text.js.map","import { z } from 'zod';\nimport { isContainedPath } from '../bridge/rules.js';\nimport { URL_MAX_LENGTH } from './limits.js';\nimport { isLocalhost } from './localhost.js';\nexport const FRAGMENT_PROBLEM = 'Expected a URL without a fragment';\n/**\n * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`\n * hides. A fragment never reaches the server, so a manifest address with one is a mistake or\n * a second spelling of the same address.\n */\nexport const hasFragment = (address) => address.includes('#');\n/**\n * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would\n * use. The length is measured on the parsed URL for the same reason, as that is what is\n * stored and checked again later.\n */\nexport function checkResolvedUrl(url, allowLocalhost) {\n if (url.href.length > URL_MAX_LENGTH) {\n return `Expected at most ${URL_MAX_LENGTH} characters`;\n }\n if (url.username || url.password) {\n return 'Expected a URL without a username or password';\n }\n if (isLocalhost(url.hostname)) {\n if (!allowLocalhost) {\n return 'Expected a public address; localhost is only allowed when Ghost runs in development';\n }\n return url.protocol === 'https:' || url.protocol === 'http:'\n ? null\n : 'Expected an http or https URL';\n }\n return url.protocol === 'https:' ? null : 'Expected an https URL';\n}\nconst ROUTE_PROBLEM = 'Expected a URL that resolves to a path starting with a single /, with no \\\\ in its query or fragment';\nconst PATH_PROBLEM = 'Expected a path on the manifest’s own origin, such as /admin';\n// Two, so a reference that names one of them still names a host other than the other's.\nconst PLACEHOLDER_HOSTS = ['manifest-a.invalid', 'manifest-b.invalid'];\n/** Whether a reference names a host, in any of the URL parser's spellings of one. */\nconst namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);\nfunction isManifestItself(url, base) {\n return url.pathname === new URL(base).pathname;\n}\n/**\n * A URL in the manifest. What Ghost loads is written as a path, resolved against the\n * address the manifest was fetched from, so an app is one origin: the one Ghost fetches\n * the manifest from and challenges is the one every surface runs on. The manifest names\n * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they\n * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.\n *\n * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and\n * may be anywhere, the publisher's own site included.\n *\n * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.\n * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.\n * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which\n * names a host, and a `\\` in the query or fragment is left as it is. Only the page is opened\n * as a route, but every URL Ghost loads is held to the one rule.\n */\nexport function urlField({ allowLocalhost, base }, linkOnly = false) {\n if (linkOnly) {\n return z.string('Expected an absolute URL').transform((value, ctx) => {\n const url = URL.parse(value);\n const problem = url ? checkResolvedUrl(url, allowLocalhost) : 'Expected an absolute URL';\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n return url.href;\n });\n }\n const origin = new URL(base).origin;\n return z.string(PATH_PROBLEM).transform((value, ctx) => {\n // A path, or a path-relative reference. A URL with a scheme, or a `//host` one, names\n // its own origin, which the manifest's would then not be, even when it's the same one\n // today. An empty one, or one that's only a query or fragment, would be the manifest\n // itself.\n const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);\n if (!url || url.origin !== origin || isManifestItself(url, base)) {\n ctx.addIssue({ code: 'custom', message: PATH_PROBLEM });\n return z.NEVER;\n }\n const problem = checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {\n ctx.addIssue({ code: 'custom', message: ROUTE_PROBLEM });\n return z.NEVER;\n }\n return url.href;\n });\n}\n/**\n * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and\n * already checked. Nothing is resolved or checked again, so a manifest accepted before the\n * site's URL changed still reads back.\n */\nexport const absoluteUrl = () => z.url('Expected an absolute URL');\n//# sourceMappingURL=url.js.map","import { z } from 'zod';\nimport { iconField } from './icon.js';\nimport { APP_ID_MAX_LENGTH, isValidAppId } from './id.js';\nimport { publicKeyField } from './keys.js';\nimport { isLocalhost } from './localhost.js';\nimport { surfacesField } from './surfaces.js';\nimport { plainText, storedText } from './text.js';\nimport { absoluteUrl, FRAGMENT_PROBLEM, hasFragment, urlField, } from './url.js';\nconst NAME_MAX_LENGTH = 50;\nconst DESCRIPTION_MAX_LENGTH = 200;\nconst AUTHOR_NAME_MAX_LENGTH = 50;\nconst HEX_COLOR = /^#[0-9a-f]{6}$/i;\nconst KEY_FIELDS = new Set(['identity_key', 'backend_key']);\nconst URL_FIELDS = new Set([\n 'author',\n 'icon',\n 'surfaces',\n 'manifest_url',\n 'development',\n]);\n/** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */\nconst parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));\n/**\n * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot\n * claim something Ghost has not designed, and adding a field is always a deliberate change\n * here.\n *\n * Defined once, with the URL and text rules left open. What a valid URL is depends on whether\n * the manifest is being parsed, when where Ghost is served from matters, or read back after it\n * was, when it doesn't. Text is held to today's rules when parsed, and read back under the\n * rules it was stored under.\n */\nfunction manifestShape(url, text) {\n return (z\n .strictObject({\n id: z.custom(isValidAppId, {\n error: `Expected a lowercase reverse-domain ID such as com.example.app, at most ${APP_ID_MAX_LENGTH} characters`,\n }),\n name: text(NAME_MAX_LENGTH),\n description: text(DESCRIPTION_MAX_LENGTH),\n author: z.strictObject({\n name: text(AUTHOR_NAME_MAX_LENGTH),\n // Only ever linked to, so it may point at the publisher's own site.\n url: url(true),\n }, 'Expected an author with a name and a url'),\n accent_color: z\n .string('Expected a hex colour such as #ff5500')\n .regex(HEX_COLOR, 'Expected a hex colour such as #ff5500')\n .toLowerCase(),\n icon: iconField(url),\n surfaces: surfacesField(url),\n // Where the signed manifest is served from: the app's one origin, which every path\n // in it resolves against. Ghost fetches it server-side and never loads it as a page.\n manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),\n identity_key: publicKeyField,\n backend_key: publicKeyField,\n // Lets Admin label a development build. Production sites may run one to test it.\n development: z.boolean('Expected true or false'),\n })\n // A backend holds its key online. If it also signed manifests, whoever took over the\n // backend could publish any manifest as the app.\n .refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {\n message: 'Expected a different key from identity_key',\n path: ['backend_key'],\n // Only once both keys are known to be keys. An issue without a path is about the\n // manifest as a whole, which may not be an object at all.\n when: parsedFields(KEY_FIELDS),\n })\n // An app on the developer's machine is always labelled as a development build.\n .refine((manifest) => manifest.development ||\n ![\n manifest.author.url,\n 'url' in manifest.icon ? manifest.icon.url : undefined,\n ...manifest.surfaces.map((surface) => surface.url),\n manifest.manifest_url,\n ].some((address) => address !== undefined && isLocalhost(new URL(address).hostname)), {\n message: 'Expected true, as the app is on localhost',\n path: ['development'],\n when: parsedFields(URL_FIELDS),\n }));\n}\n/** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */\nexport function manifestSchema(rules) {\n return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);\n}\n/**\n * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to\n * resolve or check. This is the schema to read a stored manifest with, as it holds\n * whatever the site's URL has become since, and it encodes a manifest back to the same\n * shape, so what is stored is what will be read.\n */\nexport const AppManifestSchema = manifestShape(absoluteUrl, storedText);\n//# sourceMappingURL=schema.js.map","import { hostOf, isGhostHost } from './ghost-host.js';\nimport { isLocalhost } from './localhost.js';\nimport { manifestSchema } from './schema.js';\nimport { checkResolvedUrl, FRAGMENT_PROBLEM, hasFragment } from './url.js';\nfunction formatPath(path) {\n return path.reduce((result, part) => {\n if (typeof part === 'number') {\n return `${result}[${part}]`;\n }\n return result ? `${result}.${String(part)}` : String(part);\n }, '');\n}\nconst GHOST_URLS_PROBLEM = 'Expected the URLs Ghost itself is served from';\nconst ON_GHOST_HOST = 'Expected the manifest on a host other than the one Ghost itself is served from, on any port, as browsers send Ghost’s cookies to every port on its host';\nconst ON_GHOST_HOST_LOCALLY = `${ON_GHOST_HOST}. To run the app on this machine too, serve it from a name of its own under .localhost, such as my-app.localhost`;\n/**\n * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most\n * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`\n * is a host of its own, which browsers send to the machine itself, and so does Ghost in\n * development, whatever the system's resolver knows.\n */\nfunction onGhostHost(url) {\n return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;\n}\n/**\n * Reads the address a manifest is to be read from, by the same rules as the URLs inside\n * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first\n * request never goes to an address Ghost would refuse (plain HTTP, one carrying\n * credentials, or one on Ghost's host). It cannot judge where that address redirects,\n * which is for whatever fetches it to limit.\n *\n * The address it hands back is the one to store, to compare with a later one, and that the\n * manifest must name as its `manifest_url`. The URL parser settles most differences in\n * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a\n * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.\n */\nexport function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {\n if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) {\n return { success: false, error: GHOST_URLS_PROBLEM };\n }\n const url = URL.parse(input);\n if (!url) {\n return { success: false, error: 'Expected the manifest at a URL' };\n }\n const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n return { success: false, error: `${problem} for the manifest itself` };\n }\n if (isGhostHost(url, ghostUrls)) {\n return { success: false, error: onGhostHost(url) };\n }\n return { success: true, manifestUrl: url.href };\n}\nfunction invalid(errors) {\n return { success: false, reason: 'invalid', errors };\n}\n/**\n * Validates a manifest, and checks it names the address it was fetched from as its\n * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the\n * manifest to its address as well as to every URL in it.\n *\n * Returns either the manifest, or every problem found. It does not fetch anything and it\n * never throws. Without the URLs Ghost is served from it rejects every manifest, since the\n * rule that keeps apps off Ghost's hosts could not be checked.\n */\nexport function parseManifest(input, options) {\n const allowLocalhost = options.allowLocalhost ?? false;\n const address = parseManifestUrl(options.manifestUrl, options);\n if (!address.success) {\n return invalid([{ path: '', message: address.error }]);\n }\n const result = manifestSchema({ allowLocalhost, base: address.manifestUrl }).safeParse(input);\n if (!result.success) {\n return invalid(result.error.issues.map((issue) => ({\n path: formatPath(issue.path),\n message: issue.message,\n })));\n }\n if (result.data.manifest_url !== address.manifestUrl) {\n return {\n success: false,\n reason: 'manifest_url_mismatch',\n errors: [\n {\n path: 'manifest_url',\n message: `Expected ${address.manifestUrl}, the address the manifest was read from`,\n },\n ],\n };\n }\n return { success: true, manifest: result.data };\n}\n//# sourceMappingURL=parse.js.map","import { AppManifestSchema, type AppManifest } from '@tryghost/app-contracts/manifest';\nimport { z } from 'zod';\n\n// The limits Ghost reads an app with, from App Installations in Ghost core, which doesn't\n// export them to apps.\n\n/** How long Ghost waits for each read from an app, redirects and body included. */\nexport const TIMEOUT_MS = 5000;\n\n/** How many redirects on the same host Ghost follows for a manifest. */\nexport const MAX_REDIRECTS = 3;\n\n/** The largest manifest Ghost stores, which it keeps in a TEXT column. */\nexport const MANIFEST_MAX_BYTES = 64 * 1024;\n\n/**\n * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and the\n * header and signature are well under a kilobyte.\n */\nexport const SIGNED_MANIFEST_MAX_BYTES = Math.ceil((MANIFEST_MAX_BYTES * 4) / 3) + 1024;\n\n/** The largest answer to a challenge Ghost reads. */\nexport const ANSWER_MAX_BYTES = 4 * 1024;\n\n/**\n * A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what\n * was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.\n */\nexport function storedSize(manifest: AppManifest): number {\n return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;\n}\n\nexport const signedTooLargeMessage = () =>\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;\n\nexport const tooLargeMessage = () =>\n `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;\n","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { ignoreError } from '../shared/ignore.ts';\n\nexport type IgnoredResult = { ignored: true } | { ignored: false; reason: string };\n\nfunction git(args: string[], cwd: string, input?: string) {\n return new Promise<{ code: number | string | null; stdout: string; stderr: string }>((done) => {\n const child = execFile('git', args, { cwd }, (error, stdout, stderr) => {\n done({ code: error ? ((error as { code?: number | string }).code ?? 1) : 0, stdout, stderr });\n });\n // A git that couldn't start has no stdin to write to; its error arrives above.\n child.stdin?.on('error', ignoreError);\n child.stdin?.end(input);\n });\n}\n\nfunction insideRepository(directory: string): boolean {\n for (let current = resolve(directory); ; current = dirname(current)) {\n if (existsSync(join(current, '.git'))) {\n return true;\n }\n if (dirname(current) === current) {\n return false;\n }\n }\n}\n\n/**\n * The directory itself, or the nearest one above it that exists, to run git in: a project's\n * directory may not exist before its keys are written, and git can't start in one that doesn't.\n */\nfunction existingDirectory(directory: string): string {\n let current = resolve(directory);\n while (!existsSync(current) && dirname(current) !== current) {\n current = dirname(current);\n }\n return current;\n}\n\n/**\n * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by\n * accident. A file outside any repository counts as ignored.\n */\nexport async function isGitIgnored(\n root: string,\n files: string | readonly string[],\n): Promise<IgnoredResult> {\n // git can't start in a directory that doesn't exist, and a project's may not exist yet.\n const cwd = existingDirectory(root);\n const paths = (typeof files === 'string' ? [files] : files).map((file) => ({\n // As the developer named it, for messages, and as git is asked about it, from `cwd`.\n shown: relative(root, resolve(root, file)),\n asked: relative(cwd, resolve(root, file)),\n }));\n const named = `${paths.map(({ shown }) => shown).join(' and ')} ${paths.length > 1 ? 'are' : 'is'}`;\n\n const repository = await findRepository(cwd, named);\n if (repository !== 'inside') {\n return repository === 'outside' ? { ignored: true } : repository;\n }\n return askWhichAreIgnored(cwd, paths, named);\n}\n\n/** Whether `cwd` is in a repository, or why git can't say when it seems to be. */\nasync function findRepository(\n cwd: string,\n named: string,\n): Promise<'inside' | 'outside' | { ignored: false; reason: string }> {\n // Read from what git exits with, never from what it says, which is in the developer's\n // language. A `.git` that git can't read is still a repository, so it isn't taken as outside.\n const inside = await git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (inside.code === 0) {\n return 'inside';\n }\n if (!insideRepository(cwd)) {\n return 'outside';\n }\n return {\n ignored: false,\n reason:\n inside.code === 'ENOENT'\n ? `git isn't installed, so it can't check ${named} ignored`\n : `git couldn't read the repository: ${inside.stderr.trim()}`,\n };\n}\n\nasync function askWhichAreIgnored(\n cwd: string,\n paths: { shown: string; asked: string }[],\n named: string,\n): Promise<IgnoredResult> {\n // One call for every path. It lists the ones it ignores, and exits with 1 when it ignores none.\n // Paths go in and out separated by NUL, as git would otherwise quote one with any byte outside\n // ASCII. A file git tracks isn't ignored, even if a `.gitignore` names it.\n const { code, stdout, stderr } = await git(\n ['check-ignore', '--stdin', '-z'],\n cwd,\n paths.map(({ asked }) => `${asked}\\0`).join(''),\n );\n if (code !== 0 && code !== 1) {\n return { ignored: false, reason: `git couldn't check ${named} ignored: ${stderr.trim()}` };\n }\n const ignored = new Set(stdout.split('\\0'));\n const notIgnored = paths.find(({ asked }) => !ignored.has(asked));\n return notIgnored\n ? { ignored: false, reason: `git doesn't ignore ${notIgnored.shown}` }\n : { ignored: true };\n}\n","import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nimport { isGitIgnored } from './git.ts';\n\n/**\n * Which keys to use. Development and production have separate identity keys, so an app\n * installed from the developer's machine is a different app from the deployed one.\n */\nexport type Mode = 'development' | 'production';\n\n/** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */\nexport const KEYS_DIRECTORY = '.ghost-app';\n\n/**\n * - `identity`: signs the manifest. It says who made the app, so it stays with the developer\n * (or their CI) and never reaches the backend or a bundle.\n * - `backend`: answers Ghost's challenge, so the backend holds it.\n */\nexport type KeyName = 'identity' | 'backend';\n\nexport const KEY_NAMES: readonly KeyName[] = ['identity', 'backend'];\n\n/** A private Ed25519 key as a JWK. */\nexport interface PrivateKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n d: string;\n}\n\n/** A public Ed25519 key as a JWK, as a manifest names it. */\nexport interface PublicKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n}\n\n/** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */\nexport const IDENTITY_KEY_VARIABLE = 'GHOST_APP_IDENTITY_KEY';\n\n/**\n * The backend key, as the backend reads it, and as CI may provide it to sign a production\n * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.\n */\nexport const BACKEND_KEY_VARIABLE = 'GHOST_APP_BACKEND_KEY';\n\nexport interface KeyOptions {\n /** The project's directory, which holds `.ghost-app/`. */\n root: string;\n mode: Mode;\n}\n\n/** The file a key is kept in, relative to the project. */\nexport function keyFile(mode: Mode, name: KeyName): string {\n return join(KEYS_DIRECTORY, mode, `${name}.json`);\n}\n\n/** A new private Ed25519 key. */\nexport function generateKey(): PrivateKeyJwk {\n const { x, d } = generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' });\n return { kty: 'OKP', crv: 'Ed25519', x: x!, d: d! };\n}\n\n/** A key's public half, with only `kty`, `crv` and `x`. */\nexport function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk {\n return { kty: 'OKP', crv: 'Ed25519', x: key.x };\n}\n\n/**\n * Reads a private key from JSON. `source` names where it came from, for the error: the key\n * itself is never in one.\n */\nexport function readKey(text: string, source: string): PrivateKeyJwk {\n const key = readAnyKey(text, source);\n if (!('d' in key)) {\n throw new Error(`${source} is a public key; expected the private key, with d`);\n }\n return key;\n}\n\n/** Reads a key from JSON, private or public. */\nfunction readAnyKey(text: string, source: string): PrivateKeyJwk | PublicKeyJwk {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new Error(`${source} isn't a key: it isn't JSON`);\n }\n if (!isEd25519(value)) {\n throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\" and x`);\n }\n const { d } = value as { d?: unknown };\n if (d === undefined) {\n return publicKeyOf(value);\n }\n // A key with a private part that doesn't read isn't a public key either.\n if (typeof d !== 'string') {\n throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);\n }\n // A JWK carries both halves, so a hand-edited or pasted one could pair a private half with\n // someone else's public half, and sign for a key the manifest doesn't name.\n if (publicHalfOf(d, source) !== value.x) {\n throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);\n }\n return { kty: 'OKP', crv: 'Ed25519', x: value.x, d } satisfies PrivateKeyJwk;\n}\n\nfunction isEd25519(value: unknown): value is { kty: 'OKP'; crv: 'Ed25519'; x: string } {\n const { kty, crv, x } = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >;\n return kty === 'OKP' && crv === 'Ed25519' && typeof x === 'string';\n}\n\n// What PKCS#8 puts before an Ed25519 private key's 32 bytes.\nconst ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');\n\n/**\n * The public half of a private half, as `x`. Derived from `d` alone, as Node 24.22 and later\n * refuse a JWK whose halves don't match while earlier versions take its `x` as given, so a\n * mismatch is reported the same way on any version.\n */\nfunction publicHalfOf(d: string, source: string): string | undefined {\n const bytes = Buffer.from(d, 'base64url');\n if (bytes.length !== 32) {\n throw new Error(`${source} isn't a usable Ed25519 key`);\n }\n const key = createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, bytes]),\n format: 'der',\n type: 'pkcs8',\n });\n return createPublicKey(key).export({ format: 'jwk' }).x;\n}\n\nasync function readKeyFile(root: string, mode: Mode, name: KeyName): Promise<PrivateKeyJwk> {\n const file = keyFile(mode, name);\n let text: string;\n try {\n text = await readFile(join(root, file), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n throw new Error(missingKeyMessage(mode, name, file), { cause: error });\n }\n return readKey(text, file);\n}\n\n/** Says how to create a missing key, as nothing that reads keys creates one. */\nfunction missingKeyMessage(mode: Mode, name: KeyName, file: string): string {\n if (mode === 'development') {\n return `There's no development ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys\\`.`;\n }\n // In production, CI may provide the key as a variable instead.\n return `There's no production ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys --production\\`, or set ${variableFor(name)}.`;\n}\n\nconst variableFor = (name: KeyName) =>\n name === 'identity' ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;\n\nexport interface CreateKeysResult {\n /** The keys this call created. */\n created: KeyName[];\n /** The keys that already existed, which are never replaced. */\n kept: KeyName[];\n}\n\n/**\n * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only\n * their owner can read, and keeps any that exist.\n */\nexport async function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult> {\n // Each key is written whole to a temporary file beside it first, then linked to its name.\n const keys = KEY_NAMES.map((name) => {\n const file = keyFile(mode, name);\n const pending = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);\n return { name, file, pending };\n });\n // So a private key can't be committed by accident, git must ignore every file a key is\n // written to, the temporary ones included.\n await refuseUnlessGitIgnores(root, [\n ...keys.map(({ file }) => file),\n ...keys.map(({ pending }) => pending),\n ]);\n await mkdir(join(root, KEYS_DIRECTORY, mode), { recursive: true, mode: 0o700 });\n const result: CreateKeysResult = { created: [], kept: [] };\n for (const { name, file, pending } of keys) {\n // An existing key is kept: a new identity key would make the app a different app on every\n // site that installed it.\n const created = await publishKey(join(root, file), join(root, pending));\n result[created ? 'created' : 'kept'].push(name);\n }\n return result;\n}\n\nasync function refuseUnlessGitIgnores(root: string, files: string[]) {\n const ignored = await isGitIgnored(root, files);\n if (!ignored.ignored) {\n throw new Error(\n `Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`,\n );\n }\n}\n\n/** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */\nasync function publishKey(file: string, pending: string): Promise<boolean> {\n try {\n await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\\n`, {\n flag: 'wx',\n // Only for its owner on macOS and Linux. Windows ignores the mode, and the key gets the\n // folder's inherited permissions, which the README tells developers to keep private.\n mode: 0o600,\n });\n // A link fails if the name is taken, so a key is never replaced, even by a concurrent run,\n // and an interrupted write never leaves part of a key where a key belongs.\n await link(pending, file);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n // Kept, but only for its owner, as a key written by hand or copied in may not be.\n if (process.platform !== 'win32' && ((await stat(file)).mode & 0o077) !== 0) {\n await chmod(file, 0o600);\n }\n return false;\n } finally {\n await rm(pending, { force: true });\n }\n}\n\nexport interface SigningKeys {\n identityKey: PrivateKeyJwk;\n /** The backend key's public half: all signing needs. */\n backendKey: PublicKeyJwk;\n}\n\nexport interface ReadKeysOptions extends KeyOptions {\n /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to\n * anything but blanks, or else the key's file.\n */\nexport function signingKeySource(\n mode: Mode,\n name: KeyName,\n env: Record<string, string | undefined> = process.env,\n): string {\n const variable = variableFor(name);\n return mode === 'production' && env[variable]?.trim() ? variable : keyFile(mode, name);\n}\n\n/**\n * The keys to sign a mode's manifest with, from the key files, or in production from\n * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.\n */\nexport async function readSigningKeys({\n root,\n mode,\n env = process.env,\n}: ReadKeysOptions): Promise<SigningKeys> {\n const fromVariable = (name: KeyName) =>\n signingKeySource(mode, name, env) === variableFor(name)\n ? env[variableFor(name)]!.trim()\n : undefined;\n\n const identityText = fromVariable('identity');\n const identityKey = identityText\n ? await sameAsFile(root, mode, 'identity', readKey(identityText, IDENTITY_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'identity');\n\n // CI may provide only the backend key's public half, as signing needs nothing more.\n const backendText = fromVariable('backend');\n const backendKey = publicKeyOf(\n backendText\n ? await sameAsFile(root, mode, 'backend', readAnyKey(backendText, BACKEND_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'backend'),\n );\n\n if (identityKey.x === backendKey.x) {\n throw new Error('The identity key and the backend key are the same key; they must be two keys');\n }\n return { identityKey, backendKey };\n}\n\n/**\n * A key from a variable, after checking it's the same key as the file, where there's one. A\n * variable left set, such as a development key exported for every shell, would otherwise win over\n * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every\n * site.\n */\nasync function sameAsFile<Key extends PublicKeyJwk>(\n root: string,\n mode: Mode,\n name: KeyName,\n key: Key,\n): Promise<Key> {\n const file = keyFile(mode, name);\n if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {\n const variable = variableFor(name);\n throw new Error(\n `${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`,\n );\n }\n return key;\n}\n\n/** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */\nexport function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk> {\n return readKeyFile(root, mode, 'backend');\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport { signManifest } from '@tryghost/app-contracts/identity';\nimport { parseManifest, parseManifestUrl } from '@tryghost/app-contracts/manifest';\n\nimport {\n publicKeyOf,\n readKey,\n readSigningKeys,\n type PrivateKeyJwk,\n type PublicKeyJwk,\n type ReadKeysOptions,\n} from './keys.ts';\nimport { UNKNOWN_GHOST_URL } from '../shared/manifest.ts';\nimport { parseJsonText } from '../shared/parse.ts';\nimport {\n MANIFEST_MAX_BYTES,\n SIGNED_MANIFEST_MAX_BYTES,\n signedTooLargeMessage,\n storedSize,\n tooLargeMessage,\n} from './limits.ts';\nimport type { ManifestError, SignedManifest } from './types.ts';\n\n/** The readable manifest a project keeps, which the tooling signs. */\nexport const MANIFEST_FILE = 'ghost-app.json';\n\n/** The fields the tooling adds, which `ghost-app.json` mustn't set. */\nconst ADDED_FIELDS = ['manifest_url', 'identity_key', 'backend_key', 'development'] as const;\n\nexport interface SignOptions {\n /** The address the signed manifest will be served from, which it names as its own. */\n manifestUrl: string;\n identityKey: PrivateKeyJwk;\n /** Only its public half goes in the manifest. */\n backendKey: PrivateKeyJwk | PublicKeyJwk;\n /** Whether this is a development build, as it must be when any URL is on localhost. */\n development: boolean;\n}\n\nexport type SignResult =\n | {\n success: true;\n signed: SignedManifest;\n /** The manifest as signed, with the fields the tooling added. */\n manifest: Record<string, unknown>;\n }\n | {\n success: false;\n /**\n * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or\n * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost stores.\n */\n code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';\n errors: ManifestError[];\n };\n\ntype Refusal = Extract<SignResult, { success: false }>;\n\nconst refuse = (code: Refusal['code'], message: string, path = ''): Refusal => ({\n success: false,\n code,\n errors: [{ path, message }],\n});\n\n/**\n * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it\n * with the identity key, unless Ghost would refuse it.\n */\nexport async function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult> {\n // A JWK carries both halves, so one passed in, rather than read from a file, could pair a\n // private half with another key's public half. The manifest would name a key that didn't sign\n // it, or one the backend can't answer for, and Ghost would refuse it. That's the caller's\n // mistake, so it throws.\n readKey(JSON.stringify(options.identityKey), 'identityKey');\n if ('d' in options.backendKey) {\n readKey(JSON.stringify(options.backendKey), 'backendKey');\n }\n // Ghost's own hosts are the one rule only a site knows, so a name no site has stands in.\n const address = parseManifestUrl(options.manifestUrl, {\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!address.success) {\n return refuse('APP_MANIFEST_URL_INVALID', address.error);\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return refuse('APP_MANIFEST_INVALID', 'Expected the manifest as a JSON object');\n }\n // The fields signing adds can't come from the file, or the file could name other keys.\n const added = ADDED_FIELDS.filter((field) => field in source);\n if (added.length > 0) {\n return {\n success: false,\n code: 'APP_MANIFEST_INVALID',\n errors: added.map((field) => ({\n path: field,\n message: `Leave ${field} out: it's added when the manifest is signed`,\n })),\n };\n }\n\n const manifest = {\n ...source,\n manifest_url: address.manifestUrl,\n identity_key: publicKeyOf(options.identityKey),\n backend_key: publicKeyOf(options.backendKey),\n development: options.development,\n };\n // Checked by the rules Ghost applies, so a manifest Ghost would refuse is never signed, and\n // the result lists every problem by the path to its field.\n const parsed = parseManifest(manifest, {\n manifestUrl: address.manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!parsed.success) {\n // A mismatch can't happen, as the manifest URL was just set; any failure is invalid.\n return { success: false, code: 'APP_MANIFEST_INVALID', errors: parsed.errors };\n }\n if (storedSize(parsed.manifest) > MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', tooLargeMessage());\n }\n\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // Ghost limits the signed manifest it fetches too, and the payload keeps whatever the file had,\n // such as text Ghost trims, so a manifest Ghost stores can still be too large to fetch.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse('APP_MANIFEST_TOO_LARGE', signedTooLargeMessage());\n }\n return { success: true, signed, manifest };\n}\n\n/** A signed manifest as the CLI and the Vite plugin write it to a file. */\nexport function serialiseSigned(signed: SignedManifest): string {\n return `${JSON.stringify(signed, null, 2)}\\n`;\n}\n\n/** Reads `ghost-app.json`, or another readable manifest, as JSON. */\nexport async function readManifestSource(file: string): Promise<unknown> {\n const text = await readFile(file, 'utf8');\n try {\n return parseJsonText(text);\n } catch (error) {\n throw new Error(`${file} isn't JSON: ${(error as Error).message}`, { cause: error });\n }\n}\n\nexport interface SignProjectOptions extends ReadKeysOptions {\n manifestUrl: string;\n /** The readable manifest, relative to `root`. `ghost-app.json` by default. */\n manifestFile?: string;\n}\n\n/** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */\nexport async function signProject({\n root,\n mode,\n env,\n manifestUrl,\n manifestFile = MANIFEST_FILE,\n}: SignProjectOptions): Promise<SignResult> {\n // Resolved, so an absolute path is taken as it is.\n const source = await readManifestSource(resolve(root, manifestFile));\n // Keys are read, never created: a missing one throws with how to create it.\n const keys = await readSigningKeys({ root, mode, env });\n return signAppManifest(source, { manifestUrl, ...keys, development: mode === 'development' });\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAM,iBAAiB;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;AAMA,SAAgB,oBAAoB,UAAU;CAC1C,IAAI,MAAM,SAAS;CACnB,OAAO,MAAM,KAAK,SAAS,MAAM,OAAO,KACpC,OAAO;CAEX,OAAO,SAAS,MAAM,GAAG,GAAG;AAChC;;;;;;AAMA,SAAgB,YAAY,UAAU;CAClC,MAAM,OAAO,oBAAoB,QAAQ;CACzC,OAAO,eAAe,MAAM,YAAY,QAAQ,KAAK,IAAI,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;ACZA,SAAgB,YAAY,KAAK,WAAW;CACxC,MAAM,OAAO,OAAO,GAAG;CACvB,IAAI,SAAS,MACT,OAAO;CAEX,IAAI,QAAQ;CACZ,KAAK,MAAM,YAAY,WAAW;EAC9B,MAAM,YAAY,OAAO,QAAQ;EACjC,IAAI,cAAc,QAAQ,cAAc,MACpC,OAAO;EAEX,QAAQ;CACZ;CACA,OAAO,CAAC;AACZ;;AAEA,SAAgB,OAAO,OAAO;CAC1B,IAAI;CAEJ,IAAI;EACA,MAAM,IAAI,IAAI,KAAK;CACvB,QACM;EACF,OAAO;CACX;CACA,IAAI,IAAI,aAAa,WAAW,IAAI,aAAa,UAC7C,OAAO;CAEX,OAAO,oBAAoB,IAAI,QAAQ,KAAK;AAChD;AC9CA,IAAM,aAAa;;;;;;;AAOnB,SAAgB,aAAa,OAAO;CAChC,IAAI,OAAO,UAAU,YAAY,MAAM,SAAA,KACnC,OAAO;CAEX,MAAM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QAAQ;CACvB;CAGA,MAAM,SAAS,cAAc,UAAU;EACrC,aAAa,QAAQ;EACrB,WAAW,CAAC,iBAAiB;EAC7B,gBAAgB;CAClB,CAAC;CACD,IAAI,CAAC,OAAO,SAEV,OAAO;EAAE,SAAS;EAAO,MAAM;EAAwB,QAAQ,OAAO;CAAO;CAE/E,IAAI,WAAW,OAAO,QAAQ,IAAA,OAC5B,OAAO,OAAO,0BAA0B,gBAAgB,CAAC;CAG3D,MAAM,SAAS,MAAM,aAAa,KAAK,UAAU,QAAQ,GAAG,QAAQ,WAAW;CAG/E,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,gBAAgB,MAAM,CAAC,CAAC,CAAC,aAAa,2BACjE,OAAO,OAAO,0BAA0B,sBAAsB,CAAC;CAEjE,OAAO;EAAE,SAAS;EAAM;EAAQ;CAAS;AAC3C;;AAGA,SAAgB,gBAAgB,QAAgC;CAC9D,OAAO,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE;AAC5C;;AAGA,eAAsB,mBAAmB,MAAgC;CACvE,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM;CACxC,IAAI;EACF,OAAO,cAAc,IAAI;CAC3B,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,KAAK,eAAgB,MAAgB,WAAW,EAAE,OAAO,MAAM,CAAC;CACrF;AACF;;AASA,eAAsB,YAAY,EAChC,MACA,MACA,KACA,aACA,eAAe,iBAC2B;CAK1C,OAAO,gBAAgB,MAHF,mBAAmB,QAAQ,MAAM,YAAY,CAAC,GAGpC;EAAE;EAAa,GAAG,MAD9B,gBAAgB;GAAE;GAAM;GAAM;EAAI,CAAC;EACC,aAAa,SAAS;CAAc,CAAC;AAC9F"}
package/build/index.js CHANGED
@@ -490,7 +490,7 @@ var Channel = class {
490
490
  * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
491
491
  * and doesn't read package.json.
492
492
  */
493
- var SDK_VERSION = "0.1.0-alpha.8";
493
+ var SDK_VERSION = "0.1.0-alpha.9";
494
494
  //#endregion
495
495
  //#region src/connect.ts
496
496
  /**
package/build/tooling.js CHANGED
@@ -1,3 +1,4 @@
1
- import { a as signProject, c as KEYS_DIRECTORY, d as generateKey, f as keyFile, g as checkApp, h as readSigningKeys, i as signAppManifest, m as readBackendKey, n as readManifestSource, o as BACKEND_KEY_VARIABLE, p as publicKeyOf, s as IDENTITY_KEY_VARIABLE, t as MANIFEST_FILE, u as createKeys } from "./chunks/sign-BhNJAPta.js";
2
- import { r as formatErrors } from "./chunks/manifest-DX1GTozy.js";
1
+ import { a as signProject, c as KEYS_DIRECTORY, d as generateKey, f as keyFile, h as readSigningKeys, i as signAppManifest, m as readBackendKey, n as readManifestSource, o as BACKEND_KEY_VARIABLE, p as publicKeyOf, s as IDENTITY_KEY_VARIABLE, t as MANIFEST_FILE, u as createKeys } from "./chunks/sign-DygdzQYY.js";
2
+ import { r as formatErrors } from "./chunks/manifest-iOwbzAil.js";
3
+ import { t as checkApp } from "./chunks/check-3oU5pDJc.js";
3
4
  export { BACKEND_KEY_VARIABLE, IDENTITY_KEY_VARIABLE, KEYS_DIRECTORY, MANIFEST_FILE, checkApp, createKeys, formatErrors, generateKey, keyFile, publicKeyOf, readBackendKey, readManifestSource, readSigningKeys, signAppManifest, signProject };
@@ -0,0 +1,29 @@
1
+ import { Plugin } from "vite";
2
+ //#region src/vite/index.d.ts
3
+ interface GhostAppOptions {
4
+ /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */
5
+ manifest?: string;
6
+ /**
7
+ * The public addresses of tunnels to the dev server, such as
8
+ * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from
9
+ * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`
10
+ * files.
11
+ */
12
+ tunnelUrl?: string | readonly string[];
13
+ }
14
+ /**
15
+ * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build
16
+ * emits it:
17
+ *
18
+ * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves
19
+ * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one
20
+ * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development
21
+ * backend key to `.dev.vars`.
22
+ * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the
23
+ * client build.
24
+ *
25
+ * List it before `cloudflare()`.
26
+ */
27
+ declare function ghostApp(options?: GhostAppOptions): Plugin;
28
+ //#endregion
29
+ export { GhostAppOptions, ghostApp };