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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,311 +1,56 @@
1
1
  # @tryghost/app-sdk
2
2
 
3
- The SDK apps use to talk to Ghost from inside Admin.
3
+ A TypeScript SDK for building apps that run inside Ghost Admin.
4
+ Use it to work with your site's content, respond to theme changes, and keep
5
+ navigation in sync with Admin.
4
6
 
5
- An app's page runs in a frame inside Ghost Admin. The SDK connects it to Admin,
6
- gives it the site, the user and the theme, and lets it call the Admin API, keep
7
- its route in sync with Admin's URL, and send the publisher elsewhere in Admin.
7
+ > **In development.** Apps are in private beta and the SDK is pre-alpha. They're
8
+ > for experimentation and aren't ready for production use. Expect breaking
9
+ > changes to the SDK, manifest format, and APIs. npm's `latest` tag points to
10
+ > the newest alpha.
8
11
 
9
- > **Alpha.** CI publishes each change to npm as the next `0.1.0-alpha.N` under
10
- > the `alpha` tag. Alphas make no compatibility promise.
12
+ ## Get started
11
13
 
12
- ## Quick start
13
-
14
- Without a bundler, load the bundle (`dist/app-sdk.js` in the package), a single
15
- ES module with everything inlined:
16
-
17
- ```html
18
- <script type="module">
19
- import { connect } from './app-sdk.js';
20
-
21
- const ghost = await connect();
22
- document.body.dataset.theme = ghost.theme.mode;
23
- ghost.onThemeChange((theme) => (document.body.dataset.theme = theme.mode));
24
-
25
- const response = await ghost.fetch('/posts/?limit=5');
26
- const { posts } = await response.json();
27
- document.title = `${posts.length} posts`; // Admin shows the title as its own
28
- </script>
29
- ```
30
-
31
- 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`:
14
+ You'll need a Ghost site with Apps enabled. Follow the
15
+ [getting started guide](https://tryghost.github.io/Apps/getting-started/) or
16
+ start from an [example app](https://tryghost.github.io/Apps/examples/).
33
17
 
34
18
  ```sh
