@tryghost/app-sdk 0.1.0-alpha.11 → 0.1.0-alpha.13
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 +31 -508
- package/build/bin.js +1 -1
- package/build/chunks/{sign-3ysEUyYt.js → sign-50Ayvddb.js} +4 -26
- package/build/chunks/sign-50Ayvddb.js.map +1 -0
- package/build/index.d.ts +28 -27
- package/build/index.js +2 -2
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +1 -1
- package/build/tooling.js +1 -1
- package/build/vite.js +1 -1
- package/dist/app-sdk.js +2 -2
- package/dist/app-sdk.js.map +1 -1
- package/package.json +1 -1
- package/build/chunks/sign-3ysEUyYt.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,533 +1,56 @@
|
|
|
1
1
|
# @tryghost/app-sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
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.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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.
|
|
9
11
|
|
|
10
|
-
|
|
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) |
|
|
12
|
+
## Get started
|
|
17
13
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
> the `latest` tag. Alphas make no compatibility promise.
|
|
22
|
-
|
|
23
|
-
## Quick start
|
|
24
|
-
|
|
25
|
-
Without a bundler, load the bundle (`dist/app-sdk.js` in the package), a single
|
|
26
|
-
ES module with everything inlined:
|
|
27
|
-
|
|
28
|
-
```html
|
|
29
|
-
<script type="module">
|
|
30
|
-
import { connect } from './app-sdk.js';
|
|
31
|
-
|
|
32
|
-
const ghost = await connect();
|
|
33
|
-
document.body.dataset.theme = ghost.theme.mode;
|
|
34
|
-
ghost.onThemeChange((theme) => (document.body.dataset.theme = theme.mode));
|
|
35
|
-
|
|
36
|
-
const response = await ghost.fetch('/posts/?limit=5');
|
|
37
|
-
const { posts } = await response.json();
|
|
38
|
-
document.title = `${posts.length} posts`; // Admin shows the title as its own
|
|
39
|
-
</script>
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
With a bundler, install the package. It includes the types and code it uses
|
|
43
|
-
from Ghost's contracts. The page needs only `@quilted/threads`, and the backend
|
|
44
|
-
adds `jose` and `zod`:
|
|
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/).
|
|
45
17
|
|
|
46
18
|
```sh
|
|
47
19
|
pnpm add @tryghost/app-sdk
|
|
48
20
|
```
|
|
49
21
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
try {
|
|
54
|
-
const ghost = await connect();
|
|
55
|
-
history.pushState(null, '', '/episodes/12'); // or your router's navigate(); Admin's URL follows
|
|
56
|
-
} catch (error) {
|
|
57
|
-
if (error instanceof GhostAppError && error.code === 'not_framed') {
|
|
58
|
-
// Opened outside Admin: show a link to the site's Admin instead.
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
## API
|
|
64
|
-
|
|
65
|
-
`connect(options?)` resolves with a `Ghost` once Admin has started the app. Call
|
|
66
|
-
it as soon as the page loads. Every call shares one connection. Load the SDK
|
|
67
|
-
only once per page: if a second copy calls `connect()`, it rejects with
|
|
68
|
-
`duplicate_sdk`. `options.timeout` is how long to wait, in milliseconds (10
|
|
69
|
-
seconds by default).
|
|
70
|
-
|
|
71
|
-
Admin connects each document in the frame only once. After Admin has replied,
|
|
72
|
-
that connection is the only one the page gets. If it fails or its session ends,
|
|
73
|
-
every `connect()` rejects with the error it ended with, until the page reloads.
|
|
74
|
-
A failure before Admin replied, such as `not_framed` or a timeout with no reply,
|
|
75
|
-
can be retried.
|
|
76
|
-
|
|
77
|
-
| `Ghost` | What it is |
|
|
78
|
-
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
79
|
-
| `site` | `{ url, title, timezone, locale }` |
|
|
80
|
-
| `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. |
|
|
81
|
-
| `theme` | `{ mode, accent_color }` that Admin currently uses. `mode` is `light` or `dark`, never `system`. |
|
|
82
|
-
| `onThemeChange(callback)` | Called with the new theme when the publisher switches. Returns a function that unsubscribes. |
|
|
83
|
-
| `session` | `{ revision }`: the installation's revision when the session started. |
|
|
84
|
-
| `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). |
|
|
85
|
-
| `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). |
|
|
86
|
-
| `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`. |
|
|
87
|
-
| `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. |
|
|
88
|
-
| `connected` | `false` once the session has ended. |
|
|
89
|
-
| `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. |
|
|
90
|
-
|
|
91
|
-
`site`, `user`, `session` and `theme` are frozen, so no part of the page can
|
|
92
|
-
change what the rest of it reads.
|
|
93
|
-
|
|
94
|
-
`fetch` takes `method` (any case), `headers` (anything `Headers` accepts) and
|
|
95
|
-
`body`, which is always JSON. Text is sent unchanged and must be JSON; an object
|
|
96
|
-
or array is sent as JSON. Admin labels it as JSON itself. A body on `GET`, a
|
|
97
|
-
binary body and the headers only Admin sets are refused: `cookie`,
|
|
98
|
-
`authorization`, `content-type`, `content-encoding`, `x-ghost-*`, `origin` and
|
|
99
|
-
similar. Any
|
|
100
|
-
status comes back as a `Response`. `fetch` rejects only when Admin refuses to
|
|
101
|
-
make the request.
|
|
102
|
-
|
|
103
|
-
### Admin API access
|
|
104
|
-
|
|
105
|
-
`fetch` reaches only these routes, grouped by the scope that will allow them once
|
|
106
|
-
apps have their own token. Anything else is refused as `blocked`. `:id` is an
|
|
107
|
-
object ID, 24 lowercase hexadecimal characters; a slug is one path segment.
|
|
108
|
-
|
|
109
|
-
| Scope | Routes |
|
|
110
|
-
| ------------------ | -------------------------------------------------------------------------------------- |
|
|
111
|
-
| `posts:read` | `GET /posts/`, `GET /posts/:id/`, `GET /posts/slug/:slug/`, `GET /search-index/posts/` |
|
|
112
|
-
| `posts:write` | `POST /posts/`, `PUT /posts/:id/`, `DELETE /posts/:id/` |
|
|
113
|
-
| `pages:read` | `GET /pages/`, `GET /pages/:id/`, `GET /pages/slug/:slug/`, `GET /search-index/pages/` |
|
|
114
|
-
| `pages:write` | `POST /pages/`, `PUT /pages/:id/`, `DELETE /pages/:id/` |
|
|
115
|
-
| `tags:read` | `GET /tags/`, `GET /tags/:id/`, `GET /tags/slug/:slug/`, `GET /search-index/tags/` |
|
|
116
|
-
| `tags:write` | `POST /tags/`, `PUT /tags/:id/`, `DELETE /tags/:id/` |
|
|
117
|
-
| `users:read` | `GET /users/` |
|
|
118
|
-
| `tiers:read` | `GET /tiers/` |
|
|
119
|
-
| `newsletters:read` | `GET /newsletters/` |
|
|
120
|
-
| `site:read` | `GET /site/` |
|
|
121
|
-
| `slugs:read` | `GET /slugs/:type/:name/`, `GET /slugs/:type/:name/:id/` |
|
|
122
|
-
|
|
123
|
-
An app can't ask Ghost to email a post, set a post's code injection or write
|
|
124
|
-
mobiledoc. The one exception: publishing a post that a staff member already
|
|
125
|
-
scheduled with a newsletter sends its email, as it would have at the scheduled
|
|
126
|
-
time.
|
|
127
|
-
|
|
128
|
-
- A write may carry only the query parameters its scope lists: `include`,
|
|
129
|
-
`formats` and `save_revision` for posts and pages, and `include` for tags.
|
|
130
|
-
Any other name is refused, `newsletter`, `email_segment` and `source`
|
|
131
|
-
included, however it's written.
|
|
132
|
-
- `codeinjection_head` and `codeinjection_foot` are refused with any value, even
|
|
133
|
-
`null`, on posts, pages and tags: leave them out of the body.
|
|
134
|
-
- `mobiledoc` must be `null` or left out: it's deprecated and Ghost 7.0 removes
|
|
135
|
-
it. Write `lexical` instead.
|
|
136
|
-
- The SDK and Admin set the body's content type themselves; an app can't set
|
|
137
|
-
`content-type` or `content-encoding`.
|
|
138
|
-
|
|
139
|
-
To edit a post, send `updated_at` and only the fields you change, never the
|
|
140
|
-
object you read: it comes back with `codeinjection_head` and
|
|
141
|
-
`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.
|
|
142
24
|
|
|
143
25
|
```ts
|
|
144
|
-
|
|
145
|
-
await ghost.fetch(`/posts/${id}/`, {
|
|
146
|
-
method: 'PUT',
|
|
147
|
-
body: { posts: [{ updated_at: posts[0].updated_at, title: 'New title' }] },
|
|
148
|
-
});
|
|
149
|
-
```
|
|
26
|
+
import { connect } from '@tryghost/app-sdk';
|
|
150
27
|
|
|
151
|
-
|
|
152
|
-
`codeinjection_head` and `codeinjection_foot` too, so send each as `{ id }`, or
|
|
153
|
-
`{ name }` for a new one:
|
|
28
|
+
const ghost = await connect();
|
|
154
29
|
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
await ghost.fetch(`/posts/${id}/`, {
|
|
158
|
-
method: 'PUT',
|
|
159
|
-
body: { posts: [{ updated_at: posts[0].updated_at, tags: [...tags, { name: 'Featured' }] }] },
|
|
160
|
-
});
|
|
30
|
+
const response = await ghost.fetch('/posts/?limit=5');
|
|
31
|
+
const { posts } = await response.json();
|
|
161
32
|
```
|
|
162
33
|
|
|
163
|
-
These checks are a stopgap for the private beta. They're reviewed again before
|
|
164
|
-
anyone outside the team gets access, and app scopes replace them.
|
|
165
|
-
|
|
166
|
-
The refusal names the method and path, or what in the request was refused, as
|
|
167
|
-
in `blocked: Apps can't send codeinjection_head to PUT /posts/…/`.
|
|
168
|
-
|
|
169
|
-
### Routes and history
|
|
170
|
-
|
|
171
|
-
Admin keeps the history, and the app routes as it would anywhere: with
|
|
172
|
-
`history.pushState` and `history.replaceState`, which any router uses, and with
|
|
173
|
-
links. The SDK turns each into a single entry in Admin's history:
|
|
174
|
-
|
|
175
|
-
- `pushState` and a click on a link to the app's own origin add an entry in
|
|
176
|
-
Admin; `replaceState` replaces Admin's current one. The frame itself keeps a
|
|
177
|
-
single entry, so back and forward are always Admin's.
|
|
178
|
-
- A link loads its page in place of the frame's entry, after Admin has recorded
|
|
179
|
-
the move. A link with a `target`, a `download` or a modifier key is left alone,
|
|
180
|
-
and so is one a router has already handled.
|
|
181
|
-
- When the publisher goes back or forward, or Admin moves the app itself, the
|
|
182
|
-
SDK puts the page's URL there, with the state the app last gave that route,
|
|
183
|
-
and dispatches `popstate`, so a router shows it. A multi-page app, with no
|
|
184
|
-
router, loads it: `ghost.onPathChange((path) => location.replace(path))`.
|
|
185
|
-
- Admin opens the app's page at its route, so each route must load directly, as
|
|
186
|
-
with any app that uses browser history. If the page ends up elsewhere, through
|
|
187
|
-
a redirect from its server or a form's result, Admin follows the page.
|
|
188
|
-
|
|
189
|
-
Not intercepted, so each still adds an entry of the frame's own, which back
|
|
190
|
-
steps through without Admin: a form that posts, a change to `location.hash`,
|
|
191
|
-
and the Navigation API. Route with the History API rather than the hash.
|
|
192
|
-
|
|
193
|
-
### The frame
|
|
194
|
-
|
|
195
|
-
The frame is sandboxed. The page runs scripts and posts forms on its own origin,
|
|
196
|
-
with that origin's storage and cookies, and can open popups and download files.
|
|
197
|
-
It can't navigate Admin's tab, and `alert`, `confirm` and `prompt` return at
|
|
198
|
-
once (`confirm` with `false`), so an app brings its own dialogs. Browser features
|
|
199
|
-
such as the camera, geolocation and fullscreen are off.
|
|
200
|
-
|
|
201
|
-
A popup is sandboxed the same way: it can load any page and `postMessage` back
|
|
202
|
-
to the app, but it can't navigate other windows, Admin's included, or show
|
|
203
|
-
`alert` or `confirm`. To send the publisher somewhere in Admin, use `open`.
|
|
204
|
-
|
|
205
|
-
The SDK reports the page's title automatically. It watches `<title>`, and Admin
|
|
206
|
-
shows the title, up to 200 characters, while the page is open. Characters that
|
|
207
|
-
reorder or hide text, such as direction marks, are removed.
|
|
208
|
-
|
|
209
|
-
## Errors
|
|
210
|
-
|
|
211
|
-
Every rejection is a `GhostAppError`, whose `code` gives the reason:
|
|
212
|
-
|
|
213
|
-
| `code` | Means |
|
|
214
|
-
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
215
|
-
| `not_framed` | The page is not inside a frame, so there is no Admin to talk to. |
|
|
216
|
-
| `not_connected` | Admin did not start the app before the timeout. |
|
|
217
|
-
| `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. |
|
|
218
|
-
| `invalid_context` | Admin started the app with a context this SDK cannot read. Updating the SDK usually fixes it. |
|
|
219
|
-
| `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. |
|
|
220
|
-
| `invalid_argument` | The app passed something that cannot be sent, such as a body on a `GET`. |
|
|
221
|
-
| `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 `/`. |
|
|
222
|
-
| `unsupported` | This site's Ghost version predates the call. The message names the call. |
|
|
223
|
-
| `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). |
|
|
224
|
-
| `network_error` | Admin could not reach its own API. |
|
|
225
|
-
| `rejected` | Admin refused for another reason; the message says why. |
|
|
226
|
-
|
|
227
|
-
## How it connects
|
|
228
|
-
|
|
229
|
-
The SDK posts `{ type: 'ghost-app:hello', sdk: <version>, document: <id> }` to
|
|
230
|
-
`window.parent` every 250 ms until Admin replies with `ghost-app:connect`, a
|
|
231
|
-
`MessagePort` and the names of the calls Admin exports. `document` is a random
|
|
232
|
-
ID the SDK makes when it loads. It stays the same for the life of the
|
|
233
|
-
document, so Admin can tell whether a hello comes from a page it has already
|
|
234
|
-
connected or from a new page. The SDK accepts only the first reply, and only
|
|
235
|
-
from the parent window. Over the port, it uses
|
|
236
|
-
[`@quilted/threads`](https://github.com/lemonmade/quilt/tree/main/packages/threads)
|
|
237
|
-
for the calls `@tryghost/app-contracts/bridge` defines, and Admin then calls
|
|
238
|
-
`start`. The SDK refuses a call that the connect message didn't list with
|
|
239
|
-
`unsupported`, without sending it. Admin only ever adds calls, so an older Admin
|
|
240
|
-
lacks the newer ones.
|
|
241
|
-
|
|
242
|
-
Only an error's message survives the channel, so Admin puts the code at the
|
|
243
|
-
start of the message, as in `blocked: Apps can't use GET /db/`. The SDK splits it
|
|
244
|
-
back into `code` and `message`. A message without a known code arrives as
|
|
245
|
-
`rejected`. The SDK refuses Admin's calls the same way: `invalid_context: …` for
|
|
246
|
-
a start context it can't read or a call before the start, and
|
|
247
|
-
`invalid_argument: …` for a theme or path it can't read. The codes and their
|
|
248
|
-
format are defined once, in `@tryghost/app-contracts`.
|
|
249
|
-
|
|
250
|
-
The session ends when the port closes (in browsers that report it, such as
|
|
251
|
-
Chromium), when a message on it can't be read, or when Admin refuses a call with
|
|
252
|
-
`session_ended`. Admin does that to every pending call when it releases the app.
|
|
253
|
-
In other browsers, a page Admin has released is removed along with its frame.
|
|
254
|
-
|
|
255
|
-
When a reload, a form post or a link within the app loads a new document in the
|
|
256
|
-
frame, Admin starts it in place. Admin hides the frame until the new document's
|
|
257
|
-
SDK has connected, then starts it with Admin's current route, so the page shows
|
|
258
|
-
what the form or link loaded, and Admin follows the new document's address. The
|
|
259
|
-
old document's session ends with it. A new document must
|
|
260
|
-
connect within the same 10 seconds, or Admin reloads the app's page. A page that
|
|
261
|
-
keeps reloading or navigating away is shown as not responding: more than five
|
|
262
|
-
documents in a row, each replaced within three seconds of starting. A publisher
|
|
263
|
-
clicking quickly through more than five pages of a multi-page app would trip it
|
|
264
|
-
too.
|
|
265
|
-
|
|
266
34
|
## Signing the manifest
|
|
267
35
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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
|
-
```
|
|
288
|
-
|
|
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
|
|
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.
|
|
299
40
|
|
|
300
|
-
|
|
301
|
-
Ed25519 JWKs, in files only their owner can read:
|
|
41
|
+
## Documentation
|
|
302
42
|
|
|
303
|
-
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
-
|
|
307
|
-
`ghost-app keys --production` creates.
|
|
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
|
|
308
47
|
|
|
309
|
-
|
|
310
|
-
permissions of the folder it's in, so keep the project in a folder only you can
|
|
311
|
-
read.
|
|
48
|
+
## Develop the SDK
|
|
312
49
|
|
|
313
|
-
|
|
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
|
|
332
|
-
|
|
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
|
-
```
|
|
340
|
-
|
|
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:
|
|
50
|
+
From this package's directory in the Ghost monorepo:
|
|
385
51
|
|
|
386
52
|
```sh
|
|
387
|
-
|
|
53
|
+
pnpm build
|
|
54
|
+
pnpm test
|
|
55
|
+
pnpm lint
|
|
388
56
|
```
|
|
389
|
-
|
|
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.
|
|
476
|
-
|
|
477
|
-
## Serve only the app from its origin
|
|
478
|
-
|
|
479
|
-
Admin replies to any page on the app's origin that sends a hello from the app's
|
|
480
|
-
frame, and can't tell the app's own pages apart from anything else served there.
|
|
481
|
-
Any such page gets the whole bridge, including `fetch` as the staff user with
|
|
482
|
-
their session. So the origin must serve only the app. Keep user-generated
|
|
483
|
-
content and third-party pages or widgets on another origin (a separate subdomain
|
|
484
|
-
counts). An open redirect is a risk too: a link through it puts another site's
|
|
485
|
-
page in the frame, inside Admin.
|
|
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
|
-
|
|
496
|
-
## Develop
|
|
497
|
-
|
|
498
|
-
This is a workspace package in the Ghost monorepo. From the package directory:
|
|
499
|
-
|
|
500
|
-
```bash
|
|
501
|
-
pnpm build # the package to build/ and the browser bundle to dist/, with Vite
|
|
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)
|
|
506
|
-
pnpm lint # lint source and tests
|
|
507
|
-
```
|
|
508
|
-
|
|
509
|
-
It follows the [internal package golden path](../README.md), except where it
|
|
510
|
-
ships to apps. Its `build` bundles with Vite instead of compiling with `tsc`,
|
|
511
|
-
and also writes `dist/`, which is in `files` and in the Nx build outputs.
|
|
512
|
-
|
|
513
|
-
It uses `@tryghost/app-contracts` for the bridge's message types, limits and
|
|
514
|
-
shape checks, so the SDK and Admin apply the same rules to paths, themes and
|
|
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`;
|
|
528
|
-
- `dist/` imports nothing at all.
|
|
529
|
-
|
|
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.
|
package/build/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { d as createKeys, h as readBackendKey, i as serialiseSigned, l as KEYS_DIRECTORY, m as publicKeyOf, n as formatErrors, o as signProject, p as keyFile, u as KEY_NAMES } from "./chunks/sign-
|
|
2
|
+
import { d as createKeys, h as readBackendKey, i as serialiseSigned, l as KEYS_DIRECTORY, m as publicKeyOf, n as formatErrors, o as signProject, p as keyFile, u as KEY_NAMES } from "./chunks/sign-50Ayvddb.js";
|
|
3
3
|
import { lstatSync, readlinkSync, realpathSync } from "node:fs";
|
|
4
4
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
5
5
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
@@ -97,16 +97,12 @@ function isValidAppId(value) {
|
|
|
97
97
|
* them, the manifest's own URL included, so its columns are exactly this wide.
|
|
98
98
|
*/
|
|
99
99
|
var URL_MAX_LENGTH = 2e3;
|
|
100
|
-
//#endregion
|
|
101
|
-
//#region ../app-contracts/build/identity/loading.js
|
|
102
|
-
/** The largest manifest Ghost stores, which it keeps in a TEXT column. */
|
|
103
|
-
var MANIFEST_MAX_BYTES = 64 * 1024;
|
|
104
100
|
/**
|
|
105
101
|
* The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and
|
|
106
102
|
* the header and signature are well under a kilobyte, so a manifest of the largest size
|
|
107
103
|
* still fits.
|
|
108
104
|
*/
|
|
109
|
-
var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(
|
|
105
|
+
var SIGNED_MANIFEST_MAX_BYTES = Math.ceil(64 * 1024 * 4 / 3) + 1024;
|
|
110
106
|
/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
|
|
111
107
|
function parseJsonText(text) {
|
|
112
108
|
return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
|
|
@@ -660,13 +656,7 @@ function manifestShape(url, text) {
|
|
|
660
656
|
function manifestSchema(rules) {
|
|
661
657
|
return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);
|
|
662
658
|
}
|
|
663
|
-
|
|
664
|
-
* The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to
|
|
665
|
-
* resolve or check. This is the schema to read a stored manifest with, as it holds
|
|
666
|
-
* whatever the site's URL has become since, and it encodes a manifest back to the same
|
|
667
|
-
* shape, so what is stored is what will be read.
|
|
668
|
-
*/
|
|
669
|
-
var AppManifestSchema = manifestShape(absoluteUrl, storedText);
|
|
659
|
+
manifestShape(absoluteUrl, storedText);
|
|
670
660
|
//#endregion
|
|
671
661
|
//#region ../app-contracts/build/manifest/parse.js
|
|
672
662
|
function formatPath(path) {
|
|
@@ -772,17 +762,6 @@ function parseManifest(input, options) {
|
|
|
772
762
|
};
|
|
773
763
|
}
|
|
774
764
|
//#endregion
|
|
775
|
-
//#region src/tooling/limits.ts
|
|
776
|
-
/**
|
|
777
|
-
* A manifest's size as Ghost stores it: with its paths resolved, so it can be larger than what
|
|
778
|
-
* was signed. Ghost refuses one larger than `MANIFEST_MAX_BYTES`.
|
|
779
|
-
*/
|
|
780
|
-
function storedSize(manifest) {
|
|
781
|
-
return new TextEncoder().encode(JSON.stringify(z.encode(AppManifestSchema, manifest))).byteLength;
|
|
782
|
-
}
|
|
783
|
-
var signedTooLargeMessage = () => `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB, as Ghost fetches it; text Ghost trims still counts`;
|
|
784
|
-
var tooLargeMessage = () => `Expected a manifest of at most ${MANIFEST_MAX_BYTES / 1024} KB once its paths are resolved, as Ghost stores it`;
|
|
785
|
-
//#endregion
|
|
786
765
|
//#region src/tooling/sign.ts
|
|
787
766
|
/** The readable manifest a project keeps, which the tooling signs. */
|
|
788
767
|
var MANIFEST_FILE = "ghost-app.json";
|
|
@@ -840,9 +819,8 @@ async function signAppManifest(source, options) {
|
|
|
840
819
|
code: "APP_MANIFEST_INVALID",
|
|
841
820
|
errors: parsed.errors
|
|
842
821
|
};
|
|
843
|
-
if (storedSize(parsed.manifest) > 65536) return refuse("APP_MANIFEST_TOO_LARGE", tooLargeMessage());
|
|
844
822
|
const signed = await signManifest(JSON.stringify(manifest), options.identityKey);
|
|
845
|
-
if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) return refuse("APP_MANIFEST_TOO_LARGE",
|
|
823
|
+
if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) return refuse("APP_MANIFEST_TOO_LARGE", `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB`);
|
|
846
824
|
return {
|
|
847
825
|
success: true,
|
|
848
826
|
signed,
|
|
@@ -881,4 +859,4 @@ async function signProject({ root, mode, env, manifestUrl, manifestFile = MANIFE
|
|
|
881
859
|
//#endregion
|
|
882
860
|
export { signingKeySource as _, signAppManifest as a, isLocalhost as b, IDENTITY_KEY_VARIABLE as c, createKeys as d, generateKey as f, readSigningKeys as g, readBackendKey as h, serialiseSigned as i, KEYS_DIRECTORY as l, publicKeyOf as m, formatErrors as n, signProject as o, keyFile as p, readManifestSource as r, BACKEND_KEY_VARIABLE as s, MANIFEST_FILE as t, KEY_NAMES as u, parseJsonText as v, isValidAppId as y };
|
|
883
861
|
|
|
884
|
-
//# sourceMappingURL=sign-
|
|
862
|
+
//# sourceMappingURL=sign-50Ayvddb.js.map
|