@tryghost/app-sdk 0.1.0-alpha.6 → 0.1.0-alpha.7
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 +99 -10
- package/build/backend.d.ts +1 -10
- package/build/backend.js +1 -108
- package/build/backend.js.map +1 -1
- package/build/chunks/manifest-CInTdKjI.d.ts +19 -0
- package/build/chunks/manifest-DX1GTozy.js +219 -0
- package/build/chunks/manifest-DX1GTozy.js.map +1 -0
- package/build/chunks/rules-_dou3jRF.js +159 -0
- package/build/chunks/rules-_dou3jRF.js.map +1 -0
- package/build/index.js +2 -153
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +177 -0
- package/build/tooling.js +1130 -0
- package/build/tooling.js.map +1 -0
- package/dist/app-sdk.js +1 -1
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
# @tryghost/app-sdk
|
|
2
2
|
|
|
3
|
-
The SDK apps use to talk to Ghost: from their page inside Admin,
|
|
4
|
-
backend.
|
|
3
|
+
The SDK apps use to talk to Ghost: from their page inside Admin, from their
|
|
4
|
+
backend, and from their tooling.
|
|
5
5
|
|
|
6
6
|
An app's page runs in a frame inside Ghost Admin. The SDK connects it to Admin,
|
|
7
7
|
gives it the site, the user and the theme, and lets it call the Admin API, keep
|
|
8
8
|
its route in sync with Admin's URL, and send the publisher elsewhere in Admin.
|
|
9
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)
|
|
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.1 or later | [Creating keys, and signing and checking the manifest](#signing-the-manifest) |
|
|
14
15
|
|
|
15
|
-
The page's entry point loads none of the
|
|
16
|
+
The page's entry point loads none of the others' code.
|
|
16
17
|
|
|
17
18
|
> **Alpha.** CI publishes each change to npm as the next `0.1.0-alpha.N` under
|
|
18
19
|
> the `latest` tag. Alphas make no compatibility promise.
|
|
@@ -260,6 +261,93 @@ documents in a row, each replaced within three seconds of starting. A publisher
|
|
|
260
261
|
clicking quickly through more than five pages of a multi-page app would trip it
|
|
261
262
|
too.
|
|
262
263
|
|
|
264
|
+
## Signing the manifest
|
|
265
|
+
|
|
266
|
+
Ghost installs an app from its manifest URL, where the app serves a signed
|
|
267
|
+
manifest: its `ghost-app.json`, with the fields below added, signed with the
|
|
268
|
+
app's identity key. Ghost pins that key when a site installs the app, and
|
|
269
|
+
challenges the app's origin to prove it holds the backend key the manifest
|
|
270
|
+
names. The manifest format is in
|
|
271
|
+
[`@tryghost/app-contracts`](../app-contracts/README.md#the-manifest).
|
|
272
|
+
|
|
273
|
+
`ghost-app.json` is the readable part, which the project keeps:
|
|
274
|
+
|
|
275
|
+
```json
|
|
276
|
+
{
|
|
277
|
+
"id": "com.example.hello",
|
|
278
|
+
"name": "Hello",
|
|
279
|
+
"description": "Says hello.",
|
|
280
|
+
"author": { "name": "Example", "url": "https://example.com" },
|
|
281
|
+
"accent_color": "#ff5500",
|
|
282
|
+
"icon": { "name": "hand" },
|
|
283
|
+
"surfaces": [{ "type": "admin_page", "url": "/" }]
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Signing adds `manifest_url` (the address it's signed for), `identity_key` and
|
|
288
|
+
`backend_key` (the public keys) and `development`, and refuses a file that sets
|
|
289
|
+
any of them. It checks the manifest with the rules Ghost applies first, so a
|
|
290
|
+
manifest Ghost would refuse is never signed: the error lists every problem by
|
|
291
|
+
field. Ghost also refuses a manifest on the site's or Admin's host, on any port,
|
|
292
|
+
which only Ghost knows.
|
|
293
|
+
|
|
294
|
+
### Keys
|
|
295
|
+
|
|
296
|
+
Each mode has its own identity key and backend key, as two pairs of private
|
|
297
|
+
Ed25519 JWKs, in files only their owner can read:
|
|
298
|
+
|
|
299
|
+
- `.ghost-app/development/identity.json` and `backend.json`, for apps on this
|
|
300
|
+
machine, such as on `my-app.localhost`;
|
|
301
|
+
- `.ghost-app/production/identity.json` and `backend.json`.
|
|
302
|
+
|
|
303
|
+
`createKeys({ root, mode })` creates them.
|
|
304
|
+
|
|
305
|
+
Only the owner can read a key on macOS and Linux. On Windows, a key gets the
|
|
306
|
+
permissions of the folder it's in, so keep the project in a folder only you can
|
|
307
|
+
read.
|
|
308
|
+
|
|
309
|
+
Keys are created only when git ignores `.ghost-app/` (in a repository), and an
|
|
310
|
+
existing key is never replaced. Keep a copy of the production identity key
|
|
311
|
+
somewhere safe: sites keep the identity key they installed an app with, and a
|
|
312
|
+
manifest signed with another one is another app. A development installation
|
|
313
|
+
and a production one are different apps for the same reason, so going from your
|
|
314
|
+
computer to a host means installing the app again.
|
|
315
|
+
|
|
316
|
+
The identity key stays with the developer, or CI. It never reaches the backend
|
|
317
|
+
or a build: only the signed manifest is served or emitted. The backend key goes
|
|
318
|
+
to the backend, which answers challenges with it. Developers who share a
|
|
319
|
+
development identity key must share its backend key too: a new backend key
|
|
320
|
+
retires the old one on every site that reads the new manifest.
|
|
321
|
+
|
|
322
|
+
In CI, set `GHOST_APP_IDENTITY_KEY` to the production identity key and
|
|
323
|
+
`GHOST_APP_BACKEND_KEY` to the backend key's public half, `publicKeyOf` of the
|
|
324
|
+
production backend key, in place of the files. CI only signs, so it never needs
|
|
325
|
+
the backend's private key.
|
|
326
|
+
|
|
327
|
+
### From code
|
|
328
|
+
|
|
329
|
+
`@tryghost/app-sdk/tooling` signs and checks from code:
|
|
330
|
+
|
|
331
|
+
| Export | What it does |
|
|
332
|
+
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
|
333
|
+
| `createKeys({ root, mode })` | Creates the mode's missing keys. Resolves with `{ created, kept }`. |
|
|
334
|
+
| `readSigningKeys({ root, mode, env? })` | The identity key and the backend key's public half, from the files or, in production, `env`. |
|
|
335
|
+
| `readBackendKey({ root, mode })` | The mode's private backend key. |
|
|
336
|
+
| `signProject({ root, mode, manifestUrl, manifestFile? })` | Signs the project's `ghost-app.json` with the mode's keys. |
|
|
337
|
+
| `signAppManifest(source, { manifestUrl, identityKey, backendKey, development })` | Signs a manifest with the keys given. |
|
|
338
|
+
| `checkApp(manifestUrl, { fetch? })` | Checks an app as Ghost does before installing it. Resolves with the parsed manifest, or a failure with Ghost's code. |
|
|
339
|
+
| `generateKey()`, `publicKeyOf(key)` | A new private key, and a key's public half. |
|
|
340
|
+
|
|
341
|
+
Signing resolves with `{ success: true, signed, manifest }`, or
|
|
342
|
+
`{ success: false, code, errors }`.
|
|
343
|
+
|
|
344
|
+
`checkApp` fetches the signed manifest, verifies it, and challenges the app's
|
|
345
|
+
origin, even on `localhost`, which Ghost in development doesn't. A failure
|
|
346
|
+
carries Ghost's own code, such as `APP_MANIFEST_URL_MISMATCH`,
|
|
347
|
+
`APP_MANIFEST_SIGNATURE_INVALID` or `APP_CHALLENGE_FAILED`, and what exactly was
|
|
348
|
+
wrong. It can't check what only a site knows: the key it installed the app
|
|
349
|
+
with, and backend keys a newer manifest replaced.
|
|
350
|
+
|
|
263
351
|
## The backend
|
|
264
352
|
|
|
265
353
|
`@tryghost/app-sdk/backend` uses only `Request`, `Response`, `fetch` and
|
|
@@ -332,7 +420,7 @@ This is a workspace package in the Ghost monorepo. From the package directory:
|
|
|
332
420
|
```bash
|
|
333
421
|
pnpm build # the package to build/ and the browser bundle to dist/, with Vite
|
|
334
422
|
pnpm test # type-check + unit tests (jsdom for the page, with a fake Admin on a real
|
|
335
|
-
# MessageChannel; Node for the backend), which build both
|
|
423
|
+
# MessageChannel; Node for the backend and tooling), which build both
|
|
336
424
|
# afresh to check what they import, and pack build/ and dist/ to use them from an
|
|
337
425
|
# app outside the workspace (after pnpm build; Nx runs it)
|
|
338
426
|
pnpm lint # lint source and tests
|
|
@@ -344,14 +432,15 @@ and also writes `dist/`, which is in `files` and in the Nx build outputs.
|
|
|
344
432
|
|
|
345
433
|
It uses `@tryghost/app-contracts` for the bridge's message types, limits and
|
|
346
434
|
shape checks, so the SDK and Admin apply the same rules to paths, themes and
|
|
347
|
-
start contexts, and for
|
|
348
|
-
own rules. The build inlines what it uses
|
|
435
|
+
start contexts, and for signing and checking manifests and challenges, so the
|
|
436
|
+
tooling and the backend apply Ghost's own rules. The build inlines what it uses
|
|
349
437
|
into the SDK, so the contracts are a dev dependency. `build/` has an ES module
|
|
350
438
|
per entry point, which share chunks:
|
|
351
439
|
|
|
352
440
|
- `index.js` loads only `@quilted/threads`, never `jose`, `zod` or a Node
|
|
353
441
|
builtin;
|
|
354
442
|
- `backend.js` loads only `jose` and `zod`, and no Node builtin;
|
|
443
|
+
- `tooling.js` loads Node builtins, `jose` and `zod`;
|
|
355
444
|
- each entry point's declarations, emitted by TypeScript 7 and bundled by
|
|
356
445
|
`rolldown-plugin-dts`, import nothing;
|
|
357
446
|
- `dist/` imports nothing at all.
|
package/build/backend.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { r as SignedManifest, t as MANIFEST_PATH } from "./chunks/manifest-CInTdKjI.js";
|
|
1
2
|
//#region ../app-contracts/build/identity/challenge.d.ts
|
|
2
3
|
/** Where on an origin Ghost posts a challenge. */
|
|
3
4
|
declare const CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
|
|
@@ -75,16 +76,6 @@ declare function withGhostApp<Args extends unknown[] = []>({ fetch, ...challenge
|
|
|
75
76
|
fetch: (request: Request, ...args: Args) => Promise<Response>;
|
|
76
77
|
};
|
|
77
78
|
//#endregion
|
|
78
|
-
//#region src/shared/manifest.d.ts
|
|
79
|
-
/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
|
|
80
|
-
declare const MANIFEST_PATH = "/ghost-app.json";
|
|
81
|
-
/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */
|
|
82
|
-
interface SignedManifest {
|
|
83
|
-
protected: string;
|
|
84
|
-
payload: string;
|
|
85
|
-
signature: string;
|
|
86
|
-
}
|
|
87
|
-
//#endregion
|
|
88
79
|
//#region src/backend/manifest.d.ts
|
|
89
80
|
/**
|
|
90
81
|
* A response that serves the signed manifest, for a backend that doesn't serve it as a static
|
package/build/backend.js
CHANGED
|
@@ -1,107 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
//#region ../app-contracts/build/identity/jws.js
|
|
4
|
-
/** The only algorithm either key signs with. */
|
|
5
|
-
var ALGORITHM = "Ed25519";
|
|
6
|
-
//#endregion
|
|
7
|
-
//#region ../app-contracts/build/identity/challenge.js
|
|
8
|
-
/** Where on an origin Ghost posts a challenge. */
|
|
9
|
-
var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
|
|
10
|
-
/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */
|
|
11
|
-
var CHALLENGE_PURPOSE = "ghost-app-challenge";
|
|
12
|
-
z.strictObject({ alg: z.literal(ALGORITHM) });
|
|
13
|
-
JSON.stringify({ alg: ALGORITHM });
|
|
14
|
-
var ChallengeShape = z.strictObject({
|
|
15
|
-
purpose: z.literal(CHALLENGE_PURPOSE),
|
|
16
|
-
origin: z.string(),
|
|
17
|
-
nonce: z.string()
|
|
18
|
-
});
|
|
19
|
-
z.object({ signature: z.string() });
|
|
20
|
-
/**
|
|
21
|
-
* Answers a challenge a backend received, signing it with the backend key. `requestUrl` is
|
|
22
|
-
* the URL the request arrived at, as the platform reports it (`request.url` on Workers):
|
|
23
|
-
* never one built from `X-Forwarded-Host` or any other header the sender controls. A
|
|
24
|
-
* challenge for any origin but that one is refused, so whoever takes over a name the app
|
|
25
|
-
* used to serve can't relay Ghost's challenge to the real backend to prove it.
|
|
26
|
-
*
|
|
27
|
-
* Ghost can't see this check, so it only helps where the platform routes requests by host,
|
|
28
|
-
* as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.
|
|
29
|
-
*/
|
|
30
|
-
async function answerChallenge(body, { backendKey, requestUrl }) {
|
|
31
|
-
const challenge = ChallengeShape.safeParse(parseJson(body));
|
|
32
|
-
if (!challenge.success) return {
|
|
33
|
-
success: false,
|
|
34
|
-
error: "Expected a challenge of {purpose, origin, nonce}"
|
|
35
|
-
};
|
|
36
|
-
const arrivedAt = URL.parse(requestUrl)?.origin;
|
|
37
|
-
if (arrivedAt !== challenge.data.origin) return {
|
|
38
|
-
success: false,
|
|
39
|
-
error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? "an unknown origin"}`
|
|
40
|
-
};
|
|
41
|
-
return {
|
|
42
|
-
success: true,
|
|
43
|
-
answer: { signature: await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: ALGORITHM }).sign(backendKey) }
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
function parseJson(text) {
|
|
47
|
-
try {
|
|
48
|
-
return JSON.parse(text);
|
|
49
|
-
} catch {
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
//#endregion
|
|
54
|
-
//#region src/shared/parse.ts
|
|
55
|
-
var UNSAFE_IN_POLICY = /[\s;,'"*]/;
|
|
56
|
-
/**
|
|
57
|
-
* An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
|
|
58
|
-
* `,` into a host, so the origin must also read back as itself, and hold nothing that would end
|
|
59
|
-
* a source in a Content-Security-Policy.
|
|
60
|
-
*/
|
|
61
|
-
function parseOrigin(entry) {
|
|
62
|
-
const url = URL.parse(entry);
|
|
63
|
-
const origin = url?.origin;
|
|
64
|
-
if (!url || !origin || url.protocol !== "https:" && url.protocol !== "http:" || url.href !== `${origin}/` || URL.parse(origin)?.origin !== origin || UNSAFE_IN_POLICY.test(entry) || UNSAFE_IN_POLICY.test(origin)) return;
|
|
65
|
-
return origin;
|
|
66
|
-
}
|
|
67
|
-
//#endregion
|
|
68
|
-
//#region src/shared/ignore.ts
|
|
69
|
-
/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
|
|
70
|
-
var ignoreError = () => void 0;
|
|
71
|
-
//#endregion
|
|
72
|
-
//#region src/shared/body.ts
|
|
73
|
-
/**
|
|
74
|
-
* Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
|
|
75
|
-
* stops reading as soon as the body passes the limit, so a large body is never held whole.
|
|
76
|
-
*/
|
|
77
|
-
async function readBytes(message, maxBytes) {
|
|
78
|
-
if (Number(message.headers.get("content-length")) > maxBytes) {
|
|
79
|
-
message.body?.cancel().catch(ignoreError);
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
if (!message.body) return /* @__PURE__ */ new Uint8Array();
|
|
83
|
-
const reader = message.body.getReader();
|
|
84
|
-
const chunks = [];
|
|
85
|
-
let length = 0;
|
|
86
|
-
for (;;) {
|
|
87
|
-
const { done, value } = await reader.read();
|
|
88
|
-
if (done) break;
|
|
89
|
-
length += value.byteLength;
|
|
90
|
-
if (length > maxBytes) {
|
|
91
|
-
reader.cancel().catch(ignoreError);
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
chunks.push(value);
|
|
95
|
-
}
|
|
96
|
-
const bytes = new Uint8Array(length);
|
|
97
|
-
let offset = 0;
|
|
98
|
-
for (const chunk of chunks) {
|
|
99
|
-
bytes.set(chunk, offset);
|
|
100
|
-
offset += chunk.byteLength;
|
|
101
|
-
}
|
|
102
|
-
return bytes;
|
|
103
|
-
}
|
|
104
|
-
//#endregion
|
|
1
|
+
import { c as CHALLENGE_PATH, i as readBytes, l as answerChallenge, s as parseOrigin, t as MANIFEST_PATH } from "./chunks/manifest-DX1GTozy.js";
|
|
105
2
|
//#region src/backend/body.ts
|
|
106
3
|
/**
|
|
107
4
|
* Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid
|
|
@@ -201,10 +98,6 @@ function withGhostApp({ fetch, ...challenge }) {
|
|
|
201
98
|
} };
|
|
202
99
|
}
|
|
203
100
|
//#endregion
|
|
204
|
-
//#region src/shared/manifest.ts
|
|
205
|
-
/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
|
|
206
|
-
var MANIFEST_PATH = "/ghost-app.json";
|
|
207
|
-
//#endregion
|
|
208
101
|
//#region src/backend/manifest.ts
|
|
209
102
|
/**
|
|
210
103
|
* A response that serves the signed manifest, for a backend that doesn't serve it as a static
|
package/build/backend.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backend.js","names":[],"sources":["../../app-contracts/build/identity/jws.js","../../app-contracts/build/identity/challenge.js","../src/shared/parse.ts","../src/shared/ignore.ts","../src/shared/body.ts","../src/backend/body.ts","../src/backend/challenge.ts","../src/backend/app.ts","../src/shared/manifest.ts","../src/backend/manifest.ts"],"sourcesContent":["import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","import { CompactSign, base64url, compactVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeUtf8 } from './keys.js';\n/** Where on an origin Ghost posts a challenge. */\nexport const CHALLENGE_PATH = '/.well-known/ghost-app/challenge';\n/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */\nexport const CHALLENGE_PURPOSE = 'ghost-app-challenge';\nconst NONCE_BYTES = 32;\nconst ProtectedHeader = z.strictObject({ alg: z.literal(ALGORITHM) });\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM });\nconst ChallengeShape = z.strictObject({\n purpose: z.literal(CHALLENGE_PURPOSE),\n origin: z.string(),\n nonce: z.string(),\n});\nconst ChallengeAnswerShape = z.object({ signature: z.string() });\n/** The URL to post a challenge for an origin to. */\nexport function challengeUrl(origin) {\n return new URL(CHALLENGE_PATH, origin).href;\n}\n/** A fresh challenge for an origin, as the exact text to post and to verify the answer with. */\nexport function createChallenge(origin) {\n const challenge = {\n purpose: CHALLENGE_PURPOSE,\n origin: new URL(origin).origin,\n nonce: base64url.encode(crypto.getRandomValues(new Uint8Array(NONCE_BYTES))),\n };\n return JSON.stringify(challenge);\n}\n/**\n * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is\n * the URL the request arrived at, as the platform reports it (`request.url` on Workers):\n * never one built from `X-Forwarded-Host` or any other header the sender controls. A\n * challenge for any origin but that one is refused, so whoever takes over a name the app\n * used to serve can't relay Ghost's challenge to the real backend to prove it.\n *\n * Ghost can't see this check, so it only helps where the platform routes requests by host,\n * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.\n */\nexport async function answerChallenge(body, { backendKey, requestUrl }) {\n const challenge = ChallengeShape.safeParse(parseJson(body));\n if (!challenge.success) {\n return { success: false, error: 'Expected a challenge of {purpose, origin, nonce}' };\n }\n const arrivedAt = URL.parse(requestUrl)?.origin;\n if (arrivedAt !== challenge.data.origin) {\n return {\n success: false,\n error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? 'an unknown origin'}`,\n };\n }\n const signature = await new CompactSign(new TextEncoder().encode(body))\n .setProtectedHeader({ alg: ALGORITHM })\n .sign(backendKey);\n return { success: true, answer: { signature } };\n}\n/**\n * Checks an origin's answer to a challenge: a signature with the backend key over the\n * exact text Ghost posted, under a protected header of only `alg`. The error only says how\n * the answer fell short.\n */\nexport async function verifyChallengeAnswer(challenge, answer, backendKey) {\n const parsed = ChallengeAnswerShape.safeParse(parseJson(answer));\n if (!parsed.success) {\n return { success: false, error: 'Expected an answer of {\"signature\": \"<compact JWS>\"}' };\n }\n let key;\n try {\n key = await importJWK(backendKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'backend_key is not a usable Ed25519 key' };\n }\n const [header = ''] = parsed.data.signature.split('.');\n if (!readExactHeader(header, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n let payload;\n try {\n ({ payload } = await compactVerify(parsed.data.signature, key, { algorithms: [ALGORITHM] }));\n }\n catch {\n return { success: false, error: 'The signature was not made with backend_key' };\n }\n if (!sameText(payload, challenge)) {\n return { success: false, error: 'The signature is not over the challenge that was sent' };\n }\n return { success: true };\n}\nfunction sameText(bytes, text) {\n try {\n return decodeUtf8(bytes) === text;\n }\n catch {\n return false;\n }\n}\nfunction parseJson(text) {\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=challenge.js.map","// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","import { ignoreError } from './ignore.ts';\n\n/**\n * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It\n * stops reading as soon as the body passes the limit, so a large body is never held whole.\n */\nexport async function readBytes(\n message: Request | Response,\n maxBytes: number,\n): Promise<Uint8Array | undefined> {\n if (Number(message.headers.get('content-length')) > maxBytes) {\n // Too large either way, so a body that refuses to be cancelled changes nothing. Not waited\n // for: one branch of a teed body, as a cloned request's is, cancels only once the other does.\n message.body?.cancel().catch(ignoreError);\n return undefined;\n }\n if (!message.body) {\n return new Uint8Array();\n }\n const reader = message.body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n length += value.byteLength;\n if (length > maxBytes) {\n reader.cancel().catch(ignoreError);\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n","import { readBytes } from '../shared/body.ts';\n\n/**\n * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid\n * UTF-8 throws, as the exact text matters to whoever signs it.\n */\nexport async function readText(request: Request, maxBytes: number): Promise<string | undefined> {\n const bytes = await readBytes(request, maxBytes);\n return bytes && new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\n\nexport function json(status: number, body: unknown, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...headers,\n },\n });\n}\n","import { CHALLENGE_PATH, answerChallenge } from '@tryghost/app-contracts/identity';\n\nimport { parseOrigin } from '../shared/parse.ts';\nimport { json, readText } from './body.ts';\n\nexport { CHALLENGE_PATH };\n\n/**\n * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's\n * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and\n * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.\n */\nexport type BackendJwk = {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kid?: string;\n kty?: string;\n n?: string;\n oth?: { d?: string; r?: string; t?: string }[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n};\n\n/**\n * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an\n * environment variable, such as `GHOST_APP_BACKEND_KEY`.\n */\nexport type BackendKey = BackendJwk | string;\n\nexport interface HandleChallengeOptions {\n backendKey: BackendKey;\n /**\n * The app's public origin, such as `https://app.example.com`, for a server that doesn't see\n * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees\n * `http://`. Ghost challenges the public origin, so without it every challenge is refused.\n * Take it from the app's own configuration, never from a request's headers, which the sender\n * sets. Workers, and other platforms that report the public URL, don't need it.\n */\n origin?: string;\n}\n\n// Ghost's challenge is about 150 bytes. Anything much larger isn't one.\nconst CHALLENGE_MAX_BYTES = 4 * 1024;\n\nconst INVALID_KEY =\n 'backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d';\n\n// The last key imported, so a backend that answers with one key imports it once.\nlet imported: { text: string; key: Promise<CryptoKey> } | undefined;\n\nfunction importBackendKey(backendKey: BackendKey): Promise<CryptoKey> {\n const text = typeof backendKey === 'string' ? backendKey : JSON.stringify(backendKey);\n if (imported?.text !== text) {\n const key = importPrivateKey(text);\n imported = { text, key };\n // A key that failed to import is tried again next time, so a fixed secret takes effect.\n key.catch(() => {\n if (imported?.key === key) {\n imported = undefined;\n }\n });\n }\n return imported.key;\n}\n\nasync function importPrivateKey(text: string): Promise<CryptoKey> {\n let jwk: unknown;\n try {\n jwk = JSON.parse(text);\n } catch {\n // Never says what the text was: it's a secret.\n throw new TypeError(`${INVALID_KEY}; it isn't JSON`);\n }\n const { kty, crv, x, d } = (typeof jwk === 'object' && jwk !== null ? jwk : {}) as BackendJwk;\n if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || typeof d !== 'string') {\n throw new TypeError(INVALID_KEY);\n }\n try {\n return await crypto.subtle.importKey('jwk', { kty, crv, x, d }, { name: 'Ed25519' }, false, [\n 'sign',\n ]);\n } catch (error) {\n throw new TypeError(INVALID_KEY, { cause: error });\n }\n}\n\n/**\n * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`\n * to it, or use `withGhostApp`, which does.\n */\nexport async function handleChallenge(\n request: Request,\n { backendKey, origin }: HandleChallengeOptions,\n): Promise<Response> {\n // A bad `origin` is the app's own misconfiguration, so it throws, and the platform reports a\n // server error, rather than every challenge being refused with a 400 that looks like Ghost's\n // fault.\n const publicOrigin = origin === undefined ? undefined : parseOrigin(origin);\n if (origin !== undefined && !publicOrigin) {\n throw new TypeError(\n `Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`,\n );\n }\n\n // Ghost always POSTs the challenge.\n if (request.method !== 'POST') {\n return json(405, { error: 'Expected a POST' }, { allow: 'POST' });\n }\n\n // A challenge is about 150 bytes, so stop reading at 4 KB rather than buffer whatever a\n // sender streams.\n let body: string | undefined;\n try {\n body = await readText(request, CHALLENGE_MAX_BYTES);\n } catch {\n return json(400, { error: 'Expected a challenge in UTF-8' });\n }\n if (body === undefined) {\n return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });\n }\n\n // Imported once and cached. A `backendKey` that isn't a private Ed25519 key throws a\n // `TypeError`, a server error, for the same reason as a bad `origin`.\n const key = await importBackendKey(backendKey);\n\n // The challenge names the origin Ghost sent it to, and is answered only for this app's own:\n // the one the platform reports in `request.url`, or `origin` behind a proxy. Never one taken\n // from `X-Forwarded-Host` or another header the sender sets, or anyone could have this\n // backend sign a challenge meant for another app.\n const result = await answerChallenge(body, {\n backendKey: key,\n requestUrl: publicOrigin ?? request.url,\n });\n if (!result.success) {\n return json(400, { error: result.error });\n }\n\n // `{ signature }`: Ghost verifies it against the backend key the signed manifest names.\n return json(200, result.answer);\n}\n","import { CHALLENGE_PATH, handleChallenge, type HandleChallengeOptions } from './challenge.ts';\n\n/**\n * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`\n * and `ctx`.\n */\nexport type FetchHandler<Args extends unknown[] = []> = (\n request: Request,\n ...args: Args\n) => Response | Promise<Response>;\n\nexport interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {\n /** The app's own handler, for every request but Ghost's challenge. */\n fetch: FetchHandler<Args>;\n}\n\n/**\n * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and\n * passes every other request to `fetch`, with whatever else the platform passes.\n *\n * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.\n */\nexport function withGhostApp<Args extends unknown[] = []>({\n fetch,\n ...challenge\n}: GhostAppOptions<Args>): { fetch: (request: Request, ...args: Args) => Promise<Response> } {\n return {\n async fetch(request, ...args) {\n if (new URL(request.url).pathname === CHALLENGE_PATH) {\n return handleChallenge(request, challenge);\n }\n return fetch(request, ...args);\n },\n };\n}\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n","import type { SignedManifest } from '../shared/manifest.ts';\n\nexport { MANIFEST_PATH, type SignedManifest } from '../shared/manifest.ts';\n\n/**\n * A response that serves the signed manifest, for a backend that doesn't serve it as a static\n * file. Pass the file's text as it is, or the object it holds.\n *\n * Caches may keep it, but must check it's still current each time, so a new manifest reaches\n * Ghost the next time Ghost reads it.\n */\nexport function serveManifest(signed: SignedManifest | string): Response {\n return new Response(typeof signed === 'string' ? signed : JSON.stringify(signed), {\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-cache',\n },\n });\n}\n"],"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,SAAS,KAAA,GACX,OAAO,KAAK,KAAK,EAAE,OAAO,mCAAmC,oBAAoB,QAAQ,CAAC;CAK5F,MAAM,MAAM,MAAM,iBAAiB,UAAU;CAM7C,MAAM,SAAS,MAAM,gBAAgB,MAAM;EACzC,YAAY;EACZ,YAAY,gBAAgB,QAAQ;CACtC,CAAC;CACD,IAAI,CAAC,OAAO,SACV,OAAO,KAAK,KAAK,EAAE,OAAO,OAAO,MAAM,CAAC;CAI1C,OAAO,KAAK,KAAK,OAAO,MAAM;AAChC;;;;;;;;;AChIA,SAAgB,aAA0C,EACxD,OACA,GAAG,aACwF;CAC3F,OAAO,EACL,MAAM,MAAM,SAAS,GAAG,MAAM;EAC5B,IAAI,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,aAAA,oCACvB,OAAO,gBAAgB,SAAS,SAAS;EAE3C,OAAO,MAAM,SAAS,GAAG,IAAI;CAC/B,EACF;AACF;;;;AC9BA,IAAa,gBAAgB;;;;;;;;;;ACO7B,SAAgB,cAAc,QAA2C;CACvE,OAAO,IAAI,SAAS,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,MAAM,GAAG,EAChF,SAAS;EACP,gBAAgB;EAChB,iBAAiB;CACnB,EACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"backend.js","names":[],"sources":["../src/backend/body.ts","../src/backend/challenge.ts","../src/backend/app.ts","../src/backend/manifest.ts"],"sourcesContent":["import { readBytes } from '../shared/body.ts';\n\n/**\n * Reads a request's body as UTF-8 text, or `undefined` if it is longer than `maxBytes`. Invalid\n * UTF-8 throws, as the exact text matters to whoever signs it.\n */\nexport async function readText(request: Request, maxBytes: number): Promise<string | undefined> {\n const bytes = await readBytes(request, maxBytes);\n return bytes && new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\n\nexport function json(status: number, body: unknown, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...headers,\n },\n });\n}\n","import { CHALLENGE_PATH, answerChallenge } from '@tryghost/app-contracts/identity';\n\nimport { parseOrigin } from '../shared/parse.ts';\nimport { json, readText } from './body.ts';\n\nexport { CHALLENGE_PATH };\n\n/**\n * A JWK, with the members RFC 7517 and RFC 7518 name. It's the package's own, as the DOM's\n * `JsonWebKey` doesn't exist in a backend that types against Node without the DOM library, and\n * a type alias rather than an interface, so a DOM `JsonWebKey` or a jose `JWK` passes for it.\n */\nexport type BackendJwk = {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kid?: string;\n kty?: string;\n n?: string;\n oth?: { d?: string; r?: string; t?: string }[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n};\n\n/**\n * The backend key's private half: a JWK object, or its JSON as it sits in a secret or an\n * environment variable, such as `GHOST_APP_BACKEND_KEY`.\n */\nexport type BackendKey = BackendJwk | string;\n\nexport interface HandleChallengeOptions {\n backendKey: BackendKey;\n /**\n * The app's public origin, such as `https://app.example.com`, for a server that doesn't see\n * the scheme and host Ghost reaches it at, as Node behind a proxy that terminates TLS sees\n * `http://`. Ghost challenges the public origin, so without it every challenge is refused.\n * Take it from the app's own configuration, never from a request's headers, which the sender\n * sets. Workers, and other platforms that report the public URL, don't need it.\n */\n origin?: string;\n}\n\n// Ghost's challenge is about 150 bytes. Anything much larger isn't one.\nconst CHALLENGE_MAX_BYTES = 4 * 1024;\n\nconst INVALID_KEY =\n 'backendKey must be a private Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\", x and d';\n\n// The last key imported, so a backend that answers with one key imports it once.\nlet imported: { text: string; key: Promise<CryptoKey> } | undefined;\n\nfunction importBackendKey(backendKey: BackendKey): Promise<CryptoKey> {\n const text = typeof backendKey === 'string' ? backendKey : JSON.stringify(backendKey);\n if (imported?.text !== text) {\n const key = importPrivateKey(text);\n imported = { text, key };\n // A key that failed to import is tried again next time, so a fixed secret takes effect.\n key.catch(() => {\n if (imported?.key === key) {\n imported = undefined;\n }\n });\n }\n return imported.key;\n}\n\nasync function importPrivateKey(text: string): Promise<CryptoKey> {\n let jwk: unknown;\n try {\n jwk = JSON.parse(text);\n } catch {\n // Never says what the text was: it's a secret.\n throw new TypeError(`${INVALID_KEY}; it isn't JSON`);\n }\n const { kty, crv, x, d } = (typeof jwk === 'object' && jwk !== null ? jwk : {}) as BackendJwk;\n if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || typeof d !== 'string') {\n throw new TypeError(INVALID_KEY);\n }\n try {\n return await crypto.subtle.importKey('jwk', { kty, crv, x, d }, { name: 'Ed25519' }, false, [\n 'sign',\n ]);\n } catch (error) {\n throw new TypeError(INVALID_KEY, { cause: error });\n }\n}\n\n/**\n * Answers Ghost's challenge by signing it with the backend key. Route only `CHALLENGE_PATH`\n * to it, or use `withGhostApp`, which does.\n */\nexport async function handleChallenge(\n request: Request,\n { backendKey, origin }: HandleChallengeOptions,\n): Promise<Response> {\n // A bad `origin` is the app's own misconfiguration, so it throws, and the platform reports a\n // server error, rather than every challenge being refused with a 400 that looks like Ghost's\n // fault.\n const publicOrigin = origin === undefined ? undefined : parseOrigin(origin);\n if (origin !== undefined && !publicOrigin) {\n throw new TypeError(\n `Expected origin to be the app's origin, such as https://app.example.com, not ${origin}`,\n );\n }\n\n // Ghost always POSTs the challenge.\n if (request.method !== 'POST') {\n return json(405, { error: 'Expected a POST' }, { allow: 'POST' });\n }\n\n // A challenge is about 150 bytes, so stop reading at 4 KB rather than buffer whatever a\n // sender streams.\n let body: string | undefined;\n try {\n body = await readText(request, CHALLENGE_MAX_BYTES);\n } catch {\n return json(400, { error: 'Expected a challenge in UTF-8' });\n }\n if (body === undefined) {\n return json(413, { error: `Expected a challenge of at most ${CHALLENGE_MAX_BYTES} bytes` });\n }\n\n // Imported once and cached. A `backendKey` that isn't a private Ed25519 key throws a\n // `TypeError`, a server error, for the same reason as a bad `origin`.\n const key = await importBackendKey(backendKey);\n\n // The challenge names the origin Ghost sent it to, and is answered only for this app's own:\n // the one the platform reports in `request.url`, or `origin` behind a proxy. Never one taken\n // from `X-Forwarded-Host` or another header the sender sets, or anyone could have this\n // backend sign a challenge meant for another app.\n const result = await answerChallenge(body, {\n backendKey: key,\n requestUrl: publicOrigin ?? request.url,\n });\n if (!result.success) {\n return json(400, { error: result.error });\n }\n\n // `{ signature }`: Ghost verifies it against the backend key the signed manifest names.\n return json(200, result.answer);\n}\n","import { CHALLENGE_PATH, handleChallenge, type HandleChallengeOptions } from './challenge.ts';\n\n/**\n * A fetch handler: the request, then whatever else the platform passes, such as a Worker's `env`\n * and `ctx`.\n */\nexport type FetchHandler<Args extends unknown[] = []> = (\n request: Request,\n ...args: Args\n) => Response | Promise<Response>;\n\nexport interface GhostAppOptions<Args extends unknown[] = []> extends HandleChallengeOptions {\n /** The app's own handler, for every request but Ghost's challenge. */\n fetch: FetchHandler<Args>;\n}\n\n/**\n * The app's backend: answers Ghost's challenge at `CHALLENGE_PATH` with `handleChallenge`, and\n * passes every other request to `fetch`, with whatever else the platform passes.\n *\n * It returns `{ fetch }`, so a Worker can export it as it is, and Bun can serve it.\n */\nexport function withGhostApp<Args extends unknown[] = []>({\n fetch,\n ...challenge\n}: GhostAppOptions<Args>): { fetch: (request: Request, ...args: Args) => Promise<Response> } {\n return {\n async fetch(request, ...args) {\n if (new URL(request.url).pathname === CHALLENGE_PATH) {\n return handleChallenge(request, challenge);\n }\n return fetch(request, ...args);\n },\n };\n}\n","import type { SignedManifest } from '../shared/manifest.ts';\n\nexport { MANIFEST_PATH, type SignedManifest } from '../shared/manifest.ts';\n\n/**\n * A response that serves the signed manifest, for a backend that doesn't serve it as a static\n * file. Pass the file's text as it is, or the object it holds.\n *\n * Caches may keep it, but must check it's still current each time, so a new manifest reaches\n * Ghost the next time Ghost reads it.\n */\nexport function serveManifest(signed: SignedManifest | string): Response {\n return new Response(typeof signed === 'string' ? signed : JSON.stringify(signed), {\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-cache',\n },\n });\n}\n"],"mappings":";;;;;;AAMA,eAAsB,SAAS,SAAkB,UAA+C;CAC9F,MAAM,QAAQ,MAAM,UAAU,SAAS,QAAQ;CAC/C,OAAO,SAAS,IAAI,YAAY,SAAS;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AACzF;AAEA,SAAgB,KAAK,QAAgB,MAAe,UAAkC,CAAC,GAAG;CACxF,OAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;EACxC;EACA,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,GAAG;EACL;CACF,CAAC;AACH;;;ACiCA,IAAM,sBAAsB,IAAI;AAEhC,IAAM,cACJ;AAGF,IAAI;AAEJ,SAAS,iBAAiB,YAA4C;CACpE,MAAM,OAAO,OAAO,eAAe,WAAW,aAAa,KAAK,UAAU,UAAU;CACpF,IAAI,UAAU,SAAS,MAAM;EAC3B,MAAM,MAAM,iBAAiB,IAAI;EACjC,WAAW;GAAE;GAAM;EAAI;EAEvB,IAAI,YAAY;GACd,IAAI,UAAU,QAAQ,KACpB,WAAW,KAAA;EAEf,CAAC;CACH;CACA,OAAO,SAAS;AAClB;AAEA,eAAe,iBAAiB,MAAkC;CAChE,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,IAAI;CACvB,QAAQ;EAEN,MAAM,IAAI,UAAU,GAAG,YAAY,gBAAgB;CACrD;CACA,MAAM,EAAE,KAAK,KAAK,GAAG,MAAO,OAAO,QAAQ,YAAY,QAAQ,OAAO,MAAM,CAAC;CAC7E,IAAI,QAAQ,SAAS,QAAQ,aAAa,OAAO,MAAM,YAAY,OAAO,MAAM,UAC9E,MAAM,IAAI,UAAU,WAAW;CAEjC,IAAI;EACF,OAAO,MAAM,OAAO,OAAO,UAAU,OAAO;GAAE;GAAK;GAAK;GAAG;EAAE,GAAG,E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AAG,EAChF,SAAS;EACP,gBAAgB;EAChB,iBAAiB;CACnB,EACF,CAAC;AACH"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/shared/manifest.d.ts
|
|
2
|
+
/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
|
|
3
|
+
declare const MANIFEST_PATH = "/ghost-app.json";
|
|
4
|
+
/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */
|
|
5
|
+
interface SignedManifest {
|
|
6
|
+
protected: string;
|
|
7
|
+
payload: string;
|
|
8
|
+
signature: string;
|
|
9
|
+
}
|
|
10
|
+
/** One problem with a manifest. */
|
|
11
|
+
interface ManifestError {
|
|
12
|
+
/** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */
|
|
13
|
+
path: string;
|
|
14
|
+
message: string;
|
|
15
|
+
}
|
|
16
|
+
/** A manifest's problems, one per line, as `path: message`. */
|
|
17
|
+
declare function formatErrors(errors: readonly ManifestError[], separator?: string): string;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { formatErrors as i, ManifestError as n, SignedManifest as r, MANIFEST_PATH as t };
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { CompactSign, base64url, compactVerify, importJWK } from "jose";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region ../app-contracts/build/identity/keys.js
|
|
4
|
+
function decodeUtf8(bytes) {
|
|
5
|
+
return new TextDecoder("utf-8", {
|
|
6
|
+
fatal: true,
|
|
7
|
+
ignoreBOM: true
|
|
8
|
+
}).decode(bytes);
|
|
9
|
+
}
|
|
10
|
+
function decodeText(encoded) {
|
|
11
|
+
try {
|
|
12
|
+
return decodeUtf8(base64url.decode(encoded));
|
|
13
|
+
} catch {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function decodeJson(encoded) {
|
|
18
|
+
const text = decodeText(encoded);
|
|
19
|
+
if (text === void 0) return;
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(text);
|
|
22
|
+
} catch {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region ../app-contracts/build/identity/jws.js
|
|
28
|
+
/** The only algorithm either key signs with. */
|
|
29
|
+
var ALGORITHM = "Ed25519";
|
|
30
|
+
/**
|
|
31
|
+
* Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any
|
|
32
|
+
* other member could change what the signature covers, as `b64: false` does, or name
|
|
33
|
+
* another key, so the header is checked before the signature and again when verifying.
|
|
34
|
+
*/
|
|
35
|
+
function readExactHeader(encoded, shape) {
|
|
36
|
+
const parsed = shape.safeParse(decodeJson(encoded));
|
|
37
|
+
return parsed.success ? parsed.data : void 0;
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region ../app-contracts/build/identity/challenge.js
|
|
41
|
+
/** Where on an origin Ghost posts a challenge. */
|
|
42
|
+
var CHALLENGE_PATH = "/.well-known/ghost-app/challenge";
|
|
43
|
+
/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */
|
|
44
|
+
var CHALLENGE_PURPOSE = "ghost-app-challenge";
|
|
45
|
+
var NONCE_BYTES = 32;
|
|
46
|
+
var ProtectedHeader = z.strictObject({ alg: z.literal(ALGORITHM) });
|
|
47
|
+
var EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM });
|
|
48
|
+
var ChallengeShape = z.strictObject({
|
|
49
|
+
purpose: z.literal(CHALLENGE_PURPOSE),
|
|
50
|
+
origin: z.string(),
|
|
51
|
+
nonce: z.string()
|
|
52
|
+
});
|
|
53
|
+
var ChallengeAnswerShape = z.object({ signature: z.string() });
|
|
54
|
+
/** The URL to post a challenge for an origin to. */
|
|
55
|
+
function challengeUrl(origin) {
|
|
56
|
+
return new URL(CHALLENGE_PATH, origin).href;
|
|
57
|
+
}
|
|
58
|
+
/** A fresh challenge for an origin, as the exact text to post and to verify the answer with. */
|
|
59
|
+
function createChallenge(origin) {
|
|
60
|
+
const challenge = {
|
|
61
|
+
purpose: CHALLENGE_PURPOSE,
|
|
62
|
+
origin: new URL(origin).origin,
|
|
63
|
+
nonce: base64url.encode(crypto.getRandomValues(new Uint8Array(NONCE_BYTES)))
|
|
64
|
+
};
|
|
65
|
+
return JSON.stringify(challenge);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Answers a challenge a backend received, signing it with the backend key. `requestUrl` is
|
|
69
|
+
* the URL the request arrived at, as the platform reports it (`request.url` on Workers):
|
|
70
|
+
* never one built from `X-Forwarded-Host` or any other header the sender controls. A
|
|
71
|
+
* challenge for any origin but that one is refused, so whoever takes over a name the app
|
|
72
|
+
* used to serve can't relay Ghost's challenge to the real backend to prove it.
|
|
73
|
+
*
|
|
74
|
+
* Ghost can't see this check, so it only helps where the platform routes requests by host,
|
|
75
|
+
* as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.
|
|
76
|
+
*/
|
|
77
|
+
async function answerChallenge(body, { backendKey, requestUrl }) {
|
|
78
|
+
const challenge = ChallengeShape.safeParse(parseJson(body));
|
|
79
|
+
if (!challenge.success) return {
|
|
80
|
+
success: false,
|
|
81
|
+
error: "Expected a challenge of {purpose, origin, nonce}"
|
|
82
|
+
};
|
|
83
|
+
const arrivedAt = URL.parse(requestUrl)?.origin;
|
|
84
|
+
if (arrivedAt !== challenge.data.origin) return {
|
|
85
|
+
success: false,
|
|
86
|
+
error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? "an unknown origin"}`
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
success: true,
|
|
90
|
+
answer: { signature: await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: ALGORITHM }).sign(backendKey) }
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Checks an origin's answer to a challenge: a signature with the backend key over the
|
|
95
|
+
* exact text Ghost posted, under a protected header of only `alg`. The error only says how
|
|
96
|
+
* the answer fell short.
|
|
97
|
+
*/
|
|
98
|
+
async function verifyChallengeAnswer(challenge, answer, backendKey) {
|
|
99
|
+
const parsed = ChallengeAnswerShape.safeParse(parseJson(answer));
|
|
100
|
+
if (!parsed.success) return {
|
|
101
|
+
success: false,
|
|
102
|
+
error: "Expected an answer of {\"signature\": \"<compact JWS>\"}"
|
|
103
|
+
};
|
|
104
|
+
let key;
|
|
105
|
+
try {
|
|
106
|
+
key = await importJWK(backendKey, ALGORITHM);
|
|
107
|
+
} catch {
|
|
108
|
+
return {
|
|
109
|
+
success: false,
|
|
110
|
+
error: "backend_key is not a usable Ed25519 key"
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const [header = ""] = parsed.data.signature.split(".");
|
|
114
|
+
if (!readExactHeader(header, ProtectedHeader)) return {
|
|
115
|
+
success: false,
|
|
116
|
+
error: `Expected a protected header of ${EXPECTED_HEADER}`
|
|
117
|
+
};
|
|
118
|
+
let payload;
|
|
119
|
+
try {
|
|
120
|
+
({payload} = await compactVerify(parsed.data.signature, key, { algorithms: [ALGORITHM] }));
|
|
121
|
+
} catch {
|
|
122
|
+
return {
|
|
123
|
+
success: false,
|
|
124
|
+
error: "The signature was not made with backend_key"
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
if (!sameText(payload, challenge)) return {
|
|
128
|
+
success: false,
|
|
129
|
+
error: "The signature is not over the challenge that was sent"
|
|
130
|
+
};
|
|
131
|
+
return { success: true };
|
|
132
|
+
}
|
|
133
|
+
function sameText(bytes, text) {
|
|
134
|
+
try {
|
|
135
|
+
return decodeUtf8(bytes) === text;
|
|
136
|
+
} catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function parseJson(text) {
|
|
141
|
+
try {
|
|
142
|
+
return JSON.parse(text);
|
|
143
|
+
} catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
//#region src/shared/parse.ts
|
|
149
|
+
var UNSAFE_IN_POLICY = /[\s;,'"*]/;
|
|
150
|
+
/**
|
|
151
|
+
* An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and
|
|
152
|
+
* `,` into a host, so the origin must also read back as itself, and hold nothing that would end
|
|
153
|
+
* a source in a Content-Security-Policy.
|
|
154
|
+
*/
|
|
155
|
+
function parseOrigin(entry) {
|
|
156
|
+
const url = URL.parse(entry);
|
|
157
|
+
const origin = url?.origin;
|
|
158
|
+
if (!url || !origin || url.protocol !== "https:" && url.protocol !== "http:" || url.href !== `${origin}/` || URL.parse(origin)?.origin !== origin || UNSAFE_IN_POLICY.test(entry) || UNSAFE_IN_POLICY.test(origin)) return;
|
|
159
|
+
return origin;
|
|
160
|
+
}
|
|
161
|
+
/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */
|
|
162
|
+
function parseJsonText(text) {
|
|
163
|
+
return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
//#region src/shared/ignore.ts
|
|
167
|
+
/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */
|
|
168
|
+
var ignoreError = () => void 0;
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/shared/body.ts
|
|
171
|
+
/**
|
|
172
|
+
* Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It
|
|
173
|
+
* stops reading as soon as the body passes the limit, so a large body is never held whole.
|
|
174
|
+
*/
|
|
175
|
+
async function readBytes(message, maxBytes) {
|
|
176
|
+
if (Number(message.headers.get("content-length")) > maxBytes) {
|
|
177
|
+
message.body?.cancel().catch(ignoreError);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (!message.body) return /* @__PURE__ */ new Uint8Array();
|
|
181
|
+
const reader = message.body.getReader();
|
|
182
|
+
const chunks = [];
|
|
183
|
+
let length = 0;
|
|
184
|
+
for (;;) {
|
|
185
|
+
const { done, value } = await reader.read();
|
|
186
|
+
if (done) break;
|
|
187
|
+
length += value.byteLength;
|
|
188
|
+
if (length > maxBytes) {
|
|
189
|
+
reader.cancel().catch(ignoreError);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
chunks.push(value);
|
|
193
|
+
}
|
|
194
|
+
const bytes = new Uint8Array(length);
|
|
195
|
+
let offset = 0;
|
|
196
|
+
for (const chunk of chunks) {
|
|
197
|
+
bytes.set(chunk, offset);
|
|
198
|
+
offset += chunk.byteLength;
|
|
199
|
+
}
|
|
200
|
+
return bytes;
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/shared/manifest.ts
|
|
204
|
+
/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */
|
|
205
|
+
var MANIFEST_PATH = "/ghost-app.json";
|
|
206
|
+
/**
|
|
207
|
+
* Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but
|
|
208
|
+
* the site knows: a name that's never any site's, so the rest of the rules apply as Ghost
|
|
209
|
+
* applies them.
|
|
210
|
+
*/
|
|
211
|
+
var UNKNOWN_GHOST_URL = "https://ghost.invalid/";
|
|
212
|
+
/** A manifest's problems, one per line, as `path: message`. */
|
|
213
|
+
function formatErrors(errors, separator = "\n") {
|
|
214
|
+
return errors.map(({ path, message }) => path ? `${path}: ${message}` : message).join(separator);
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
export { ignoreError as a, CHALLENGE_PATH as c, createChallenge as d, verifyChallengeAnswer as f, decodeText as h, readBytes as i, answerChallenge as l, readExactHeader as m, UNKNOWN_GHOST_URL as n, parseJsonText as o, ALGORITHM as p, formatErrors as r, parseOrigin as s, MANIFEST_PATH as t, challengeUrl as u };
|
|
218
|
+
|
|
219
|
+
//# sourceMappingURL=manifest-DX1GTozy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manifest-DX1GTozy.js","names":[],"sources":["../../../app-contracts/build/identity/keys.js","../../../app-contracts/build/identity/jws.js","../../../app-contracts/build/identity/challenge.js","../../src/shared/parse.ts","../../src/shared/ignore.ts","../../src/shared/body.ts","../../src/shared/manifest.ts"],"sourcesContent":["import { base64url, calculateJwkThumbprint } from 'jose';\n/**\n * A key's RFC 7638 thumbprint: the same for a key however its JWK is written, so it is\n * what Ghost stores to recognise a key again.\n */\nexport function thumbprintOf(key) {\n return calculateJwkThumbprint({ kty: key.kty, crv: key.crv, x: key.x }, 'sha256');\n}\nexport function decodeUtf8(bytes) {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n}\nexport function decodeText(encoded) {\n try {\n return decodeUtf8(base64url.decode(encoded));\n }\n catch {\n return undefined;\n }\n}\nexport function decodeJson(encoded) {\n const text = decodeText(encoded);\n if (text === undefined) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=keys.js.map","import { decodeJson } from './keys.js';\n/** The only algorithm either key signs with. */\nexport const ALGORITHM = 'Ed25519';\n/**\n * Reads a JWS protected header that must be exactly `shape`, which is a strict object. Any\n * other member could change what the signature covers, as `b64: false` does, or name\n * another key, so the header is checked before the signature and again when verifying.\n */\nexport function readExactHeader(encoded, shape) {\n const parsed = shape.safeParse(decodeJson(encoded));\n return parsed.success ? parsed.data : undefined;\n}\n//# sourceMappingURL=jws.js.map","import { CompactSign, base64url, compactVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeUtf8 } from './keys.js';\n/** Where on an origin Ghost posts a challenge. */\nexport const CHALLENGE_PATH = '/.well-known/ghost-app/challenge';\n/** What a challenge is for, signed with it, so its answer can't pass for any other signature. */\nexport const CHALLENGE_PURPOSE = 'ghost-app-challenge';\nconst NONCE_BYTES = 32;\nconst ProtectedHeader = z.strictObject({ alg: z.literal(ALGORITHM) });\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM });\nconst ChallengeShape = z.strictObject({\n purpose: z.literal(CHALLENGE_PURPOSE),\n origin: z.string(),\n nonce: z.string(),\n});\nconst ChallengeAnswerShape = z.object({ signature: z.string() });\n/** The URL to post a challenge for an origin to. */\nexport function challengeUrl(origin) {\n return new URL(CHALLENGE_PATH, origin).href;\n}\n/** A fresh challenge for an origin, as the exact text to post and to verify the answer with. */\nexport function createChallenge(origin) {\n const challenge = {\n purpose: CHALLENGE_PURPOSE,\n origin: new URL(origin).origin,\n nonce: base64url.encode(crypto.getRandomValues(new Uint8Array(NONCE_BYTES))),\n };\n return JSON.stringify(challenge);\n}\n/**\n * Answers a challenge a backend received, signing it with the backend key. `requestUrl` is\n * the URL the request arrived at, as the platform reports it (`request.url` on Workers):\n * never one built from `X-Forwarded-Host` or any other header the sender controls. A\n * challenge for any origin but that one is refused, so whoever takes over a name the app\n * used to serve can't relay Ghost's challenge to the real backend to prove it.\n *\n * Ghost can't see this check, so it only helps where the platform routes requests by host,\n * as Workers, Vercel, Netlify and Fly do. A server that answers for any host gains nothing.\n */\nexport async function answerChallenge(body, { backendKey, requestUrl }) {\n const challenge = ChallengeShape.safeParse(parseJson(body));\n if (!challenge.success) {\n return { success: false, error: 'Expected a challenge of {purpose, origin, nonce}' };\n }\n const arrivedAt = URL.parse(requestUrl)?.origin;\n if (arrivedAt !== challenge.data.origin) {\n return {\n success: false,\n error: `The challenge is for ${challenge.data.origin}, but arrived at ${arrivedAt ?? 'an unknown origin'}`,\n };\n }\n const signature = await new CompactSign(new TextEncoder().encode(body))\n .setProtectedHeader({ alg: ALGORITHM })\n .sign(backendKey);\n return { success: true, answer: { signature } };\n}\n/**\n * Checks an origin's answer to a challenge: a signature with the backend key over the\n * exact text Ghost posted, under a protected header of only `alg`. The error only says how\n * the answer fell short.\n */\nexport async function verifyChallengeAnswer(challenge, answer, backendKey) {\n const parsed = ChallengeAnswerShape.safeParse(parseJson(answer));\n if (!parsed.success) {\n return { success: false, error: 'Expected an answer of {\"signature\": \"<compact JWS>\"}' };\n }\n let key;\n try {\n key = await importJWK(backendKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'backend_key is not a usable Ed25519 key' };\n }\n const [header = ''] = parsed.data.signature.split('.');\n if (!readExactHeader(header, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n let payload;\n try {\n ({ payload } = await compactVerify(parsed.data.signature, key, { algorithms: [ALGORITHM] }));\n }\n catch {\n return { success: false, error: 'The signature was not made with backend_key' };\n }\n if (!sameText(payload, challenge)) {\n return { success: false, error: 'The signature is not over the challenge that was sent' };\n }\n return { success: true };\n}\nfunction sameText(bytes, text) {\n try {\n return decodeUtf8(bytes) === text;\n }\n catch {\n return false;\n }\n}\nfunction parseJson(text) {\n try {\n return JSON.parse(text);\n }\n catch {\n return undefined;\n }\n}\n//# sourceMappingURL=challenge.js.map","// Characters that end a source in a policy, a directive or a whole policy, and the wildcard.\nconst UNSAFE_IN_POLICY = /[\\s;,'\"*]/;\n\n/**\n * An HTTP or HTTPS origin, or `undefined` for anything more or less. The URL parser lets `;` and\n * `,` into a host, so the origin must also read back as itself, and hold nothing that would end\n * a source in a Content-Security-Policy.\n */\nexport function parseOrigin(entry: string): string | undefined {\n const url = URL.parse(entry);\n const origin = url?.origin;\n if (\n !url ||\n !origin ||\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.href !== `${origin}/` ||\n URL.parse(origin)?.origin !== origin ||\n UNSAFE_IN_POLICY.test(entry) ||\n UNSAFE_IN_POLICY.test(origin)\n ) {\n return undefined;\n }\n return origin;\n}\n\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text: string): unknown {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n","/** For an error that changes nothing, such as one from cancelling what's no longer wanted. */\nexport const ignoreError = (): undefined => undefined;\n","import { ignoreError } from './ignore.ts';\n\n/**\n * Reads a request's or a response's body, or `undefined` if it is longer than `maxBytes`. It\n * stops reading as soon as the body passes the limit, so a large body is never held whole.\n */\nexport async function readBytes(\n message: Request | Response,\n maxBytes: number,\n): Promise<Uint8Array | undefined> {\n if (Number(message.headers.get('content-length')) > maxBytes) {\n // Too large either way, so a body that refuses to be cancelled changes nothing. Not waited\n // for: one branch of a teed body, as a cloned request's is, cancels only once the other does.\n message.body?.cancel().catch(ignoreError);\n return undefined;\n }\n if (!message.body) {\n return new Uint8Array();\n }\n const reader = message.body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n length += value.byteLength;\n if (length > maxBytes) {\n reader.cancel().catch(ignoreError);\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n","// What the backend, the tooling and the Vite plugin agree on about the signed manifest. Free of\n// Node and of the contracts' validation, as the backend runs on any platform.\n\n/** Where an app serves its signed manifest by convention, and where the SDK's tooling signs it for. */\nexport const MANIFEST_PATH = '/ghost-app.json';\n\n/** A signed manifest: flattened JWS JSON, as `ghost-app sign` or the Vite plugin writes it. */\nexport interface SignedManifest {\n protected: string;\n payload: string;\n signature: string;\n}\n\n/** One problem with a manifest. */\nexport interface ManifestError {\n /** Where in the manifest the problem is, such as `surfaces[0].url`. Empty for the whole. */\n path: string;\n message: string;\n}\n\n/**\n * Stands in for the site's own URL when checking a manifest as Ghost would, which nothing but\n * the site knows: a name that's never any site's, so the rest of the rules apply as Ghost\n * applies them.\n */\nexport const UNKNOWN_GHOST_URL = 'https://ghost.invalid/';\n\n/** A manifest's problems, one per line, as `path: message`. */\nexport function formatErrors(errors: readonly ManifestError[], separator = '\\n'): string {\n return errors\n .map(({ path, message }) => (path ? `${path}: ${message}` : message))\n .join(separator);\n}\n"],"mappings":";;;AAQA,SAAgB,WAAW,OAAO;CAC9B,OAAO,IAAI,YAAY,SAAS;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