@tryghost/app-sdk 0.1.0-alpha.4 → 0.1.0-alpha.6

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 CHANGED
@@ -1,11 +1,19 @@
1
1
  # @tryghost/app-sdk
2
2
 
3
- The SDK apps use to talk to Ghost from inside Admin.
3
+ The SDK apps use to talk to Ghost: from their page inside Admin, and from their
4
+ backend.
4
5
 
5
6
  An app's page runs in a frame inside Ghost Admin. The SDK connects it to Admin,
6
7
  gives it the site, the user and the theme, and lets it call the Admin API, keep
7
8
  its route in sync with Admin's URL, and send the publisher elsewhere in Admin.
8
9
 
10
+ | Entry point | Runs in | What it's for |
11
+ | --------------------------- | -------------------------- | -------------------------------------------------------------------- |
12
+ | `@tryghost/app-sdk` | The app's page | Talking to Admin (below) |
13
+ | `@tryghost/app-sdk/backend` | Any platform with web APIs | [Answering Ghost's challenge and serving the manifest](#the-backend) |
14
+
15
+ The page's entry point loads none of the backend's code.
16
+
9
17
  > **Alpha.** CI publishes each change to npm as the next `0.1.0-alpha.N` under
10
18
  > the `latest` tag. Alphas make no compatibility promise.
11
19
 
@@ -29,7 +37,8 @@ ES module with everything inlined:
29
37
  ```
30
38
 
31
39
  With a bundler, install the package. It includes the types and code it uses
32
- from Ghost's contracts, so its only dependency is `@quilted/threads`:
40
+ from Ghost's contracts. The page needs only `@quilted/threads`, and the backend
41
+ adds `jose` and `zod`:
33
42
 
34
43
  ```sh
35
44
  pnpm add @tryghost/app-sdk
@@ -251,24 +260,51 @@ documents in a row, each replaced within three seconds of starting. A publisher
251
260
  clicking quickly through more than five pages of a multi-page app would trip it
252
261
  too.
253
262
 
254
- ## Who can frame the page
263
+ ## The backend
255
264
 
256
- The SDK talks to whichever window frames the page. It can't know a site's Admin
257
- origin in advance, so if any site can frame the page, any site can fool it: send
258
- it a start context of its choosing, and answer every `fetch` itself. No Ghost
259
- credential is ever in the page. But whatever the publisher types into the page
260
- is exposed, and the app acts on whatever responses it gets.
265
+ `@tryghost/app-sdk/backend` uses only `Request`, `Response`, `fetch` and
266
+ WebCrypto, so the same code runs on Cloudflare Workers, Node, Bun and Deno, and
267
+ in frameworks such as Hono. Configuration is passed in.
261
268
 
262
- Serve app pages with a `frame-ancestors` Content Security Policy that names the
263
- Ghost Admin origins of the sites using the app, so nothing else can frame them:
269
+ `withGhostApp` is the app's backend. It answers Ghost's challenge itself and
270
+ passes every other request to `fetch`. It returns `{ fetch }`, so a Worker
271
+ exports it as it is, reading its configuration from `cloudflare:workers`:
264
272
 
265
- ```http
266
- Content-Security-Policy: frame-ancestors https://site.example
273
+ ```ts
274
+ import { env } from 'cloudflare:workers';
275
+ import { withGhostApp } from '@tryghost/app-sdk/backend';
276
+
277
+ export default withGhostApp({
278
+ backendKey: env.GHOST_APP_BACKEND_KEY,
279
+ fetch: (request) => env.ASSETS.fetch(request),
280
+ });
267
281
  ```
268
282
 
269
- Admin is usually on the site's own origin, or on a separate Admin domain when
270
- the site has one. An app installed on many sites can build the list from its
271
- own record of where it is installed.
283
+ It takes `handleChallenge`'s options and `fetch`, which gets whatever else the
284
+ platform passes too, such as a Worker's `env` and `ctx`. Frameworks that route
285
+ requests themselves, such as Hono, use `handleChallenge` directly.
286
+
287
+ | Export | What it does |
288
+ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
289
+ | `withGhostApp({ backendKey, fetch })` | The app's backend, as `{ fetch }`: answers the challenge at `CHALLENGE_PATH` with `handleChallenge`, and passes every other request to `fetch`. |
290
+ | `handleChallenge(request, { backendKey, origin? })` | Answers Ghost's challenge, posted to `CHALLENGE_PATH`, with the backend key: a private JWK, or its JSON as a secret holds it. `405` for any method but `POST`, `413` past 4 KB, `400` for anything that isn't a challenge for `origin` when it's given, or else `request.url`'s origin, `200` with the answer. |
291
+ | `serveManifest(signed)` | A response for the signed manifest, for a backend that doesn't serve it as a file. Caches must revalidate it, so a new manifest reaches Ghost the next time it reads it. |
292
+
293
+ `handleChallenge` refuses a challenge for any origin but the one the platform
294
+ reports in `request.url`, so pass the request as the platform hands it over,
295
+ never one rebuilt from `X-Forwarded-Host`. A server that doesn't see the public
296
+ scheme and host, such as Node behind a proxy that terminates TLS, passes the
297
+ app's public origin as `origin` (`https://app.example.com`), from its own
298
+ configuration, never from a request's headers. Workers don't need it.
299
+
300
+ ## Who can frame the page
301
+
302
+ The SDK talks to whichever window frames the page, and can't yet tell whether
303
+ it's Ghost Admin. A site that frames the page can send it a start context of
304
+ its choosing and answer every `fetch` itself. No Ghost credential is ever in the
305
+ page, but whatever the publisher types into the page reaches that site, and the
306
+ app acts on the responses it gets. Ghost will close this by vouching for the
307
+ site and the staff user to the app's backend.
272
308
 
273
309
  ## Serve only the app from its origin
274
310
 
@@ -280,15 +316,25 @@ content and third-party pages or widgets on another origin (a separate subdomain
280
316
  counts). An open redirect is a risk too: a link through it puts another site's
281
317
  page in the frame, inside Admin.
282
318
 
319
+ Serve the app from a host of its own, too. Ghost refuses an app on the site's
320
+ or Admin's host, whatever the port, because browsers send a host's cookies to
321
+ every port on it, Ghost's session cookie included. On your own machine, serve
322
+ the app from a name of its own under `.localhost`, such as `my-app.localhost`.
323
+ Browsers treat it as another host and send it to the machine itself, Vite
324
+ accepts it with no setup, and Ghost in development reaches it even where the
325
+ system's resolver doesn't know it. Open Admin on the name Ghost is configured
326
+ with, as Admin refuses an app on the host it's opened from too.
327
+
283
328
  ## Develop
284
329
 
285
330
  This is a workspace package in the Ghost monorepo. From the package directory:
286
331
 
287
332
  ```bash
288
333
  pnpm build # the package to build/ and the browser bundle to dist/, with Vite
289
- pnpm test # type-check + unit tests (jsdom, with a fake Admin on a real MessageChannel),
290
- # which build both afresh to check what they import, and pack build/ and dist/
291
- # to use them from an app outside the workspace (after pnpm build; Nx runs it)
334
+ pnpm test # type-check + unit tests (jsdom for the page, with a fake Admin on a real
335
+ # MessageChannel; Node for the backend), which build both
336
+ # afresh to check what they import, and pack build/ and dist/ to use them from an
337
+ # app outside the workspace (after pnpm build; Nx runs it)
292
338
  pnpm lint # lint source and tests
293
339
  ```
294
340
 
@@ -298,14 +344,19 @@ and also writes `dist/`, which is in `files` and in the Nx build outputs.
298
344
 
299
345
  It uses `@tryghost/app-contracts` for the bridge's message types, limits and
300
346
  shape checks, so the SDK and Admin apply the same rules to paths, themes and
301
- start contexts. It imports only the contracts' root entry point, which doesn't
302
- load `zod`, and the build inlines what it uses into the SDK, so the contracts
303
- are a dev dependency:
304
-
305
- - `build/index.js` imports only `@quilted/threads`;
306
- - `build/index.d.ts`, emitted by TypeScript 7 and bundled by
307
- `rolldown-plugin-dts`, imports nothing;
347
+ start contexts, and for answering challenges, so the backend applies Ghost's
348
+ own rules. The build inlines what it uses
349
+ into the SDK, so the contracts are a dev dependency. `build/` has an ES module
350
+ per entry point, which share chunks:
351
+
352
+ - `index.js` loads only `@quilted/threads`, never `jose`, `zod` or a Node
353
+ builtin;
354
+ - `backend.js` loads only `jose` and `zod`, and no Node builtin;
355
+ - each entry point's declarations, emitted by TypeScript 7 and bundled by
356
+ `rolldown-plugin-dts`, import nothing;
308
357
  - `dist/` imports nothing at all.
309
358
 
310
- `test/bundle.test.ts` checks this on a fresh build. The build fails if the code
311
- imports a Node builtin, which Vite would otherwise replace with an empty stub.
359
+ `test/bundle.test.ts` checks this on a fresh build. The build keeps `node:`
360
+ imports as imports, so a builtin the page or the backend reaches shows up there.
361
+ Lint requires the `node:` prefix, as Vite replaces a builtin imported without it
362
+ with an empty stub.
@@ -0,0 +1,98 @@
1
+ //#region ../app-contracts/build/identity/challenge.d.ts
2
+ /** Where on an origin Ghost posts a challenge. */
3
+ declare const CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
4
+ //#endregion
5
+ //#region src/backend/challenge.d.ts
6
+ /**
7
+ * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's
8
+ * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and
9
+ * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.
10
+ */
11
+ type BackendJwk = {
12
+ alg?: string;
13
+ crv?: string;
14
+ d?: string;
15
+ dp?: string;
16
+ dq?: string;
17
+ e?: string;
18
+ ext?: boolean;
19
+ k?: string;
20
+ key_ops?: string[];
21
+ kid?: string;
22
+ kty?: string;
23
+ n?: string;
24
+ oth?: {
25
+ d?: string;
26
+ r?: string;
27
+ t?: string;
28
+ }[];
29
+ p?: string;
30
+ q?: string;
31
+ qi?: string;
32
+ use?: string;
33
+ x?: string;
34
+ y?: string;
35
+ };
36
+ /**
37
+ * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an
38
+ * environment variable, such as `GHOST_APP_BACKEND_KEY`.
39
+ */
40
+ type BackendKey = BackendJwk | string;
41
+ interface HandleChallengeOptions {
42
+ backendKey: BackendKey;
43
+ /**
44
+ * The app's public origin, such as `https://app.example.com`, for a server that doesn't see
45
+ * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees
46
+ * `http://`. Ghost challenges the public origin, so without it every challenge is refused.
47
+ * Take it from the app's own configuration, never from a request's headers, which the sender
48
+ * sets. Workers, and other platforms that report the public URL, don't need it.
49
+ */
50
+ origin?: string;
51
+ }
52
+ /**
53
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
54
+ * to it, or use `withGhostApp`, which does.
55
+ */
56
+ declare function handleChallenge(request: Request, { backendKey, origin }: HandleChallengeOptions): Promise<Response>;
57
+ //#endregion
58
+ //#region src/backend/app.d.ts
59
+ /**
60
+ * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`
61
+ * and `ctx`.
62
+ */
63
+ type FetchHandler<Args extends unknown[] = []> = (request: Request, ...args: Args) => Response | Promise<Response>;
64
+ interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {
65
+ /** The app's own handler, for every request but Ghost's challenge. */
66
+ fetch: FetchHandler<Args>;
67
+ }
68
+ /**
69
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
70
+ * passes every other request to `fetch`, with whatever else the platform passes.
71
+ *
72
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
73
+ */
74
+ declare function withGhostApp<Args extends unknown[] = []>({ fetch, ...challenge }: GhostAppOptions<Args>): {
75
+ fetch: (request: Request, ...args: Args) => Promise<Response>;
76
+ };
77
+ //#endregion
78
+ //#region src/shared/manifest.d.ts
79
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
80
+ declare const MANIFEST_PATH = "/ghost-app.json";
81
+ /** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */
82
+ interface SignedManifest {
83
+ protected: string;
84
+ payload: string;
85
+ signature: string;
86
+ }
87
+ //#endregion
88
+ //#region src/backend/manifest.d.ts
89
+ /**
90
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
91
+ * file. Pass the file's text as it is, or the object it holds.
92
+ *
93
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
94
+ * Ghost the next time Ghost reads it.
95
+ */
96
+ declare function serveManifest(signed: SignedManifest | string): Response;
97
+ //#endregion
98
+ export { type BackendKey, CHALLENGE_PATH, type FetchHandler, type GhostAppOptions, type HandleChallengeOptions, MANIFEST_PATH, type SignedManifest, handleChallenge, serveManifest, withGhostApp };
@@ -0,0 +1,225 @@
1
+ import { CompactSign } from "jose";
2
+ import { z } from "zod";
3
+ //#region ../app-contracts/build/identity/jws.js
4
+ /** The only algorithm either key signs with. */
5
+ var ALGORITHM = "Ed25519";
6
+ //#endregion
7
+ //#region ../app-contracts/build/identity/challenge.js
8
+ /** Where on an origin Ghost posts a challenge. */
9
+ var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
10
+ /** What a challenge is for, signed with it, so its answer can't pass for any other signature. */
11
+ var CHALLENGE_PURPOSE = "ghost-app-challenge";
12
+ z.strictObject({ alg: z.literal(ALGORITHM) });
13
+ JSON.stringify({ alg: ALGORITHM });
14
+ var ChallengeShape = z.strictObject({
15
+ purpose: z.literal(CHALLENGE_PURPOSE),
16
+ origin: z.string(),
17
+ nonce: z.string()
18
+ });
19
+ z.object({ signature: z.string() });
20
+ /**
21
+ * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is
22
+ * the URL the request arrived at, as the platform reports it (`request.url` on Workers):
23
+ * never one built from `X-Forwarded-Host` or any other header the sender controls. A
24
+ * challenge for any origin but that one is refused, so whoever takes over a name the app
25
+ * used to serve can't relay Ghost's challenge to the real backend to prove it.
26
+ *
27
+ * Ghost can't see this check, so it only helps where the platform routes requests by host,
28
+ * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.
29
+ */
30
+ async function answerChallenge(body, { backendKey, requestUrl }) {
31
+ const challenge = ChallengeShape.safeParse(parseJson(body));
32
+ if (!challenge.success) return {
33
+ success: false,
34
+ error: "Expected a challenge of {purpose, origin, nonce}"
35
+ };
36
+ const arrivedAt = URL.parse(requestUrl)?.origin;
37
+ if (arrivedAt !== challenge.data.origin) return {
38
+ success: false,
39
+ error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? "an unknown origin"}`
40
+ };
41
+ return {
42
+ success: true,
43
+ answer: { signature: await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: ALGORITHM }).sign(backendKey) }
44
+ };
45
+ }
46
+ function parseJson(text) {
47
+ try {
48
+ return JSON.parse(text);
49
+ } catch {
50
+ return;
51
+ }
52
+ }
53
+ //#endregion
54
+ //#region src/shared/parse.ts
55
+ var UNSAFE_IN_POLICY = /[\s;,'"*]/;
56
+ /**
57
+ * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
58
+ * `,` into a host, so the origin must also read back as itself, and hold nothing that would end
59
+ * a source in a Content-Security-Policy.
60
+ */
61
+ function parseOrigin(entry) {
62
+ const url = URL.parse(entry);
63
+ const origin = url?.origin;
64
+ if (!url || !origin || url.protocol !== "https:" && url.protocol !== "http:" || url.href !== `${origin}/` || URL.parse(origin)?.origin !== origin || UNSAFE_IN_POLICY.test(entry) || UNSAFE_IN_POLICY.test(origin)) return;
65
+ return origin;
66
+ }
67
+ //#endregion
68
+ //#region src/shared/ignore.ts
69
+ /** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
70
+ var ignoreError = () => void 0;
71
+ //#endregion
72
+ //#region src/shared/body.ts
73
+ /**
74
+ * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
75
+ * stops reading as soon as the body passes the limit, so a large body is never held whole.
76
+ */
77
+ async function readBytes(message, maxBytes) {
78
+ if (Number(message.headers.get("content-length")) > maxBytes) {
79
+ message.body?.cancel().catch(ignoreError);
80
+ return;
81
+ }
82
+ if (!message.body) return /* @__PURE__ */ new Uint8Array();
83
+ const reader = message.body.getReader();
84
+ const chunks = [];
85
+ let length = 0;
86
+ for (;;) {
87
+ const { done, value } = await reader.read();
88
+ if (done) break;
89
+ length += value.byteLength;
90
+ if (length > maxBytes) {
91
+ reader.cancel().catch(ignoreError);
92
+ return;
93
+ }
94
+ chunks.push(value);
95
+ }
96
+ const bytes = new Uint8Array(length);
97
+ let offset = 0;
98
+ for (const chunk of chunks) {
99
+ bytes.set(chunk, offset);
100
+ offset += chunk.byteLength;
101
+ }
102
+ return bytes;
103
+ }
104
+ //#endregion
105
+ //#region src/backend/body.ts
106
+ /**
107
+ * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
108
+ * UTF-8 throws, as the exact text matters to whoever signs it.
109
+ */
110
+ async function readText(request, maxBytes) {
111
+ const bytes = await readBytes(request, maxBytes);
112
+ return bytes && new TextDecoder("utf-8", {
113
+ fatal: true,
114
+ ignoreBOM: true
115
+ }).decode(bytes);
116
+ }
117
+ function json(status, body, headers = {}) {
118
+ return new Response(JSON.stringify(body), {
119
+ status,
120
+ headers: {
121
+ "content-type": "application/json; charset=utf-8",
122
+ "cache-control": "no-store",
123
+ ...headers
124
+ }
125
+ });
126
+ }
127
+ //#endregion
128
+ //#region src/backend/challenge.ts
129
+ var CHALLENGE_MAX_BYTES = 4 * 1024;
130
+ var INVALID_KEY = "backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d";
131
+ var imported;
132
+ function importBackendKey(backendKey) {
133
+ const text = typeof backendKey === "string" ? backendKey : JSON.stringify(backendKey);
134
+ if (imported?.text !== text) {
135
+ const key = importPrivateKey(text);
136
+ imported = {
137
+ text,
138
+ key
139
+ };
140
+ key.catch(() => {
141
+ if (imported?.key === key) imported = void 0;
142
+ });
143
+ }
144
+ return imported.key;
145
+ }
146
+ async function importPrivateKey(text) {
147
+ let jwk;
148
+ try {
149
+ jwk = JSON.parse(text);
150
+ } catch {
151
+ throw new TypeError(`${INVALID_KEY}; it isn't JSON`);
152
+ }
153
+ const { kty, crv, x, d } = typeof jwk === "object" && jwk !== null ? jwk : {};
154
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") throw new TypeError(INVALID_KEY);
155
+ try {
156
+ return await crypto.subtle.importKey("jwk", {
157
+ kty,
158
+ crv,
159
+ x,
160
+ d
161
+ }, { name: "Ed25519" }, false, ["sign"]);
162
+ } catch (error) {
163
+ throw new TypeError(INVALID_KEY, { cause: error });
164
+ }
165
+ }
166
+ /**
167
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
168
+ * to it, or use `withGhostApp`, which does.
169
+ */
170
+ async function handleChallenge(request, { backendKey, origin }) {
171
+ const publicOrigin = origin === void 0 ? void 0 : parseOrigin(origin);
172
+ if (origin !== void 0 && !publicOrigin) throw new TypeError(`Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`);
173
+ if (request.method !== "POST") return json(405, { error: "Expected a POST" }, { allow: "POST" });
174
+ let body;
175
+ try {
176
+ body = await readText(request, CHALLENGE_MAX_BYTES);
177
+ } catch {
178
+ return json(400, { error: "Expected a challenge in UTF-8" });
179
+ }
180
+ if (body === void 0) return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });
181
+ const key = await importBackendKey(backendKey);
182
+ const result = await answerChallenge(body, {
183
+ backendKey: key,
184
+ requestUrl: publicOrigin ?? request.url
185
+ });
186
+ if (!result.success) return json(400, { error: result.error });
187
+ return json(200, result.answer);
188
+ }
189
+ //#endregion
190
+ //#region src/backend/app.ts
191
+ /**
192
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
193
+ * passes every other request to `fetch`, with whatever else the platform passes.
194
+ *
195
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
196
+ */
197
+ function withGhostApp({ fetch, ...challenge }) {
198
+ return { async fetch(request, ...args) {
199
+ if (new URL(request.url).pathname === "/.well-known/ghost-app/challenge") return handleChallenge(request, challenge);
200
+ return fetch(request, ...args);
201
+ } };
202
+ }
203
+ //#endregion
204
+ //#region src/shared/manifest.ts
205
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
206
+ var MANIFEST_PATH = "/ghost-app.json";
207
+ //#endregion
208
+ //#region src/backend/manifest.ts
209
+ /**
210
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
211
+ * file. Pass the file's text as it is, or the object it holds.
212
+ *
213
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
214
+ * Ghost the next time Ghost reads it.
215
+ */
216
+ function serveManifest(signed) {
217
+ return new Response(typeof signed === "string" ? signed : JSON.stringify(signed), { headers: {
218
+ "content-type": "application/json; charset=utf-8",
219
+ "cache-control": "no-cache"
220
+ } });
221
+ }
222
+ //#endregion
223
+ export { CHALLENGE_PATH, MANIFEST_PATH, handleChallenge, serveManifest, withGhostApp };
224
+
225
+ //# sourceMappingURL=backend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.js","names":[],"sources":["../../app-contracts/build/identity/jws.js","../../app-contracts/build/identity/challenge.js","../src/shared/parse.ts","../src/shared/ignore.ts","../src/shared/body.ts","../src/backend/body.ts","../src/backend/challenge.ts","../src/backend/app.ts","../src/shared/manifest.ts","../src/backend/manifest.ts"],"sourcesContent":["import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","import { CompactSign, base64url, compactVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeUtf8 } from './keys.js';\n/** Where on an origin Ghost posts a challenge. */\nexport const CHALLENGE_PATH = '/.well-known/ghost-app/challenge';\n/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */\nexport const CHALLENGE_PURPOSE = 'ghost-app-challenge';\nconst NONCE_BYTES = 32;\nconst ProtectedHeader = z.strictObject({ alg: z.literal(ALGORITHM) });\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM });\nconst ChallengeShape = z.strictObject({\n purpose: z.literal(CHALLENGE_PURPOSE),\n origin: z.string(),\n nonce: z.string(),\n});\nconst ChallengeAnswerShape = z.object({ signature: z.string() });\n/** The URL to post a challenge for an origin to. */\nexport function challengeUrl(origin) {\n return new URL(CHALLENGE_PATH, origin).href;\n}\n/** A fresh challenge for an origin, as the exact text to post and to verify the answer with. */\nexport function createChallenge(origin) {\n const challenge = {\n purpose: CHALLENGE_PURPOSE,\n origin: new URL(origin).origin,\n nonce: base64url.encode(crypto.getRandomValues(new Uint8Array(NONCE_BYTES))),\n };\n return JSON.stringify(challenge);\n}\n/**\n * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is\n * the URL the request arrived at, as the platform reports it (`request.url` on Workers):\n * never one built from `X-Forwarded-Host` or any other header the sender controls. A\n * challenge for any origin but that one is refused, so whoever takes over a name the app\n * used to serve can't relay Ghost's challenge to the real backend to prove it.\n *\n * Ghost can't see this check, so it only helps where the platform routes requests by host,\n * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.\n */\nexport async function answerChallenge(body, { backendKey, requestUrl }) {\n const challenge = ChallengeShape.safeParse(parseJson(body));\n if (!challenge.success) {\n return { success: false, error: 'Expected a challenge of {purpose, origin, nonce}' };\n }\n const arrivedAt = URL.parse(requestUrl)?.origin;\n if (arrivedAt !== challenge.data.origin) {\n return {\n success: false,\n error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? 'an unknown origin'}`,\n };\n }\n const signature = await new CompactSign(new TextEncoder().encode(body))\n .setProtectedHeader({ alg: ALGORITHM })\n .sign(backendKey);\n return { success: true, answer: { signature } };\n}\n/**\n * Checks an origin's answer to a challenge: a signature with the backend key over the\n * exact text Ghost posted, under a protected header of only `alg`. The error only says how\n * the answer fell short.\n */\nexport async function verifyChallengeAnswer(challenge, answer, backendKey) {\n const parsed = ChallengeAnswerShape.safeParse(parseJson(answer));\n if (!parsed.success) {\n return { success: false, error: 'Expected an answer of {\"signature\": \"<compact JWS>\"}' };\n }\n let key;\n try {\n key = await importJWK(backendKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'backend_key is not a usable Ed25519 key' };\n }\n const [header = ''] = parsed.data.signature.split('.');\n if (!readExactHeader(header, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n let payload;\n try {\n ({ payload } = await compactVerify(parsed.data.signature, key, { algorithms: [ALGORITHM] }));\n }\n catch {\n return { success: false, error: 'The signature was not made with backend_key' };\n }\n if (!sameText(payload, challenge)) {\n return { success: false, error: 'The signature is not over the challenge that was sent' };\n }\n return { success: true };\n}\nfunction sameText(bytes, text) {\n try {\n return decodeUtf8(bytes) === text;\n }\n catch {\n return false;\n }\n}\nfunction parseJson(text) {\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=challenge.js.map","// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","import { ignoreError } from './ignore.ts';\n\n/**\n * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It\n * stops reading as soon as the body passes the limit, so a large body is never held whole.\n */\nexport async function readBytes(\n message: Request | Response,\n maxBytes: number,\n): Promise<Uint8Array | undefined> {\n if (Number(message.headers.get('content-length')) > maxBytes) {\n // Too large either way, so a body that refuses to be cancelled changes nothing. Not waited\n // for: one branch of a teed body, as a cloned request's is, cancels only once the other does.\n message.body?.cancel().catch(ignoreError);\n return undefined;\n }\n if (!message.body) {\n return new Uint8Array();\n }\n const reader = message.body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n length += value.byteLength;\n if (length > maxBytes) {\n reader.cancel().catch(ignoreError);\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n","import { readBytes } from '../shared/body.ts';\n\n/**\n * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid\n * UTF-8 throws, as the exact text matters to whoever signs it.\n */\nexport async function readText(request: Request, maxBytes: number): Promise<string | undefined> {\n const bytes = await readBytes(request, maxBytes);\n return bytes && new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\n\nexport function json(status: number, body: unknown, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...headers,\n },\n });\n}\n","import { CHALLENGE_PATH, answerChallenge } from '@tryghost/app-contracts/identity';\n\nimport { parseOrigin } from '../shared/parse.ts';\nimport { json, readText } from './body.ts';\n\nexport { CHALLENGE_PATH };\n\n/**\n * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's\n * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and\n * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.\n */\nexport type BackendJwk = {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kid?: string;\n kty?: string;\n n?: string;\n oth?: { d?: string; r?: string; t?: string }[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n};\n\n/**\n * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an\n * environment variable, such as `GHOST_APP_BACKEND_KEY`.\n */\nexport type BackendKey = BackendJwk | string;\n\nexport interface HandleChallengeOptions {\n backendKey: BackendKey;\n /**\n * The app's public origin, such as `https://app.example.com`, for a server that doesn't see\n * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees\n * `http://`. Ghost challenges the public origin, so without it every challenge is refused.\n * Take it from the app's own configuration, never from a request's headers, which the sender\n * sets. Workers, and other platforms that report the public URL, don't need it.\n */\n origin?: string;\n}\n\n// Ghost's challenge is about 150 bytes. Anything much larger isn't one.\nconst CHALLENGE_MAX_BYTES = 4 * 1024;\n\nconst INVALID_KEY =\n 'backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d';\n\n// The last key imported, so a backend that answers with one key imports it once.\nlet imported: { text: string; key: Promise<CryptoKey> } | undefined;\n\nfunction importBackendKey(backendKey: BackendKey): Promise<CryptoKey> {\n const text = typeof backendKey === 'string' ? backendKey : JSON.stringify(backendKey);\n if (imported?.text !== text) {\n const key = importPrivateKey(text);\n imported = { text, key };\n // A key that failed to import is tried again next time, so a fixed secret takes effect.\n key.catch(() => {\n if (imported?.key === key) {\n imported = undefined;\n }\n });\n }\n return imported.key;\n}\n\nasync function importPrivateKey(text: string): Promise<CryptoKey> {\n let jwk: unknown;\n try {\n jwk = JSON.parse(text);\n } catch {\n // Never says what the text was: it's a secret.\n throw new TypeError(`${INVALID_KEY}; it isn't JSON`);\n }\n const { kty, crv, x, d } = (typeof jwk === 'object' && jwk !== null ? jwk : {}) as BackendJwk;\n if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || typeof d !== 'string') {\n throw new TypeError(INVALID_KEY);\n }\n try {\n return await crypto.subtle.importKey('jwk', { kty, crv, x, d }, { name: 'Ed25519' }, false, [\n 'sign',\n ]);\n } catch (error) {\n throw new TypeError(INVALID_KEY, { cause: error });\n }\n}\n\n/**\n * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`\n * to it, or use `withGhostApp`, which does.\n */\nexport async function handleChallenge(\n request: Request,\n { backendKey, origin }: HandleChallengeOptions,\n): Promise<Response> {\n // A bad `origin` is the app's own misconfiguration, so it throws, and the platform reports a\n // server error, rather than every challenge being refused with a 400 that looks like Ghost's\n // fault.\n const publicOrigin = origin === undefined ? undefined : parseOrigin(origin);\n if (origin !== undefined && !publicOrigin) {\n throw new TypeError(\n `Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`,\n );\n }\n\n // Ghost always POSTs the challenge.\n if (request.method !== 'POST') {\n return json(405, { error: 'Expected a POST' }, { allow: 'POST' });\n }\n\n // A challenge is about 150 bytes, so stop reading at 4 KB rather than buffer whatever a\n // sender streams.\n let body: string | undefined;\n try {\n body = await readText(request, CHALLENGE_MAX_BYTES);\n } catch {\n return json(400, { error: 'Expected a challenge in UTF-8' });\n }\n if (body === undefined) {\n return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });\n }\n\n // Imported once and cached. A `backendKey` that isn't a private Ed25519 key throws a\n // `TypeError`, a server error, for the same reason as a bad `origin`.\n const key = await importBackendKey(backendKey);\n\n // The challenge names the origin Ghost sent it to, and is answered only for this app's own:\n // the one the platform reports in `request.url`, or `origin` behind a proxy. Never one taken\n // from `X-Forwarded-Host` or another header the sender sets, or anyone could have this\n // backend sign a challenge meant for another app.\n const result = await answerChallenge(body, {\n backendKey: key,\n requestUrl: publicOrigin ?? request.url,\n });\n if (!result.success) {\n return json(400, { error: result.error });\n }\n\n // `{ signature }`: Ghost verifies it against the backend key the signed manifest names.\n return json(200, result.answer);\n}\n","import { CHALLENGE_PATH, handleChallenge, type HandleChallengeOptions } from './challenge.ts';\n\n/**\n * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`\n * and `ctx`.\n */\nexport type FetchHandler<Args extends unknown[] = []> = (\n request: Request,\n ...args: Args\n) => Response | Promise<Response>;\n\nexport interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {\n /** The app's own handler, for every request but Ghost's challenge. */\n fetch: FetchHandler<Args>;\n}\n\n/**\n * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and\n * passes every other request to `fetch`, with whatever else the platform passes.\n *\n * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.\n */\nexport function withGhostApp<Args extends unknown[] = []>({\n fetch,\n ...challenge\n}: GhostAppOptions<Args>): { fetch: (request: Request, ...args: Args) => Promise<Response> } {\n return {\n async fetch(request, ...args) {\n if (new URL(request.url).pathname === CHALLENGE_PATH) {\n return handleChallenge(request, challenge);\n }\n return fetch(request, ...args);\n },\n };\n}\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n","import type { SignedManifest } from '../shared/manifest.ts';\n\nexport { MANIFEST_PATH, type SignedManifest } from '../shared/manifest.ts';\n\n/**\n * A response that serves the signed manifest, for a backend that doesn't serve it as a static\n * file. Pass the file's text as it is, or the object it holds.\n *\n * Caches may keep it, but must check it's still current each time, so a new manifest reaches\n * Ghost the next time Ghost reads it.\n */\nexport function serveManifest(signed: SignedManifest | string): Response {\n return new Response(typeof signed === 'string' ? signed : JSON.stringify(signed), {\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-cache',\n },\n });\n}\n"],"mappings":";;;;AAEA,IAAa,YAAY;;;;ACGzB,IAAa,iBAAiB;;AAE9B,IAAa,oBAAoB;AAET,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,SAAS,EAAE,CAAC;AAC5C,KAAK,UAAU,EAAE,KAAK,UAAU,CAAC;AACzD,IAAM,iBAAiB,EAAE,aAAa;CAClC,SAAS,EAAE,QAAQ,iBAAiB;CACpC,QAAQ,EAAE,OAAO;CACjB,OAAO,EAAE,OAAO;AACpB,CAAC;AAC4B,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;;;;;;;;;;;AAwB/D,eAAsB,gBAAgB,MAAM,EAAE,YAAY,cAAc;CACpE,MAAM,YAAY,eAAe,UAAU,UAAU,IAAI,CAAC;CAC1D,IAAI,CAAC,UAAU,SACX,OAAO;EAAE,SAAS;EAAO,OAAO;CAAmD;CAEvF,MAAM,YAAY,IAAI,MAAM,UAAU,CAAC,EAAE;CACzC,IAAI,cAAc,UAAU,KAAK,QAC7B,OAAO;EACH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2C;CACvE,OAAO,IAAI,SAAS,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,MAAM,GAAG,EAChF,SAAS;EACP,gBAAgB;EAChB,iBAAiB;CACnB,EACF,CAAC;AACH"}
package/build/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { ThreadMessagePort } from "@quilted/threads";
2
- //#endregion
3
2
  //#region ../app-contracts/build/plain-text.js
