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

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,158 @@
1
+ import { t as SignedManifest } from "./chunks/signed-manifest-tbnMbfyw.js";
2
+ //#region ../../contracts/app-contracts/build/manifest/parse.d.ts
3
+ /** One problem with a manifest. */
4
+ interface ManifestError {
5
+ /** Where in the manifest the problem is, e.g. `surfaces[0].url`. Empty for the whole. */
6
+ path: string;
7
+ message: string;
8
+ }
9
+ //#endregion
10
+ //#region src/tooling/keys.d.ts
11
+ /**
12
+ * Which keys to use. Development and production have separate identity keys, so an app
13
+ * installed from the developer's machine is a different app from the deployed one.
14
+ */
15
+ type Mode = 'development' | 'production';
16
+ /** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */
17
+ declare const KEYS_DIRECTORY = ".ghost-app";
18
+ /**
19
+ * - `identity`: signs the manifest. It says who made the app, so it stays with the developer
20
+ * (or their CI) and never reaches the backend or a bundle.
21
+ * - `backend`: answers Ghost's challenge, so the backend holds it.
22
+ */
23
+ type KeyName = 'identity' | 'backend';
24
+ /** A private Ed25519 key as a JWK. */
25
+ interface PrivateKeyJwk {
26
+ kty: 'OKP';
27
+ crv: 'Ed25519';
28
+ x: string;
29
+ d: string;
30
+ }
31
+ /** A public Ed25519 key as a JWK, as a manifest names it. */
32
+ interface PublicKeyJwk {
33
+ kty: 'OKP';
34
+ crv: 'Ed25519';
35
+ x: string;
36
+ }
37
+ /** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */
38
+ declare const IDENTITY_KEY_VARIABLE = "GHOST_APP_IDENTITY_KEY";
39
+ /**
40
+ * The backend key, as the backend reads it, and as CI may provide it to sign a production
41
+ * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.
42
+ */
43
+ declare const BACKEND_KEY_VARIABLE = "GHOST_APP_BACKEND_KEY";
44
+ interface KeyOptions {
45
+ /** The project's directory, which holds `.ghost-app/`. */
46
+ root: string;
47
+ mode: Mode;
48
+ }
49
+ /** The file a key is kept in, relative to the project. */
50
+ declare function keyFile(mode: Mode, name: KeyName): string;
51
+ /** A new private Ed25519 key. */
52
+ declare function generateKey(): PrivateKeyJwk;
53
+ /** A key's public half, with only `kty`, `crv` and `x`. */
54
+ declare function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk;
55
+ interface CreateKeysResult {
56
+ /** The keys this call created. */
57
+ created: KeyName[];
58
+ /** The keys that already existed, which are never replaced. */
59
+ kept: KeyName[];
60
+ }
61
+ /**
62
+ * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only
63
+ * their owner can read, and keeps any that exist.
64
+ */
65
+ declare function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult>;
66
+ interface SigningKeys {
67
+ identityKey: PrivateKeyJwk;
68
+ /** The backend key's public half: all signing needs. */
69
+ backendKey: PublicKeyJwk;
70
+ }
71
+ interface ReadKeysOptions extends KeyOptions {
72
+ /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */
73
+ env?: Record<string, string | undefined>;
74
+ }
75
+ /**
76
+ * The keys to sign a mode's manifest with, from the key files, or in production from
77
+ * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.
78
+ */
79
+ declare function readSigningKeys({ root, mode, env }: ReadKeysOptions): Promise<SigningKeys>;
80
+ /** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */
81
+ declare function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk>;
82
+ //#endregion
83
+ //#region src/tooling/types.d.ts
84
+ /**
85
+ * What `ghost-app.json` holds: the manifest, without the fields the tooling adds when it
86
+ * signs. See the SDK's README for each field's rules.
87
+ */
88
+ interface ManifestSource {
89
+ id: string;
90
+ name: string;
91
+ description: string;
92
+ author: {
93
+ name: string;
94
+ url: string;
95
+ };
96
+ accent_color: string;
97
+ icon: {
98
+ name: string;
99
+ } | {
100
+ url: string;
101
+ };
102
+ surfaces: {
103
+ type: 'admin_page';
104
+ url: string;
105
+ }[];
106
+ }
107
+ /** A manifest as Ghost reads it from a signed manifest, with every path resolved. */
108
+ interface AppManifest extends ManifestSource {
109
+ manifest_url: string;
110
+ identity_key: PublicKeyJwk;
111
+ backend_key: PublicKeyJwk;
112
+ development: boolean;
113
+ }
114
+ //#endregion
115
+ //#region src/tooling/sign.d.ts
116
+ /** The readable manifest a project keeps, which the tooling signs. */
117
+ declare const MANIFEST_FILE = "ghost-app.json";
118
+ interface SignOptions {
119
+ /** The address the signed manifest will be served from, which it names as its own. */
120
+ manifestUrl: string;
121
+ identityKey: PrivateKeyJwk;
122
+ /** Only its public half goes in the manifest. */
123
+ backendKey: PrivateKeyJwk | PublicKeyJwk;
124
+ /** Whether this is a development build, as it must be when any URL is on localhost. */
125
+ development: boolean;
126
+ }
127
+ type SignResult = {
128
+ success: true;
129
+ signed: SignedManifest;
130
+ /** The manifest as signed, with the fields the tooling added. */
131
+ manifest: Record<string, unknown>;
132
+ } | {
133
+ success: false;
134
+ /**
135
+ * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or
136
+ * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost fetches.
137
+ */
138
+ code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';
139
+ errors: ManifestError[];
140
+ };
141
+ /**
142
+ * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it
143
+ * with the identity key, unless Ghost would refuse it.
144
+ */
145
+ declare function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult>;
146
+ /** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */
147
+ declare function formatErrors(errors: readonly ManifestError[]): string;
148
+ /** Reads `ghost-app.json`, or another readable manifest, as JSON. */
149
+ declare function readManifestSource(file: string): Promise<unknown>;
150
+ interface SignProjectOptions extends ReadKeysOptions {
151
+ manifestUrl: string;
152
+ /** The readable manifest, relative to `root`. `ghost-app.json` by default. */
153
+ manifestFile?: string;
154
+ }
155
+ /** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */
156
+ declare function signProject({ root, mode, env, manifestUrl, manifestFile }: SignProjectOptions): Promise<SignResult>;
157
+ //#endregion
158
+ export { type AppManifest, BACKEND_KEY_VARIABLE, type CreateKeysResult, IDENTITY_KEY_VARIABLE, KEYS_DIRECTORY, type KeyName, type KeyOptions, MANIFEST_FILE, type ManifestError, type ManifestSource, type Mode, type PrivateKeyJwk, type PublicKeyJwk, type ReadKeysOptions, type SignOptions, type SignProjectOptions, type SignResult, type SignedManifest, type SigningKeys, createKeys, formatErrors, generateKey, keyFile, publicKeyOf, readBackendKey, readManifestSource, readSigningKeys, signAppManifest, signProject };
@@ -0,0 +1,2 @@
1
+ import { a as signAppManifest, c as IDENTITY_KEY_VARIABLE, d as createKeys, f as generateKey, g as readSigningKeys, h as readBackendKey, l as KEYS_DIRECTORY, m as publicKeyOf, n as formatErrors, o as signProject, p as keyFile, r as readManifestSource, s as BACKEND_KEY_VARIABLE, t as MANIFEST_FILE } from "./chunks/sign-B1y31TLX.js";
2
+ export { BACKEND_KEY_VARIABLE, IDENTITY_KEY_VARIABLE, KEYS_DIRECTORY, MANIFEST_FILE, 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 };
package/build/vite.js ADDED
@@ -0,0 +1,229 @@
1
+ import { _ as signingKeySource, b as isLocalhost, c as IDENTITY_KEY_VARIABLE, d as createKeys, h as readBackendKey, i as serialiseSigned, l as KEYS_DIRECTORY, n as formatErrors, o as signProject, p as keyFile, s as BACKEND_KEY_VARIABLE, v as parseJsonText, y as isValidAppId } from "./chunks/sign-B1y31TLX.js";
2
+ import { t as MANIFEST_PATH } from "./chunks/manifest-DmfZ-0r7.js";
3
+ import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { appendFile, readFile } from "node:fs/promises";
6
+ import { join, resolve } from "node:path";
7
+ //#region src/vite/deny.ts
8
+ var VITE_DEFAULT_DENY = [
9
+ ".env",
10
+ ".env.*",
11
+ "*.{crt,pem,key,p12,pfx,cer,der}",
12
+ ".npmrc",
13
+ ".yarnrc.yml",
14
+ "**/.git/**"
15
+ ];
16
+ var DENY = [
17
+ "**/.ghost-app/**",
18
+ ".dev.vars*",
19
+ ".env",
20
+ ".env.*"
21
+ ];
22
+ //#endregion
23
+ //#region src/vite/dev-vars.ts
24
+ var WRANGLER_CONFIGS = [
25
+ "wrangler.json",
26
+ "wrangler.jsonc",
27
+ "wrangler.toml"
28
+ ];
29
+ var DEV_VARS = ".dev.vars";
30
+ /**
31
+ * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as
32
+ * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development
33
+ * as it does in production. Returns what to tell the developer, if anything.
34
+ */
35
+ async function provideDevBackendKey(root) {
36
+ const there = (file) => existsSync(join(root, file));
37
+ if (!WRANGLER_CONFIGS.some(there)) return;
38
+ const key = await readBackendKey({
39
+ root,
40
+ mode: "development"
41
+ });
42
+ const read = there(DEV_VARS) ? [DEV_VARS] : [".env.local", ".env"].filter(there);
43
+ let last = "";
44
+ for (const file of read) {
45
+ last = await readFile(join(root, file), "utf8");
46
+ if (last.includes("GHOST_APP_BACKEND_KEY")) return last.includes(key.x) ? void 0 : {
47
+ level: "warn",
48
+ message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile("development", "backend")}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`
49
+ };
50
+ }
51
+ if (read.length > 0 && read[0] !== DEV_VARS) return {
52
+ level: "warn",
53
+ message: `Wrangler reads ${read.join(" and ")} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \`ghost-app backend-key\`, so the Worker can answer Ghost's challenge.`
54
+ };
55
+ const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\n`;
56
+ await appendFile(join(root, DEV_VARS), `${last && !last.endsWith("\n") ? "\n" : ""}${line}`, { mode: 384 });
57
+ return {
58
+ level: "info",
59
+ message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`
60
+ };
61
+ }
62
+ //#endregion
63
+ //#region src/vite/index.ts
64
+ /**
65
+ * A Vite plugin that serves and builds an app's signed manifest.
66
+ *
67
+ * ```ts
68
+ * import { cloudflare } from '@cloudflare/vite-plugin';
69
+ * import { ghostApp } from '@tryghost/app-sdk/vite';
70
+ * import { defineConfig } from 'vite';
71
+ *
72
+ * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });
73
+ * ```
74
+ */
75
+ function readTunnels(input) {
76
+ return (typeof input === "string" ? input.split(",") : input ?? []).map((entry) => entry.trim()).filter(Boolean).map((entry) => {
77
+ const origin = parseOrigin(entry);
78
+ if (!origin) throw new Error(`ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`);
79
+ return origin;
80
+ });
81
+ }
82
+ /**
83
+ * The name `vite dev` prints the app at, such as `hello-world.localhost` for
84
+ * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.
85
+ */
86
+ function devHostname(manifestFile) {
87
+ try {
88
+ const { id } = parseJsonText(readFileSync(manifestFile, "utf8"));
89
+ if (isValidAppId(id)) return `${id.slice(id.lastIndexOf(".") + 1)}.localhost`;
90
+ } catch {}
91
+ return "app.localhost";
92
+ }
93
+ /**
94
+ * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build
95
+ * emits it:
96
+ *
97
+ * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves
98
+ * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one
99
+ * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development
100
+ * backend key to `.dev.vars`.
101
+ * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the
102
+ * client build.
103
+ *
104
+ * List it before `cloudflare()`.
105
+ */
106
+ function ghostApp(options = {}) {
107
+ const manifestFile = options.manifest ?? "ghost-app.json";
108
+ let tunnels = [];
109
+ let appUrl;
110
+ let ghostUrl;
111
+ let config;
112
+ let pending;
113
+ let dev = false;
114
+ /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */
115
+ function manifestUrlFor(host) {
116
+ const url = URL.parse(`${config.server.https ? "https" : "http"}://${host ?? ""}`);
117
+ const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);
118
+ if (tunnel) return `${tunnel}${MANIFEST_PATH}`;
119
+ return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : void 0;
120
+ }
121
+ return {
122
+ name: "@tryghost/app-sdk/vite",
123
+ enforce: "pre",
124
+ async config(userConfig, { command, isPreview, mode }) {
125
+ const root = resolve(userConfig.root ?? "");
126
+ const { loadEnv } = await import("vite");
127
+ const env = userConfig.envDir === false ? process.env : loadEnv(mode, resolve(root, userConfig.envDir ?? ""), [
128
+ "GHOST_APP_URL",
129
+ "GHOST_APP_TUNNEL_URL",
130
+ "GHOST_URL"
131
+ ]);
132
+ appUrl = env.GHOST_APP_URL?.trim() || void 0;
133
+ ghostUrl = env.GHOST_URL?.trim() || void 0;
134
+ if (command !== "serve" || isPreview) return;
135
+ tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);
136
+ dev = !process.env.VITEST && mode !== "test";
137
+ if (dev) {
138
+ await createKeys({
139
+ root,
140
+ mode: "development"
141
+ });
142
+ pending = await provideDevBackendKey(root);
143
+ }
144
+ return { server: {
145
+ fs: { deny: [...userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY, ...DENY] },
146
+ ...tunnels.length > 0 && userConfig.server?.allowedHosts !== true ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) } : {}
147
+ } };
148
+ },
149
+ configResolved(resolved) {
150
+ config = resolved;
151
+ const exposed = [resolved.envPrefix ?? "VITE_"].flat().find((prefix) => [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)));
152
+ if (exposed !== void 0) throw new Error(`ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`);
153
+ if (dev && !resolved.server.fs.strict) throw new Error(`ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`);
154
+ if (pending) config.logger[pending.level](`ghost-app: ${pending.message}`);
155
+ },
156
+ configureServer(server) {
157
+ server.middlewares.use((req, res, next) => {
158
+ if (req.url?.split("?")[0] !== "/ghost-app.json" || !["GET", "HEAD"].includes(req.method)) {
159
+ next();
160
+ return;
161
+ }
162
+ const host = req.headers.host ?? req.headers[":authority"];
163
+ const manifestUrl = manifestUrlFor(host);
164
+ if (!manifestUrl) {
165
+ const allowed = ["this machine", ...tunnels.map((origin) => new URL(origin).host)];
166
+ res.statusCode = 421;
167
+ res.setHeader("content-type", "text/plain; charset=utf-8");
168
+ res.end(`The dev server signs ghost-app.json only for ${allowed.join(", ")}, not ${host ?? "a request without a Host"}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\n`);
169
+ return;
170
+ }
171
+ signProject({
172
+ root: config.root,
173
+ mode: "development",
174
+ manifestUrl,
175
+ manifestFile
176
+ }).then((result) => {
177
+ if (!result.success) throw new Error(`${manifestFile} can't be signed:\n${formatErrors(result.errors)}`);
178
+ res.setHeader("content-type", "application/json; charset=utf-8");
179
+ res.setHeader("cache-control", "no-store");
180
+ res.end(req.method === "HEAD" ? void 0 : serialiseSigned(result.signed));
181
+ }).catch((error) => {
182
+ const message = `ghost-app: ${error.message}`;
183
+ config.logger.error(message, { timestamp: true });
184
+ res.statusCode = 500;
185
+ res.setHeader("content-type", "text/plain; charset=utf-8");
186
+ res.end(`${message}\n`);
187
+ });
188
+ });
189
+ const printUrls = server.printUrls.bind(server);
190
+ server.printUrls = () => {
191
+ printUrls();
192
+ const address = server.httpServer?.address();
193
+ const port = typeof address === "object" && address ? address.port : void 0;
194
+ const local = `${config.server.https ? "https" : "http"}://${devHostname(resolve(config.root, manifestFile))}:${port}`;
195
+ const ghost = (ghostUrl ?? "http://localhost:2368").replace(/\/+$/, "");
196
+ const lines = [...port ? [local] : [], ...tunnels].flatMap((origin) => [` Ghost app: ${origin}${MANIFEST_PATH}`, ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`]);
197
+ config.logger.info(`\n${lines.join("\n")}\n`);
198
+ };
199
+ },
200
+ async buildStart() {
201
+ if (config.command !== "build" || this.environment.config.consumer !== "client") return;
202
+ if (!appUrl) {
203
+ config.logger.warn(`ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`);
204
+ return;
205
+ }
206
+ const base = URL.parse(appUrl.endsWith("/") ? appUrl : `${appUrl}/`);
207
+ if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) this.error(`ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`);
208
+ const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;
209
+ this.addWatchFile(resolve(config.root, manifestFile));
210
+ const result = await signProject({
211
+ root: config.root,
212
+ mode: "production",
213
+ manifestUrl,
214
+ manifestFile
215
+ }).catch((error) => this.error(`ghost-app: ${error.message}`));
216
+ if (!result.success) this.error(`ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\n${formatErrors(result.errors)}`);
217
+ this.emitFile({
218
+ type: "asset",
219
+ fileName: MANIFEST_PATH.slice(1),
220
+ source: serialiseSigned(result.signed)
221
+ });
222
+ config.logger.info(`ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource("production", "identity")}`);
223
+ }
224
+ };
225
+ }
226
+ //#endregion
227
+ export { ghostApp };
228
+
229
+ //# sourceMappingURL=vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport { parseJsonText } from '@tryghost/app-contracts/identity';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH } from '../shared/manifest.ts';\nimport { parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, formatErrors, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CA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