@tryghost/app-sdk 0.1.0-alpha.1 → 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +251 -29
- package/build/backend.d.ts +89 -0
- package/build/backend.js +200 -0
- package/build/backend.js.map +1 -0
- package/build/bin.d.ts +1 -0
- package/build/bin.js +124 -0
- package/build/bin.js.map +1 -0
- package/build/chunks/manifest-B9vQoSfm.js +43 -0
- package/build/chunks/manifest-B9vQoSfm.js.map +1 -0
- package/build/chunks/manifest-DFLCKcwH.d.ts +19 -0
- package/build/chunks/rules-_dou3jRF.js +159 -0
- package/build/chunks/rules-_dou3jRF.js.map +1 -0
- package/build/chunks/sign-Deg9TCUr.js +869 -0
- package/build/chunks/sign-Deg9TCUr.js.map +1 -0
- package/build/index.d.ts +19 -5
- package/build/index.js +40 -176
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +148 -0
- package/build/tooling.js +3 -0
- package/build/vite.d.ts +29 -0
- package/build/vite.js +228 -0
- package/build/vite.js.map +1 -0
- package/dist/app-sdk.js +40 -24
- package/dist/app-sdk.js.map +1 -1
- package/package.json +32 -3
package/README.md
CHANGED
|
@@ -1,13 +1,24 @@
|
|
|
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, from their
|
|
4
|
+
backend, and from their tooling.
|
|
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
|
+
| `@tryghost/app-sdk/tooling` | Node 22.12 or later | [Creating keys, and signing the manifest](#signing-the-manifest) |
|
|
15
|
+
| `@tryghost/app-sdk/vite` | Vite 6 or later | [Signing the manifest in `vite dev` and `vite build`](#the-vite-plugin) |
|
|
16
|
+
| `ghost-app` | Node 22.12 or later | [The same tooling on the command line](#the-ghost-app-cli) |
|
|
17
|
+
|
|
18
|
+
The page's entry point loads none of the others' code.
|
|
19
|
+
|
|
9
20
|
> **Alpha.** CI publishes each change to npm as the next `0.1.0-alpha.N` under
|
|
10
|
-
> the `
|
|
21
|
+
> the `latest` tag. Alphas make no compatibility promise.
|
|
11
22
|
|
|
12
23
|
## Quick start
|
|
13
24
|
|
|
@@ -29,10 +40,11 @@ ES module with everything inlined:
|
|
|
29
40
|
```
|
|
30
41
|
|
|
31
42
|
With a bundler, install the package. It includes the types and code it uses
|
|
32
|
-
from Ghost's contracts
|
|
43
|
+
from Ghost's contracts. The page needs only `@quilted/threads`, and the backend
|
|
44
|
+
adds `jose` and `zod`:
|
|
33
45
|
|
|
34
46
|
```sh
|
|
35
|
-
pnpm add @tryghost/app-sdk
|
|
47
|
+
pnpm add @tryghost/app-sdk
|
|
36
48
|
```
|
|
37
49
|
|
|
38
50
|
```ts
|
|
@@ -251,24 +263,216 @@ documents in a row, each replaced within three seconds of starting. A publisher
|
|
|
251
263
|
clicking quickly through more than five pages of a multi-page app would trip it
|
|
252
264
|
too.
|
|
253
265
|
|
|
254
|
-
##
|
|
266
|
+
## Signing the manifest
|
|
267
|
+
|
|
268
|
+
Ghost installs an app from its manifest URL, where the app serves a signed
|
|
269
|
+
manifest: its `ghost-app.json`, with the fields below added, signed with the
|
|
270
|
+
app's identity key. Ghost pins that key when a site installs the app, and
|
|
271
|
+
challenges the app's origin to prove it holds the backend key the manifest
|
|
272
|
+
names. The manifest format is in
|
|
273
|
+
[`@tryghost/app-contracts`](../app-contracts/README.md#the-manifest).
|
|
274
|
+
|
|
275
|
+
`ghost-app.json` is the readable part, which the project keeps:
|
|
276
|
+
|
|
277
|
+
```json
|
|
278
|
+
{
|
|
279
|
+
"id": "com.example.hello",
|
|
280
|
+
"name": "Hello",
|
|
281
|
+
"description": "Says hello.",
|
|
282
|
+
"author": { "name": "Example", "url": "https://example.com" },
|
|
283
|
+
"accent_color": "#ff5500",
|
|
284
|
+
"icon": { "name": "hand" },
|
|
285
|
+
"surfaces": [{ "type": "admin_page", "url": "/" }]
|
|
286
|
+
}
|
|
287
|
+
```
|
|
255
288
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
289
|
+
Signing adds `manifest_url` (the address it's signed for), `identity_key` and
|
|
290
|
+
`backend_key` (the public keys) and `development`, and refuses a file that sets
|
|
291
|
+
any of them. It checks the manifest with the rules Ghost applies first, so a
|
|
292
|
+
manifest Ghost would refuse is never signed: the error lists every problem by
|
|
293
|
+
field. Ghost also refuses a manifest on the site's or Admin's host, on any port,
|
|
294
|
+
which only Ghost knows. To check a signed app end to end, install it on a Ghost
|
|
295
|
+
site, which fetches and verifies the manifest, challenges the backend, and says
|
|
296
|
+
why if it refuses.
|
|
297
|
+
|
|
298
|
+
### Keys
|
|
299
|
+
|
|
300
|
+
Each mode has its own identity key and backend key, as two pairs of private
|
|
301
|
+
Ed25519 JWKs, in files only their owner can read:
|
|
302
|
+
|
|
303
|
+
- `.ghost-app/development/identity.json` and `backend.json`, for `vite dev`
|
|
304
|
+
and apps on this machine, such as on `my-app.localhost`, which `ghost-app keys`
|
|
305
|
+
or the Vite plugin's first run creates;
|
|
306
|
+
- `.ghost-app/production/identity.json` and `backend.json`, which only
|
|
307
|
+
`ghost-app keys --production` creates.
|
|
308
|
+
|
|
309
|
+
Only the owner can read a key on macOS and Linux. On Windows, a key gets the
|
|
310
|
+
permissions of the folder it's in, so keep the project in a folder only you can
|
|
311
|
+
read.
|
|
312
|
+
|
|
313
|
+
Keys are created only when git ignores `.ghost-app/` (in a repository), and an
|
|
314
|
+
existing key is never replaced. Keep a copy of the production identity key
|
|
315
|
+
somewhere safe: sites keep the identity key they installed an app with, and a
|
|
316
|
+
manifest signed with another one is another app. A development installation
|
|
317
|
+
and a production one are different apps for the same reason, so going from your
|
|
318
|
+
computer to a host means installing the app again.
|
|
319
|
+
|
|
320
|
+
The identity key stays with the developer, or CI. It never reaches the backend
|
|
321
|
+
or a build: only the signed manifest is served or emitted. The backend key goes
|
|
322
|
+
to the backend, which answers challenges with it. Developers who share a
|
|
323
|
+
development identity key must share its backend key too: a new backend key
|
|
324
|
+
retires the old one on every site that reads the new manifest.
|
|
325
|
+
|
|
326
|
+
In CI, set `GHOST_APP_IDENTITY_KEY` to the production identity key and
|
|
327
|
+
`GHOST_APP_BACKEND_KEY` to the backend key's public half, which
|
|
328
|
+
`ghost-app backend-key --production --public` prints, in place of the files. CI
|
|
329
|
+
only signs, so it never needs the backend's private key.
|
|
330
|
+
|
|
331
|
+
### The Vite plugin
|
|
261
332
|
|
|
262
|
-
|
|
263
|
-
|
|
333
|
+
```ts
|
|
334
|
+
import { cloudflare } from '@cloudflare/vite-plugin';
|
|
335
|
+
import { ghostApp } from '@tryghost/app-sdk/vite';
|
|
336
|
+
import { defineConfig } from 'vite';
|
|
337
|
+
|
|
338
|
+
export default defineConfig({ plugins: [ghostApp(), cloudflare()] });
|
|
339
|
+
```
|
|
264
340
|
|
|
265
|
-
|
|
266
|
-
|
|
341
|
+
In `vite dev`, the plugin creates the development keys if there are none, and
|
|
342
|
+
serves `/ghost-app.json` signed for the address it's requested at: a name for
|
|
343
|
+
this machine, such as `localhost`, `127.0.0.1` or any `.localhost` name, or a
|
|
344
|
+
tunnel named by the `tunnelUrl` option or `GHOST_APP_TUNNEL_URL`
|
|
345
|
+
(comma-separated). It refuses any other host with a 421, so the dev server never
|
|
346
|
+
signs a manifest for someone else's address. Ghost in Docker reaches the machine
|
|
347
|
+
through `host.docker.internal` with the original Host, which counts as the
|
|
348
|
+
machine. It prints the app at a name of its own under `.localhost`, from the
|
|
349
|
+
last part of its ID, such as
|
|
350
|
+
`http://hello-world.localhost:<port>/ghost-app.json` for
|
|
351
|
+
`org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host
|
|
352
|
+
on any port. It prints the install link too, for `GHOST_URL` or
|
|
353
|
+
`http://localhost:2368`.
|
|
354
|
+
|
|
355
|
+
The dev server is for development only. The plugin adds `.ghost-app/`,
|
|
356
|
+
`.dev.vars*`, `.env` and `.env.*` to Vite's `server.fs.deny`, and refuses to
|
|
357
|
+
start with `server.fs.strict` off, which would make Vite skip that list. In dev
|
|
358
|
+
and in a build, it refuses an `envPrefix` that the key variables start with, such as
|
|
359
|
+
`GHOST_APP_`, which would put the keys in the page's bundle. Like Vite's own
|
|
360
|
+
`.env` protection, the list matches files by name: a link or alias you make to
|
|
361
|
+
the keys elsewhere in the project is served like any other file. Keep the keys
|
|
362
|
+
out of `publicDir`, which Vite serves and copies into the build as it is.
|
|
363
|
+
|
|
364
|
+
In a Cloudflare Workers project (one with a `wrangler.json`, `wrangler.jsonc`
|
|
365
|
+
or `wrangler.toml`), it adds `GHOST_APP_BACKEND_KEY` to `.dev.vars` with the
|
|
366
|
+
development backend key, so the Worker answers challenges in development as it
|
|
367
|
+
does in production. It never changes a value that's already there, and says so
|
|
368
|
+
when it isn't the development key. Wrangler reads `.env` and `.env.local` only
|
|
369
|
+
when there's no `.dev.vars`, so in a project with either and no `.dev.vars`, it
|
|
370
|
+
asks you to add the key to `.env.local` instead. Git must ignore whichever file
|
|
371
|
+
holds it.
|
|
372
|
+
|
|
373
|
+
In `vite build`, it signs `ghost-app.json` for `GHOST_APP_URL`, the app's public
|
|
374
|
+
address (the manifest is at `<GHOST_APP_URL>/ghost-app.json`), with the
|
|
375
|
+
production keys, and emits it with the client build. A missing key fails the
|
|
376
|
+
build with how to create one; the plugin never creates a production key.
|
|
377
|
+
Without `GHOST_APP_URL`, the build emits no manifest and warns, and deploying
|
|
378
|
+
it takes the app down wherever it's installed.
|
|
379
|
+
|
|
380
|
+
The plugin reads `GHOST_APP_URL`, `GHOST_APP_TUNNEL_URL` and `GHOST_URL` from
|
|
381
|
+
the environment, or from the mode's `.env` files as Vite reads them; the
|
|
382
|
+
environment wins. `.env.development` is the easy way to name a tunnel or your
|
|
383
|
+
Ghost in development, on Windows too. Commit the app's address in `.env.production` once it has
|
|
384
|
+
one, so no deploy can forget it:
|
|
385
|
+
|
|
386
|
+
```sh
|
|
387
|
+
GHOST_APP_URL=https://hello.example.com
|
|
267
388
|
```
|
|
268
389
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
390
|
+
List the plugin before `cloudflare()`. `options.manifest` names another file
|
|
391
|
+
than `ghost-app.json`.
|
|
392
|
+
|
|
393
|
+
### The ghost-app CLI
|
|
394
|
+
|
|
395
|
+
```sh
|
|
396
|
+
ghost-app keys [--production]
|
|
397
|
+
ghost-app sign --url <manifest URL> [--production] [--out <file>] [--manifest <file>]
|
|
398
|
+
ghost-app backend-key [--production] [--public | --check]
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
- `keys` creates the mode's keys, keeping any that exist.
|
|
402
|
+
- `sign` prints the signed manifest, or writes it to `--out`.
|
|
403
|
+
- `backend-key` prints the mode's private backend key, for a host's secret
|
|
404
|
+
store. It's the only command that prints a private key. `--public` prints
|
|
405
|
+
only its public half, for CI. `--check` prints nothing, and exits with 0
|
|
406
|
+
only if the key is there and usable, with the reason on stderr otherwise,
|
|
407
|
+
so a script can stop before piping nothing into a secret store, in any shell:
|
|
408
|
+
|
|
409
|
+
```sh
|
|
410
|
+
ghost-app backend-key --production --check && ghost-app backend-key --production | wrangler secret put GHOST_APP_BACKEND_KEY
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
`--dir` points any of them at another project directory.
|
|
414
|
+
|
|
415
|
+
### From code
|
|
416
|
+
|
|
417
|
+
`@tryghost/app-sdk/tooling` is what the CLI is built on, to sign from code:
|
|
418
|
+
|
|
419
|
+
| Export | What it does |
|
|
420
|
+
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
421
|
+
| `createKeys({ root, mode })` | Creates the mode's missing keys. Resolves with `{ created, kept }`. |
|
|
422
|
+
| `readSigningKeys({ root, mode, env? })` | The identity key and the backend key's public half, from the files or, in production, `env`. |
|
|
423
|
+
| `readBackendKey({ root, mode })` | The mode's private backend key. |
|
|
424
|
+
| `signProject({ root, mode, manifestUrl, manifestFile? })` | Signs the project's `ghost-app.json` with the mode's keys. |
|
|
425
|
+
| `signAppManifest(source, { manifestUrl, identityKey, backendKey, development })` | Signs a manifest with the keys given. |
|
|
426
|
+
| `generateKey()`, `publicKeyOf(key)` | A new private key, and a key's public half. |
|
|
427
|
+
|
|
428
|
+
Signing resolves with `{ success: true, signed, manifest }`, or
|
|
429
|
+
`{ success: false, code, errors }`.
|
|
430
|
+
|
|
431
|
+
## The backend
|
|
432
|
+
|
|
433
|
+
`@tryghost/app-sdk/backend` uses only `Request`, `Response`, `fetch` and
|
|
434
|
+
WebCrypto, so the same code runs on Cloudflare Workers, Node, Bun and Deno, and
|
|
435
|
+
in frameworks such as Hono. Configuration is passed in.
|
|
436
|
+
|
|
437
|
+
`withGhostApp` is the app's backend. It answers Ghost's challenge itself and
|
|
438
|
+
passes every other request to `fetch`. It returns `{ fetch }`, so a Worker
|
|
439
|
+
exports it as it is, reading its configuration from `cloudflare:workers`:
|
|
440
|
+
|
|
441
|
+
```ts
|
|
442
|
+
import { env } from 'cloudflare:workers';
|
|
443
|
+
import { withGhostApp } from '@tryghost/app-sdk/backend';
|
|
444
|
+
|
|
445
|
+
export default withGhostApp({
|
|
446
|
+
backendKey: env.GHOST_APP_BACKEND_KEY,
|
|
447
|
+
fetch: (request) => env.ASSETS.fetch(request),
|
|
448
|
+
});
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
It takes `handleChallenge`'s options and `fetch`, which gets whatever else the
|
|
452
|
+
platform passes too, such as a Worker's `env` and `ctx`. Frameworks that route
|
|
453
|
+
requests themselves, such as Hono, use `handleChallenge` directly.
|
|
454
|
+
|
|
455
|
+
| Export | What it does |
|
|
456
|
+
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
457
|
+
| `withGhostApp({ backendKey, fetch })` | The app's backend, as `{ fetch }`: answers the challenge at `CHALLENGE_PATH` with `handleChallenge`, and passes every other request to `fetch`. |
|
|
458
|
+
| `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. |
|
|
459
|
+
| `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. |
|
|
460
|
+
|
|
461
|
+
`handleChallenge` refuses a challenge for any origin but the one the platform
|
|
462
|
+
reports in `request.url`, so pass the request as the platform hands it over,
|
|
463
|
+
never one rebuilt from `X-Forwarded-Host`. A server that doesn't see the public
|
|
464
|
+
scheme and host, such as Node behind a proxy that terminates TLS, passes the
|
|
465
|
+
app's public origin as `origin` (`https://app.example.com`), from its own
|
|
466
|
+
configuration, never from a request's headers. Workers don't need it.
|
|
467
|
+
|
|
468
|
+
## Who can frame the page
|
|
469
|
+
|
|
470
|
+
The SDK talks to whichever window frames the page, and can't yet tell whether
|
|
471
|
+
it's Ghost Admin. A site that frames the page can send it a start context of
|
|
472
|
+
its choosing and answer every `fetch` itself. No Ghost credential is ever in the
|
|
473
|
+
page, but whatever the publisher types into the page reaches that site, and the
|
|
474
|
+
app acts on the responses it gets. Ghost will close this by vouching for the
|
|
475
|
+
site and the staff user to the app's backend.
|
|
272
476
|
|
|
273
477
|
## Serve only the app from its origin
|
|
274
478
|
|
|
@@ -280,15 +484,25 @@ content and third-party pages or widgets on another origin (a separate subdomain
|
|
|
280
484
|
counts). An open redirect is a risk too: a link through it puts another site's
|
|
281
485
|
page in the frame, inside Admin.
|
|
282
486
|
|
|
487
|
+
Serve the app from a host of its own, too. Ghost refuses an app on the site's
|
|
488
|
+
or Admin's host, whatever the port, because browsers send a host's cookies to
|
|
489
|
+
every port on it, Ghost's session cookie included. On your own machine, serve
|
|
490
|
+
the app from a name of its own under `.localhost`, such as `my-app.localhost`.
|
|
491
|
+
Browsers treat it as another host and send it to the machine itself, Vite
|
|
492
|
+
accepts it with no setup, and Ghost in development reaches it even where the
|
|
493
|
+
system's resolver doesn't know it. Open Admin on the name Ghost is configured
|
|
494
|
+
with, as Admin refuses an app on the host it's opened from too.
|
|
495
|
+
|
|
283
496
|
## Develop
|
|
284
497
|
|
|
285
498
|
This is a workspace package in the Ghost monorepo. From the package directory:
|
|
286
499
|
|
|
287
500
|
```bash
|
|
288
501
|
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
|
|
290
|
-
#
|
|
291
|
-
# to
|
|
502
|
+
pnpm test # type-check + unit tests (jsdom for the page, with a fake Admin on a real
|
|
503
|
+
# MessageChannel; Node for the backend, tooling, CLI and plugin), which build both
|
|
504
|
+
# afresh to check what they import, and pack build/ and dist/ to use them from an
|
|
505
|
+
# app outside the workspace (after pnpm build; Nx runs it)
|
|
292
506
|
pnpm lint # lint source and tests
|
|
293
507
|
```
|
|
294
508
|
|
|
@@ -298,14 +512,22 @@ and also writes `dist/`, which is in `files` and in the Nx build outputs.
|
|
|
298
512
|
|
|
299
513
|
It uses `@tryghost/app-contracts` for the bridge's message types, limits and
|
|
300
514
|
shape checks, so the SDK and Admin apply the same rules to paths, themes and
|
|
301
|
-
start contexts
|
|
302
|
-
|
|
303
|
-
are a dev dependency
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
- `
|
|
307
|
-
|
|
515
|
+
start contexts, and for signing and checking manifests and challenges, so the
|
|
516
|
+
tooling and the backend apply Ghost's own rules. The build inlines what it uses
|
|
517
|
+
into the SDK, so the contracts are a dev dependency. `build/` has an ES module
|
|
518
|
+
per entry point, which share chunks:
|
|
519
|
+
|
|
520
|
+
- `index.js` loads only `@quilted/threads`, never `jose`, `zod` or a Node
|
|
521
|
+
builtin;
|
|
522
|
+
- `backend.js` loads only `jose` and `zod`, and no Node builtin;
|
|
523
|
+
- `tooling.js`, `vite.js` and `bin.js` load Node builtins, `jose` and `zod`, and
|
|
524
|
+
`bin.js` `commander` too; `vite.js` imports Vite only when Vite runs the
|
|
525
|
+
plugin, not when it loads, as Vite is an optional peer dependency;
|
|
526
|
+
- each entry point's declarations, emitted by TypeScript 7 and bundled by
|
|
527
|
+
`rolldown-plugin-dts`, import nothing, but Vite's types for `vite.d.ts`;
|
|
308
528
|
- `dist/` imports nothing at all.
|
|
309
529
|
|
|
310
|
-
`test/bundle.test.ts` checks this on a fresh build. The build
|
|
311
|
-
imports a
|
|
530
|
+
`test/bundle.test.ts` checks this on a fresh build. The build keeps `node:`
|
|
531
|
+
imports as imports, so a builtin the page or the backend reaches shows up there.
|
|
532
|
+
Lint requires the `node:` prefix, as Vite replaces a builtin imported without it
|
|
533
|
+
with an empty stub.
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { r as SignedManifest, t as MANIFEST_PATH } from "./chunks/manifest-DFLCKcwH.js";
|
|
2
|
+
//#region ../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/backend/manifest.d.ts
|
|
80
|
+
/**
|
|
81
|
+
* A response that serves the signed manifest, for a backend that doesn't serve it as a static
|
|
82
|
+
* file. Pass the file's text as it is, or the object it holds.
|
|
83
|
+
*
|
|
84
|
+
* Caches may keep it, but must check it's still current each time, so a new manifest reaches
|
|
85
|
+
* Ghost the next time Ghost reads it.
|
|
86
|
+
*/
|
|
87
|
+
declare function serveManifest(signed: SignedManifest | string): Response;
|
|
88
|
+
//#endregion
|
|
89
|
+
export { type BackendKey, CHALLENGE_PATH, type FetchHandler, type GhostAppOptions, type HandleChallengeOptions, MANIFEST_PATH, type SignedManifest, handleChallenge, serveManifest, withGhostApp };
|
package/build/backend.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { i as ignoreError, o as parseOrigin, s as ALGORITHM, t as MANIFEST_PATH } from "./chunks/manifest-B9vQoSfm.js";
|
|
2
|
+
import { CompactSign } from "jose";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region ../app-contracts/build/identity/challenge.js
|
|
5
|
+
/** Where on an origin Ghost posts a challenge. */
|
|
6
|
+
var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
|
|
7
|
+
/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */
|
|
8
|
+
var CHALLENGE_PURPOSE = "ghost-app-challenge";
|
|
9
|
+
z.strictObject({ alg: z.literal(ALGORITHM) });
|
|
10
|
+
JSON.stringify({ alg: ALGORITHM });
|
|
11
|
+
var ChallengeShape = z.strictObject({
|
|
12
|
+
purpose: z.literal(CHALLENGE_PURPOSE),
|
|
13
|
+
origin: z.string(),
|
|
14
|
+
nonce: z.string()
|
|
15
|
+
});
|
|
16
|
+
z.object({ signature: z.string() });
|
|
17
|
+
/**
|
|
18
|
+
* Answers a challenge a backend received, signing it with the backend key. `requestUrl` is
|
|
19
|
+
* the URL the request arrived at, as the platform reports it (`request.url` on Workers):
|
|
20
|
+
* never one built from `X-Forwarded-Host` or any other header the sender controls. A
|
|
21
|
+
* challenge for any origin but that one is refused, so whoever takes over a name the app
|
|
22
|
+
* used to serve can't relay Ghost's challenge to the real backend to prove it.
|
|
23
|
+
*
|
|
24
|
+
* Ghost can't see this check, so it only helps where the platform routes requests by host,
|
|
25
|
+
* as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.
|
|
26
|
+
*/
|
|
27
|
+
async function answerChallenge(body, { backendKey, requestUrl }) {
|
|
28
|
+
const challenge = ChallengeShape.safeParse(parseJson(body));
|
|
29
|
+
if (!challenge.success) return {
|
|
30
|
+
success: false,
|
|
31
|
+
error: "Expected a challenge of {purpose, origin, nonce}"
|
|
32
|
+
};
|
|
33
|
+
const arrivedAt = URL.parse(requestUrl)?.origin;
|
|
34
|
+
if (arrivedAt !== challenge.data.origin) return {
|
|
35
|
+
success: false,
|
|
36
|
+
error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? "an unknown origin"}`
|
|
37
|
+
};
|
|
38
|
+
return {
|
|
39
|
+
success: true,
|
|
40
|
+
answer: { signature: await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: ALGORITHM }).sign(backendKey) }
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function parseJson(text) {
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(text);
|
|
46
|
+
} catch {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/shared/body.ts
|
|
52
|
+
/**
|
|
53
|
+
* Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
|
|
54
|
+
* stops reading as soon as the body passes the limit, so a large body is never held whole.
|
|
55
|
+
*/
|
|
56
|
+
async function readBytes(message, maxBytes) {
|
|
57
|
+
if (Number(message.headers.get("content-length")) > maxBytes) {
|
|
58
|
+
message.body?.cancel().catch(ignoreError);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (!message.body) return /* @__PURE__ */ new Uint8Array();
|
|
62
|
+
const reader = message.body.getReader();
|
|
63
|
+
const chunks = [];
|
|
64
|
+
let length = 0;
|
|
65
|
+
for (;;) {
|
|
66
|
+
const { done, value } = await reader.read();
|
|
67
|
+
if (done) break;
|
|
68
|
+
length += value.byteLength;
|
|
69
|
+
if (length > maxBytes) {
|
|
70
|
+
reader.cancel().catch(ignoreError);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
chunks.push(value);
|
|
74
|
+
}
|
|
75
|
+
const bytes = new Uint8Array(length);
|
|
76
|
+
let offset = 0;
|
|
77
|
+
for (const chunk of chunks) {
|
|
78
|
+
bytes.set(chunk, offset);
|
|
79
|
+
offset += chunk.byteLength;
|
|
80
|
+
}
|
|
81
|
+
return bytes;
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/backend/body.ts
|
|
85
|
+
/**
|
|
86
|
+
* Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
|
|
87
|
+
* UTF-8 throws, as the exact text matters to whoever signs it.
|
|
88
|
+
*/
|
|
89
|
+
async function readText(request, maxBytes) {
|
|
90
|
+
const bytes = await readBytes(request, maxBytes);
|
|
91
|
+
return bytes && new TextDecoder("utf-8", {
|
|
92
|
+
fatal: true,
|
|
93
|
+
ignoreBOM: true
|
|
94
|
+
}).decode(bytes);
|
|
95
|
+
}
|
|
96
|
+
function json(status, body, headers = {}) {
|
|
97
|
+
return new Response(JSON.stringify(body), {
|
|
98
|
+
status,
|
|
99
|
+
headers: {
|
|
100
|
+
"content-type": "application/json; charset=utf-8",
|
|
101
|
+
"cache-control": "no-store",
|
|
102
|
+
...headers
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/backend/challenge.ts
|
|
108
|
+
var CHALLENGE_MAX_BYTES = 4 * 1024;
|
|
109
|
+
var INVALID_KEY = "backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d";
|
|
110
|
+
var imported;
|
|
111
|
+
function importBackendKey(backendKey) {
|
|
112
|
+
const text = typeof backendKey === "string" ? backendKey : JSON.stringify(backendKey);
|
|
113
|
+
if (imported?.text !== text) {
|
|
114
|
+
const key = importPrivateKey(text);
|
|
115
|
+
imported = {
|
|
116
|
+
text,
|
|
117
|
+
key
|
|
118
|
+
};
|
|
119
|
+
key.catch(() => {
|
|
120
|
+
if (imported?.key === key) imported = void 0;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return imported.key;
|
|
124
|
+
}
|
|
125
|
+
async function importPrivateKey(text) {
|
|
126
|
+
let jwk;
|
|
127
|
+
try {
|
|
128
|
+
jwk = JSON.parse(text);
|
|
129
|
+
} catch {
|
|
130
|
+
throw new TypeError(`${INVALID_KEY}; it isn't JSON`);
|
|
131
|
+
}
|
|
132
|
+
const { kty, crv, x, d } = typeof jwk === "object" && jwk !== null ? jwk : {};
|
|
133
|
+
if (kty !== "OKP" || crv !== "Ed25519" || typeof x !== "string" || typeof d !== "string") throw new TypeError(INVALID_KEY);
|
|
134
|
+
try {
|
|
135
|
+
return await crypto.subtle.importKey("jwk", {
|
|
136
|
+
kty,
|
|
137
|
+
crv,
|
|
138
|
+
x,
|
|
139
|
+
d
|
|
140
|
+
}, { name: "Ed25519" }, false, ["sign"]);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
throw new TypeError(INVALID_KEY, { cause: error });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`
|
|
147
|
+
* to it, or use `withGhostApp`, which does.
|
|
148
|
+
*/
|
|
149
|
+
async function handleChallenge(request, { backendKey, origin }) {
|
|
150
|
+
const publicOrigin = origin === void 0 ? void 0 : parseOrigin(origin);
|
|
151
|
+
if (origin !== void 0 && !publicOrigin) throw new TypeError(`Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`);
|
|
152
|
+
if (request.method !== "POST") return json(405, { error: "Expected a POST" }, { allow: "POST" });
|
|
153
|
+
let body;
|
|
154
|
+
try {
|
|
155
|
+
body = await readText(request, CHALLENGE_MAX_BYTES);
|
|
156
|
+
} catch {
|
|
157
|
+
return json(400, { error: "Expected a challenge in UTF-8" });
|
|
158
|
+
}
|
|
159
|
+
if (body === void 0) return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });
|
|
160
|
+
const key = await importBackendKey(backendKey);
|
|
161
|
+
const result = await answerChallenge(body, {
|
|
162
|
+
backendKey: key,
|
|
163
|
+
requestUrl: publicOrigin ?? request.url
|
|
164
|
+
});
|
|
165
|
+
if (!result.success) return json(400, { error: result.error });
|
|
166
|
+
return json(200, result.answer);
|
|
167
|
+
}
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region src/backend/app.ts
|
|
170
|
+
/**
|
|
171
|
+
* The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and
|
|
172
|
+
* passes every other request to `fetch`, with whatever else the platform passes.
|
|
173
|
+
*
|
|
174
|
+
* It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.
|
|
175
|
+
*/
|
|
176
|
+
function withGhostApp({ fetch, ...challenge }) {
|
|
177
|
+
return { async fetch(request, ...args) {
|
|
178
|
+
if (new URL(request.url).pathname === "/.well-known/ghost-app/challenge") return handleChallenge(request, challenge);
|
|
179
|
+
return fetch(request, ...args);
|
|
180
|
+
} };
|
|
181
|
+
}
|
|
182
|
+
//#endregion
|
|
183
|
+
//#region src/backend/manifest.ts
|
|
184
|
+
/**
|
|
185
|
+
* A response that serves the signed manifest, for a backend that doesn't serve it as a static
|
|
186
|
+
* file. Pass the file's text as it is, or the object it holds.
|
|
187
|
+
*
|
|
188
|
+
* Caches may keep it, but must check it's still current each time, so a new manifest reaches
|
|
189
|
+
* Ghost the next time Ghost reads it.
|
|
190
|
+
*/
|
|
191
|
+
function serveManifest(signed) {
|
|
192
|
+
return new Response(typeof signed === "string" ? signed : JSON.stringify(signed), { headers: {
|
|
193
|
+
"content-type": "application/json; charset=utf-8",
|
|
194
|
+
"cache-control": "no-cache"
|
|
195
|
+
} });
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
198
|
+
export { CHALLENGE_PATH, MANIFEST_PATH, handleChallenge, serveManifest, withGhostApp };
|
|
199
|
+
|
|
200
|
+
//# sourceMappingURL=backend.js.map
|