35
- pnpm add @tryghost/app-sdk@alpha
19
+ pnpm add @tryghost/app-sdk
36
20
  ```
37
21
 
38
- ```ts
39
- import { connect, GhostAppError } from '@tryghost/app-sdk';
40
-
41
- try {
42
- const ghost = await connect();
43
- history.pushState(null, '', '/episodes/12'); // or your router's navigate(); Admin's URL follows
44
- } catch (error) {
45
- if (error instanceof GhostAppError && error.code === 'not_framed') {
46
- // Opened outside Admin: show a link to the site's Admin instead.
47
- }
48
- }
49
- ```
50
-
51
- ## API
52
-
53
- `connect(options?)` resolves with a `Ghost` once Admin has started the app. Call
54
- it as soon as the page loads. Every call shares one connection. Load the SDK
55
- only once per page: if a second copy calls `connect()`, it rejects with
56
- `duplicate_sdk`. `options.timeout` is how long to wait, in milliseconds (10
57
- seconds by default).
58
-
59
- Admin connects each document in the frame only once. After Admin has replied,
60
- that connection is the only one the page gets. If it fails or its session ends,
61
- every `connect()` rejects with the error it ended with, until the page reloads.
62
- A failure before Admin replied, such as `not_framed` or a timeout with no reply,
63
- can be retried.
64
-
65
- | `Ghost` | What it is |
66
- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
67
- | `site` | `{ url, title, timezone, locale }` |
68
- | `user` | `{ id, role }` of the staff user. No name or email. To read those, use `fetch('/users/?filter=id:' + user.id)` (`/users/:id/` isn't allowed), where app scopes will apply. |
69
- | `theme` | `{ mode, accent_color }` that Admin currently uses. `mode` is `light` or `dark`, never `system`. |
70
- | `onThemeChange(callback)` | Called with the new theme when the publisher switches. Returns a function that unsubscribes. |
71
- | `session` | `{ revision }`: the installation's revision when the session started. |
72
- | `path.current` | The app's route: the path, query and fragment of the page's URL, such as `/episodes/12`, normalised the way Admin stores it (`..` resolved, escaped once). |
73
- | `onPathChange(callback)` | Called when Admin moves the app: back or forward in Admin, or one of Admin's links. The page's URL is already there and `popstate` has fired; a multi-page app loads it (see below). |
74
- | `fetch(path, init?)` | Calls the Admin API as the staff user. `path` is relative to the API root (`/posts/?limit=5`), never a URL. Resolves with a real `Response`. |
75
- | `open(place)` | Sends the publisher to `{ post: { id } }`, `{ page: { id } }`, `{ member: { id } }` or `{ apps: true }`. Rejects with `rejected` if they're already leaving the app. |
76
- | `connected` | `false` once the session has ended. |
77
- | `onSessionEnd(callback)` | Called once, with the `session_ended` error, when this document leaves the app session (a reload, form post or link) or the session ends. |
78
-
79
- `site`, `user`, `session` and `theme` are frozen, so no part of the page can
80
- change what the rest of it reads.
81
-
82
- `fetch` takes `method` (any case), `headers` (anything `Headers` accepts) and
83
- `body`, which is always JSON. Text is sent unchanged and must be JSON; an object
84
- or array is sent as JSON. Admin labels it as JSON itself. A body on `GET`, a
85
- binary body and the headers only Admin sets are refused: `cookie`,
86
- `authorization`, `content-type`, `content-encoding`, `x-ghost-*`, `origin` and
87
- similar. Any
88
- status comes back as a `Response`. `fetch` rejects only when Admin refuses to
89
- make the request.
90
-
91
- ### Admin API access
92
-
93
- `fetch` reaches only these routes, grouped by the scope that will allow them once
94
- apps have their own token. Anything else is refused as `blocked`. `:id` is an
95
- object ID, 24 lowercase hexadecimal characters; a slug is one path segment.
96
-
97
- | Scope | Routes |
98
- | ------------------ | -------------------------------------------------------------------------------------- |
99
- | `posts:read` | `GET /posts/`, `GET /posts/:id/`, `GET /posts/slug/:slug/`, `GET /search-index/posts/` |
100
- | `posts:write` | `POST /posts/`, `PUT /posts/:id/`, `DELETE /posts/:id/` |
101
- | `pages:read` | `GET /pages/`, `GET /pages/:id/`, `GET /pages/slug/:slug/`, `GET /search-index/pages/` |
102
- | `pages:write` | `POST /pages/`, `PUT /pages/:id/`, `DELETE /pages/:id/` |
103
- | `tags:read` | `GET /tags/`, `GET /tags/:id/`, `GET /tags/slug/:slug/`, `GET /search-index/tags/` |
104
- | `tags:write` | `POST /tags/`, `PUT /tags/:id/`, `DELETE /tags/:id/` |
105
- | `users:read` | `GET /users/` |
106
- | `tiers:read` | `GET /tiers/` |
107
- | `newsletters:read` | `GET /newsletters/` |
108
- | `site:read` | `GET /site/` |
109
- | `slugs:read` | `GET /slugs/:type/:name/`, `GET /slugs/:type/:name/:id/` |
110
-
111
- An app can't ask Ghost to email a post, set a post's code injection or write
112
- mobiledoc. The one exception: publishing a post that a staff member already
113
- scheduled with a newsletter sends its email, as it would have at the scheduled
114
- time.
115
-
116
- - A write may carry only the query parameters its scope lists: `include`,
117
- `formats` and `save_revision` for posts and pages, and `include` for tags.
118
- Any other name is refused, `newsletter`, `email_segment` and `source`
119
- included, however it's written.
120
- - `codeinjection_head` and `codeinjection_foot` are refused with any value, even
121
- `null`, on posts, pages and tags: leave them out of the body.
122
- - `mobiledoc` must be `null` or left out: it's deprecated and Ghost 7.0 removes
123
- it. Write `lexical` instead.
124
- - The SDK and Admin set the body's content type themselves; an app can't set
125
- `content-type` or `content-encoding`.
126
-
127
- To edit a post, send `updated_at` and only the fields you change, never the
128
- object you read: it comes back with `codeinjection_head` and
129
- `codeinjection_foot` as `null`, which are refused even as `null`.
22
+ Call `connect()` as early as possible when your app loads. Ghost keeps showing
23
+ a loading screen until your app connects.
130
24
 
131
25
  ```ts
