@tryghost/app-sdk 0.1.0-alpha.5 → 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 +158 -27
- package/build/backend.d.ts +89 -0
- package/build/backend.js +118 -0
- package/build/backend.js.map +1 -0
- 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 -154
- 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 +16 -3
|
@@ -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;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AAClF;AACA,SAAgB,WAAW,SAAS;CAChC,IAAI;EACA,OAAO,WAAW,UAAU,OAAO,OAAO,CAAC;CAC/C,QACM;EACF;CACJ;AACJ;AACA,SAAgB,WAAW,SAAS;C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K,EAAE,MAAM,cAAe,OAAO,GAAG,KAAK,IAAI,YAAY,OAAQ,CAAC,CACpE,KAAK,SAAS;AACnB"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
//#region ../app-contracts/build/plain-text.js
|
|
2
|
+
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
3
|
+
var PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, "u");
|
|
4
|
+
var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
|
|
5
|
+
/** Whether text is one line of plain text, as a name, a description or a title must be. */
|
|
6
|
+
function isPlainText(value) {
|
|
7
|
+
return PLAIN_TEXT.test(value);
|
|
8
|
+
}
|
|
9
|
+
/** Returns the text with the characters `isPlainText` refuses removed. */
|
|
10
|
+
function toPlainText(value) {
|
|
11
|
+
return value.replace(NOT_PLAIN_TEXT, "");
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region ../app-contracts/build/bridge/rules.js
|
|
15
|
+
/**
|
|
16
|
+
* The bridge's rules that have no dependencies. The root entry point exports them so the SDK
|
|
17
|
+
* can use them without zod. The schemas in this folder build on them, so the SDK and Admin
|
|
18
|
+
* read a path or a refusal the same way.
|
|
19
|
+
*
|
|
20
|
+
* What Admin sends the page has no schema, because Admin builds it and never parses it. Its
|
|
21
|
+
* types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so
|
|
22
|
+
* the guards only check shape and path containment. They turn a mismatch into a clear error
|
|
23
|
+
* rather than `undefined` somewhere in the app. Only the schemas check limits.
|
|
24
|
+
*/
|
|
25
|
+
/** Posted by the app's page to `window.parent` once the SDK has loaded. */
|
|
26
|
+
var HELLO_MESSAGE_TYPE = "ghost-app:hello";
|
|
27
|
+
/**
|
|
28
|
+
* How long an app's page has to start, in milliseconds. Admin gives up on a frame this long
|
|
29
|
+
* after mounting it, and the SDK waits this long for Admin to start the app unless the app
|
|
30
|
+
* passes its own `timeout`. Long enough for a slow page on a slow connection to load and send
|
|
31
|
+
* its hello.
|
|
32
|
+
*/
|
|
33
|
+
var START_TIMEOUT_MS = 1e4;
|
|
34
|
+
/**
|
|
35
|
+
* The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK
|
|
36
|
+
* uppercases what apps pass.
|
|
37
|
+
*/
|
|
38
|
+
var FETCH_METHODS = [
|
|
39
|
+
"GET",
|
|
40
|
+
"POST",
|
|
41
|
+
"PUT",
|
|
42
|
+
"DELETE"
|
|
43
|
+
];
|
|
44
|
+
/**
|
|
45
|
+
* Whether a request with this method may carry a body. Expects an uppercase method from
|
|
46
|
+
* `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.
|
|
47
|
+
*/
|
|
48
|
+
function methodAllowsBody(method) {
|
|
49
|
+
return method !== "GET";
|
|
50
|
+
}
|
|
51
|
+
var RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;
|
|
52
|
+
/**
|
|
53
|
+
* Whether a request header is one that apps may not set, in any case. Admin refuses a request
|
|
54
|
+
* that sets one rather than dropping the header, so the app gets an error instead of wondering
|
|
55
|
+
* why the header never arrived. The browser refuses some of these anyway; they are listed here
|
|
56
|
+
* so that none of them relies on the browser.
|
|
57
|
+
*/
|
|
58
|
+
function isReservedRequestHeader(name) {
|
|
59
|
+
return RESERVED_REQUEST_HEADER.test(name);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The messages Admin and the SDK use when they refuse an argument for the same reason, so an
|
|
63
|
+
* app gets the same message whichever side catches the problem. The SDK checks only for obvious
|
|
64
|
+
* mistakes, before anything crosses the channel; Admin's schemas check everything again.
|
|
65
|
+
*/
|
|
66
|
+
var ARGUMENT_MESSAGES = {
|
|
67
|
+
fetchPath: "Expected an Admin API path such as /posts/, not a URL",
|
|
68
|
+
fetchMethod: `Expected a method of: ${FETCH_METHODS.join(", ")}`,
|
|
69
|
+
fetchBody: "Expected no body on a GET request",
|
|
70
|
+
reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,
|
|
71
|
+
jsonBody: "Expected the body as JSON text",
|
|
72
|
+
appPath: "Expected a path within the app, starting with a single /",
|
|
73
|
+
pathMove: "Expected a move of push or replace",
|
|
74
|
+
place: "Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }"
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* The codes a refused call carries across the channel. The structured clone that carries an
|
|
78
|
+
* error keeps only its message, so the refusing side puts the code at the start of the
|
|
79
|
+
* message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes
|
|
80
|
+
* are only ever added: an SDK that doesn't know a code treats the whole message as a generic
|
|
81
|
+
* refusal.
|
|
82
|
+
*
|
|
83
|
+
* The host codes, which Admin refuses the page's calls with:
|
|
84
|
+
*
|
|
85
|
+
* - `session_ended`: the session is over; the page is about to be replaced.
|
|
86
|
+
* - `invalid_argument`: an argument Admin does not take.
|
|
87
|
+
* - `invalid_path`: a path that is not an Admin API path or a route within the app, or one
|
|
88
|
+
* the Admin API only responds to with a redirect, such as a path without its trailing `/`.
|
|
89
|
+
* - `blocked`: a request the allowlist doesn't allow, or a write it refuses.
|
|
90
|
+
* - `network_error`: Admin could not reach its own API.
|
|
91
|
+
* - `rejected`: anything else; the detail says why.
|
|
92
|
+
*/
|
|
93
|
+
var HOST_ERROR_CODES = [
|
|
94
|
+
"session_ended",
|
|
95
|
+
"invalid_argument",
|
|
96
|
+
"invalid_path",
|
|
97
|
+
"blocked",
|
|
98
|
+
"network_error",
|
|
99
|
+
"rejected"
|
|
100
|
+
];
|
|
101
|
+
[...HOST_ERROR_CODES];
|
|
102
|
+
var CODED_MESSAGE = /^([a-z_]+): ([\s\S]*)$/;
|
|
103
|
+
/**
|
|
104
|
+
* Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass
|
|
105
|
+
* only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.
|
|
106
|
+
*/
|
|
107
|
+
function encodeBridgeError(code, detail) {
|
|
108
|
+
return `${code}: ${detail}`;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the
|
|
112
|
+
* other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for
|
|
113
|
+
* one from the page. Returns `undefined` for a message that doesn't start with one of them.
|
|
114
|
+
*/
|
|
115
|
+
function decodeBridgeError(message, codes) {
|
|
116
|
+
const [, code = "", detail = ""] = CODED_MESSAGE.exec(message) ?? [];
|
|
117
|
+
return codes.includes(code) ? {
|
|
118
|
+
code,
|
|
119
|
+
detail
|
|
120
|
+
} : void 0;
|
|
121
|
+
}
|
|
122
|
+
var THEME_MODES = ["light", "dark"];
|
|
123
|
+
var CONTROL_CHARACTER = /\p{Cc}/u;
|
|
124
|
+
/**
|
|
125
|
+
* Whether a value is a path that stays within the base it is resolved against, rather than
|
|
126
|
+
* escaping it. It must start with a single `/`, so it can't carry a scheme or be read as
|
|
127
|
+
* `//host`. It must not contain `\`, which URL parsers read as `/`, or any control character.
|
|
128
|
+
*/
|
|
129
|
+
function isContainedPath(value) {
|
|
130
|
+
return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
|
|
131
|
+
}
|
|
132
|
+
/** An object, or an array: anything whose fields can be read. */
|
|
133
|
+
function isRecord(value) {
|
|
134
|
+
return typeof value === "object" && value !== null;
|
|
135
|
+
}
|
|
136
|
+
function hasStrings(value, keys) {
|
|
137
|
+
return isRecord(value) && keys.every((key) => typeof value[key] === "string");
|
|
138
|
+
}
|
|
139
|
+
function isTheme(value) {
|
|
140
|
+
return hasStrings(value, ["accent_color"]) && THEME_MODES.includes(value.mode);
|
|
141
|
+
}
|
|
142
|
+
function isStartContext(value) {
|
|
143
|
+
return isRecord(value) && hasStrings(value.site, [
|
|
144
|
+
"url",
|
|
145
|
+
"title",
|
|
146
|
+
"timezone",
|
|
147
|
+
"locale"
|
|
148
|
+
]) && hasStrings(value.user, ["id", "role"]) && isTheme(value.theme) && isRecord(value.session) && Number.isSafeInteger(value.session.revision) && value.session.revision >= 0 && isContainedPath(value.path);
|
|
149
|
+
}
|
|
150
|
+
function isConnectMessage(value) {
|
|
151
|
+
return isRecord(value) && value.type === "ghost-app:connect" && Array.isArray(value.exports) && value.exports.every((name) => typeof name === "string");
|
|
152
|
+
}
|
|
153
|
+
function isFetchResponse(value) {
|
|
154
|
+
return isRecord(value) && Number.isSafeInteger(value.status) && value.status >= 200 && value.status <= 599 && typeof value.statusText === "string" && isRecord(value.headers) && !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string") && typeof value.body === "string";
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
export { toPlainText as _, START_TIMEOUT_MS as a, isConnectMessage as c, isRecord as d, isReservedRequestHeader as f, isPlainText as g, methodAllowsBody as h, HOST_ERROR_CODES as i, isContainedPath as l, isTheme as m, FETCH_METHODS as n, decodeBridgeError as o, isStartContext as p, HELLO_MESSAGE_TYPE as r, encodeBridgeError as s, ARGUMENT_MESSAGES as t, isFetchResponse as u };
|
|
158
|
+
|
|
159
|
+
//# sourceMappingURL=rules-_dou3jRF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rules-_dou3jRF.js","names":[],"sources":["../../../app-contracts/build/plain-text.js","../../../app-contracts/build/bridge/rules.js"],"sourcesContent":["// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so `..` can never climb above its root.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. Even then, the result may not be: resolving `.` and `..` can leave `//` at the\n * start, so `/.//host` becomes `//host`, which resolves to another site. Check the result with\n * `isContainedPath` before resolving it against anything. `AppPathSchema` does both and returns\n * this form.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map"],"mappings":";AAMA,IAAM,UAAU;AAChB,IAAM,aAAa,IAAI,OAAO,KAAK,QAAQ,MAAM,GAAG;AACpD,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI;;AAEvD,SAAgB,YAAY,OAAO;CAC/B,OAAO,WAAW,KAAK,KAAK;AAChC;;AAEA,SAAgB,YAAY,OAAO;CAC/B,OAAO,MAAM,QAAQ,gBAAgB,EAAE;AAC3C;;;;;;;;;;;;;;ACLA,IAAa,qBAAqB;;;;;;;AASlC,IAAa,mBAAmB;;;;;AAOhC,IAAa,gBAAgB;CAAC;CAAO;CAAQ;CAAO;AAAQ;;;;;AAK5D,SAAgB,iBAAiB,QAAQ;CACrC,OAAO,WAAW;AACtB;AAOA,IAAM,0BAA0B;;;;;;;AAOhC,SAAgB,wBAAwB,MAAM;CAC1C,OAAO,wBAAwB,KAAK,IAAI;AAC5C;;;;;;AAMA,IAAa,oBAAoB;CAC7B,WAAW;CACX,aAAa,yBAAyB,cAAc,KAAK,IAAI;CAC7D,WAAW;CAGX,iBAAiB,SAAS,eAAe,KAAK,YAAY,EAAE;CAC5D,UAAU;CACV,SAAS;CACT,UAAU;CACV,OAAO;AACX;;;;;;;;;;;;;;;;;;AAyBA,IAAa,mBAAmB;CAC5B;CACA;CACA;CACA;CACA;CACA;AACJ;AAUkC,CAAC,GAAG,gBAAmC;AACzE,IAAM,gBAAgB;;;;;AAKtB,SAAgB,kBAAkB,MAAM,QAAQ;C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BAAgB,OAAO;CACnC,OAAQ,SAAS,KAAK,KAClB,OAAO,cAAc,MAAM,MAAM,KACjC,MAAM,UAAA,OACN,MAAM,UAAA,OACN,OAAO,MAAM,eAAe,YAC5B,SAAS,MAAM,OAAO,KACtB,CAAC,MAAM,QAAQ,MAAM,OAAO,KAC5B,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,OAAO,WAAW,OAAO,WAAW,QAAQ,KACzE,OAAO,MAAM,SAAS;AAC9B"}
|
package/build/index.js
CHANGED
|
@@ -1,157 +1,5 @@
|
|
|
1
|
+
import { _ as toPlainText, a as START_TIMEOUT_MS, c as isConnectMessage, d as isRecord, f as isReservedRequestHeader, h as methodAllowsBody, i as HOST_ERROR_CODES, l as isContainedPath, m as isTheme, n as FETCH_METHODS, o as decodeBridgeError, p as isStartContext, r as HELLO_MESSAGE_TYPE, s as encodeBridgeError, t as ARGUMENT_MESSAGES, u as isFetchResponse } from "./chunks/rules-_dou3jRF.js";
|
|
1
2
|
import { ThreadMessagePort } from "@quilted/threads";
|
|
2
|
-
//#endregion
|
|
3
|
-
//#region ../app-contracts/build/plain-text.js
|
|
4
|
-
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
5
|
-
new RegExp(`^[${ALLOWED}]*$`, "u");
|
|
6
|
-
var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
|
|
7
|
-
/** Returns the text with the characters `isPlainText` refuses removed. */
|
|
8
|
-
function toPlainText(value) {
|
|
9
|
-
return value.replace(NOT_PLAIN_TEXT, "");
|
|
10
|
-
}
|
|
11
|
-
//#endregion
|
|
12
|
-
//#region ../app-contracts/build/bridge/rules.js
|
|
13
|
-
/**
|
|
14
|
-
* The bridge's rules that have no dependencies. The root entry point exports them so the SDK
|
|
15
|
-
* can use them without zod. The schemas in this folder build on them, so the SDK and Admin
|
|
16
|
-
* read a path or a refusal the same way.
|
|
17
|
-
*
|
|
18
|
-
* What Admin sends the page has no schema, because Admin builds it and never parses it. Its
|
|
19
|
-
* types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so
|
|
20
|
-
* the guards only check shape and path containment. They turn a mismatch into a clear error
|
|
21
|
-
* rather than `undefined` somewhere in the app. Only the schemas check limits.
|
|
22
|
-
*/
|
|
23
|
-
/** Posted by the app's page to `window.parent` once the SDK has loaded. */
|
|
24
|
-
var HELLO_MESSAGE_TYPE = "ghost-app:hello";
|
|
25
|
-
/**
|
|
26
|
-
* How long an app's page has to start, in milliseconds. Admin gives up on a frame this long
|
|
27
|
-
* after mounting it, and the SDK waits this long for Admin to start the app unless the app
|
|
28
|
-
* passes its own `timeout`. Long enough for a slow page on a slow connection to load and send
|
|
29
|
-
* its hello.
|
|
30
|
-
*/
|
|
31
|
-
var START_TIMEOUT_MS = 1e4;
|
|
32
|
-
/**
|
|
33
|
-
* The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK
|
|
34
|
-
* uppercases what apps pass.
|
|
35
|
-
*/
|
|
36
|
-
var FETCH_METHODS = [
|
|
37
|
-
"GET",
|
|
38
|
-
"POST",
|
|
39
|
-
"PUT",
|
|
40
|
-
"DELETE"
|
|
41
|
-
];
|
|
42
|
-
/**
|
|
43
|
-
* Whether a request with this method may carry a body. Expects an uppercase method from
|
|
44
|
-
* `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.
|
|
45
|
-
*/
|
|
46
|
-
function methodAllowsBody(method) {
|
|
47
|
-
return method !== "GET";
|
|
48
|
-
}
|
|
49
|
-
var RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;
|
|
50
|
-
/**
|
|
51
|
-
* Whether a request header is one that apps may not set, in any case. Admin refuses a request
|
|
52
|
-
* that sets one rather than dropping the header, so the app gets an error instead of wondering
|
|
53
|
-
* why the header never arrived. The browser refuses some of these anyway; they are listed here
|
|
54
|
-
* so that none of them relies on the browser.
|
|
55
|
-
*/
|
|
56
|
-
function isReservedRequestHeader(name) {
|
|
57
|
-
return RESERVED_REQUEST_HEADER.test(name);
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* The messages Admin and the SDK use when they refuse an argument for the same reason, so an
|
|
61
|
-
* app gets the same message whichever side catches the problem. The SDK checks only for obvious
|
|
62
|
-
* mistakes, before anything crosses the channel; Admin's schemas check everything again.
|
|
63
|
-
*/
|
|
64
|
-
var ARGUMENT_MESSAGES = {
|
|
65
|
-
fetchPath: "Expected an Admin API path such as /posts/, not a URL",
|
|
66
|
-
fetchMethod: `Expected a method of: ${FETCH_METHODS.join(", ")}`,
|
|
67
|
-
fetchBody: "Expected no body on a GET request",
|
|
68
|
-
reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,
|
|
69
|
-
jsonBody: "Expected the body as JSON text",
|
|
70
|
-
appPath: "Expected a path within the app, starting with a single /",
|
|
71
|
-
pathMove: "Expected a move of push or replace",
|
|
72
|
-
place: "Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }"
|
|
73
|
-
};
|
|
74
|
-
/**
|
|
75
|
-
* The codes a refused call carries across the channel. The structured clone that carries an
|
|
76
|
-
* error keeps only its message, so the refusing side puts the code at the start of the
|
|
77
|
-
* message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes
|
|
78
|
-
* are only ever added: an SDK that doesn't know a code treats the whole message as a generic
|
|
79
|
-
* refusal.
|
|
80
|
-
*
|
|
81
|
-
* The host codes, which Admin refuses the page's calls with:
|
|
82
|
-
*
|
|
83
|
-
* - `session_ended`: the session is over; the page is about to be replaced.
|
|
84
|
-
* - `invalid_argument`: an argument Admin does not take.
|
|
85
|
-
* - `invalid_path`: a path that is not an Admin API path or a route within the app, or one
|
|
86
|
-
* the Admin API only responds to with a redirect, such as a path without its trailing `/`.
|
|
87
|
-
* - `blocked`: a request the allowlist doesn't allow, or a write it refuses.
|
|
88
|
-
* - `network_error`: Admin could not reach its own API.
|
|
89
|
-
* - `rejected`: anything else; the detail says why.
|
|
90
|
-
*/
|
|
91
|
-
var HOST_ERROR_CODES = [
|
|
92
|
-
"session_ended",
|
|
93
|
-
"invalid_argument",
|
|
94
|
-
"invalid_path",
|
|
95
|
-
"blocked",
|
|
96
|
-
"network_error",
|
|
97
|
-
"rejected"
|
|
98
|
-
];
|
|
99
|
-
[...HOST_ERROR_CODES];
|
|
100
|
-
var CODED_MESSAGE = /^([a-z_]+): ([\s\S]*)$/;
|
|
101
|
-
/**
|
|
102
|
-
* Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass
|
|
103
|
-
* only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.
|
|
104
|
-
*/
|
|
105
|
-
function encodeBridgeError(code, detail) {
|
|
106
|
-
return `${code}: ${detail}`;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the
|
|
110
|
-
* other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for
|
|
111
|
-
* one from the page. Returns `undefined` for a message that doesn't start with one of them.
|
|
112
|
-
*/
|
|
113
|
-
function decodeBridgeError(message, codes) {
|
|
114
|
-
const [, code = "", detail = ""] = CODED_MESSAGE.exec(message) ?? [];
|
|
115
|
-
return codes.includes(code) ? {
|
|
116
|
-
code,
|
|
117
|
-
detail
|
|
118
|
-
} : void 0;
|
|
119
|
-
}
|
|
120
|
-
var THEME_MODES = ["light", "dark"];
|
|
121
|
-
var CONTROL_CHARACTER = /\p{Cc}/u;
|
|
122
|
-
/**
|
|
123
|
-
* Whether a value is a path that stays within the base it is resolved against, rather than
|
|
124
|
-
* escaping it. It must start with a single `/`, so it can't carry a scheme or be read as
|
|
125
|
-
* `//host`. It must not contain `\`, which URL parsers read as `/`, or any control character.
|
|
126
|
-
*/
|
|
127
|
-
function isContainedPath(value) {
|
|
128
|
-
return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
|
|
129
|
-
}
|
|
130
|
-
/** An object, or an array: anything whose fields can be read. */
|
|
131
|
-
function isRecord(value) {
|
|
132
|
-
return typeof value === "object" && value !== null;
|
|
133
|
-
}
|
|
134
|
-
function hasStrings(value, keys) {
|
|
135
|
-
return isRecord(value) && keys.every((key) => typeof value[key] === "string");
|
|
136
|
-
}
|
|
137
|
-
function isTheme(value) {
|
|
138
|
-
return hasStrings(value, ["accent_color"]) && THEME_MODES.includes(value.mode);
|
|
139
|
-
}
|
|
140
|
-
function isStartContext(value) {
|
|
141
|
-
return isRecord(value) && hasStrings(value.site, [
|
|
142
|
-
"url",
|
|
143
|
-
"title",
|
|
144
|
-
"timezone",
|
|
145
|
-
"locale"
|
|
146
|
-
]) && hasStrings(value.user, ["id", "role"]) && isTheme(value.theme) && isRecord(value.session) && Number.isSafeInteger(value.session.revision) && value.session.revision >= 0 && isContainedPath(value.path);
|
|
147
|
-
}
|
|
148
|
-
function isConnectMessage(value) {
|
|
149
|
-
return isRecord(value) && value.type === "ghost-app:connect" && Array.isArray(value.exports) && value.exports.every((name) => typeof name === "string");
|
|
150
|
-
}
|
|
151
|
-
function isFetchResponse(value) {
|
|
152
|
-
return isRecord(value) && Number.isSafeInteger(value.status) && value.status >= 200 && value.status <= 599 && typeof value.statusText === "string" && isRecord(value.headers) && !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string") && typeof value.body === "string";
|
|
153
|
-
}
|
|
154
|
-
//#endregion
|
|
155
3
|
//#region src/errors.ts
|
|
156
4
|
/** The only error type the SDK rejects with, so an app can branch on `code`. */
|
|
157
5
|
var GhostAppError = class extends Error {
|
|
@@ -642,7 +490,7 @@ var Channel = class {
|
|
|
642
490
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
643
491
|
* and doesn't read package.json.
|
|
644
492
|
*/
|
|
645
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
493
|
+
var SDK_VERSION = "0.1.0-alpha.7";
|
|
646
494
|
//#endregion
|
|
647
495
|
//#region src/connect.ts
|
|
648
496
|
/**
|