@tryghost/app-sdk 0.1.0-alpha.0 → 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +252 -29
- package/build/backend.d.ts +89 -0
- package/build/backend.js +200 -0
- package/build/backend.js.map +1 -0
- package/build/bin.d.ts +1 -0
- package/build/bin.js +124 -0
- package/build/bin.js.map +1 -0
- package/build/chunks/manifest-B9vQoSfm.js +43 -0
- package/build/chunks/manifest-B9vQoSfm.js.map +1 -0
- package/build/chunks/manifest-DFLCKcwH.d.ts +19 -0
- package/build/chunks/rules-_dou3jRF.js +159 -0
- package/build/chunks/rules-_dou3jRF.js.map +1 -0
- package/build/chunks/sign-Deg9TCUr.js +869 -0
- package/build/chunks/sign-Deg9TCUr.js.map +1 -0
- package/build/index.d.ts +19 -5
- package/build/index.js +40 -176
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +148 -0
- package/build/tooling.js +3 -0
- package/build/vite.d.ts +29 -0
- package/build/vite.js +228 -0
- package/build/vite.js.map +1 -0
- package/dist/app-sdk.js +40 -24
- package/dist/app-sdk.js.map +1 -1
- package/package.json +32 -3
package/build/vite.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { _ as isValidAppId, a as signProject, c as KEYS_DIRECTORY, f as keyFile, g as signingKeySource, m as readBackendKey, o as BACKEND_KEY_VARIABLE, r as serialiseSigned, s as IDENTITY_KEY_VARIABLE, u as createKeys, v as isLocalhost } from "./chunks/sign-Deg9TCUr.js";
|
|
2
|
+
import { a as parseJsonText, o as parseOrigin, r as formatErrors, t as MANIFEST_PATH } from "./chunks/manifest-B9vQoSfm.js";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { appendFile, readFile } from "node:fs/promises";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
//#region src/vite/deny.ts
|
|
7
|
+
var VITE_DEFAULT_DENY = [
|
|
8
|
+
".env",
|
|
9
|
+
".env.*",
|
|
10
|
+
"*.{crt,pem,key,p12,pfx,cer,der}",
|
|
11
|
+
".npmrc",
|
|
12
|
+
".yarnrc.yml",
|
|
13
|
+
"**/.git/**"
|
|
14
|
+
];
|
|
15
|
+
var DENY = [
|
|
16
|
+
"**/.ghost-app/**",
|
|
17
|
+
".dev.vars*",
|
|
18
|
+
".env",
|
|
19
|
+
".env.*"
|
|
20
|
+
];
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/vite/dev-vars.ts
|
|
23
|
+
var WRANGLER_CONFIGS = [
|
|
24
|
+
"wrangler.json",
|
|
25
|
+
"wrangler.jsonc",
|
|
26
|
+
"wrangler.toml"
|
|
27
|
+
];
|
|
28
|
+
var DEV_VARS = ".dev.vars";
|
|
29
|
+
/**
|
|
30
|
+
* Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as
|
|
31
|
+
* `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development
|
|
32
|
+
* as it does in production. Returns what to tell the developer, if anything.
|
|
33
|
+
*/
|
|
34
|
+
async function provideDevBackendKey(root) {
|
|
35
|
+
const there = (file) => existsSync(join(root, file));
|
|
36
|
+
if (!WRANGLER_CONFIGS.some(there)) return;
|
|
37
|
+
const key = await readBackendKey({
|
|
38
|
+
root,
|
|
39
|
+
mode: "development"
|
|
40
|
+
});
|
|
41
|
+
const read = there(DEV_VARS) ? [DEV_VARS] : [".env.local", ".env"].filter(there);
|
|
42
|
+
let last = "";
|
|
43
|
+
for (const file of read) {
|
|
44
|
+
last = await readFile(join(root, file), "utf8");
|
|
45
|
+
if (last.includes("GHOST_APP_BACKEND_KEY")) return last.includes(key.x) ? void 0 : {
|
|
46
|
+
level: "warn",
|
|
47
|
+
message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile("development", "backend")}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (read.length > 0 && read[0] !== DEV_VARS) return {
|
|
51
|
+
level: "warn",
|
|
52
|
+
message: `Wrangler reads ${read.join(" and ")} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \`ghost-app backend-key\`, so the Worker can answer Ghost's challenge.`
|
|
53
|
+
};
|
|
54
|
+
const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\n`;
|
|
55
|
+
await appendFile(join(root, DEV_VARS), `${last && !last.endsWith("\n") ? "\n" : ""}${line}`, { mode: 384 });
|
|
56
|
+
return {
|
|
57
|
+
level: "info",
|
|
58
|
+
message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/vite/index.ts
|
|
63
|
+
/**
|
|
64
|
+
* A Vite plugin that serves and builds an app's signed manifest.
|
|
65
|
+
*
|
|
66
|
+
* ```ts
|
|
67
|
+
* import { cloudflare } from '@cloudflare/vite-plugin';
|
|
68
|
+
* import { ghostApp } from '@tryghost/app-sdk/vite';
|
|
69
|
+
* import { defineConfig } from 'vite';
|
|
70
|
+
*
|
|
71
|
+
* export default defineConfig({ plugins: [ghostApp(), cloudflare()] });
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
function readTunnels(input) {
|
|
75
|
+
return (typeof input === "string" ? input.split(",") : input ?? []).map((entry) => entry.trim()).filter(Boolean).map((entry) => {
|
|
76
|
+
const origin = parseOrigin(entry);
|
|
77
|
+
if (!origin) throw new Error(`ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`);
|
|
78
|
+
return origin;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The name `vite dev` prints the app at, such as `hello-world.localhost` for
|
|
83
|
+
* `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.
|
|
84
|
+
*/
|
|
85
|
+
function devHostname(manifestFile) {
|
|
86
|
+
try {
|
|
87
|
+
const { id } = parseJsonText(readFileSync(manifestFile, "utf8"));
|
|
88
|
+
if (isValidAppId(id)) return `${id.slice(id.lastIndexOf(".") + 1)}.localhost`;
|
|
89
|
+
} catch {}
|
|
90
|
+
return "app.localhost";
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build
|
|
94
|
+
* emits it:
|
|
95
|
+
*
|
|
96
|
+
* - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves
|
|
97
|
+
* `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one
|
|
98
|
+
* of the tunnels it's told about. In a Cloudflare Workers project, it adds the development
|
|
99
|
+
* backend key to `.dev.vars`.
|
|
100
|
+
* - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the
|
|
101
|
+
* client build.
|
|
102
|
+
*
|
|
103
|
+
* List it before `cloudflare()`.
|
|
104
|
+
*/
|
|
105
|
+
function ghostApp(options = {}) {
|
|
106
|
+
const manifestFile = options.manifest ?? "ghost-app.json";
|
|
107
|
+
let tunnels = [];
|
|
108
|
+
let appUrl;
|
|
109
|
+
let ghostUrl;
|
|
110
|
+
let config;
|
|
111
|
+
let pending;
|
|
112
|
+
let dev = false;
|
|
113
|
+
/** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */
|
|
114
|
+
function manifestUrlFor(host) {
|
|
115
|
+
const url = URL.parse(`${config.server.https ? "https" : "http"}://${host ?? ""}`);
|
|
116
|
+
const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);
|
|
117
|
+
if (tunnel) return `${tunnel}${MANIFEST_PATH}`;
|
|
118
|
+
return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : void 0;
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
name: "@tryghost/app-sdk/vite",
|
|
122
|
+
enforce: "pre",
|
|
123
|
+
async config(userConfig, { command, isPreview, mode }) {
|
|
124
|
+
const root = resolve(userConfig.root ?? "");
|
|
125
|
+
const { loadEnv } = await import("vite");
|
|
126
|
+
const env = userConfig.envDir === false ? process.env : loadEnv(mode, resolve(root, userConfig.envDir ?? ""), [
|
|
127
|
+
"GHOST_APP_URL",
|
|
128
|
+
"GHOST_APP_TUNNEL_URL",
|
|
129
|
+
"GHOST_URL"
|
|
130
|
+
]);
|
|
131
|
+
appUrl = env.GHOST_APP_URL?.trim() || void 0;
|
|
132
|
+
ghostUrl = env.GHOST_URL?.trim() || void 0;
|
|
133
|
+
if (command !== "serve" || isPreview) return;
|
|
134
|
+
tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);
|
|
135
|
+
dev = !process.env.VITEST && mode !== "test";
|
|
136
|
+
if (dev) {
|
|
137
|
+
await createKeys({
|
|
138
|
+
root,
|
|
139
|
+
mode: "development"
|
|
140
|
+
});
|
|
141
|
+
pending = await provideDevBackendKey(root);
|
|
142
|
+
}
|
|
143
|
+
return { server: {
|
|
144
|
+
fs: { deny: [...userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY, ...DENY] },
|
|
145
|
+
...tunnels.length > 0 && userConfig.server?.allowedHosts !== true ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) } : {}
|
|
146
|
+
} };
|
|
147
|
+
},
|
|
148
|
+
configResolved(resolved) {
|
|
149
|
+
config = resolved;
|
|
150
|
+
const exposed = [resolved.envPrefix ?? "VITE_"].flat().find((prefix) => [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)));
|
|
151
|
+
if (exposed !== void 0) throw new Error(`ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`);
|
|
152
|
+
if (dev && !resolved.server.fs.strict) throw new Error(`ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`);
|
|
153
|
+
if (pending) config.logger[pending.level](`ghost-app: ${pending.message}`);
|
|
154
|
+
},
|
|
155
|
+
configureServer(server) {
|
|
156
|
+
server.middlewares.use((req, res, next) => {
|
|
157
|
+
if (req.url?.split("?")[0] !== "/ghost-app.json" || !["GET", "HEAD"].includes(req.method)) {
|
|
158
|
+
next();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const host = req.headers.host ?? req.headers[":authority"];
|
|
162
|
+
const manifestUrl = manifestUrlFor(host);
|
|
163
|
+
if (!manifestUrl) {
|
|
164
|
+
const allowed = ["this machine", ...tunnels.map((origin) => new URL(origin).host)];
|
|
165
|
+
res.statusCode = 421;
|
|
166
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
167
|
+
res.end(`The dev server signs ghost-app.json only for ${allowed.join(", ")}, not ${host ?? "a request without a Host"}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\n`);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
signProject({
|
|
171
|
+
root: config.root,
|
|
172
|
+
mode: "development",
|
|
173
|
+
manifestUrl,
|
|
174
|
+
manifestFile
|
|
175
|
+
}).then((result) => {
|
|
176
|
+
if (!result.success) throw new Error(`${manifestFile} can't be signed:\n${formatErrors(result.errors)}`);
|
|
177
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
178
|
+
res.setHeader("cache-control", "no-store");
|
|
179
|
+
res.end(req.method === "HEAD" ? void 0 : serialiseSigned(result.signed));
|
|
180
|
+
}).catch((error) => {
|
|
181
|
+
const message = `ghost-app: ${error.message}`;
|
|
182
|
+
config.logger.error(message, { timestamp: true });
|
|
183
|
+
res.statusCode = 500;
|
|
184
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
185
|
+
res.end(`${message}\n`);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
const printUrls = server.printUrls.bind(server);
|
|
189
|
+
server.printUrls = () => {
|
|
190
|
+
printUrls();
|
|
191
|
+
const address = server.httpServer?.address();
|
|
192
|
+
const port = typeof address === "object" && address ? address.port : void 0;
|
|
193
|
+
const local = `${config.server.https ? "https" : "http"}://${devHostname(resolve(config.root, manifestFile))}:${port}`;
|
|
194
|
+
const ghost = (ghostUrl ?? "http://localhost:2368").replace(/\/+$/, "");
|
|
195
|
+
const lines = [...port ? [local] : [], ...tunnels].flatMap((origin) => [` Ghost app: ${origin}${MANIFEST_PATH}`, ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`]);
|
|
196
|
+
config.logger.info(`\n${lines.join("\n")}\n`);
|
|
197
|
+
};
|
|
198
|
+
},
|
|
199
|
+
async buildStart() {
|
|
200
|
+
if (config.command !== "build" || this.environment.config.consumer !== "client") return;
|
|
201
|
+
if (!appUrl) {
|
|
202
|
+
config.logger.warn(`ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const base = URL.parse(appUrl.endsWith("/") ? appUrl : `${appUrl}/`);
|
|
206
|
+
if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) this.error(`ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`);
|
|
207
|
+
const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;
|
|
208
|
+
this.addWatchFile(resolve(config.root, manifestFile));
|
|
209
|
+
const result = await signProject({
|
|
210
|
+
root: config.root,
|
|
211
|
+
mode: "production",
|
|
212
|
+
manifestUrl,
|
|
213
|
+
manifestFile
|
|
214
|
+
}).catch((error) => this.error(`ghost-app: ${error.message}`));
|
|
215
|
+
if (!result.success) this.error(`ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\n${formatErrors(result.errors)}`);
|
|
216
|
+
this.emitFile({
|
|
217
|
+
type: "asset",
|
|
218
|
+
fileName: MANIFEST_PATH.slice(1),
|
|
219
|
+
source: serialiseSigned(result.signed)
|
|
220
|
+
});
|
|
221
|
+
config.logger.info(`ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource("production", "identity")}`);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
226
|
+
export { ghostApp };
|
|
227
|
+
|
|
228
|
+
//# sourceMappingURL=vite.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH, formatErrors } from '../shared/manifest.ts';\nimport { parseJsonText, parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CAAC;CAAoB;CAAc;CAAQ;AAAQ;;;ACZvE,IAAM,mBAAmB;CAAC;CAAiB;CAAkB;AAAe;AAE5E,IAAM,WAAW;;;;;;AAOjB,eAAsB,qBACpB,MACkE;CAClE,MAAM,SAAS,SAAiB,WAAW,KAAK,MAAM,IAAI,CAAC;CAC3D,IAAI,CAAC,iBAAiB,KAAK,KAAK,GAC9B;CAEF,MAAM,MAAM,MAAM,eAAe;EAAE;EAAM,MAAM;CAAc,CAAC;CAG9D,MAAM,OAAO,MAAM,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,cAAc,MAAM,CAAC,CAAC,OAAO,KAAK;CAC/E,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;EACvB,OAAO,MAAM,SAAS,KAAK,MAAM,IAAI,GAAG,MAAM;EAC9C,IAAI,KAAK,SAAA,uBAA6B,GAEpC,OAAO,KAAK,SAAS,IAAI,CA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AO,KAAK,MAAM,GACjE,KAAK,MACH,mGAAmG,QACrG;GAEF,MAAM,cAAc,IAAI,IAAI,cAAc,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;GAE1D,KAAK,aAAa,QAAQ,OAAO,MAAM,YAAY,CAAC;GACpD,MAAM,SAAS,MAAM,YAAY;IAC/B,MAAM,OAAO;IACb,MAAM;IACN;IACA;GACF,CAAC,CAAC,CAAC,OAAO,UAAmB,KAAK,MAAM,cAAe,MAAgB,SAAS,CAAC;GACjF,IAAI,CAAC,OAAO,SACV,KAAK,MACH,cAAc,aAAa,uBAAuB,YAAY,KAAK,aAAa,OAAO,MAAM,GAC/F;GAEF,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,cAAc,MAAM,CAAC;IAC/B,QAAQ,gBAAgB,OAAO,MAAM;GACvC,CAAC;GACD,OAAO,OAAO,KACZ,wCAAwC,YAAY,QAAQ,iBAAiB,cAAc,UAAU,GACvG;EACF;CACF;AACF"}
|
package/dist/app-sdk.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
//#endregion
|
|
1
2
|
//#region ../app-contracts/build/plain-text.js
|
|
2
3
|
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
3
4
|
new RegExp(`^[${ALLOWED}]*$`, "u");
|
|
@@ -125,22 +126,6 @@ var CONTROL_CHARACTER = /\p{Cc}/u;
|
|
|
125
126
|
function isContainedPath(value) {
|
|
126
127
|
return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
|
|
127
128
|
}
|
|
128
|
-
var APP_PATH_BASE = "https://app.invalid";
|
|
129
|
-
/**
|
|
130
|
-
* Returns an app path in the URL parser's normalised form, the one form Admin and the SDK
|
|
131
|
-
* store it in. `.` and `..` are resolved within the app, so a path can never climb out of it.
|
|
132
|
-
* Characters that need escaping are escaped once, so a path the app reported compares equal to
|
|
133
|
-
* the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and
|
|
134
|
-
* `/x/../episodes/1` becomes `/episodes/1`.
|
|
135
|
-
*
|
|
136
|
-
* Expects a path that `isContainedPath` accepts; anything else may not be a path within the
|
|
137
|
-
* app at all. `AppPathSchema` already returns this form, so Admin never calls this directly.
|
|
138
|
-
* The SDK, which doesn't load zod, does.
|
|
139
|
-
*/
|
|
140
|
-
function normaliseAppPath(path) {
|
|
141
|
-
const url = new URL(path, APP_PATH_BASE);
|
|
142
|
-
return `${url.pathname}${url.search}${url.hash}`;
|
|
143
|
-
}
|
|
144
129
|
/** An object, or an array: anything whose fields can be read. */
|
|
145
130
|
function isRecord(value) {
|
|
146
131
|
return typeof value === "object" && value !== null;
|
|
@@ -853,18 +838,43 @@ function toResponse(answer) {
|
|
|
853
838
|
//#endregion
|
|
854
839
|
//#region src/history.ts
|
|
855
840
|
/**
|
|
856
|
-
*
|
|
857
|
-
* stores app paths in.
|
|
841
|
+
* A URL's route: its path, query and fragment. The URL parser has already put them in the
|
|
842
|
+
* normalised form Admin stores app paths in. Resolving them again would read a path that starts
|
|
843
|
+
* with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that
|
|
844
|
+
* route fails `isContainedPath` and is never reported.
|
|
858
845
|
*/
|
|
846
|
+
function routeOf({ pathname, search, hash }) {
|
|
847
|
+
return `${pathname}${search}${hash}`;
|
|
848
|
+
}
|
|
849
|
+
/** The page's route. */
|
|
859
850
|
function currentRoute() {
|
|
860
|
-
|
|
861
|
-
return normaliseAppPath(`${pathname}${search}${hash}`);
|
|
851
|
+
return routeOf(window.location);
|
|
862
852
|
}
|
|
863
853
|
/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */
|
|
864
854
|
function isLink(node) {
|
|
865
855
|
return (node instanceof HTMLAnchorElement || node instanceof SVGElement && node.localName === "a") && node.hasAttribute("href");
|
|
866
856
|
}
|
|
867
857
|
/**
|
|
858
|
+
* Whether a route is one Admin would take. Admin owns the app's address, so the page never
|
|
859
|
+
* moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin
|
|
860
|
+
* link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is
|
|
861
|
+
* dropped, with a warning for the app's developer.
|
|
862
|
+
*/
|
|
863
|
+
function isContained(route) {
|
|
864
|
+
if (isContainedPath(route)) return true;
|
|
865
|
+
console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);
|
|
866
|
+
return false;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL
|
|
870
|
+
* parser can't read is left to the browser, which throws as it would without the SDK.
|
|
871
|
+
*/
|
|
872
|
+
function refuses(url) {
|
|
873
|
+
if (url === void 0 || url === null) return false;
|
|
874
|
+
const next = URL.parse(url, window.location.href);
|
|
875
|
+
return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
868
878
|
* Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,
|
|
869
879
|
* and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's
|
|
870
880
|
* entries, which left back steps that did nothing once the app's page opened again, and WebKit
|
|
@@ -877,6 +887,7 @@ function isLink(node) {
|
|
|
877
887
|
* - A click on a link to the app's own origin, which a router hasn't already handled, is reported
|
|
878
888
|
* as a push, and the page then loads the link's address in place of its own entry. A link that
|
|
879
889
|
* opens elsewhere (a `target`, `download`, or a modifier key) is left alone.
|
|
890
|
+
* - Neither is made to a route Admin would refuse, one that isn't contained.
|
|
880
891
|
* - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.
|
|
881
892
|
*
|
|
882
893
|
* Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the
|
|
@@ -897,10 +908,12 @@ function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
|
897
908
|
}
|
|
898
909
|
};
|
|
899
910
|
const push = (data, unused, url) => {
|
|
911
|
+
if (refuses(url)) return;
|
|
900
912
|
replaceState.call(history, data, unused, url);
|
|
901
913
|
report("push");
|
|
902
914
|
};
|
|
903
915
|
const replace = (data, unused, url) => {
|
|
916
|
+
if (refuses(url)) return;
|
|
904
917
|
replaceState.call(history, data, unused, url);
|
|
905
918
|
report("replace");
|
|
906
919
|
};
|
|
@@ -915,7 +928,8 @@ function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
|
915
928
|
if (url.origin !== window.location.origin) return;
|
|
916
929
|
event.preventDefault();
|
|
917
930
|
const go = () => load(url.href);
|
|
918
|
-
const next =
|
|
931
|
+
const next = routeOf(url);
|
|
932
|
+
if (!isContained(next)) return;
|
|
919
933
|
if (next === route) {
|
|
920
934
|
go();
|
|
921
935
|
return;
|
|
@@ -1069,8 +1083,9 @@ var Channel = class {
|
|
|
1069
1083
|
};
|
|
1070
1084
|
this.#theme = Object.freeze({ ...context.theme });
|
|
1071
1085
|
this.#history = watchHistory((route, move) => this.#moved(route, move));
|
|
1072
|
-
|
|
1073
|
-
|
|
1086
|
+
const route = currentRoute();
|
|
1087
|
+
this.#path = context.path;
|
|
1088
|
+
if (route !== context.path) this.#moved(route, "replace");
|
|
1074
1089
|
if (this.#hostExports.has("titleChanged")) this.#stopWatchingTitle = watchTitle((title) => {
|
|
1075
1090
|
this.#call("titleChanged", title).catch(() => {});
|
|
1076
1091
|
});
|
|
@@ -1094,6 +1109,7 @@ var Channel = class {
|
|
|
1094
1109
|
* for the app, or has refused; a refused move leaves the page where it is.
|
|
1095
1110
|
*/
|
|
1096
1111
|
async #moved(route, move) {
|
|
1112
|
+
if (!isContainedPath(route)) return;
|
|
1097
1113
|
this.#path = route;
|
|
1098
1114
|
this.#moves += 1;
|
|
1099
1115
|
const thisMove = this.#moves;
|
|
@@ -1202,7 +1218,7 @@ var Channel = class {
|
|
|
1202
1218
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
1203
1219
|
* and doesn't read package.json.
|
|
1204
1220
|
*/
|
|
1205
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
1221
|
+
var SDK_VERSION = "0.1.0-alpha.10";
|
|
1206
1222
|
//#endregion
|
|
1207
1223
|
//#region src/connect.ts
|
|
1208
1224
|
/**
|