132
- const { posts } = await (await ghost.fetch(`/posts/${id}/`)).json();
133
- await ghost.fetch(`/posts/${id}/`, {
134
- method: 'PUT',
135
- body: { posts: [{ updated_at: posts[0].updated_at, title: 'New title' }] },
136
- });
137
- ```
26
+ import { connect } from '@tryghost/app-sdk';
138
27
 
139
- The tags you send replace the post's tags. The tags you read come back with
140
- `codeinjection_head` and `codeinjection_foot` too, so send each as `{ id }`, or
141
- `{ name }` for a new one:
28
+ const ghost = await connect();
142
29
 
143
- ```ts
144
- const tags = posts[0].tags.map(({ id }) => ({ id }));
145
- await ghost.fetch(`/posts/${id}/`, {
146
- method: 'PUT',
147
- body: { posts: [{ updated_at: posts[0].updated_at, tags: [...tags, { name: 'Featured' }] }] },
148
- });
30
+ const response = await ghost.fetch('/posts/?limit=5');
31
+ const { posts } = await response.json();
149
32
  ```
150
33
 
151
- These checks are a stopgap for the private beta. They're reviewed again before
152
- anyone outside the team gets access, and app scopes replace them.
153
-
154
- The refusal names the method and path, or what in the request was refused, as
155
- in `blocked: Apps can't send codeinjection_head to PUT /posts/…/`.
156
-
157
- ### Routes and history
34
+ ## Signing the manifest
158
35
 