4
3
  var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
5
4
  new RegExp(`^[${ALLOWED}]*$`, "u");
@@ -642,7 +641,7 @@ var Channel = class {
642
641
  * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
643
642
  * and doesn't read package.json.
644
643
  */
645
- var SDK_VERSION = "0.1.0-alpha.4";
644
+ var SDK_VERSION = "0.1.0-alpha.6";
646
645
  //#endregion
647
646
  //#region src/connect.ts
648
647
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#port","#thread","#hostExports","#events","#themeListeners","#pathListeners","#endListeners","#start","#themeChanged","#pathChanged","#context","#theme","#history","#moved","#path","#stopWatchingTitle","#call","#assertStarted","#moves","#ended","#createGhost","#createPath","#onSessionEnd","#fetch","#open"],"sources":["../../app-contracts/build/identity/codes.js","../../app-contracts/build/plain-text.js","../../app-contracts/build/bridge/rules.js","../src/errors.ts","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["/**\n * The codes Ghost fails with when it couldn't confirm an app is the one it says it is,\n * whether reviewing an install link or starting a session. They're kept apart from the\n * codes for an app that is down or broken, because the publisher should hear something\n * different: contact the developer, and don't install it again from a link, which is the\n * one way a different developer's key gets pinned.\n *\n * Free of jose and zod, so Admin reads it from the root entry point.\n */\nexport const UNCONFIRMED_APP_CODES = [\n /** The manifest names another address than the one it was fetched from. */\n 'APP_MANIFEST_URL_MISMATCH',\n /** The signature wasn't made with the identity key the manifest names. */\n 'APP_MANIFEST_SIGNATURE_INVALID',\n /** The manifest is signed with another key than the one the app was installed with. */\n 'APP_IDENTITY_MISMATCH',\n /** The manifest names a backend key a newer manifest from the same developer replaced. */\n 'APP_BACKEND_KEY_RETIRED',\n /** The app's origin didn't answer the challenge with the manifest's backend key. */\n 'APP_CHALLENGE_FAILED',\n];\nconst UNCONFIRMED = new Set(UNCONFIRMED_APP_CODES);\nexport function isUnconfirmedAppCode(code) {\n return UNCONFIRMED.has(code);\n}\n//# sourceMappingURL=codes.js.map","// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so `..` can never climb above its root.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. Even then, the result may not be: resolving `.` and `..` can leave `//` at the\n * start, so `/.//host` becomes `//host`, which resolves to another site. Check the result with\n * `isContainedPath` before resolving it against anything. `AppPathSchema` does both and returns\n * this form.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map","import { HOST_ERROR_CODES, decodeBridgeError, type BridgeErrorCode } from '@tryghost/app-contracts';\n\n/**\n * Why an SDK call failed:\n *\n * - `not_framed`: the page is not framed in Admin, so there is nothing to connect to.\n * - `not_connected`: Admin did not start the app in time.\n * - `duplicate_sdk`: another copy of the SDK in the page has already connected, or tried to,\n * because the page loads the SDK more than once. Load a single copy for the whole page.\n * - `invalid_context`: Admin started the app with a context this SDK cannot read. Updating the\n * SDK usually fixes it.\n * - `session_ended`: this document has left the app session, usually because the page reloaded\n * or navigated away, or the session has ended. Every call fails after that.\n * - `invalid_argument`: the app passed something that cannot be sent.\n * - `invalid_path`: a path that is not an Admin API path, or not a route within the app; or\n * one the Admin API only redirects, such as a path without its trailing `/`.\n * - `unsupported`: this site's version of Ghost doesn't have the call the app made yet. The\n * SDK knows this from the calls Admin listed when it connected.\n * - `blocked`: Admin refused by policy, such as a request the allowlist doesn't allow.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: Admin refused for any other reason; the message says why.\n *\n * `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes; the\n * rest are bridge codes, which cross the channel.\n */\nexport type GhostAppErrorCode =\n | 'not_framed'\n | 'not_connected'\n | 'duplicate_sdk'\n | 'unsupported'\n | BridgeErrorCode;\n\n/** The only error type the SDK rejects with, so an app can branch on `code`. */\nexport class GhostAppError extends Error {\n readonly code: GhostAppErrorCode;\n\n constructor(code: GhostAppErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'GhostAppError';\n this.code = code;\n }\n}\n\n/**\n * Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin\n * gave or, if there is none, `rejected` with Admin's message.\n */\nexport function fromHostError(error: unknown, operation: string): GhostAppError {\n const message =\n typeof error === 'object' && error !== null && 'message' in error\n ? String(error.message)\n : undefined;\n if (message === undefined) {\n return new GhostAppError('rejected', `Ghost refused ${operation}`, { cause: error });\n }\n // Only the codes Admin refuses with are parsed; any other prefix stays part of the message.\n const coded = decodeBridgeError(message, HOST_ERROR_CODES);\n if (coded) {\n return new GhostAppError(coded.code, coded.detail, { cause: error });\n }\n return new GhostAppError('rejected', message, { cause: error });\n}\n\nexport function invalidArgument(message: string): GhostAppError {\n return new GhostAppError('invalid_argument', message);\n}\n\nexport function invalidPath(message: string): GhostAppError {\n return new GhostAppError('invalid_path', message);\n}\n\nexport function unsupported(operation: string): GhostAppError {\n return new GhostAppError('unsupported', `This site's Ghost doesn't support ${operation} yet`);\n}\n\nexport function sessionEnded(): GhostAppError {\n return new GhostAppError('session_ended', 'The session with Ghost has ended');\n}\n","import {\n ARGUMENT_MESSAGES,\n FETCH_METHODS,\n isContainedPath,\n isFetchResponse,\n isRecord,\n isReservedRequestHeader,\n methodAllowsBody,\n type FetchMethod,\n type FetchRequest,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument, invalidPath } from './errors.ts';\nimport type { GhostFetchInit, JsonBody } from './types.ts';\n\nconst JSON_BODY = 'Expected a body that can be sent as JSON';\n\n// The statuses a `Response` must be built without a body for, or its constructor throws.\nconst NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\nfunction isJsonBody(value: unknown): value is JsonBody {\n if (Array.isArray(value)) {\n return true;\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n// A cycle or a BigInt makes `JSON.stringify` throw, and a `toJSON` that returns `undefined`\n// makes it return `undefined`.\nfunction toJson(body: JsonBody): string {\n let json: string | undefined;\n try {\n json = JSON.stringify(body) as string | undefined;\n } catch (error) {\n throw new GhostAppError('invalid_argument', JSON_BODY, { cause: error });\n }\n if (json === undefined) {\n throw invalidArgument(JSON_BODY);\n }\n return json;\n}\n\nfunction toHeaders(init: HeadersInit | undefined): Record<string, string> {\n let headers: Headers;\n try {\n headers = new Headers(init);\n } catch (error) {\n throw new GhostAppError('invalid_argument', 'Expected headers with valid names and values', {\n cause: error,\n });\n }\n // `Headers` lowercases the names, so a reserved header the app set is found in any case.\n const entries = [...headers.entries()];\n const reserved = entries.find(([name]) => isReservedRequestHeader(name));\n if (reserved) {\n throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));\n }\n return Object.fromEntries(entries);\n}\n\n/**\n * Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are\n * refused here, using the same rules Admin applies; Admin checks everything again.\n */\nexport function toFetchRequest(path: string, init: GhostFetchInit = {}): FetchRequest {\n if (!isContainedPath(path)) {\n throw invalidPath(ARGUMENT_MESSAGES.fetchPath);\n }\n // The types rule this out, but a page without TypeScript can pass anything.\n if (typeof init !== 'object' || init === null) {\n throw invalidArgument('Expected options such as { method, headers, body }');\n }\n\n const { method: given = 'GET' } = init as { method?: unknown };\n const method = (typeof given === 'string' ? given.toUpperCase() : given) as FetchMethod;\n if (!FETCH_METHODS.includes(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);\n }\n\n const headers = toHeaders(init.headers);\n const request: FetchRequest = { path, method };\n\n if (init.body !== undefined && init.body !== null) {\n if (!methodAllowsBody(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);\n }\n if (typeof init.body === 'string') {\n request.body = init.body;\n } else if (isJsonBody(init.body)) {\n request.body = toJson(init.body);\n } else {\n // Binary and streamed bodies cannot cross the channel as text.\n throw invalidArgument('Expected the body as text, or as an object or array to send as JSON');\n }\n }\n\n if (Object.keys(headers).length > 0) {\n request.headers = headers;\n }\n return request;\n}\n\nconst UNREADABLE_ANSWER = \"Ghost answered with a response this SDK doesn't understand\";\n\n/** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */\nexport function toResponse(answer: unknown): Response {\n if (!isFetchResponse(answer)) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER);\n }\n // The `Response` constructor throws on a header name or status text it can't hold.\n try {\n return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {\n status: answer.status,\n statusText: answer.statusText,\n headers: answer.headers,\n });\n } catch (error) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER, { cause: error });\n }\n}\n","import { isContainedPath, type PathMove } from '@tryghost/app-contracts';\n\n/**\n * A URL's route: its path, query and fragment. The URL parser has already put them in the\n * normalised form Admin stores app paths in. Resolving them again would read a path that starts\n * with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that\n * route fails `isContainedPath` and is never reported.\n */\nfunction routeOf({ pathname, search, hash }: { pathname: string; search: string; hash: string }) {\n return `${pathname}${search}${hash}`;\n}\n\n/** The page's route. */\nexport function currentRoute(): string {\n return routeOf(window.location);\n}\n\n/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */\nfunction isLink(node: EventTarget): node is Element {\n return (\n (node instanceof HTMLAnchorElement || (node instanceof SVGElement && node.localName === 'a')) &&\n node.hasAttribute('href')\n );\n}\n\nexport interface HistoryWatch {\n /**\n * Puts the page at `path` without adding a history entry, because Admin moved it there, and\n * dispatches `popstate` so the app's router shows it.\n */\n follow(path: string): void;\n /** Gives the page its own history methods and links back. */\n stop(): void;\n}\n\n/**\n * Whether a route is one Admin would take. Admin owns the app's address, so the page never\n * moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin\n * link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is\n * dropped, with a warning for the app's developer.\n */\nfunction isContained(route: string): boolean {\n if (isContainedPath(route)) {\n return true;\n }\n // The only place the app's developer would learn why the move did nothing.\n // eslint-disable-next-line no-console\n console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);\n return false;\n}\n\n/**\n * Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL\n * parser can't read is left to the browser, which throws as it would without the SDK.\n */\nfunction refuses(url: string | URL | null | undefined): boolean {\n if (url === undefined || url === null) {\n return false;\n }\n const next = URL.parse(url, window.location.href);\n return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));\n}\n\n/**\n * Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,\n * and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's\n * entries, which left back steps that did nothing once the app's page opened again, and WebKit\n * applies Admin's replace after a frame's push to the entry before it. So the frame keeps a\n * single entry, and Admin keeps one for each of the app's moves.\n *\n * - `history.pushState` and `history.replaceState` replace the frame's entry, then report the\n * move to Admin as a push or a replace, which is how Admin records it. A move to the route the\n * page is already on isn't reported, so Admin never gets an entry that changes nothing.\n * - A click on a link to the app's own origin, which a router hasn't already handled, is reported\n * as a push, and the page then loads the link's address in place of its own entry. A link that\n * opens elsewhere (a `target`, `download`, or a modifier key) is left alone.\n * - Neither is made to a route Admin would refuse, one that isn't contained.\n * - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.\n *\n * Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the\n * fragment through `location.hash` and the Navigation API, which have added the entry before\n * any event says so.\n */\nexport function watchHistory(\n moved: (route: string, move: PathMove) => Promise<void>,\n // How the page loads a link's address in place of its own entry. Tests pass their own.\n load: (url: string) => void = (url) => window.location.replace(url),\n): HistoryWatch {\n const { history } = window;\n const { pushState, replaceState } = history;\n let route = currentRoute();\n // The state the app gave each route, so following Admin back to one gives it back.\n const states = new Map<string, unknown>([[route, history.state]]);\n\n const report = (move: PathMove) => {\n const next = currentRoute();\n states.set(next, history.state);\n if (next !== route) {\n route = next;\n void moved(next, move);\n }\n };\n\n const push: History['pushState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('push');\n };\n const replace: History['replaceState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('replace');\n };\n history.pushState = push;\n history.replaceState = replace;\n\n const onClick = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // Found through the event's path, which reaches into shadow roots, and read through its\n // attributes, because an SVG link has none of `HTMLAnchorElement`'s properties.\n const link = event.composedPath().find(isLink);\n const target = link?.getAttribute('target') ?? '';\n if (!link || link.hasAttribute('download') || (target !== '' && target !== '_self')) {\n return;\n }\n const url = new URL(link.getAttribute('href') as string, document.baseURI);\n if (url.origin !== window.location.origin) {\n return;\n }\n event.preventDefault();\n const go = () => load(url.href);\n const next = routeOf(url);\n if (!isContained(next)) {\n return;\n }\n if (next === route) {\n go();\n return;\n }\n route = next;\n // Admin records the move before the page leaves, so the next document starts where it is.\n moved(next, 'push').then(go, go);\n };\n document.addEventListener('click', onClick);\n\n return {\n follow(path) {\n route = path;\n const state = states.get(path) ?? null;\n replaceState.call(history, state, '', path);\n window.dispatchEvent(new PopStateEvent('popstate', { state }));\n },\n stop() {\n if (history.pushState === push) {\n history.pushState = pushState;\n }\n if (history.replaceState === replace) {\n history.replaceState = replaceState;\n }\n document.removeEventListener('click', onClick);\n },\n };\n}\n","import { TITLE_MAX_LENGTH, toPlainText } from '@tryghost/app-contracts';\n\n/**\n * Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a\n * title containing a character that reorders or hides text, so the SDK drops those characters\n * rather than losing the whole title: a right-to-left title often contains a direction mark.\n */\nfunction clampTitle(title: string): string {\n const trimmed = toPlainText(title).trim();\n if (trimmed.length <= TITLE_MAX_LENGTH) {\n return trimmed;\n }\n const end = /[\\uD800-\\uDBFF]/.test(trimmed.charAt(TITLE_MAX_LENGTH - 1))\n ? TITLE_MAX_LENGTH - 1\n : TITLE_MAX_LENGTH;\n return trimmed.slice(0, end);\n}\n\n/**\n * Reports the page's title now and every time it changes, so Admin can show it as its own.\n * Returns a function that stops watching.\n *\n * A title can change in three ways, and frameworks use all three: its text is edited, its\n * element is replaced, or an element is added where there was none. Rather than distinguish\n * them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it\n * only if it differs from the last one. A mutation observer already delivers each batch once,\n * in a microtask.\n */\nexport function watchTitle(report: (title: string) => void): () => void {\n let last: string | undefined;\n const check = () => {\n const title = clampTitle(document.title);\n if (title !== last) {\n last = title;\n report(title);\n }\n };\n\n check();\n const observer = new MutationObserver(check);\n observer.observe(document.head ?? document.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n });\n return () => observer.disconnect();\n}\n","import { ThreadMessagePort } from '@quilted/threads';\nimport {\n ARGUMENT_MESSAGES,\n encodeBridgeError,\n type AppErrorCode,\n isContainedPath,\n isRecord,\n isStartContext,\n isTheme,\n type AppExports,\n type HostExports,\n type PathMove,\n type Place,\n type Theme,\n} from '@tryghost/app-contracts';\n\nimport {\n GhostAppError,\n fromHostError,\n invalidArgument,\n sessionEnded,\n unsupported,\n} from './errors.ts';\nimport { toFetchRequest, toResponse } from './fetch.ts';\nimport { currentRoute, watchHistory, type HistoryWatch } from './history.ts';\nimport { watchTitle } from './title.ts';\nimport type {\n Ghost,\n GhostFetchInit,\n GhostPath,\n Session,\n Site,\n Unsubscribe,\n User,\n} from './types.ts';\n\ntype HostCall<K extends keyof HostExports> = (\n ...args: Parameters<HostExports[K]>\n) => ReturnType<HostExports[K]>;\n\n/** Calls each listener the app registered, so that one that throws can't stop the others. */\nfunction notify<T>(listeners: ReadonlySet<(value: T) => void>, value: T) {\n for (const listener of [...listeners]) {\n try {\n listener(value);\n } catch (error) {\n // Rethrown outside the SDK, where the page's own error handling sees it.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * An error that refuses one of Admin's calls. Only its message reaches Admin, so the message\n * starts with the code, as Admin's own refusals do.\n */\nfunction refusal(code: AppErrorCode, detail: string): Error {\n return new Error(encodeBridgeError(code, detail));\n}\n\n/**\n * Returns the copy of an argument that will cross the channel, or throws `invalid_argument`\n * with `message` if it can't cross. The structured clone that carries a call only refuses a\n * symbol or a DOM node once the call is in progress, and the channel would proxy a function,\n * though no argument in the bridge's calls is a function. Cloning first refuses all of these\n * before anything is sent to Admin.\n */\nfunction cloneArgument<T>(value: T, message: string): T {\n try {\n return structuredClone(value);\n } catch (error) {\n throw new GhostAppError('invalid_argument', message, { cause: error });\n }\n}\n\nfunction subscribe<T>(listeners: Set<T>, listener: T): Unsubscribe {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The parts of Admin's start context that `start` keeps. The theme and path can change, so\n * they are stored separately.\n */\ninterface StartedContext {\n site: Site;\n user: User;\n session: Session;\n}\n\nexport interface ChannelEvents {\n /** Admin started the app, and the connection is ready for it to use. */\n started(ghost: Ghost): void;\n /** The channel ended, before or after the start. */\n ended(error: GhostAppError): void;\n}\n\n/**\n * The channel to Admin over the port Admin handed the page, and the `Ghost` object the app\n * gets once Admin has called `start`. The channel itself stays inside the SDK.\n *\n * The channel ends in three cases: when the port closes, which browsers that fire `close` on\n * a port (and Node) report when Admin closes its end or its document goes away; when a call\n * fails because the thread has closed; or when Admin rejects a call with `session_ended`.\n * After that, every call rejects with the same error.\n */\nexport class Channel {\n readonly #port: MessagePort;\n readonly #thread: ThreadMessagePort<HostExports, AppExports>;\n // What this Admin exports, from its connect message.\n readonly #hostExports: ReadonlySet<string>;\n readonly #events: ChannelEvents;\n readonly #themeListeners = new Set<(theme: Readonly<Theme>) => void>();\n readonly #pathListeners = new Set<(path: string) => void>();\n readonly #endListeners = new Set<(error: GhostAppError) => void>();\n #context: StartedContext | undefined;\n #theme: Readonly<Theme> | undefined;\n #path = '/';\n #ended: GhostAppError | undefined;\n #stopWatchingTitle: (() => void) | undefined;\n #history: HistoryWatch | undefined;\n // Counts the page's moves, so an answer to one the page has since moved on from is ignored.\n #moves = 0;\n\n constructor(port: MessagePort, hostExports: readonly string[], events: ChannelEvents) {\n this.#port = port;\n this.#hostExports = new Set(hostExports);\n this.#events = events;\n this.#thread = new ThreadMessagePort<HostExports, AppExports>(port, {\n exports: {\n start: async (context) => this.#start(context),\n themeChanged: async (theme) => this.#themeChanged(theme),\n pathChanged: async (path) => this.#pathChanged(path),\n },\n });\n port.addEventListener('close', () => this.end(sessionEnded()));\n // A message that could not be read is a call that will never be answered.\n port.addEventListener('messageerror', () => this.end(sessionEnded()));\n port.start();\n }\n\n #start(context: unknown) {\n if (this.#context) {\n return;\n }\n if (!isStartContext(context)) {\n const detail = \"Ghost started the app with a context this SDK doesn't understand\";\n // End the channel only after Admin has received the refusal, so Admin learns why instead\n // of waiting for its timeout.\n setTimeout(() => this.end(new GhostAppError('invalid_context', detail)), 0);\n throw refusal('invalid_context', detail);\n }\n this.#context = {\n site: Object.freeze({ ...context.site }),\n user: Object.freeze({ ...context.user }),\n session: Object.freeze({ ...context.session }),\n };\n this.#theme = Object.freeze({ ...context.theme });\n // Admin owns the history from here on. The page's own address is its route: Admin loads a\n // new frame at its own path, so the two differ only when the page's server redirected it or\n // a form or link loaded another page in place, and then Admin follows the page.\n this.#history = watchHistory((route, move) => this.#moved(route, move));\n const route = currentRoute();\n this.#path = context.path;\n if (route !== context.path) {\n void this.#moved(route, 'replace');\n }\n // Report the title before `start` returns, so Admin has it by the time it shows the page.\n // An older Admin without `titleChanged` keeps its own title.\n if (this.#hostExports.has('titleChanged')) {\n this.#stopWatchingTitle = watchTitle((title) => {\n this.#call('titleChanged', title).catch(() => {\n // If Admin refuses a title, it keeps showing its own.\n });\n });\n }\n this.#events.started(this.ghost);\n }\n\n #themeChanged(theme: unknown) {\n this.#assertStarted();\n if (!isTheme(theme)) {\n throw refusal('invalid_argument', \"Ghost sent a theme this SDK doesn't understand\");\n }\n this.#theme = Object.freeze({ ...theme });\n notify(this.#themeListeners, this.#theme);\n }\n\n #pathChanged(path: unknown) {\n this.#assertStarted();\n if (!isContainedPath(path)) {\n throw refusal('invalid_argument', \"Ghost sent a path this SDK doesn't understand\");\n }\n this.#path = path;\n this.#history?.follow(path);\n notify(this.#pathListeners, path);\n }\n\n /**\n * Reports a move the page made. Resolves once Admin has answered, with the path Admin now has\n * for the app, or has refused; a refused move leaves the page where it is.\n */\n async #moved(route: string, move: PathMove): Promise<void> {\n // A route that leaves the app once normalised, such as `/.//host/`, is one Admin refuses\n // and the SDK never hands out, so the app's path stays where it was.\n if (!isContainedPath(route)) {\n return;\n }\n this.#path = route;\n this.#moves += 1;\n const thisMove = this.#moves;\n try {\n const adminPath = await this.#call('pathChanged', route, move);\n // Admin's answer, rather than `route`: it's Admin's own path when Admin didn't follow\n // the move, such as when the publisher is leaving the app, and Admin then moves the page\n // back with `pathChanged`. An answer to an earlier move is out of date.\n if (thisMove === this.#moves && isContainedPath(adminPath)) {\n this.#path = adminPath;\n }\n } catch {\n // Refused, or the session ended: either way there's nothing for the page to do.\n }\n }\n\n #assertStarted() {\n if (!this.#context) {\n throw refusal('invalid_context', 'Ghost has not started the app yet');\n }\n }\n\n async #call<K extends keyof HostExports>(\n name: K,\n ...args: Parameters<HostExports[K]>\n ): Promise<Awaited<ReturnType<HostExports[K]>>> {\n if (this.#ended) {\n throw this.#ended;\n }\n if (!this.#hostExports.has(name)) {\n throw unsupported(name);\n }\n try {\n const call = this.#thread.imports[name] as HostCall<K>;\n return await call(...args);\n } catch (error) {\n if (this.#thread.closed) {\n throw this.end(sessionEnded());\n }\n const appError = fromHostError(error, name);\n if (appError.code === 'session_ended') {\n this.end(appError);\n }\n throw appError;\n }\n }\n\n /**\n * Ends the channel. Only the first call has an effect: pending and later calls reject with\n * its `error`. Returns the error the channel ended with.\n */\n end(error: GhostAppError): GhostAppError {\n if (this.#ended) {\n return this.#ended;\n }\n this.#ended = error;\n this.#stopWatchingTitle?.();\n this.#history?.stop();\n this.#thread.close();\n this.#port.close();\n this.#events.ended(error);\n notify(this.#endListeners, error);\n this.#endListeners.clear();\n return error;\n }\n\n /**\n * The `Ghost` object the app gets once `start` has set the context. It has only the members\n * its type declares, so no part of the channel, such as `end`, is reachable from the app.\n */\n readonly ghost: Ghost = this.#createGhost();\n\n #createGhost(): Ghost {\n const context = () => this.#context as StartedContext;\n const theme = () => this.#theme as Readonly<Theme>;\n const connected = () => this.#ended === undefined;\n return Object.freeze({\n get site(): Site {\n return context().site;\n },\n get user(): User {\n return context().user;\n },\n get theme(): Readonly<Theme> {\n return theme();\n },\n get session(): Session {\n return context().session;\n },\n get connected(): boolean {\n return connected();\n },\n path: this.#createPath(),\n onThemeChange: (callback: (theme: Readonly<Theme>) => void): Unsubscribe =>\n subscribe(this.#themeListeners, callback),\n onPathChange: (callback: (path: string) => void): Unsubscribe =>\n subscribe(this.#pathListeners, callback),\n onSessionEnd: (callback: (error: GhostAppError) => void): Unsubscribe =>\n this.#onSessionEnd(callback),\n fetch: (path: string, init?: GhostFetchInit): Promise<Response> => this.#fetch(path, init),\n open: (place: Place): Promise<void> => this.#open(place),\n });\n }\n\n #createPath(): GhostPath {\n const current = () => this.#path;\n return Object.freeze({\n get current(): string {\n return current();\n },\n });\n }\n\n #onSessionEnd(callback: (error: GhostAppError) => void): Unsubscribe {\n const ended = this.#ended;\n if (ended) {\n // Notify it in a microtask, as an earlier subscriber would be, unless it has\n // unsubscribed by then.\n let left = false;\n queueMicrotask(() => {\n if (!left) {\n callback(ended);\n }\n });\n return () => {\n left = true;\n };\n }\n return subscribe(this.#endListeners, callback);\n }\n\n async #fetch(path: string, init?: GhostFetchInit): Promise<Response> {\n const request = toFetchRequest(path, init);\n return toResponse(await this.#call('fetch', request));\n }\n\n async #open(place: Place): Promise<void> {\n if (!isRecord(place)) {\n throw invalidArgument(ARGUMENT_MESSAGES.place);\n }\n await this.#call('open', cloneArgument(place, ARGUMENT_MESSAGES.place));\n }\n}\n","declare const __SDK_VERSION__: string;\n\n/**\n * The SDK's version, sent in the hello for Admin's logs. The build and the tests replace\n * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`\n * and doesn't read package.json.\n */\nexport const SDK_VERSION: string = __SDK_VERSION__;\n","import {\n HELLO_MESSAGE_TYPE,\n START_TIMEOUT_MS,\n isConnectMessage,\n isRecord,\n type HelloMessage,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument } from './errors.ts';\nimport { Channel } from './session.ts';\nimport type { ConnectOptions, Ghost } from './types.ts';\nimport { SDK_VERSION } from './version.ts';\n\n/**\n * How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only\n * start listening after the page has loaded and sent its first hello, so one hello is not\n * enough.\n */\nconst HELLO_INTERVAL = 250;\n\n/**\n * The target origin for the hello: the embedding page's origin where the browser exposes it\n * (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants\n * nothing: the port goes the other way, and Admin addresses it to this page's origin only.\n * `document.referrer` doesn't work here: once the page has navigated within itself, it holds\n * the page's own origin.\n */\nfunction parentOrigin(): string {\n const origin = window.location.ancestorOrigins?.[0];\n return origin && origin !== 'null' ? origin : '*';\n}\n\n/**\n * The global key where the first copy of the SDK to connect claims the page. It is a symbol\n * from the global registry, so a second copy bundled into the same page finds the same key.\n */\nconst PAGE_CLAIM = Symbol.for('@tryghost/app-sdk');\n\n/**\n * The claim also holds the hello's `document` ID. It's made when the SDK loads, so every\n * `connect()` in a document sends the same ID, and a new document (after a reload, a form post\n * or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some\n * privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession\n * could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the\n * plain HTTP origins apps use in development.\n */\nconst thisCopy = Object.freeze({\n sdk: SDK_VERSION,\n document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,\n});\n\n/** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */\nfunction claimPage(): boolean {\n const page = globalThis as unknown as Record<symbol, unknown>;\n page[PAGE_CLAIM] ??= thisCopy;\n return page[PAGE_CLAIM] === thisCopy;\n}\n\n/**\n * The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout\n * would fire immediately.\n */\nconst TIMEOUT_MAX = 2 ** 31 - 1;\n\nfunction handshake(\n options: ConnectOptions,\n onEnded: (error: GhostAppError) => void,\n): Promise<Ghost> {\n if (!isRecord(options)) {\n return Promise.reject(invalidArgument('Expected options such as { timeout: 10000 }'));\n }\n // By default, wait as long as Admin gives the page. Waiting longer would mean waiting on a\n // frame Admin has already given up on.\n const { timeout = START_TIMEOUT_MS } = options;\n if (typeof timeout !== 'number' || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) {\n return Promise.reject(\n invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`),\n );\n }\n if (typeof window === 'undefined' || window.parent === window) {\n return Promise.reject(\n new GhostAppError('not_framed', 'This page is not open inside Ghost Admin'),\n );\n }\n\n const parent = window.parent;\n const targetOrigin = parentOrigin();\n\n return new Promise<Ghost>((resolve, reject) => {\n const stopWaiting = () => {\n clearInterval(helloTimer);\n clearTimeout(timeoutTimer);\n window.removeEventListener('message', onMessage);\n };\n\n // A promise ignores `reject` once it has settled, so a failure after `started` changes\n // nothing.\n const fail = (error: GhostAppError) => {\n stopWaiting();\n reject(error);\n };\n\n // The channel is bound to the first valid answer from the parent window. The listener is\n // removed as soon as that answer arrives, so later answers are ignored.\n const onMessage = (event: MessageEvent) => {\n const port = event.ports?.[0];\n if (\n event.source !== parent ||\n !isConnectMessage(event.data) ||\n !port ||\n (targetOrigin !== '*' && event.origin !== targetOrigin)\n ) {\n return;\n }\n clearInterval(helloTimer);\n window.removeEventListener('message', onMessage);\n channel = new Channel(port, event.data.exports, {\n started: (ghost) => {\n stopWaiting();\n resolve(ghost);\n },\n ended: (error) => {\n fail(error);\n onEnded(error);\n },\n });\n };\n\n const hello: HelloMessage = {\n type: HELLO_MESSAGE_TYPE,\n sdk: SDK_VERSION,\n document: thisCopy.document,\n };\n const sayHello = () => {\n parent.postMessage(hello, targetOrigin);\n };\n\n let channel: Channel | undefined;\n window.addEventListener('message', onMessage);\n sayHello();\n const helloTimer = setInterval(sayHello, HELLO_INTERVAL);\n const timeoutTimer = setTimeout(() => {\n const error = new GhostAppError('not_connected', 'Ghost Admin did not start the app in time');\n fail(error);\n channel?.end(error);\n }, timeout);\n });\n}\n\nlet connecting: Promise<Ghost> | undefined;\n// The error the page's connection ended with, after Admin answered it. Admin answers each\n// document only once, so this connection was the page's only one.\nlet spent: GhostAppError | undefined;\n\n// Forgets an attempt only if it is still the shared one: an attempt that ended may report\n// that after a newer attempt has started.\nfunction forget(attempt: Promise<Ghost>) {\n if (connecting === attempt) {\n connecting = undefined;\n }\n}\n\n/**\n * Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the\n * app. Safe to call as soon as the page loads.\n *\n * Every call shares one connection, and the first call's options apply. Only one copy of the\n * SDK in a page can connect; any other copy rejects with `duplicate_sdk`. Admin answers each\n * document only once, so after it answers, that connection is the page's only one. Once it\n * fails or its session ends, every call rejects with the error it ended with, and only a new\n * document (after a reload, for example) can connect again. A failure before Admin answered,\n * such as a bad option or a timeout, can be retried.\n */\nexport function connect(options: ConnectOptions = {}): Promise<Ghost> {\n // Two copies would both send a hello for the same document, and Admin answers each document\n // only once.\n if (!claimPage()) {\n return Promise.reject(\n new GhostAppError(\n 'duplicate_sdk',\n 'This page loads the app SDK more than once; load one copy, which every part of the page shares',\n ),\n );\n }\n if (spent) {\n return Promise.reject(spent);\n }\n if (!connecting) {\n const attempt: Promise<Ghost> = handshake(options, (error) => {\n spent = error;\n forget(attempt);\n }).catch((error: unknown) => {\n forget(attempt);\n throw error;\n });\n connecting = attempt;\n }\n return connecting;\n}\n"],"mappings":";;;ACMA,IAAM,UAAU;AACG,IAAI,OAAO,KAAK,QAAQ,MAAM,GAAG;AACpD,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI;;AAMvD,SAAgB,YAAY,OAAO;CAC/B,OAAO,MAAM,QAAQ,gBAAgB,EAAE;AAC3C;;;;;;;;;;;;;;ACLA,IAAa,qBAAqB;;;;;;;AASlC,IAAa,mBAAmB;;;;;AAOhC,IAAa,gBAAgB;CAAC;CAAO;CAAQ;CAAO;AAAQ;;;;;AAK5D,SAAgB,iBAAiB,QAAQ;CACrC,OAAO,WAAW;AACtB;AAOA,IAAM,0BAA0B;;;;;;;AAOhC,SAAgB,wBAAwB,MAAM;CAC1C,OAAO,wBAAwB,KAAK,IAAI;AAC5C;;;;;;AAMA,IAAa,oBAAoB;CAC7B,WAAW;CACX,aAAa,yBAAyB,cAAc,KAAK,IAAI;CAC7D,WAAW;CAGX,iBAAiB,SAAS,eAAe,KAAK,YAAY,EAAE;CAC5D,UAAU;CACV,SAAS;CACT,UAAU;CACV,OAAO;AACX;;;;;;;;;;;;;;;;;;AAyBA,IAAa,mBAAmB;CAC5B;CACA;CACA;CACA;CACA;CACA;AACJ;AAUkC,CAAC,GAAG,gBAAmC;AACzE,IAAM,gBAAgB;;;;;AAKtB,SAAgB,kBAAkB,MAAM,QAAQ;CAC5C,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AS;GAC/C,UAAU,IAAI,QAAQ,MAAM,MAAM,KAAK,SAAS;IAC9C,UAAU,UAAU;KAClB,YAAY;KACZ,QAAQ,KAAK;IACf;IACA,QAAQ,UAAU;KAChB,KAAK,KAAK;KACV,QAAQ,KAAK;IACf;GACF,CAAC;EACH;EAEA,MAAM,QAAsB;GAC1B,MAAM;GACN,KAAK;GACL,UAAU,SAAS;EACrB;EACA,MAAM,iBAAiB;GACrB,OAAO,YAAY,OAAO,YAAY;EACxC;EAEA,IAAI;EACJ,OAAO,iBAAiB,WAAW,SAAS;EAC5C,SAAS;EACT,MAAM,aAAa,YAAY,UAAU,cAAc;EACvD,MAAM,eAAe,iBAAiB;GACpC,MAAM,QAAQ,IAAI,cAAc,iBAAiB,2CAA2C;GAC5F,KAAK,KAAK;GACV,SAAS,IAAI,KAAK;EACpB,GAAG,OAAO;CACZ,CAAC;AACH;AAEA,IAAI;AAGJ,IAAI;AAIJ,SAAS,OAAO,SAAyB;CACvC,IAAI,eAAe,SACjB,aAAa,KAAA;AAEjB;;;;;;;;;;;;AAaA,SAAgB,QAAQ,UAA0B,CAAC,GAAmB;CAGpE,IAAI,CAAC,UAAU,GACb,OAAO,QAAQ,OACb,IAAI,cACF,iBACA,gGACF,CACF;CAEF,IAAI,OACF,OAAO,QAAQ,OAAO,KAAK;CAE7B,IAAI,CAAC,YAAY;EACf,MAAM,UAA0B,UAAU,UAAU,UAAU;GAC5D,QAAQ;GACR,OAAO,OAAO;EAChB,CAAC,CAAC,CAAC,OAAO,UAAmB;GAC3B,OAAO,OAAO;GACd,MAAM;EACR,CAAC;EACD,aAAa;CACf;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":["#port","#thread","#hostExports","#events","#themeListeners","#pathListeners","#endListeners","#start","#themeChanged","#pathChanged","#context","#theme","#history","#moved","#path","#stopWatchingTitle","#call","#assertStarted","#moves","#ended","#createGhost","#createPath","#onSessionEnd","#fetch","#open"],"sources":["../../app-contracts/build/plain-text.js","../../app-contracts/build/bridge/rules.js","../src/errors.ts","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so `..` can never climb above its root.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. Even then, the result may not be: resolving `.` and `..` can leave `//` at the\n * start, so `/.//host` becomes `//host`, which resolves to another site. Check the result with\n * `isContainedPath` before resolving it against anything. `AppPathSchema` does both and returns\n * this form.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map","import { HOST_ERROR_CODES, decodeBridgeError, type BridgeErrorCode } from '@tryghost/app-contracts';\n\n/**\n * Why an SDK call failed:\n *\n * - `not_framed`: the page is not framed in Admin, so there is nothing to connect to.\n * - `not_connected`: Admin did not start the app in time.\n * - `duplicate_sdk`: another copy of the SDK in the page has already connected, or tried to,\n * because the page loads the SDK more than once. Load a single copy for the whole page.\n * - `invalid_context`: Admin started the app with a context this SDK cannot read. Updating the\n * SDK usually fixes it.\n * - `session_ended`: this document has left the app session, usually because the page reloaded\n * or navigated away, or the session has ended. Every call fails after that.\n * - `invalid_argument`: the app passed something that cannot be sent.\n * - `invalid_path`: a path that is not an Admin API path, or not a route within the app; or\n * one the Admin API only redirects, such as a path without its trailing `/`.\n * - `unsupported`: this site's version of Ghost doesn't have the call the app made yet. The\n * SDK knows this from the calls Admin listed when it connected.\n * - `blocked`: Admin refused by policy, such as a request the allowlist doesn't allow.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: Admin refused for any other reason; the message says why.\n *\n * `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes; the\n * rest are bridge codes, which cross the channel.\n */\nexport type GhostAppErrorCode =\n | 'not_framed'\n | 'not_connected'\n | 'duplicate_sdk'\n | 'unsupported'\n | BridgeErrorCode;\n\n/** The only error type the SDK rejects with, so an app can branch on `code`. */\nexport class GhostAppError extends Error {\n readonly code: GhostAppErrorCode;\n\n constructor(code: GhostAppErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'GhostAppError';\n this.code = code;\n }\n}\n\n/**\n * Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin\n * gave or, if there is none, `rejected` with Admin's message.\n */\nexport function fromHostError(error: unknown, operation: string): GhostAppError {\n const message =\n typeof error === 'object' && error !== null && 'message' in error\n ? String(error.message)\n : undefined;\n if (message === undefined) {\n return new GhostAppError('rejected', `Ghost refused ${operation}`, { cause: error });\n }\n // Only the codes Admin refuses with are parsed; any other prefix stays part of the message.\n const coded = decodeBridgeError(message, HOST_ERROR_CODES);\n if (coded) {\n return new GhostAppError(coded.code, coded.detail, { cause: error });\n }\n return new GhostAppError('rejected', message, { cause: error });\n}\n\nexport function invalidArgument(message: string): GhostAppError {\n return new GhostAppError('invalid_argument', message);\n}\n\nexport function invalidPath(message: string): GhostAppError {\n return new GhostAppError('invalid_path', message);\n}\n\nexport function unsupported(operation: string): GhostAppError {\n return new GhostAppError('unsupported', `This site's Ghost doesn't support ${operation} yet`);\n}\n\nexport function sessionEnded(): GhostAppError {\n return new GhostAppError('session_ended', 'The session with Ghost has ended');\n}\n","import {\n ARGUMENT_MESSAGES,\n FETCH_METHODS,\n isContainedPath,\n isFetchResponse,\n isRecord,\n isReservedRequestHeader,\n methodAllowsBody,\n type FetchMethod,\n type FetchRequest,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument, invalidPath } from './errors.ts';\nimport type { GhostFetchInit, JsonBody } from './types.ts';\n\nconst JSON_BODY = 'Expected a body that can be sent as JSON';\n\n// The statuses a `Response` must be built without a body for, or its constructor throws.\nconst NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\nfunction isJsonBody(value: unknown): value is JsonBody {\n if (Array.isArray(value)) {\n return true;\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n// A cycle or a BigInt makes `JSON.stringify` throw, and a `toJSON` that returns `undefined`\n// makes it return `undefined`.\nfunction toJson(body: JsonBody): string {\n let json: string | undefined;\n try {\n json = JSON.stringify(body) as string | undefined;\n } catch (error) {\n throw new GhostAppError('invalid_argument', JSON_BODY, { cause: error });\n }\n if (json === undefined) {\n throw invalidArgument(JSON_BODY);\n }\n return json;\n}\n\nfunction toHeaders(init: HeadersInit | undefined): Record<string, string> {\n let headers: Headers;\n try {\n headers = new Headers(init);\n } catch (error) {\n throw new GhostAppError('invalid_argument', 'Expected headers with valid names and values', {\n cause: error,\n });\n }\n // `Headers` lowercases the names, so a reserved header the app set is found in any case.\n const entries = [...headers.entries()];\n const reserved = entries.find(([name]) => isReservedRequestHeader(name));\n if (reserved) {\n throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));\n }\n return Object.fromEntries(entries);\n}\n\n/**\n * Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are\n * refused here, using the same rules Admin applies; Admin checks everything again.\n */\nexport function toFetchRequest(path: string, init: GhostFetchInit = {}): FetchRequest {\n if (!isContainedPath(path)) {\n throw invalidPath(ARGUMENT_MESSAGES.fetchPath);\n }\n // The types rule this out, but a page without TypeScript can pass anything.\n if (typeof init !== 'object' || init === null) {\n throw invalidArgument('Expected options such as { method, headers, body }');\n }\n\n const { method: given = 'GET' } = init as { method?: unknown };\n const method = (typeof given === 'string' ? given.toUpperCase() : given) as FetchMethod;\n if (!FETCH_METHODS.includes(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);\n }\n\n const headers = toHeaders(init.headers);\n const request: FetchRequest = { path, method };\n\n if (init.body !== undefined && init.body !== null) {\n if (!methodAllowsBody(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);\n }\n if (typeof init.body === 'string') {\n request.body = init.body;\n } else if (isJsonBody(init.body)) {\n request.body = toJson(init.body);\n } else {\n // Binary and streamed bodies cannot cross the channel as text.\n throw invalidArgument('Expected the body as text, or as an object or array to send as JSON');\n }\n }\n\n if (Object.keys(headers).length > 0) {\n request.headers = headers;\n }\n return request;\n}\n\nconst UNREADABLE_ANSWER = \"Ghost answered with a response this SDK doesn't understand\";\n\n/** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */\nexport function toResponse(answer: unknown): Response {\n if (!isFetchResponse(answer)) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER);\n }\n // The `Response` constructor throws on a header name or status text it can't hold.\n try {\n return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {\n status: answer.status,\n statusText: answer.statusText,\n headers: answer.headers,\n });\n } catch (error) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER, { cause: error });\n }\n}\n","import { isContainedPath, type PathMove } from '@tryghost/app-contracts';\n\n/**\n * A URL's route: its path, query and fragment. The URL parser has already put them in the\n * normalised form Admin stores app paths in. Resolving them again would read a path that starts\n * with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that\n * route fails `isContainedPath` and is never reported.\n */\nfunction routeOf({ pathname, search, hash }: { pathname: string; search: string; hash: string }) {\n return `${pathname}${search}${hash}`;\n}\n\n/** The page's route. */\nexport function currentRoute(): string {\n return routeOf(window.location);\n}\n\n/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */\nfunction isLink(node: EventTarget): node is Element {\n return (\n (node instanceof HTMLAnchorElement || (node instanceof SVGElement && node.localName === 'a')) &&\n node.hasAttribute('href')\n );\n}\n\nexport interface HistoryWatch {\n /**\n * Puts the page at `path` without adding a history entry, because Admin moved it there, and\n * dispatches `popstate` so the app's router shows it.\n */\n follow(path: string): void;\n /** Gives the page its own history methods and links back. */\n stop(): void;\n}\n\n/**\n * Whether a route is one Admin would take. Admin owns the app's address, so the page never\n * moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin\n * link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is\n * dropped, with a warning for the app's developer.\n */\nfunction isContained(route: string): boolean {\n if (isContainedPath(route)) {\n return true;\n }\n // The only place the app's developer would learn why the move did nothing.\n // eslint-disable-next-line no-console\n console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);\n return false;\n}\n\n/**\n * Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL\n * parser can't read is left to the browser, which throws as it would without the SDK.\n */\nfunction refuses(url: string | URL | null | undefined): boolean {\n if (url === undefined || url === null) {\n return false;\n }\n const next = URL.parse(url, window.location.href);\n return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));\n}\n\n/**\n * Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,\n * and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's\n * entries, which left back steps that did nothing once the app's page opened again, and WebKit\n * applies Admin's replace after a frame's push to the entry before it. So the frame keeps a\n * single entry, and Admin keeps one for each of the app's moves.\n *\n * - `history.pushState` and `history.replaceState` replace the frame's entry, then report the\n * move to Admin as a push or a replace, which is how Admin records it. A move to the route the\n * page is already on isn't reported, so Admin never gets an entry that changes nothing.\n * - A click on a link to the app's own origin, which a router hasn't already handled, is reported\n * as a push, and the page then loads the link's address in place of its own entry. A link that\n * opens elsewhere (a `target`, `download`, or a modifier key) is left alone.\n * - Neither is made to a route Admin would refuse, one that isn't contained.\n * - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.\n *\n * Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the\n * fragment through `location.hash` and the Navigation API, which have added the entry before\n * any event says so.\n */\nexport function watchHistory(\n moved: (route: string, move: PathMove) => Promise<void>,\n // How the page loads a link's address in place of its own entry. Tests pass their own.\n load: (url: string) => void = (url) => window.location.replace(url),\n): HistoryWatch {\n const { history } = window;\n const { pushState, replaceState } = history;\n let route = currentRoute();\n // The state the app gave each route, so following Admin back to one gives it back.\n const states = new Map<string, unknown>([[route, history.state]]);\n\n const report = (move: PathMove) => {\n const next = currentRoute();\n states.set(next, history.state);\n if (next !== route) {\n route = next;\n void moved(next, move);\n }\n };\n\n const push: History['pushState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('push');\n };\n const replace: History['replaceState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('replace');\n };\n history.pushState = push;\n history.replaceState = replace;\n\n const onClick = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // Found through the event's path, which reaches into shadow roots, and read through its\n // attributes, because an SVG link has none of `HTMLAnchorElement`'s properties.\n const link = event.composedPath().find(isLink);\n const target = link?.getAttribute('target') ?? '';\n if (!link || link.hasAttribute('download') || (target !== '' && target !== '_self')) {\n return;\n }\n const url = new URL(link.getAttribute('href') as string, document.baseURI);\n if (url.origin !== window.location.origin) {\n return;\n }\n event.preventDefault();\n const go = () => load(url.href);\n const next = routeOf(url);\n if (!isContained(next)) {\n return;\n }\n if (next === route) {\n go();\n return;\n }\n route = next;\n // Admin records the move before the page leaves, so the next document starts where it is.\n moved(next, 'push').then(go, go);\n };\n document.addEventListener('click', onClick);\n\n return {\n follow(path) {\n route = path;\n const state = states.get(path) ?? null;\n replaceState.call(history, state, '', path);\n window.dispatchEvent(new PopStateEvent('popstate', { state }));\n },\n stop() {\n if (history.pushState === push) {\n history.pushState = pushState;\n }\n if (history.replaceState === replace) {\n history.replaceState = replaceState;\n }\n document.removeEventListener('click', onClick);\n },\n };\n}\n","import { TITLE_MAX_LENGTH, toPlainText } from '@tryghost/app-contracts';\n\n/**\n * Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a\n * title containing a character that reorders or hides text, so the SDK drops those characters\n * rather than losing the whole title: a right-to-left title often contains a direction mark.\n */\nfunction clampTitle(title: string): string {\n const trimmed = toPlainText(title).trim();\n if (trimmed.length <= TITLE_MAX_LENGTH) {\n return trimmed;\n }\n const end = /[\\uD800-\\uDBFF]/.test(trimmed.charAt(TITLE_MAX_LENGTH - 1))\n ? TITLE_MAX_LENGTH - 1\n : TITLE_MAX_LENGTH;\n return trimmed.slice(0, end);\n}\n\n/**\n * Reports the page's title now and every time it changes, so Admin can show it as its own.\n * Returns a function that stops watching.\n *\n * A title can change in three ways, and frameworks use all three: its text is edited, its\n * element is replaced, or an element is added where there was none. Rather than distinguish\n * them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it\n * only if it differs from the last one. A mutation observer already delivers each batch once,\n * in a microtask.\n */\nexport function watchTitle(report: (title: string) => void): () => void {\n let last: string | undefined;\n const check = () => {\n const title = clampTitle(document.title);\n if (title !== last) {\n last = title;\n report(title);\n }\n };\n\n check();\n const observer = new MutationObserver(check);\n observer.observe(document.head ?? document.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n });\n return () => observer.disconnect();\n}\n","import { ThreadMessagePort } from '@quilted/threads';\nimport {\n ARGUMENT_MESSAGES,\n encodeBridgeError,\n type AppErrorCode,\n isContainedPath,\n isRecord,\n isStartContext,\n isTheme,\n type AppExports,\n type HostExports,\n type PathMove,\n type Place,\n type Theme,\n} from '@tryghost/app-contracts';\n\nimport {\n GhostAppError,\n fromHostError,\n invalidArgument,\n sessionEnded,\n unsupported,\n} from './errors.ts';\nimport { toFetchRequest, toResponse } from './fetch.ts';\nimport { currentRoute, watchHistory, type HistoryWatch } from './history.ts';\nimport { watchTitle } from './title.ts';\nimport type {\n Ghost,\n GhostFetchInit,\n GhostPath,\n Session,\n Site,\n Unsubscribe,\n User,\n} from './types.ts';\n\ntype HostCall<K extends keyof HostExports> = (\n ...args: Parameters<HostExports[K]>\n) => ReturnType<HostExports[K]>;\n\n/** Calls each listener the app registered, so that one that throws can't stop the others. */\nfunction notify<T>(listeners: ReadonlySet<(value: T) => void>, value: T) {\n for (const listener of [...listeners]) {\n try {\n listener(value);\n } catch (error) {\n // Rethrown outside the SDK, where the page's own error handling sees it.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * An error that refuses one of Admin's calls. Only its message reaches Admin, so the message\n * starts with the code, as Admin's own refusals do.\n */\nfunction refusal(code: AppErrorCode, detail: string): Error {\n return new Error(encodeBridgeError(code, detail));\n}\n\n/**\n * Returns the copy of an argument that will cross the channel, or throws `invalid_argument`\n * with `message` if it can't cross. The structured clone that carries a call only refuses a\n * symbol or a DOM node once the call is in progress, and the channel would proxy a function,\n * though no argument in the bridge's calls is a function. Cloning first refuses all of these\n * before anything is sent to Admin.\n */\nfunction cloneArgument<T>(value: T, message: string): T {\n try {\n return structuredClone(value);\n } catch (error) {\n throw new GhostAppError('invalid_argument', message, { cause: error });\n }\n}\n\nfunction subscribe<T>(listeners: Set<T>, listener: T): Unsubscribe {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The parts of Admin's start context that `start` keeps. The theme and path can change, so\n * they are stored separately.\n */\ninterface StartedContext {\n site: Site;\n user: User;\n session: Session;\n}\n\nexport interface ChannelEvents {\n /** Admin started the app, and the connection is ready for it to use. */\n started(ghost: Ghost): void;\n /** The channel ended, before or after the start. */\n ended(error: GhostAppError): void;\n}\n\n/**\n * The channel to Admin over the port Admin handed the page, and the `Ghost` object the app\n * gets once Admin has called `start`. The channel itself stays inside the SDK.\n *\n * The channel ends in three cases: when the port closes, which browsers that fire `close` on\n * a port (and Node) report when Admin closes its end or its document goes away; when a call\n * fails because the thread has closed; or when Admin rejects a call with `session_ended`.\n * After that, every call rejects with the same error.\n */\nexport class Channel {\n readonly #port: MessagePort;\n readonly #thread: ThreadMessagePort<HostExports, AppExports>;\n // What this Admin exports, from its connect message.\n readonly #hostExports: ReadonlySet<string>;\n readonly #events: ChannelEvents;\n readonly #themeListeners = new Set<(theme: Readonly<Theme>) => void>();\n readonly #pathListeners = new Set<(path: string) => void>();\n readonly #endListeners = new Set<(error: GhostAppError) => void>();\n #context: StartedContext | undefined;\n #theme: Readonly<Theme> | undefined;\n #path = '/';\n #ended: GhostAppError | undefined;\n #stopWatchingTitle: (() => void) | undefined;\n #history: HistoryWatch | undefined;\n // Counts the page's moves, so an answer to one the page has since moved on from is ignored.\n #moves = 0;\n\n constructor(port: MessagePort, hostExports: readonly string[], events: ChannelEvents) {\n this.#port = port;\n this.#hostExports = new Set(hostExports);\n this.#events = events;\n this.#thread = new ThreadMessagePort<HostExports, AppExports>(port, {\n exports: {\n start: async (context) => this.#start(context),\n themeChanged: async (theme) => this.#themeChanged(theme),\n pathChanged: async (path) => this.#pathChanged(path),\n },\n });\n port.addEventListener('close', () => this.end(sessionEnded()));\n // A message that could not be read is a call that will never be answered.\n port.addEventListener('messageerror', () => this.end(sessionEnded()));\n port.start();\n }\n\n #start(context: unknown) {\n if (this.#context) {\n return;\n }\n if (!isStartContext(context)) {\n const detail = \"Ghost started the app with a context this SDK doesn't understand\";\n // End the channel only after Admin has received the refusal, so Admin learns why instead\n // of waiting for its timeout.\n setTimeout(() => this.end(new GhostAppError('invalid_context', detail)), 0);\n throw refusal('invalid_context', detail);\n }\n this.#context = {\n site: Object.freeze({ ...context.site }),\n user: Object.freeze({ ...context.user }),\n session: Object.freeze({ ...context.session }),\n };\n this.#theme = Object.freeze({ ...context.theme });\n // Admin owns the history from here on. The page's own address is its route: Admin loads a\n // new frame at its own path, so the two differ only when the page's server redirected it or\n // a form or link loaded another page in place, and then Admin follows the page.\n this.#history = watchHistory((route, move) => this.#moved(route, move));\n const route = currentRoute();\n this.#path = context.path;\n if (route !== context.path) {\n void this.#moved(route, 'replace');\n }\n // Report the title before `start` returns, so Admin has it by the time it shows the page.\n // An older Admin without `titleChanged` keeps its own title.\n if (this.#hostExports.has('titleChanged')) {\n this.#stopWatchingTitle = watchTitle((title) => {\n this.#call('titleChanged', title).catch(() => {\n // If Admin refuses a title, it keeps showing its own.\n });\n });\n }\n this.#events.started(this.ghost);\n }\n\n #themeChanged(theme: unknown) {\n this.#assertStarted();\n if (!isTheme(theme)) {\n throw refusal('invalid_argument', \"Ghost sent a theme this SDK doesn't understand\");\n }\n this.#theme = Object.freeze({ ...theme });\n notify(this.#themeListeners, this.#theme);\n }\n\n #pathChanged(path: unknown) {\n this.#assertStarted();\n if (!isContainedPath(path)) {\n throw refusal('invalid_argument', \"Ghost sent a path this SDK doesn't understand\");\n }\n this.#path = path;\n this.#history?.follow(path);\n notify(this.#pathListeners, path);\n }\n\n /**\n * Reports a move the page made. Resolves once Admin has answered, with the path Admin now has\n * for the app, or has refused; a refused move leaves the page where it is.\n */\n async #moved(route: string, move: PathMove): Promise<void> {\n // A route that leaves the app once normalised, such as `/.//host/`, is one Admin refuses\n // and the SDK never hands out, so the app's path stays where it was.\n if (!isContainedPath(route)) {\n return;\n }\n this.#path = route;\n this.#moves += 1;\n const thisMove = this.#moves;\n try {\n const adminPath = await this.#call('pathChanged', route, move);\n // Admin's answer, rather than `route`: it's Admin's own path when Admin didn't follow\n // the move, such as when the publisher is leaving the app, and Admin then moves the page\n // back with `pathChanged`. An answer to an earlier move is out of date.\n if (thisMove === this.#moves && isContainedPath(adminPath)) {\n this.#path = adminPath;\n }\n } catch {\n // Refused, or the session ended: either way there's nothing for the page to do.\n }\n }\n\n #assertStarted() {\n if (!this.#context) {\n throw refusal('invalid_context', 'Ghost has not started the app yet');\n }\n }\n\n async #call<K extends keyof HostExports>(\n name: K,\n ...args: Parameters<HostExports[K]>\n ): Promise<Awaited<ReturnType<HostExports[K]>>> {\n if (this.#ended) {\n throw this.#ended;\n }\n if (!this.#hostExports.has(name)) {\n throw unsupported(name);\n }\n try {\n const call = this.#thread.imports[name] as HostCall<K>;\n return await call(...args);\n } catch (error) {\n if (this.#thread.closed) {\n throw this.end(sessionEnded());\n }\n const appError = fromHostError(error, name);\n if (appError.code === 'session_ended') {\n this.end(appError);\n }\n throw appError;\n }\n }\n\n /**\n * Ends the channel. Only the first call has an effect: pending and later calls reject with\n * its `error`. Returns the error the channel ended with.\n */\n end(error: GhostAppError): GhostAppError {\n if (this.#ended) {\n return this.#ended;\n }\n this.#ended = error;\n this.#stopWatchingTitle?.();\n this.#history?.stop();\n this.#thread.close();\n this.#port.close();\n this.#events.ended(error);\n notify(this.#endListeners, error);\n this.#endListeners.clear();\n return error;\n }\n\n /**\n * The `Ghost` object the app gets once `start` has set the context. It has only the members\n * its type declares, so no part of the channel, such as `end`, is reachable from the app.\n */\n readonly ghost: Ghost = this.#createGhost();\n\n #createGhost(): Ghost {\n const context = () => this.#context as StartedContext;\n const theme = () => this.#theme as Readonly<Theme>;\n const connected = () => this.#ended === undefined;\n return Object.freeze({\n get site(): Site {\n return context().site;\n },\n get user(): User {\n return context().user;\n },\n get theme(): Readonly<Theme> {\n return theme();\n },\n get session(): Session {\n return context().session;\n },\n get connected(): boolean {\n return connected();\n },\n path: this.#createPath(),\n onThemeChange: (callback: (theme: Readonly<Theme>) => void): Unsubscribe =>\n subscribe(this.#themeListeners, callback),\n onPathChange: (callback: (path: string) => void): Unsubscribe =>\n subscribe(this.#pathListeners, callback),\n onSessionEnd: (callback: (error: GhostAppError) => void): Unsubscribe =>\n this.#onSessionEnd(callback),\n fetch: (path: string, init?: GhostFetchInit): Promise<Response> => this.#fetch(path, init),\n open: (place: Place): Promise<void> => this.#open(place),\n });\n }\n\n #createPath(): GhostPath {\n const current = () => this.#path;\n return Object.freeze({\n get current(): string {\n return current();\n },\n });\n }\n\n #onSessionEnd(callback: (error: GhostAppError) => void): Unsubscribe {\n const ended = this.#ended;\n if (ended) {\n // Notify it in a microtask, as an earlier subscriber would be, unless it has\n // unsubscribed by then.\n let left = false;\n queueMicrotask(() => {\n if (!left) {\n callback(ended);\n }\n });\n return () => {\n left = true;\n };\n }\n return subscribe(this.#endListeners, callback);\n }\n\n async #fetch(path: string, init?: GhostFetchInit): Promise<Response> {\n const request = toFetchRequest(path, init);\n return toResponse(await this.#call('fetch', request));\n }\n\n async #open(place: Place): Promise<void> {\n if (!isRecord(place)) {\n throw invalidArgument(ARGUMENT_MESSAGES.place);\n }\n await this.#call('open', cloneArgument(place, ARGUMENT_MESSAGES.place));\n }\n}\n","declare const __SDK_VERSION__: string;\n\n/**\n * The SDK's version, sent in the hello for Admin's logs. The build and the tests replace\n * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`\n * and doesn't read package.json.\n */\nexport const SDK_VERSION: string = __SDK_VERSION__;\n","import {\n HELLO_MESSAGE_TYPE,\n START_TIMEOUT_MS,\n isConnectMessage,\n isRecord,\n type HelloMessage,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument } from './errors.ts';\nimport { Channel } from './session.ts';\nimport type { ConnectOptions, Ghost } from './types.ts';\nimport { SDK_VERSION } from './version.ts';\n\n/**\n * How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only\n * start listening after the page has loaded and sent its first hello, so one hello is not\n * enough.\n */\nconst HELLO_INTERVAL = 250;\n\n/**\n * The target origin for the hello: the embedding page's origin where the browser exposes it\n * (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants\n * nothing: the port goes the other way, and Admin addresses it to this page's origin only.\n * `document.referrer` doesn't work here: once the page has navigated within itself, it holds\n * the page's own origin.\n */\nfunction parentOrigin(): string {\n const origin = window.location.ancestorOrigins?.[0];\n return origin && origin !== 'null' ? origin : '*';\n}\n\n/**\n * The global key where the first copy of the SDK to connect claims the page. It is a symbol\n * from the global registry, so a second copy bundled into the same page finds the same key.\n */\nconst PAGE_CLAIM = Symbol.for('@tryghost/app-sdk');\n\n/**\n * The claim also holds the hello's `document` ID. It's made when the SDK loads, so every\n * `connect()` in a document sends the same ID, and a new document (after a reload, a form post\n * or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some\n * privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession\n * could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the\n * plain HTTP origins apps use in development.\n */\nconst thisCopy = Object.freeze({\n sdk: SDK_VERSION,\n document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,\n});\n\n/** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */\nfunction claimPage(): boolean {\n const page = globalThis as unknown as Record<symbol, unknown>;\n page[PAGE_CLAIM] ??= thisCopy;\n return page[PAGE_CLAIM] === thisCopy;\n}\n\n/**\n * The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout\n * would fire immediately.\n */\nconst TIMEOUT_MAX = 2 ** 31 - 1;\n\nfunction handshake(\n options: ConnectOptions,\n onEnded: (error: GhostAppError) => void,\n): Promise<Ghost> {\n if (!isRecord(options)) {\n return Promise.reject(invalidArgument('Expected options such as { timeout: 10000 }'));\n }\n // By default, wait as long as Admin gives the page. Waiting longer would mean waiting on a\n // frame Admin has already given up on.\n const { timeout = START_TIMEOUT_MS } = options;\n if (typeof timeout !== 'number' || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) {\n return Promise.reject(\n invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`),\n );\n }\n if (typeof window === 'undefined' || window.parent === window) {\n return Promise.reject(\n new GhostAppError('not_framed', 'This page is not open inside Ghost Admin'),\n );\n }\n\n const parent = window.parent;\n const targetOrigin = parentOrigin();\n\n return new Promise<Ghost>((resolve, reject) => {\n const stopWaiting = () => {\n clearInterval(helloTimer);\n clearTimeout(timeoutTimer);\n window.removeEventListener('message', onMessage);\n };\n\n // A promise ignores `reject` once it has settled, so a failure after `started` changes\n // nothing.\n const fail = (error: GhostAppError) => {\n stopWaiting();\n reject(error);\n };\n\n // The channel is bound to the first valid answer from the parent window. The listener is\n // removed as soon as that answer arrives, so later answers are ignored.\n const onMessage = (event: MessageEvent) => {\n const port = event.ports?.[0];\n if (\n event.source !== parent ||\n !isConnectMessage(event.data) ||\n !port ||\n (targetOrigin !== '*' && event.origin !== targetOrigin)\n ) {\n return;\n }\n clearInterval(helloTimer);\n window.removeEventListener('message', onMessage);\n channel = new Channel(port, event.data.exports, {\n started: (ghost) => {\n stopWaiting();\n resolve(ghost);\n },\n ended: (error) => {\n fail(error);\n onEnded(error);\n },\n });\n };\n\n const hello: HelloMessage = {\n type: HELLO_MESSAGE_TYPE,\n sdk: SDK_VERSION,\n document: thisCopy.document,\n };\n const sayHello = () => {\n parent.postMessage(hello, targetOrigin);\n };\n\n let channel: Channel | undefined;\n window.addEventListener('message', onMessage);\n sayHello();\n const helloTimer = setInterval(sayHello, HELLO_INTERVAL);\n const timeoutTimer = setTimeout(() => {\n const error = new GhostAppError('not_connected', 'Ghost Admin did not start the app in time');\n fail(error);\n channel?.end(error);\n }, timeout);\n });\n}\n\nlet connecting: Promise<Ghost> | undefined;\n// The error the page's connection ended with, after Admin answered it. Admin answers each\n// document only once, so this connection was the page's only one.\nlet spent: GhostAppError | undefined;\n\n// Forgets an attempt only if it is still the shared one: an attempt that ended may report\n// that after a newer attempt has started.\nfunction forget(attempt: Promise<Ghost>) {\n if (connecting === attempt) {\n connecting = undefined;\n }\n}\n\n/**\n * Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the\n * app. Safe to call as soon as the page loads.\n *\n * Every call shares one connection, and the first call's options apply. Only one copy of the\n * SDK in a page can connect; any other copy rejects with `duplicate_sdk`. Admin answers each\n * document only once, so after it answers, that connection is the page's only one. Once it\n * fails or its session ends, every call rejects with the error it ended with, and only a new\n * document (after a reload, for example) can connect again. A failure before Admin answered,\n * such as a bad option or a timeout, can be retried.\n */\nexport function connect(options: ConnectOptions = {}): Promise<Ghost> {\n // Two copies would both send a hello for the same document, and Admin answers each document\n // only once.\n if (!claimPage()) {\n return Promise.reject(\n new GhostAppError(\n 'duplicate_sdk',\n 'This page loads the app SDK more than once; load one copy, which every part of the page shares',\n ),\n );\n }\n if (spent) {\n return Promise.reject(spent);\n }\n if (!connecting) {\n const attempt: Promise<Ghost> = handshake(options, (error) => {\n spent = error;\n forget(attempt);\n }).catch((error: unknown) => {\n forget(attempt);\n throw error;\n });\n connecting = attempt;\n }\n return connecting;\n}\n"],"mappings":";;AAMA,IAAM,UAAU;AACG,IAAI,OAAO,KAAK,QAAQ,MAAM,GAAG;AACpD,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI;;AAMvD,SAAgB,YAAY,OAAO;CAC/B,OAAO,MAAM,QAAQ,gBAAgB,EAAE;AAC3C;;;;;;;;;;;;;;ACLA,IAAa,qBAAqB;;;;;;;AASlC,IAAa,mBAAmB;;;;;AAOhC,IAAa,gBAAgB;CAAC;CAAO;CAAQ;CAAO;AAAQ;;;;;AAK5D,SAAgB,iBAAiB,QAAQ;CACrC,OAAO,WAAW;AACtB;AAOA,IAAM,0BAA0B;;;;;;;AAOhC,SAAgB,wBAAwB,MAAM;CAC1C,OAAO,wBAAwB,KAAK,IAAI;AAC5C;;;;;;AAMA,IAAa,oBAAoB;CAC7B,WAAW;CACX,aAAa,yBAAyB,cAAc,KAAK,IAAI;CAC7D,WAAW;CAGX,iBAAiB,SAAS,eAAe,KAAK,YAAY,EAAE;CAC5D,UAAU;CACV,SAAS;CACT,UAAU;CACV,OAAO;AACX;;;;;;;;;;;;;;;;;;AAyBA,IAAa,mBAAmB;CAC5B;CACA;CACA;CACA;CACA;CACA;AACJ;AAUkC,CAAC,GAAG,gBAAmC;AACzE,IAAM,gBAAgB;;;;;AAKtB,SAAgB,kBAAkB,MAAM,QAAQ;CAC5C,OAAO,GAAG,KAAK,IAAI;AACvB;;;;;;AAMA,SAAgB,kBAAkB,SAAS,OAAO;CAC9C,MAAM,GAAG,OAAO,IAAI,SAAS,MAAM,cAAc,KAAK,OAAO,KAAK,CAAC;CACnE,OAAO,MAAM,SAAS,IAAI,IAAI;EAAQ;EAAM;CAAO,IAAI,KAAA;AAC3D;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ACN,KAAK;GACL,UAAU,SAAS;EACrB;EACA,MAAM,iBAAiB;GACrB,OAAO,YAAY,OAAO,YAAY;EACxC;EAEA,IAAI;EACJ,OAAO,iBAAiB,WAAW,SAAS;EAC5C,SAAS;EACT,MAAM,aAAa,YAAY,UAAU,cAAc;EACvD,MAAM,eAAe,iBAAiB;GACpC,MAAM,QAAQ,IAAI,cAAc,iBAAiB,2CAA2C;GAC5F,KAAK,KAAK;GACV,SAAS,IAAI,KAAK;EACpB,GAAG,OAAO;CACZ,CAAC;AACH;AAEA,IAAI;AAGJ,IAAI;AAIJ,SAAS,OAAO,SAAyB;CACvC,IAAI,eAAe,SACjB,aAAa,KAAA;AAEjB;;;;;;;;;;;;AAaA,SAAgB,QAAQ,UAA0B,CAAC,GAAmB;CAGpE,IAAI,CAAC,UAAU,GACb,OAAO,QAAQ,OACb,IAAI,cACF,iBACA,gGACF,CACF;CAEF,IAAI,OACF,OAAO,QAAQ,OAAO,KAAK;CAE7B,IAAI,CAAC,YAAY;EACf,MAAM,UAA0B,UAAU,UAAU,UAAU;GAC5D,QAAQ;GACR,OAAO,OAAO;EAChB,CAAC,CAAC,CAAC,OAAO,UAAmB;GAC3B,OAAO,OAAO;GACd,MAAM;EACR,CAAC;EACD,aAAa;CACf;CACA,OAAO;AACT"}
package/dist/app-sdk.js CHANGED
@@ -1218,7 +1218,7 @@ var Channel = class {
1218
1218
  * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
1219
1219
  * and doesn't read package.json.
1220
1220
  */
1221
- var SDK_VERSION = "0.1.0-alpha.4";
1221
+ var SDK_VERSION = "0.1.0-alpha.6";
1222
1222
  //#endregion
1223
1223
  //#region src/connect.ts
1224
1224
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tryghost/app-sdk",
3
- "version": "0.1.0-alpha.4",
4
- "description": "The SDK apps use to talk to Ghost from inside Admin",
3
+ "version": "0.1.0-alpha.6",
4
+ "description": "The SDK apps use to talk to Ghost: from their page inside Admin, and from their backend",
5
5
  "license": "MIT",
6
6
  "author": "Ghost Foundation",
7
7
  "repository": {
@@ -20,10 +20,19 @@
20
20
  ".": {
21
21
  "types": "./build/index.d.ts",
22
22
  "default": "./build/index.js"
23
+ },
24
+ "./backend": {
25
+ "types": "./build/backend.d.ts",
26
+ "default": "./build/backend.js"
23
27
  }
24
28
  },
25
29
  "dependencies": {
26
- "@quilted/threads": "4.1.0"
30
+ "@quilted/threads": "4.1.0",
31
+ "jose": "6.2.15",
32
+ "zod": "4.6.7"
33
+ },
34
+ "engines": {
35
+ "node": ">=22.1"
27
36
  },
28
37
  "scripts": {
29
38
  "build": "vite build --mode package && vite build",