@tryghost/app-sdk 0.1.0-alpha.2 → 0.1.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -289
- package/build/backend.d.ts +93 -0
- package/build/backend.js +202 -0
- package/build/backend.js.map +1 -0
- package/build/bin.d.ts +1 -0
- package/build/bin.js +123 -0
- package/build/bin.js.map +1 -0
- package/build/chunks/manifest-DmfZ-0r7.js +47 -0
- package/build/chunks/manifest-DmfZ-0r7.js.map +1 -0
- package/build/chunks/parse-C6hK3wRD.js +17 -0
- package/build/chunks/parse-C6hK3wRD.js.map +1 -0
- package/build/chunks/rules-BAEnzs5i.js +159 -0
- package/build/chunks/rules-BAEnzs5i.js.map +1 -0
- package/build/chunks/sign-B1y31TLX.js +898 -0
- package/build/chunks/sign-B1y31TLX.js.map +1 -0
- package/build/chunks/signed-manifest-tbnMbfyw.d.ts +9 -0
- package/build/index.d.ts +43 -28
- package/build/index.js +41 -178
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +158 -0
- package/build/tooling.js +2 -0
- package/build/vite.d.ts +29 -0
- package/build/vite.js +229 -0
- package/build/vite.js.map +1 -0
- package/dist/app-sdk.js +94 -27
- package/dist/app-sdk.js.map +1 -1
- package/package.json +32 -3
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;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,KA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;GACA,MAAM,OAAO,IAAI,MAAM,OAAO,SAAS,GAAG,IAAI,SAAS,GAAG,OAAO,EAAE;GAEnE,IAAI,CAAC,QAAQ,CAAC,YAAY,KAAK,KAAK,QAAQ,KAAK,OAAO,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,5 +1,57 @@
|
|
|
1
|
+
//#region ../../contracts/app-contracts/build/identity/codes.js
|
|
2
|
+
/**
|
|
3
|
+
* Ghost couldn't confirm the app is the one it says it is. Kept apart from an app that's down
|
|
4
|
+
* or broken because the publisher should hear something different: contact the developer, and
|
|
5
|
+
* don't install it again from a link, the one way a different developer's key gets pinned.
|
|
6
|
+
*/
|
|
7
|
+
var UNCONFIRMED_APP_CODES = [
|
|
8
|
+
"APP_MANIFEST_URL_MISMATCH",
|
|
9
|
+
"APP_MANIFEST_SIGNATURE_INVALID",
|
|
10
|
+
"APP_IDENTITY_MISMATCH",
|
|
11
|
+
"APP_BACKEND_KEY_RETIRED",
|
|
12
|
+
"APP_CHALLENGE_FAILED"
|
|
13
|
+
];
|
|
14
|
+
new Set(UNCONFIRMED_APP_CODES);
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region ../../contracts/app-contracts/build/failure-codes.js
|
|
17
|
+
/** Trying again may work. */
|
|
18
|
+
var UNREACHABLE_APP_CODES = ["APP_MANIFEST_UNREACHABLE", "APP_CHALLENGE_UNREACHABLE"];
|
|
19
|
+
/** Only the app's developer can fix these. */
|
|
20
|
+
var UNUSABLE_MANIFEST_CODES = [
|
|
21
|
+
"APP_MANIFEST_URL_INVALID",
|
|
22
|
+
"APP_MANIFEST_REDIRECTED",
|
|
23
|
+
"APP_MANIFEST_TOO_LARGE",
|
|
24
|
+
"APP_MANIFEST_NOT_JSON",
|
|
25
|
+
"APP_MANIFEST_UNSIGNED",
|
|
26
|
+
"APP_MANIFEST_INVALID",
|
|
27
|
+
"APP_MANIFEST_OTHER_APP"
|
|
28
|
+
];
|
|
29
|
+
/**
|
|
30
|
+
* The publisher confirmed a review that's out of date. A changed manifest or installation
|
|
31
|
+
* carries the current review in the error's details when Ghost has one.
|
|
32
|
+
*/
|
|
33
|
+
var OUTDATED_REVIEW_CODES = [
|
|
34
|
+
"APP_MANIFEST_CHANGED",
|
|
35
|
+
"APP_INSTALLATION_CHANGED",
|
|
36
|
+
"APP_ALREADY_INSTALLED",
|
|
37
|
+
"APP_INSTALLATION_UNINSTALLED"
|
|
38
|
+
];
|
|
39
|
+
/**
|
|
40
|
+
* Admin can only explain a code listed here; any other shows as an unknown error. A Ghost
|
|
41
|
+
* core test checks the list against the codes the app installations service throws.
|
|
42
|
+
*/
|
|
43
|
+
var APP_FAILURE_CODES = [
|
|
44
|
+
...UNREACHABLE_APP_CODES,
|
|
45
|
+
...UNCONFIRMED_APP_CODES,
|
|
46
|
+
...UNUSABLE_MANIFEST_CODES,
|
|
47
|
+
...OUTDATED_REVIEW_CODES,
|
|
48
|
+
"APP_NOT_INSTALLED",
|
|
49
|
+
"APP_UNAVAILABLE"
|
|
50
|
+
];
|
|
51
|
+
new Set(APP_FAILURE_CODES);
|
|
52
|
+
new Set(OUTDATED_REVIEW_CODES);
|
|
1
53
|
//#endregion
|
|
2
|
-
//#region
|
|
54
|
+
//#region ../../contracts/app-contracts/build/plain-text.js
|
|
3
55
|
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
4
56
|
new RegExp(`^[${ALLOWED}]*$`, "u");
|
|
5
57
|
var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
|
|
@@ -8,7 +60,7 @@ function toPlainText(value) {
|
|
|
8
60
|
return value.replace(NOT_PLAIN_TEXT, "");
|
|
9
61
|
}
|
|
10
62
|
//#endregion
|
|
11
|
-
//#region
|
|
63
|
+
//#region ../../contracts/app-contracts/build/bridge/rules.js
|
|
12
64
|
/**
|
|
13
65
|
* The bridge's rules that have no dependencies. The root entry point exports them so the SDK
|
|
14
66
|
* can use them without zod. The schemas in this folder build on them, so the SDK and Admin
|
|
@@ -126,22 +178,6 @@ var CONTROL_CHARACTER = /\p{Cc}/u;
|
|
|
126
178
|
function isContainedPath(value) {
|
|
127
179
|
return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
|
|
128
180
|
}
|
|
129
|
-
var APP_PATH_BASE = "https://app.invalid";
|
|
130
|
-
/**
|
|
131
|
-
* Returns an app path in the URL parser's normalised form, the one form Admin and the SDK
|
|
132
|
-
* store it in. `.` and `..` are resolved within the app, so a path can never climb out of it.
|
|
133
|
-
* Characters that need escaping are escaped once, so a path the app reported compares equal to
|
|
134
|
-
* the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and
|
|
135
|
-
* `/x/../episodes/1` becomes `/episodes/1`.
|
|
136
|
-
*
|
|
137
|
-
* Expects a path that `isContainedPath` accepts; anything else may not be a path within the
|
|
138
|
-
* app at all. `AppPathSchema` already returns this form, so Admin never calls this directly.
|
|
139
|
-
* The SDK, which doesn't load zod, does.
|
|
140
|
-
*/
|
|
141
|
-
function normaliseAppPath(path) {
|
|
142
|
-
const url = new URL(path, APP_PATH_BASE);
|
|
143
|
-
return `${url.pathname}${url.search}${url.hash}`;
|
|
144
|
-
}
|
|
145
181
|
/** An object, or an array: anything whose fields can be read. */
|
|
146
182
|
function isRecord(value) {
|
|
147
183
|
return typeof value === "object" && value !== null;
|
|
@@ -854,18 +890,43 @@ function toResponse(answer) {
|
|
|
854
890
|
//#endregion
|
|
855
891
|
//#region src/history.ts
|
|
856
892
|
/**
|
|
857
|
-
*
|
|
858
|
-
* stores app paths in.
|
|
893
|
+
* A URL's route: its path, query and fragment. The URL parser has already put them in the
|
|
894
|
+
* normalised form Admin stores app paths in. Resolving them again would read a path that starts
|
|
895
|
+
* with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that
|
|
896
|
+
* route fails `isContainedPath` and is never reported.
|
|
859
897
|
*/
|
|
898
|
+
function routeOf({ pathname, search, hash }) {
|
|
899
|
+
return `${pathname}${search}${hash}`;
|
|
900
|
+
}
|
|
901
|
+
/** The page's route. */
|
|
860
902
|
function currentRoute() {
|
|
861
|
-
|
|
862
|
-
return normaliseAppPath(`${pathname}${search}${hash}`);
|
|
903
|
+
return routeOf(window.location);
|
|
863
904
|
}
|
|
864
905
|
/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */
|
|
865
906
|
function isLink(node) {
|
|
866
907
|
return (node instanceof HTMLAnchorElement || node instanceof SVGElement && node.localName === "a") && node.hasAttribute("href");
|
|
867
908
|
}
|
|
868
909
|
/**
|
|
910
|
+
* Whether a route is one Admin would take. Admin owns the app's address, so the page never
|
|
911
|
+
* moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin
|
|
912
|
+
* link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is
|
|
913
|
+
* dropped, with a warning for the app's developer.
|
|
914
|
+
*/
|
|
915
|
+
function isContained(route) {
|
|
916
|
+
if (isContainedPath(route)) return true;
|
|
917
|
+
console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL
|
|
922
|
+
* parser can't read is left to the browser, which throws as it would without the SDK.
|
|
923
|
+
*/
|
|
924
|
+
function refuses(url) {
|
|
925
|
+
if (url === void 0 || url === null) return false;
|
|
926
|
+
const next = URL.parse(url, window.location.href);
|
|
927
|
+
return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
869
930
|
* Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,
|
|
870
931
|
* and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's
|
|
871
932
|
* entries, which left back steps that did nothing once the app's page opened again, and WebKit
|
|
@@ -878,6 +939,7 @@ function isLink(node) {
|
|
|
878
939
|
* - A click on a link to the app's own origin, which a router hasn't already handled, is reported
|
|
879
940
|
* as a push, and the page then loads the link's address in place of its own entry. A link that
|
|
880
941
|
* opens elsewhere (a `target`, `download`, or a modifier key) is left alone.
|
|
942
|
+
* - Neither is made to a route Admin would refuse, one that isn't contained.
|
|
881
943
|
* - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.
|
|
882
944
|
*
|
|
883
945
|
* Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the
|
|
@@ -898,10 +960,12 @@ function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
|
898
960
|
}
|
|
899
961
|
};
|
|
900
962
|
const push = (data, unused, url) => {
|
|
963
|
+
if (refuses(url)) return;
|
|
901
964
|
replaceState.call(history, data, unused, url);
|
|
902
965
|
report("push");
|
|
903
966
|
};
|
|
904
967
|
const replace = (data, unused, url) => {
|
|
968
|
+
if (refuses(url)) return;
|
|
905
969
|
replaceState.call(history, data, unused, url);
|
|
906
970
|
report("replace");
|
|
907
971
|
};
|
|
@@ -916,7 +980,8 @@ function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
|
916
980
|
if (url.origin !== window.location.origin) return;
|
|
917
981
|
event.preventDefault();
|
|
918
982
|
const go = () => load(url.href);
|
|
919
|
-
const next =
|
|
983
|
+
const next = routeOf(url);
|
|
984
|
+
if (!isContained(next)) return;
|
|
920
985
|
if (next === route) {
|
|
921
986
|
go();
|
|
922
987
|
return;
|
|
@@ -1070,8 +1135,9 @@ var Channel = class {
|
|
|
1070
1135
|
};
|
|
1071
1136
|
this.#theme = Object.freeze({ ...context.theme });
|
|
1072
1137
|
this.#history = watchHistory((route, move) => this.#moved(route, move));
|
|
1073
|
-
|
|
1074
|
-
|
|
1138
|
+
const route = currentRoute();
|
|
1139
|
+
this.#path = context.path;
|
|
1140
|
+
if (route !== context.path) this.#moved(route, "replace");
|
|
1075
1141
|
if (this.#hostExports.has("titleChanged")) this.#stopWatchingTitle = watchTitle((title) => {
|
|
1076
1142
|
this.#call("titleChanged", title).catch(() => {});
|
|
1077
1143
|
});
|
|
@@ -1095,6 +1161,7 @@ var Channel = class {
|
|
|
1095
1161
|
* for the app, or has refused; a refused move leaves the page where it is.
|
|
1096
1162
|
*/
|
|
1097
1163
|
async #moved(route, move) {
|
|
1164
|
+
if (!isContainedPath(route)) return;
|
|
1098
1165
|
this.#path = route;
|
|
1099
1166
|
this.#moves += 1;
|
|
1100
1167
|
const thisMove = this.#moves;
|
|
@@ -1203,7 +1270,7 @@ var Channel = class {
|
|
|
1203
1270
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
1204
1271
|
* and doesn't read package.json.
|
|
1205
1272
|
*/
|
|
1206
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
1273
|
+
var SDK_VERSION = "0.1.0-alpha.20";
|
|
1207
1274
|
//#endregion
|
|
1208
1275
|
//#region src/connect.ts
|
|
1209
1276
|
/**
|
|
@@ -1313,7 +1380,7 @@ function forget(attempt) {
|
|
|
1313
1380
|
* app. Safe to call as soon as the page loads.
|
|
1314
1381
|
*
|
|
1315
1382
|
* Every call shares one connection, and the first call's options apply. Only one copy of the
|
|
1316
|
-
* SDK in a page can connect
|
|
1383
|
+
* SDK in a page can connect. Any other copy rejects with `duplicate_sdk`. Admin answers each
|
|
1317
1384
|
* document only once, so after it answers, that connection is the page's only one. Once it
|
|
1318
1385
|
* fails or its session ends, every call rejects with the error it ended with, and only a new
|
|
1319
1386
|
* document (after a reload, for example) can connect again. A failure before Admin answered,
|