159
- Admin keeps the history, and the app routes as it would anywhere: with
160
- `history.pushState` and `history.replaceState`, which any router uses, and with
161
- links. The SDK turns each into a single entry in Admin's history:
36
+ Use the Vite plugin (`@tryghost/app-sdk/vite`) to sign your app's manifest
37
+ while developing and building, or `pnpm exec ghost-app` to manage keys and
38
+ sign from the command line. The [app docs](https://tryghost.github.io/Apps/sdk/#signing-and-your-server)
39
+ cover these tools and the backend helper.
162
40
 
163
- - `pushState` and a click on a link to the app's own origin add an entry in
164
- Admin; `replaceState` replaces Admin's current one. The frame itself keeps a
165
- single entry, so back and forward are always Admin's.
166
- - A link loads its page in place of the frame's entry, after Admin has recorded
167
- the move. A link with a `target`, a `download` or a modifier key is left alone,
168
- and so is one a router has already handled.
169
- - When the publisher goes back or forward, or Admin moves the app itself, the
170
- SDK puts the page's URL there, with the state the app last gave that route,
171
- and dispatches `popstate`, so a router shows it. A multi-page app, with no
172
- router, loads it: `ghost.onPathChange((path) => location.replace(path))`.
173
- - Admin opens the app's page at its route, so each route must load directly, as
174
- with any app that uses browser history. If the page ends up elsewhere, through
175
- a redirect from its server or a form's result, Admin follows the page.
41
+ ## Documentation
176
42
 
177
- Not intercepted, so each still adds an entry of the frame's own, which back
178
- steps through without Admin: a form that posts, a change to `location.hash`,
179
- and the Navigation API. Route with the History API rather than the hash.
43
+ - [SDK guide](https://tryghost.github.io/Apps/sdk/): Capabilities and usage
44
+ - [API reference](https://tryghost.github.io/Apps/sdk-reference/): Functions and types
45
+ - [Deployment](https://tryghost.github.io/Apps/deployment/): Hosting and production setup
46
+ - [Security](https://tryghost.github.io/Apps/security/) and [roadmap](https://tryghost.github.io/Apps/roadmap/): Current limitations and planned changes
180
47
 
181
- ### The frame
48
+ ## Develop the SDK
182
49
 
183
- The frame is sandboxed. The page runs scripts and posts forms on its own origin,
184
- with that origin's storage and cookies, and can open popups and download files.
185
- It can't navigate Admin's tab, and `alert`, `confirm` and `prompt` return at
186
- once (`confirm` with `false`), so an app brings its own dialogs. Browser features
187
- such as the camera, geolocation and fullscreen are off.
50
+ From this package's directory in the Ghost monorepo:
188
51
 
189
- A popup is sandboxed the same way: it can load any page and `postMessage` back
190
- to the app, but it can't navigate other windows, Admin's included, or show
191
- `alert` or `confirm`. To send the publisher somewhere in Admin, use `open`.
192
-
193
- The SDK reports the page's title automatically. It watches `<title>`, and Admin
194
- shows the title, up to 200 characters, while the page is open. Characters that
195
- reorder or hide text, such as direction marks, are removed.
196
-
197
- ## Errors
198
-
199
- Every rejection is a `GhostAppError`, whose `code` gives the reason:
200
-
201
- | `code` | Means |
202
- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
203
- | `not_framed` | The page is not inside a frame, so there is no Admin to talk to. |
204
- | `not_connected` | Admin did not start the app before the timeout. |
205
- | `duplicate_sdk` | Another copy of the SDK in the page called `connect()` first, because the page loads the SDK more than once. Load a single copy for the whole page. |
206
- | `invalid_context` | Admin started the app with a context this SDK cannot read. Updating the SDK usually fixes it. |
207
- | `session_ended` | The channel to Admin has closed, usually because Admin is reloading the app or the page navigated away from the document. Every call fails after that. |
208
- | `invalid_argument` | The app passed something that cannot be sent, such as a body on a `GET`. |
209
- | `invalid_path` | `fetch` was given a URL, a path that leaves the Admin API, or a path the Admin API only redirects, such as `/posts` without its trailing `/`. |
210
- | `unsupported` | This site's Ghost version predates the call. The message names the call. |
211
- | `blocked` | A request the allowlist doesn't allow, such as `GET /db/`, or a write that could send email, set code injection or carry mobiledoc (see Admin API access). |
212
- | `network_error` | Admin could not reach its own API. |
213
- | `rejected` | Admin refused for another reason; the message says why. |
214
-
215
- ## How it connects
216
-
217
- The SDK posts `{ type: 'ghost-app:hello', sdk: <version>, document: <id> }` to
218
- `window.parent` every 250 ms until Admin replies with `ghost-app:connect`, a
219
- `MessagePort` and the names of the calls Admin exports. `document` is a random
220
- ID the SDK makes when it loads. It stays the same for the life of the
221
- document, so Admin can tell whether a hello comes from a page it has already
222
- connected or from a new page. The SDK accepts only the first reply, and only
223
- from the parent window. Over the port, it uses
224
- [`@quilted/threads`](https://github.com/lemonmade/quilt/tree/main/packages/threads)
225
- for the calls `@tryghost/app-contracts/bridge` defines, and Admin then calls
226
- `start`. The SDK refuses a call that the connect message didn't list with
227
- `unsupported`, without sending it. Admin only ever adds calls, so an older Admin
228
- lacks the newer ones.
229
-
230
- Only an error's message survives the channel, so Admin puts the code at the
231
- start of the message, as in `blocked: Apps can't use GET /db/`. The SDK splits it
232
- back into `code` and `message`. A message without a known code arrives as
233
- `rejected`. The SDK refuses Admin's calls the same way: `invalid_context: …` for
234
- a start context it can't read or a call before the start, and
235
- `invalid_argument: …` for a theme or path it can't read. The codes and their
236
- format are defined once, in `@tryghost/app-contracts`.
237
-
238
- The session ends when the port closes (in browsers that report it, such as
239
- Chromium), when a message on it can't be read, or when Admin refuses a call with
240
- `session_ended`. Admin does that to every pending call when it releases the app.
241
- In other browsers, a page Admin has released is removed along with its frame.
242
-
243
- When a reload, a form post or a link within the app loads a new document in the
244
- frame, Admin starts it in place. Admin hides the frame until the new document's
245
- SDK has connected, then starts it with Admin's current route, so the page shows
246
- what the form or link loaded, and Admin follows the new document's address. The
247
- old document's session ends with it. A new document must
248
- connect within the same 10 seconds, or Admin reloads the app's page. A page that
249
- keeps reloading or navigating away is shown as not responding: more than five
250
- documents in a row, each replaced within three seconds of starting. A publisher
251
- clicking quickly through more than five pages of a multi-page app would trip it
252
- too.
253
-
254
- ## Who can frame the page
255
-
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.
261
-
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:
264
-
265
- ```http
266
- Content-Security-Policy: frame-ancestors https://site.example
267
- ```
268
-
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.
272
-
273
- ## Serve only the app from its origin
274
-
275
- Admin replies to any page on the app's origin that sends a hello from the app's
276
- frame, and can't tell the app's own pages apart from anything else served there.
277
- Any such page gets the whole bridge, including `fetch` as the staff user with
278
- their session. So the origin must serve only the app. Keep user-generated
279
- content and third-party pages or widgets on another origin (a separate subdomain
280
- counts). An open redirect is a risk too: a link through it puts another site's
281
- page in the frame, inside Admin.
282
-
283
- ## Develop
284
-
285
- This is a workspace package in the Ghost monorepo. From the package directory:
286
-
287
- ```bash
288
- 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)
292
- pnpm lint # lint source and tests
52
+ ```sh
53
+ pnpm build
54
+ pnpm test
55
+ pnpm lint
293
56
  ```
294
-
295
- It follows the [internal package golden path](../README.md), except where it
296
- ships to apps. Its `build` bundles with Vite instead of compiling with `tsc`,
297
- and also writes `dist/`, which is in `files` and in the Nx build outputs.
298
-
299
- It uses `@tryghost/app-contracts` for the bridge's message types, limits and
300
- 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;
308
- - `dist/` imports nothing at all.
309
-
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.
@@ -0,0 +1,93 @@
1
+ import { t as SignedManifest } from "./chunks/signed-manifest-tbnMbfyw.js";
2
+ //#region ../../contracts/app-contracts/build/identity/challenge.d.ts
3
+ /** Where on an origin Ghost posts a challenge. */
4
+ declare const CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
5
+ //#endregion
6
+ //#region src/backend/challenge.d.ts
7
+ /**
8
+ * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's
9
+ * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and
10
+ * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.
11
+ */
12
+ type BackendJwk = {
13
+ alg?: string;
14
+ crv?: string;
15
+ d?: string;
16
+ dp?: string;
17
+ dq?: string;
18
+ e?: string;
19
+ ext?: boolean;
20
+ k?: string;
21
+ key_ops?: string[];
22
+ kid?: string;
23
+ kty?: string;
24
+ n?: string;
25
+ oth?: {
26
+ d?: string;
27
+ r?: string;
28
+ t?: string;
29
+ }[];
30
+ p?: string;
31
+ q?: string;
32
+ qi?: string;
33
+ use?: string;
34
+ x?: string;
35
+ y?: string;
36
+ };
37
+ /**
38
+ * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an
39
+ * environment variable, such as `GHOST_APP_BACKEND_KEY`.
40
+ */
41
+ type BackendKey = BackendJwk | string;
42
+ interface HandleChallengeOptions {
43
+ backendKey: BackendKey;
44
+ /**
45
+ * The app's public origin, such as `https://app.example.com`, for a server that doesn't see
46
+ * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees
47
+ * `http://`. Ghost challenges the public origin, so without it every challenge is refused.
48
+ * Take it from the app's own configuration, never from a request's headers, which the sender
49
+ * sets. Workers, and other platforms that report the public URL, don't need it.
50
+ */
51
+ origin?: string;
52
+ }
53
+ /**
54
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
55
+ * to it, or use `withGhostApp`, which does.
56
+ */
57
+ declare function handleChallenge(request: Request, { backendKey, origin }: HandleChallengeOptions): Promise<Response>;
58
+ //#endregion
59
+ //#region src/backend/app.d.ts
60
+ /**
61
+ * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`
62
+ * and `ctx`.
63
+ */
64
+ type FetchHandler<Args extends unknown[] = []> = (request: Request, ...args: Args) => Response | Promise<Response>;
65
+ interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {
66
+ /** The app's own handler, for every request but Ghost's challenge. */
67
+ fetch: FetchHandler<Args>;
68
+ }
69
+ /**
70
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
71
+ * passes every other request to `fetch`, with whatever else the platform passes.
72
+ *
73
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
74
+ */
75
+ declare function withGhostApp<Args extends unknown[] = []>({ fetch, ...challenge }: GhostAppOptions<Args>): {
76
+ fetch: (request: Request, ...args: Args) => Promise<Response>;
77
+ };
78
+ //#endregion
79
+ //#region src/shared/manifest.d.ts
80
+ /** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
81
+ declare const MANIFEST_PATH = "/ghost-app.json";
82
+ //#endregion
83
+ //#region src/backend/manifest.d.ts
84
+ /**
85
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
86
+ * file. Pass the file's text as it is, or the object it holds.
87
+ *
88
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
89
+ * Ghost the next time Ghost reads it.
90
+ */
91
+ declare function serveManifest(signed: SignedManifest | string): Response;
92
+ //#endregion
93
+ export { type BackendKey, CHALLENGE_PATH, type FetchHandler, type GhostAppOptions, type HandleChallengeOptions, MANIFEST_PATH, type SignedManifest, handleChallenge, serveManifest, withGhostApp };
@@ -0,0 +1,202 @@
1
+ import { a as ALGORITHM, i as publicHalfOf, r as ignoreError, t as MANIFEST_PATH } from "./chunks/manifest-DmfZ-0r7.js";
2
+ import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
3
+ import { CompactSign, base64url } from "jose";
4
+ import { z } from "zod";
5
+ //#region ../../contracts/app-contracts/build/identity/challenge.js
6
+ /** Where on an origin Ghost posts a challenge. */
7
+ var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
8
+ /** What a challenge is for, signed with it, so its answer can't pass for any other signature. */
9
+ var CHALLENGE_PURPOSE = "ghost-app-challenge";
10
+ z.strictObject({ alg: z.literal(ALGORITHM) });
11
+ JSON.stringify({ alg: ALGORITHM });
12
+ var ChallengeShape = z.strictObject({
13
+ purpose: z.literal(CHALLENGE_PURPOSE),
14
+ origin: z.string(),
15
+ nonce: z.string()
16
+ });
17
+ z.object({ signature: z.string() });
18
+ /**
19
+ * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is
20
+ * the URL the request arrived at, as the platform reports it (`request.url` on Workers):
21
+ * never one built from `X-Forwarded-Host` or any other header the sender controls. A
22
+ * challenge for any origin but that one is refused, so whoever takes over a name the app
23
+ * used to serve can't relay Ghost's challenge to the real backend to prove it.
24
+ *
25
+ * Ghost can't see this check, so it only helps where the platform routes requests by host,
26
+ * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.
27
+ */
28
+ async function answerChallenge(body, { backendKey, requestUrl }) {
29
+ const challenge = ChallengeShape.safeParse(parseJson(body));
30
+ if (!challenge.success) return {
31
+ success: false,
32
+ error: "Expected a challenge of {purpose, origin, nonce}"
33
+ };
34
+ const arrivedAt = URL.parse(requestUrl)?.origin;
35
+ if (arrivedAt !== challenge.data.origin) return {
36
+ success: false,
37
+ error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? "an unknown origin"}`
38
+ };
39
+ return {
40
+ success: true,
41
+ answer: { signature: await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: ALGORITHM }).sign(backendKey) }
42
+ };
43
+ }
44
+ function parseJson(text) {
45
+ try {
46
+ return JSON.parse(text);
47
+ } catch {
48
+ return;
49
+ }
50
+ }
51
+ //#endregion
52
+ //#region src/shared/body.ts
53
+ /**
54
+ * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
55
+ * stops reading as soon as the body passes the limit, so a large body is never held whole.
56
+ */
57
+ async function readBytes(message, maxBytes) {
58
+ if (Number(message.headers.get("content-length")) > maxBytes) {
59
+ message.body?.cancel().catch(ignoreError);
60
+ return;
61
+ }
62
+ if (!message.body) return /* @__PURE__ */ new Uint8Array();
63
+ const reader = message.body.getReader();
64
+ const chunks = [];
65
+ let length = 0;
66
+ for (;;) {
67
+ const { done, value } = await reader.read();
68
+ if (done) break;
69
+ length += value.byteLength;
70
+ if (length > maxBytes) {
71
+ reader.cancel().catch(ignoreError);
72
+ return;
73
+ }
74
+ chunks.push(value);
75
+ }
76
+ const bytes = new Uint8Array(length);
77
+ let offset = 0;
78
+ for (const chunk of chunks) {
79
+ bytes.set(chunk, offset);
80
+ offset += chunk.byteLength;
81
+ }
82
+ return bytes;
83
+ }
84
+ //#endregion
85
+ //#region src/backend/body.ts
86
+ /**
87
+ * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
88
+ * UTF-8 throws, as the exact text matters to whoever signs it.
89
+ */
90
+ async function readText(request, maxBytes) {
91
+ const bytes = await readBytes(request, maxBytes);
92
+ return bytes && new TextDecoder("utf-8", {
93
+ fatal: true,
94
+ ignoreBOM: true
95
+ }).decode(bytes);
96
+ }
97
+ function json(status, body, headers = {}) {
98
+ return new Response(JSON.stringify(body), {
99
+ status,
100
+ headers: {
101
+ "content-type": "application/json; charset=utf-8",
102
+ "cache-control": "no-store",
103
+ ...headers
104
+ }
105
+ });
106
+ }
107
+ //#endregion
108
+ //#region src/backend/challenge.ts
109
+ var CHALLENGE_MAX_BYTES = 4 * 1024;
110
+ var INVALID_KEY = "backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d";
111
+ var imported;
112
+ function importBackendKey(backendKey) {
113
+ const text = typeof backendKey === "string" ? backendKey : JSON.stringify(backendKey);
114
+ if (imported?.text !== text) {
115
+ const key = importPrivateKey(text);
116
+ imported = {
117
+ text,
118
+ key
119
+ };
120
+ key.catch(() => {
121
+ if (imported?.key === key) imported = void 0;
122
+ });
123
+ }
124
+ return imported.key;
125
+ }
126
+ async function importPrivateKey(text) {
127
+ let jwk;
128
+ try {
129
+ jwk = JSON.parse(text);
130
+ } catch {
131
+ throw new TypeError(`${INVALID_KEY}; it isn't JSON`);
132
+ }
133
+ const { kty, crv, x, d } = typeof jwk === "object" && jwk !== null ? jwk : {};
134
+ if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") throw new TypeError(INVALID_KEY);
135
+ try {
136
+ if (await publicHalfOf(base64url.decode(d)) === x) return await crypto.subtle.importKey("jwk", {
137
+ kty,
138
+ crv,
139
+ x,
140
+ d
141
+ }, { name: "Ed25519" }, false, ["sign"]);
142
+ } catch (error) {
143
+ throw new TypeError(INVALID_KEY, { cause: error });
144
+ }
145
+ throw new TypeError("backendKey is invalid because its x and d are from different keys");
146
+ }
147
+ /**
148
+ * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
149
+ * to it, or use `withGhostApp`, which does.
150
+ */
151
+ async function handleChallenge(request, { backendKey, origin }) {
152
+ const publicOrigin = origin === void 0 ? void 0 : parseOrigin(origin);
153
+ if (origin !== void 0 && !publicOrigin) throw new TypeError(`Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`);
154
+ if (request.method !== "POST") return json(405, { error: "Expected a POST" }, { allow: "POST" });
155
+ let body;
156
+ try {
157
+ body = await readText(request, CHALLENGE_MAX_BYTES);
158
+ } catch {
159
+ return json(400, { error: "Expected a challenge in UTF-8" });
160
+ }
161
+ if (body === void 0) return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });
162
+ const key = await importBackendKey(backendKey);
163
+ const result = await answerChallenge(body, {
164
+ backendKey: key,
165
+ requestUrl: publicOrigin ?? request.url
166
+ });
167
+ if (!result.success) return json(400, { error: result.error });
168
+ return json(200, result.answer);
169
+ }
170
+ //#endregion
171
+ //#region src/backend/app.ts
172
+ /**
173
+ * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
174
+ * passes every other request to `fetch`, with whatever else the platform passes.
175
+ *
176
+ * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
177
+ */
178
+ function withGhostApp({ fetch, ...challenge }) {
179
+ return { async fetch(request, ...args) {
180
+ if (new URL(request.url).pathname === "/.well-known/ghost-app/challenge") return handleChallenge(request, challenge);
181
+ return fetch(request, ...args);
182
+ } };
183
+ }
184
+ //#endregion
185
+ //#region src/backend/manifest.ts
186
+ /**
187
+ * A response that serves the signed manifest, for a backend that doesn't serve it as a static
188
+ * file. Pass the file's text as it is, or the object it holds.
189
+ *
190
+ * Caches may keep it, but must check it's still current each time, so a new manifest reaches
191
+ * Ghost the next time Ghost reads it.
192
+ */
193
+ function serveManifest(signed) {
194
+ return new Response(typeof signed === "string" ? signed : JSON.stringify(signed), { headers: {
195
+ "content-type": "application/json; charset=utf-8",
196
+ "cache-control": "no-cache"
197
+ } });
198
+ }
199
+ //#endregion
200
+ export { CHALLENGE_PATH, MANIFEST_PATH, handleChallenge, serveManifest, withGhostApp };
201
+
202
+ //# sourceMappingURL=backend.js.map