@foliwake/server 0.8.0 → 0.10.0
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/CHANGELOG.md +60 -0
- package/README.md +589 -7
- package/dist/blocks-header.d.ts +5 -0
- package/dist/blocks-header.js +47 -0
- package/dist/config-checks.d.ts +9 -0
- package/dist/config-checks.js +53 -0
- package/dist/config-parts.d.ts +50 -0
- package/dist/config-parts.js +190 -0
- package/dist/config-v3.d.ts +22 -0
- package/dist/config-v3.js +104 -0
- package/dist/config.d.ts +11 -11
- package/dist/config.js +7 -222
- package/dist/discovery.d.ts +48 -0
- package/dist/discovery.js +150 -0
- package/dist/handler.d.ts +46 -0
- package/dist/handler.js +153 -0
- package/dist/hook-endpoint.d.ts +35 -0
- package/dist/hook-endpoint.js +143 -0
- package/dist/hook.d.ts +91 -0
- package/dist/hook.js +188 -0
- package/dist/page-title.d.ts +3 -0
- package/dist/page-title.js +16 -0
- package/dist/page.d.ts +12 -2
- package/dist/page.js +32 -12
- package/dist/preload.d.ts +1 -1
- package/dist/preload.js +4 -4
- package/dist/resolve.d.ts +31 -0
- package/dist/resolve.js +76 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/package.json +25 -3
- package/schemas/remote-3.schema.json +204 -0
package/dist/config.js
CHANGED
|
@@ -7,236 +7,21 @@
|
|
|
7
7
|
import { readFile } from 'node:fs/promises';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { FoliwakeConfigError } from './errors.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
10
|
+
import { compileGlob, globMatches } from './glob.js';
|
|
11
|
+
import { isObject, onlyKeys, parseApp, parseEndpoint, refuseSecrets, SITE } from './config-parts.js';
|
|
12
12
|
export { FoliwakeConfigError } from './errors.js';
|
|
13
|
+
export { checkEnvName, checkUsername, isLoopbackName, parseRemoteUrl } from './config-checks.js';
|
|
13
14
|
/** The default config file name, looked up in the current directory. */
|
|
14
15
|
export const CONFIG_FILE = 'foliwake.remote.json';
|
|
15
16
|
/** The environment variable that names another config file. */
|
|
16
17
|
export const CONFIG_ENV = 'FOLIWAKE_REMOTE';
|
|
17
18
|
/** The channels a config can name. */
|
|
18
19
|
export const CHANNELS = Object.freeze(['live', 'preview']);
|
|
19
|
-
const SECRET_KEYS = /^(password|passwd|pass|secret|token|apikey|api_key|authorization|credentials?|private_?key|signing_?key|jwk|d)$/i;
|
|
20
|
-
const ISSUER = /^[A-Za-z0-9._:/-]{1,256}$/;
|
|
21
|
-
const KID = /^[A-Za-z0-9._-]{1,128}$/;
|
|
22
|
-
const SITE = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
23
|
-
const PREFIX = /^(?:\/[a-z0-9-]+)+$/;
|
|
24
|
-
const RESERVED_PREFIXES = ['/', '/_next', '/api', '/code', '/media'];
|
|
25
|
-
const ENTRY_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
|
|
26
|
-
const ENTRY_ROOTS = ['scripts', 'components', '_foliwake'];
|
|
27
|
-
const CONTRACT = /^foliwake-blocks\/([1-9][0-9]{0,2})$/;
|
|
28
|
-
const EVENT_PREFIX = /^[a-z][a-z0-9-]{0,31}$/;
|
|
29
|
-
const DEFAULTS = { code: '/foliwake-code', media: '/foliwake-media', contract: 'foliwake-blocks/2', eventPrefix: 'block', revalidate: 300 };
|
|
30
|
-
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
31
|
-
/** True for 127.x, localhost, *.localhost and ::1. */
|
|
32
|
-
export function isLoopbackName(hostname) {
|
|
33
|
-
const name = hostname.toLowerCase().replace(/\.$/, '');
|
|
34
|
-
if (name === 'localhost' || name.endsWith('.localhost'))
|
|
35
|
-
return true;
|
|
36
|
-
if (name === '[::1]' || name === '::1')
|
|
37
|
-
return true;
|
|
38
|
-
return /^127(?:\.\d{1,3}){3}$/.test(name);
|
|
39
|
-
}
|
|
40
|
-
function safeUrlText(value) {
|
|
41
|
-
return value.replace(/\/\/[^/@]*@/, '//…@').slice(0, 200);
|
|
42
|
-
}
|
|
43
|
-
/** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
|
|
44
|
-
export function parseRemoteUrl(value, where) {
|
|
45
|
-
if (typeof value !== 'string' || value.trim() === '')
|
|
46
|
-
throw new FoliwakeConfigError(`${where}: give the URL of the deployed site, e.g. "https://preview.example.org".`);
|
|
47
|
-
let url;
|
|
48
|
-
try {
|
|
49
|
-
url = new URL(value);
|
|
50
|
-
}
|
|
51
|
-
catch {
|
|
52
|
-
throw new FoliwakeConfigError(`${where}: "${safeUrlText(value)}" is not a valid URL.`);
|
|
53
|
-
}
|
|
54
|
-
if (url.username || url.password)
|
|
55
|
-
throw new FoliwakeConfigError(`${where}: the URL must not contain a user name or password; name the password's environment variable in "auth" instead.`);
|
|
56
|
-
if (url.protocol !== 'https:' && url.protocol !== 'http:')
|
|
57
|
-
throw new FoliwakeConfigError(`${where}: only https URLs are supported.`);
|
|
58
|
-
if (url.protocol === 'http:' && !isLoopbackName(url.hostname)) {
|
|
59
|
-
throw new FoliwakeConfigError(`${where}: ${url.origin} uses plain http; use https (http is accepted only for loopback hosts such as 127.0.0.1).`);
|
|
60
|
-
}
|
|
61
|
-
if (url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) {
|
|
62
|
-
throw new FoliwakeConfigError(`${where}: give the site origin only (scheme, host and port), without a path, query or fragment: ${url.origin}`);
|
|
63
|
-
}
|
|
64
|
-
return url.origin;
|
|
65
|
-
}
|
|
66
|
-
/** Validates an environment variable NAME (never a value). */
|
|
67
|
-
export function checkEnvName(value, where, extra) {
|
|
68
|
-
const problem = basicEnvNameProblem(value, where) ?? (extra ? extra(value, where) : null);
|
|
69
|
-
if (problem)
|
|
70
|
-
throw new FoliwakeConfigError(problem);
|
|
71
|
-
return value;
|
|
72
|
-
}
|
|
73
|
-
/** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
|
|
74
|
-
export function checkUsername(value, where) {
|
|
75
|
-
if (typeof value !== 'string' || value === '' || value.length > 128 || /[:\u0000-\u001f\u007f]/.test(value)) {
|
|
76
|
-
throw new FoliwakeConfigError(`${where}: give a user name without ":" or control characters.`);
|
|
77
|
-
}
|
|
78
|
-
return value;
|
|
79
|
-
}
|
|
80
|
-
function refuseSecrets(value, at, file) {
|
|
81
|
-
if (Array.isArray(value))
|
|
82
|
-
value.forEach((item, i) => refuseSecrets(item, `${at}[${i}]`, file));
|
|
83
|
-
if (!isObject(value))
|
|
84
|
-
return;
|
|
85
|
-
for (const [key, child] of Object.entries(value)) {
|
|
86
|
-
if (SECRET_KEYS.test(key)) {
|
|
87
|
-
throw new FoliwakeConfigError(`${file}: "${at}${key}" looks like a stored secret. This file is committed: ` +
|
|
88
|
-
'keep only the NAME of an environment variable ("passwordEnv", "privateKeyEnv") ' +
|
|
89
|
-
'and remove the secret (rotate it if it was committed).');
|
|
90
|
-
}
|
|
91
|
-
refuseSecrets(child, `${at}${key}.`, file);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
function onlyKeys(value, allowed, where) {
|
|
95
|
-
for (const key of Object.keys(value)) {
|
|
96
|
-
if (!allowed.includes(key))
|
|
97
|
-
throw new FoliwakeConfigError(`${where}: unknown key "${key}" (allowed: ${allowed.join(', ')}).`);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
function parseEndpoint(value, where, opts) {
|
|
101
|
-
if (!isObject(value))
|
|
102
|
-
throw new FoliwakeConfigError(`${where}: must be an object {"url": …, "auth": …}.`);
|
|
103
|
-
onlyKeys(value, ['url', 'auth'], where);
|
|
104
|
-
const origin = parseRemoteUrl(value.url, `${where}.url`);
|
|
105
|
-
if (value.auth === undefined || value.auth === null)
|
|
106
|
-
return { origin, auth: null };
|
|
107
|
-
return { origin, auth: parseAuth(value.auth, `${where}.auth`, opts) };
|
|
108
|
-
}
|
|
109
|
-
const AUTH_SHAPES = '{"type": "basic", "username": …, "passwordEnv": …} or ' +
|
|
110
|
-
'{"type": "service-token", "issuer": …, "kid": …, "privateKeyEnv": …}';
|
|
111
|
-
function parseBasicAuth(auth, where, opts) {
|
|
112
|
-
onlyKeys(auth, ['type', 'username', 'passwordEnv'], where);
|
|
113
|
-
return {
|
|
114
|
-
type: 'basic',
|
|
115
|
-
username: checkUsername(auth.username, `${where}.username`),
|
|
116
|
-
passwordEnv: checkEnvName(auth.passwordEnv, `${where}.passwordEnv`, opts.envNameProblem),
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
function parseServiceTokenAuth(auth, where, opts) {
|
|
120
|
-
onlyKeys(auth, ['type', 'issuer', 'kid', 'privateKeyEnv'], where);
|
|
121
|
-
if (typeof auth.issuer !== 'string' || !ISSUER.test(auth.issuer)) {
|
|
122
|
-
throw new FoliwakeConfigError(`${where}.issuer: the issuer the delivery expects (its TOKEN_ISSUER), [A-Za-z0-9._:/-], such as "my-app".`);
|
|
123
|
-
}
|
|
124
|
-
if (typeof auth.kid !== 'string' || !KID.test(auth.kid)) {
|
|
125
|
-
throw new FoliwakeConfigError(`${where}.kid: the key id of the public key the delivery holds, [A-Za-z0-9._-], such as "my-app-2026-11".`);
|
|
126
|
-
}
|
|
127
|
-
return {
|
|
128
|
-
type: 'service-token',
|
|
129
|
-
issuer: auth.issuer,
|
|
130
|
-
kid: auth.kid,
|
|
131
|
-
privateKeyEnv: checkEnvName(auth.privateKeyEnv, `${where}.privateKeyEnv`, opts.envNameProblem),
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
function parseAuth(auth, where, opts) {
|
|
135
|
-
if (!isObject(auth))
|
|
136
|
-
throw new FoliwakeConfigError(`${where}: must be ${AUTH_SHAPES}.`);
|
|
137
|
-
if (auth.type === 'basic')
|
|
138
|
-
return parseBasicAuth(auth, where, opts);
|
|
139
|
-
if (auth.type === 'service-token')
|
|
140
|
-
return parseServiceTokenAuth(auth, where, opts);
|
|
141
|
-
throw new FoliwakeConfigError(`${where}.type: "basic" or "service-token"; the auth must be ${AUTH_SHAPES}.`);
|
|
142
|
-
}
|
|
143
|
-
function parsePrefix(value, fallback, where) {
|
|
144
|
-
if (value === undefined)
|
|
145
|
-
return fallback;
|
|
146
|
-
if (typeof value !== 'string' || !PREFIX.test(value))
|
|
147
|
-
throw new FoliwakeConfigError(`${where}: an absolute app path of [a-z0-9-] segments, such as "${fallback}".`);
|
|
148
|
-
return value;
|
|
149
|
-
}
|
|
150
|
-
function parseProxies(value, where) {
|
|
151
|
-
if (value === undefined)
|
|
152
|
-
return { code: DEFAULTS.code, media: DEFAULTS.media, pages: null };
|
|
153
|
-
if (!isObject(value))
|
|
154
|
-
throw new FoliwakeConfigError(`${where}: must be an object {"code": …, "media": …, "pages": null}.`);
|
|
155
|
-
onlyKeys(value, ['code', 'media', 'pages'], where);
|
|
156
|
-
if (value.pages !== undefined && value.pages !== null)
|
|
157
|
-
throw new FoliwakeConfigError(`${where}.pages: must be null in this version (the pages proxy comes with client-side reads).`);
|
|
158
|
-
const proxies = { code: parsePrefix(value.code, DEFAULTS.code, `${where}.code`), media: parsePrefix(value.media, DEFAULTS.media, `${where}.media`), pages: null };
|
|
159
|
-
const list = [proxies.code, proxies.media];
|
|
160
|
-
for (const prefix of list) {
|
|
161
|
-
const reserved = RESERVED_PREFIXES.find((r) => prefix === r || (r !== '/' && prefix.startsWith(`${r}/`)));
|
|
162
|
-
if (reserved)
|
|
163
|
-
throw new FoliwakeConfigError(`${where}: "${prefix}" collides with the reserved app path ${reserved}.`);
|
|
164
|
-
}
|
|
165
|
-
if (proxies.code === proxies.media || proxies.code.startsWith(`${proxies.media}/`) || proxies.media.startsWith(`${proxies.code}/`)) {
|
|
166
|
-
throw new FoliwakeConfigError(`${where}: "code" and "media" must be different prefixes, neither inside the other.`);
|
|
167
|
-
}
|
|
168
|
-
return proxies;
|
|
169
|
-
}
|
|
170
|
-
function parseEntry(value, where) {
|
|
171
|
-
if (value === undefined || value === null)
|
|
172
|
-
return null;
|
|
173
|
-
const problem = 'a path inside a code release, such as "scripts/blocks.js": 1–8 segments of [A-Za-z0-9_.-], the first one scripts, components or _foliwake, ending in .js';
|
|
174
|
-
if (typeof value !== 'string')
|
|
175
|
-
throw new FoliwakeConfigError(`${where}: ${problem}.`);
|
|
176
|
-
const segments = value.split('/');
|
|
177
|
-
if (segments.length < 2 || segments.length > 8 || !ENTRY_ROOTS.includes(segments[0]) || !value.endsWith('.js')
|
|
178
|
-
|| segments.some((s) => !ENTRY_SEGMENT.test(s) || s === '.' || s === '..' || s.includes('..'))) {
|
|
179
|
-
throw new FoliwakeConfigError(`${where}: ${problem}.`);
|
|
180
|
-
}
|
|
181
|
-
return value;
|
|
182
|
-
}
|
|
183
|
-
function parseBlocks(value, where) {
|
|
184
|
-
const blocks = value === undefined ? {} : value;
|
|
185
|
-
if (!isObject(blocks))
|
|
186
|
-
throw new FoliwakeConfigError(`${where}: must be an object {"entry": …, "contract": …, "eventPrefix": …}.`);
|
|
187
|
-
onlyKeys(blocks, ['entry', 'contract', 'eventPrefix'], where);
|
|
188
|
-
const contract = blocks.contract === undefined ? DEFAULTS.contract : blocks.contract;
|
|
189
|
-
const match = typeof contract === 'string' ? CONTRACT.exec(contract) : null;
|
|
190
|
-
if (!match)
|
|
191
|
-
throw new FoliwakeConfigError(`${where}.contract: "foliwake-blocks/<major>", such as "foliwake-blocks/2".`);
|
|
192
|
-
const eventPrefix = blocks.eventPrefix === undefined ? DEFAULTS.eventPrefix : blocks.eventPrefix;
|
|
193
|
-
if (typeof eventPrefix !== 'string' || !EVENT_PREFIX.test(eventPrefix))
|
|
194
|
-
throw new FoliwakeConfigError(`${where}.eventPrefix: [a-z][a-z0-9-], at most 32 characters.`);
|
|
195
|
-
return { entry: parseEntry(blocks.entry, `${where}.entry`), contract: contract, major: Number(match[1]), eventPrefix };
|
|
196
|
-
}
|
|
197
|
-
function parseMedia(value, where) {
|
|
198
|
-
if (value === undefined || value === null)
|
|
199
|
-
return null;
|
|
200
|
-
if (!isObject(value))
|
|
201
|
-
throw new FoliwakeConfigError(`${where}: must be an object {"base": "https://…", "transform": "cloudflare-images"}.`);
|
|
202
|
-
onlyKeys(value, ['base', 'transform'], where);
|
|
203
|
-
const base = parseRemoteUrl(value.base, `${where}.base`);
|
|
204
|
-
if (!base.startsWith('https:'))
|
|
205
|
-
throw new FoliwakeConfigError(`${where}.base: must be https.`);
|
|
206
|
-
if (value.transform !== undefined && value.transform !== null && value.transform !== 'cloudflare-images') {
|
|
207
|
-
throw new FoliwakeConfigError(`${where}.transform: only "cloudflare-images" (or null) is supported.`);
|
|
208
|
-
}
|
|
209
|
-
return { base, transform: value.transform === 'cloudflare-images' ? 'cloudflare-images' : null };
|
|
210
|
-
}
|
|
211
|
-
function parsePages(value, where) {
|
|
212
|
-
if (!Array.isArray(value) || value.length === 0 || value.length > GLOB_LIMITS.globsPerList) {
|
|
213
|
-
throw new FoliwakeConfigError(`${where}: a list of 1–${GLOB_LIMITS.globsPerList} page globs, such as ["/lessons/**"].`);
|
|
214
|
-
}
|
|
215
|
-
return value.map((glob, i) => {
|
|
216
|
-
const problem = typeof glob === 'string' ? globProblem(glob) : 'must be a string';
|
|
217
|
-
if (problem)
|
|
218
|
-
throw new FoliwakeConfigError(`${where}[${i}]: ${problem}.`);
|
|
219
|
-
return glob;
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
function parseApp(value, where) {
|
|
223
|
-
if (!isObject(value))
|
|
224
|
-
throw new FoliwakeConfigError(`${where}: must be an object {"pages": […], …}.`);
|
|
225
|
-
onlyKeys(value, ['pages', 'proxies', 'blocks', 'media', 'revalidate'], where);
|
|
226
|
-
const revalidate = value.revalidate === undefined ? DEFAULTS.revalidate : value.revalidate;
|
|
227
|
-
if (typeof revalidate !== 'number' || !Number.isInteger(revalidate) || revalidate < 1 || revalidate > 86_400) {
|
|
228
|
-
throw new FoliwakeConfigError(`${where}.revalidate: whole seconds between 1 and 86400.`);
|
|
229
|
-
}
|
|
230
|
-
return {
|
|
231
|
-
pages: Object.freeze(parsePages(value.pages, `${where}.pages`)),
|
|
232
|
-
proxies: parseProxies(value.proxies, `${where}.proxies`),
|
|
233
|
-
blocks: parseBlocks(value.blocks, `${where}.blocks`),
|
|
234
|
-
media: parseMedia(value.media, `${where}.media`),
|
|
235
|
-
revalidate,
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
20
|
function unsupportedVersion(file, version) {
|
|
239
|
-
|
|
21
|
+
const text = `${file}: unsupported "version" ${JSON.stringify(version)}; it must be 2.`;
|
|
22
|
+
if (version !== 3)
|
|
23
|
+
return new FoliwakeConfigError(text);
|
|
24
|
+
return new FoliwakeConfigError(`${text} Version 3 holds overrides for an app configured by FOLIWAKE_URL.`);
|
|
240
25
|
}
|
|
241
26
|
/** Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field. */
|
|
242
27
|
export function parseFoliwakeConfig(text, opts = {}) {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Where a site serves its discovery document, on each of its hosts. */
|
|
2
|
+
export declare const DISCOVERY_PATH = "/.well-known/foliwake.json";
|
|
3
|
+
/** The environment variable with the site's live origin. */
|
|
4
|
+
export declare const URL_ENV = "FOLIWAKE_URL";
|
|
5
|
+
/** The major of the discovery format this package reads. */
|
|
6
|
+
export declare const DISCOVERY_VERSION = 1;
|
|
7
|
+
/** The plain HTML contract this package reads (`X-Code-Release` on `.plain.html`). */
|
|
8
|
+
export declare const PLAIN_CONTRACT = 2;
|
|
9
|
+
/** The largest discovery document read, in bytes. */
|
|
10
|
+
export declare const DISCOVERY_LIMIT: number;
|
|
11
|
+
/** A validated discovery document. Unknown keys are ignored, so a newer engine may add some. */
|
|
12
|
+
export interface FoliwakeDiscovery {
|
|
13
|
+
site: string;
|
|
14
|
+
live: {
|
|
15
|
+
url: string;
|
|
16
|
+
};
|
|
17
|
+
/** Null when the site has no preview host. Its Basic user is always `preview`. */
|
|
18
|
+
preview: {
|
|
19
|
+
url: string;
|
|
20
|
+
} | null;
|
|
21
|
+
/** The CDN that resizes live images (its origin), or null. */
|
|
22
|
+
media: {
|
|
23
|
+
cdn: string;
|
|
24
|
+
} | null;
|
|
25
|
+
contracts: {
|
|
26
|
+
plain: number;
|
|
27
|
+
html: number | null;
|
|
28
|
+
blocks: number | null;
|
|
29
|
+
hook: number | null;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** Options of `fetchDiscovery`. */
|
|
33
|
+
export interface FetchDiscoveryOptions {
|
|
34
|
+
/** A fetch implementation (tests); default globalThis.fetch. */
|
|
35
|
+
fetch?: typeof fetch;
|
|
36
|
+
/** Per attempt; default 5000. */
|
|
37
|
+
timeoutMs?: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Validates a discovery document read from `origin` (the scheme, host and port of FOLIWAKE_URL).
|
|
41
|
+
* Throws FoliwakeConfigError naming the field.
|
|
42
|
+
*/
|
|
43
|
+
export declare function parseDiscovery(value: unknown, origin: string): FoliwakeDiscovery;
|
|
44
|
+
/**
|
|
45
|
+
* Reads and validates the discovery document of the site at `siteUrl` (FOLIWAKE_URL: https, or http for loopback
|
|
46
|
+
* hosts; origin only). 5 s per attempt, one retry, no redirects, at most 16 KiB of JSON.
|
|
47
|
+
*/
|
|
48
|
+
export declare function fetchDiscovery(siteUrl: string, opts?: FetchDiscoveryOptions): Promise<FoliwakeDiscovery>;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// The site's discovery document, `GET <live origin>/.well-known/foliwake.json`: the public facts an app needs to
|
|
2
|
+
// read a site (its preview origin, media CDN and contract majors), so the app is configured by one address,
|
|
3
|
+
// FOLIWAKE_URL. The document holds no secrets; trust in it is limited by these rules: `live.url` must be the
|
|
4
|
+
// origin it was read from, other origins are parsed like config origins, redirects are not followed and the
|
|
5
|
+
// size is capped.
|
|
6
|
+
import { parseRemoteUrl } from './config-checks.js';
|
|
7
|
+
import { isObject, SITE } from './config-parts.js';
|
|
8
|
+
import { FoliwakeConfigError } from './errors.js';
|
|
9
|
+
import { readLimited, TooLargeError } from './stream.js';
|
|
10
|
+
/** Where a site serves its discovery document, on each of its hosts. */
|
|
11
|
+
export const DISCOVERY_PATH = '/.well-known/foliwake.json';
|
|
12
|
+
/** The environment variable with the site's live origin. */
|
|
13
|
+
export const URL_ENV = 'FOLIWAKE_URL';
|
|
14
|
+
/** The major of the discovery format this package reads. */
|
|
15
|
+
export const DISCOVERY_VERSION = 1;
|
|
16
|
+
/** The plain HTML contract this package reads (`X-Code-Release` on `.plain.html`). */
|
|
17
|
+
export const PLAIN_CONTRACT = 2;
|
|
18
|
+
/** The largest discovery document read, in bytes. */
|
|
19
|
+
export const DISCOVERY_LIMIT = 16 * 1024;
|
|
20
|
+
const TIMEOUT_MS = 5000;
|
|
21
|
+
function problem(where, text) {
|
|
22
|
+
return new FoliwakeConfigError(`${where}: ${text}`);
|
|
23
|
+
}
|
|
24
|
+
function positiveOrNull(value) {
|
|
25
|
+
return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null;
|
|
26
|
+
}
|
|
27
|
+
function checkVersions(doc, where) {
|
|
28
|
+
const format = isObject(doc.foliwake) ? doc.foliwake.discovery : undefined;
|
|
29
|
+
if (format !== DISCOVERY_VERSION) {
|
|
30
|
+
const text = `discovery format ${JSON.stringify(format)}; this package reads ${DISCOVERY_VERSION}.`;
|
|
31
|
+
throw problem(where, `${text} Update @foliwake/next (or the engine) so both speak the same format.`);
|
|
32
|
+
}
|
|
33
|
+
const contracts = isObject(doc.contracts) ? doc.contracts : {};
|
|
34
|
+
if (contracts.plain !== PLAIN_CONTRACT) {
|
|
35
|
+
const served = JSON.stringify(contracts.plain);
|
|
36
|
+
const text = `the site serves plain/${served}; this package reads plain/${PLAIN_CONTRACT}.`;
|
|
37
|
+
throw problem(where, `${text} The site runs an older or newer engine than this package expects.`);
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
plain: PLAIN_CONTRACT,
|
|
41
|
+
html: positiveOrNull(contracts.html),
|
|
42
|
+
blocks: positiveOrNull(contracts.blocks),
|
|
43
|
+
hook: positiveOrNull(contracts.hook),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function liveOf(doc, origin, where) {
|
|
47
|
+
const live = isObject(doc.live) ? parseRemoteUrl(doc.live.url, `${where} "live.url"`) : null;
|
|
48
|
+
if (live !== origin) {
|
|
49
|
+
throw problem(where, `"live.url" is ${JSON.stringify(live)}, but the document was read from ${origin}.`);
|
|
50
|
+
}
|
|
51
|
+
return { url: live };
|
|
52
|
+
}
|
|
53
|
+
function previewOf(doc, where) {
|
|
54
|
+
if (doc.preview === null || doc.preview === undefined)
|
|
55
|
+
return null;
|
|
56
|
+
if (!isObject(doc.preview))
|
|
57
|
+
throw problem(where, '"preview" must be an object {"url": …} or null.');
|
|
58
|
+
return { url: parseRemoteUrl(doc.preview.url, `${where} "preview.url"`) };
|
|
59
|
+
}
|
|
60
|
+
function mediaOf(doc, where) {
|
|
61
|
+
const cdn = isObject(doc.media) ? doc.media.cdn : null;
|
|
62
|
+
if (cdn === null || cdn === undefined)
|
|
63
|
+
return null;
|
|
64
|
+
const origin = parseRemoteUrl(cdn, `${where} "media.cdn"`);
|
|
65
|
+
if (!origin.startsWith('https:'))
|
|
66
|
+
throw problem(where, '"media.cdn" must be https.');
|
|
67
|
+
return { cdn: origin };
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Validates a discovery document read from `origin` (the scheme, host and port of FOLIWAKE_URL).
|
|
71
|
+
* Throws FoliwakeConfigError naming the field.
|
|
72
|
+
*/
|
|
73
|
+
export function parseDiscovery(value, origin) {
|
|
74
|
+
const where = `${origin}${DISCOVERY_PATH}`;
|
|
75
|
+
if (!isObject(value))
|
|
76
|
+
throw problem(where, 'not a JSON object.');
|
|
77
|
+
const contracts = checkVersions(value, where);
|
|
78
|
+
if (typeof value.site !== 'string' || !SITE.test(value.site))
|
|
79
|
+
throw problem(where, '"site" is not a site name.');
|
|
80
|
+
return Object.freeze({
|
|
81
|
+
site: value.site,
|
|
82
|
+
live: liveOf(value, origin, where),
|
|
83
|
+
preview: previewOf(value, where),
|
|
84
|
+
media: mediaOf(value, where),
|
|
85
|
+
contracts,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function isJson(response) {
|
|
89
|
+
return /^application\/json\s*(;|$)/i.test(response.headers.get('content-type') ?? '');
|
|
90
|
+
}
|
|
91
|
+
async function bodyOf(response, where) {
|
|
92
|
+
if (!isJson(response))
|
|
93
|
+
throw problem(where, 'the answer is not application/json.');
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(new TextDecoder().decode(await readLimited(response, DISCOVERY_LIMIT)));
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error instanceof TooLargeError)
|
|
99
|
+
throw problem(where, `larger than ${DISCOVERY_LIMIT} bytes.`);
|
|
100
|
+
throw problem(where, 'the answer is not valid JSON.');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function statusProblem(response, where) {
|
|
104
|
+
if (response.status >= 300 && response.status < 400) {
|
|
105
|
+
return problem(where, `redirects (HTTP ${response.status}); give FOLIWAKE_URL as the site's final origin.`);
|
|
106
|
+
}
|
|
107
|
+
if (response.status === 404) {
|
|
108
|
+
return problem(where, 'not found (HTTP 404): the site runs an engine without discovery, or this is not its URL.');
|
|
109
|
+
}
|
|
110
|
+
return problem(where, `HTTP ${response.status}.`);
|
|
111
|
+
}
|
|
112
|
+
/** Network failures and 5xx are tried once more; anything else is an answer. */
|
|
113
|
+
async function requestTwice(url, opts) {
|
|
114
|
+
const doFetch = opts.fetch ?? globalThis.fetch;
|
|
115
|
+
const attempt = () => doFetch(url, {
|
|
116
|
+
redirect: 'manual',
|
|
117
|
+
headers: { Accept: 'application/json' },
|
|
118
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? TIMEOUT_MS),
|
|
119
|
+
});
|
|
120
|
+
try {
|
|
121
|
+
const first = await attempt();
|
|
122
|
+
if (first.status < 500)
|
|
123
|
+
return first;
|
|
124
|
+
await first.body?.cancel().catch(() => { });
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// tried again below
|
|
128
|
+
}
|
|
129
|
+
return attempt();
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Reads and validates the discovery document of the site at `siteUrl` (FOLIWAKE_URL: https, or http for loopback
|
|
133
|
+
* hosts; origin only). 5 s per attempt, one retry, no redirects, at most 16 KiB of JSON.
|
|
134
|
+
*/
|
|
135
|
+
export async function fetchDiscovery(siteUrl, opts = {}) {
|
|
136
|
+
const origin = parseRemoteUrl(siteUrl, URL_ENV);
|
|
137
|
+
const where = `${origin}${DISCOVERY_PATH}`;
|
|
138
|
+
let response;
|
|
139
|
+
try {
|
|
140
|
+
response = await requestTwice(where, opts);
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
throw problem(where, `no answer (${error.name}).`);
|
|
144
|
+
}
|
|
145
|
+
if (response.status !== 200) {
|
|
146
|
+
await response.body?.cancel().catch(() => { });
|
|
147
|
+
throw statusProblem(response, where);
|
|
148
|
+
}
|
|
149
|
+
return parseDiscovery(await bodyOf(response, where), origin);
|
|
150
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type FoliwakeAppConfig } from './config.js';
|
|
2
|
+
import { type AuthorizePreview } from './handlers.js';
|
|
3
|
+
import type { FoliwakeDeliveryPayload } from './hook.js';
|
|
4
|
+
/** The variable the hook's shared secret is read from by default. */
|
|
5
|
+
export declare const HOOK_SECRET_ENV = "FOLIWAKE_HOOK_SECRET";
|
|
6
|
+
/** Where the handler is mounted by default: `/foliwake/hook`, `/foliwake/health`. */
|
|
7
|
+
export declare const HANDLER_BASE = "/foliwake";
|
|
8
|
+
/** The hook endpoint of the handler. */
|
|
9
|
+
export interface FoliwakeHookOptions {
|
|
10
|
+
/** The variable holding the shared secret; default FOLIWAKE_HOOK_SECRET. */
|
|
11
|
+
secretEnv?: string;
|
|
12
|
+
/** While the secret is rotated: the variable holding the previous one, also accepted. */
|
|
13
|
+
previousSecretEnv?: string;
|
|
14
|
+
/** Called for every delivery (expire your own caches here); a throw answers 500 and the server retries. */
|
|
15
|
+
onDelivery?: (payload: FoliwakeDeliveryPayload) => void | Promise<void>;
|
|
16
|
+
/** The allowed clock distance of the signature, in seconds; default 300. */
|
|
17
|
+
toleranceS?: number;
|
|
18
|
+
/** Replaces the endpoint (a framework adapter's own, such as Next's tag expiry). */
|
|
19
|
+
endpoint?: (request: Request) => Promise<Response>;
|
|
20
|
+
}
|
|
21
|
+
/** Options of `createFoliwakeHandler`. */
|
|
22
|
+
export interface FoliwakeHandlerOptions {
|
|
23
|
+
/** The app config, or how to get it; default loadAppConfig() (FOLIWAKE_URL + the optional file), once. */
|
|
24
|
+
config?: FoliwakeAppConfig | (() => FoliwakeAppConfig | Promise<FoliwakeAppConfig>);
|
|
25
|
+
/** The app path of the hook and health routes; default `/foliwake`. */
|
|
26
|
+
base?: string;
|
|
27
|
+
/** The app's author check for preview files; default `false` (preview answers 404). */
|
|
28
|
+
authorizePreview?: AuthorizePreview;
|
|
29
|
+
/** The hook endpoint's options; `false` answers 404 on `<base>/hook`. */
|
|
30
|
+
hook?: false | FoliwakeHookOptions;
|
|
31
|
+
/** Where secrets and FOLIWAKE_URL are read; default process.env. */
|
|
32
|
+
env?: NodeJS.ProcessEnv;
|
|
33
|
+
/** A fetch implementation (tests); default globalThis.fetch. */
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
log?: Pick<Console, 'warn' | 'error'>;
|
|
36
|
+
}
|
|
37
|
+
/** A request handler on the Web Fetch API. */
|
|
38
|
+
export type FoliwakeFetchHandler = (request: Request) => Promise<Response>;
|
|
39
|
+
/**
|
|
40
|
+
* The Foliwake routes of an app as one `(request) => Promise<Response>`. The config is read on the first request
|
|
41
|
+
* (FOLIWAKE_URL and its discovery document, unless `config` is given) and kept; a failed read is tried again on the
|
|
42
|
+
* next request and answers 503 meanwhile.
|
|
43
|
+
*
|
|
44
|
+
* @param opts - `config`, `base`, `authorizePreview` (default false), `hook`, `env`, `fetch`, `log`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function createFoliwakeHandler(opts?: FoliwakeHandlerOptions): FoliwakeFetchHandler;
|
package/dist/handler.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// One handler for every Foliwake route of an app, on the Web Request/Response of any framework (Hono, Express with a
|
|
2
|
+
// fetch adapter, Bun, Deno, Next): the code and media proxies under the config's prefixes, the hook a Foliwake
|
|
3
|
+
// server calls after a change, and a health check. Preview is off unless the app passes its author check.
|
|
4
|
+
//
|
|
5
|
+
// <proxies.code>/[preview/]<cd>/<file> GET, HEAD files of a code release (codeHandler)
|
|
6
|
+
// <proxies.media>/[preview/]<sha256>.<ext> GET, HEAD hashed pictures (mediaHandler)
|
|
7
|
+
// <base>/hook POST signed hook (FOLIWAKE_HOOK_SECRET)
|
|
8
|
+
// <base>/health GET, HEAD { ok, site }, no-store
|
|
9
|
+
// anything else 404
|
|
10
|
+
import { checkEnvName } from './config.js';
|
|
11
|
+
import { PREFIX } from './config-parts.js';
|
|
12
|
+
import { codeHandler, mediaHandler } from './handlers.js';
|
|
13
|
+
import { createHookEndpoint } from './hook-endpoint.js';
|
|
14
|
+
import { createOriginClient } from './origin.js';
|
|
15
|
+
import { loadAppConfig } from './resolve.js';
|
|
16
|
+
import { SERVER_SDK } from './version.js';
|
|
17
|
+
/** The variable the hook's shared secret is read from by default. */
|
|
18
|
+
export const HOOK_SECRET_ENV = 'FOLIWAKE_HOOK_SECRET';
|
|
19
|
+
/** Where the handler is mounted by default: `/foliwake/hook`, `/foliwake/health`. */
|
|
20
|
+
export const HANDLER_BASE = '/foliwake';
|
|
21
|
+
function text(status, body) {
|
|
22
|
+
const headers = { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' };
|
|
23
|
+
return new Response(`${body}\n`, { status, headers: { ...headers, 'X-Content-Type-Options': 'nosniff' } });
|
|
24
|
+
}
|
|
25
|
+
/** The decoded segments of `pathname` under `prefix`, or null when it is not under it. */
|
|
26
|
+
function segmentsUnder(pathname, prefix) {
|
|
27
|
+
if (!pathname.startsWith(`${prefix}/`))
|
|
28
|
+
return null;
|
|
29
|
+
try {
|
|
30
|
+
return pathname
|
|
31
|
+
.slice(prefix.length + 1)
|
|
32
|
+
.split('/')
|
|
33
|
+
.map(decodeURIComponent);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function routeOf(pathname, config, base) {
|
|
40
|
+
const app = config.app;
|
|
41
|
+
const code = segmentsUnder(pathname, app.proxies.code);
|
|
42
|
+
if (code)
|
|
43
|
+
return { kind: 'code', path: code };
|
|
44
|
+
const media = segmentsUnder(pathname, app.proxies.media);
|
|
45
|
+
if (media)
|
|
46
|
+
return { kind: 'media', path: media };
|
|
47
|
+
if (pathname === `${base}/hook`)
|
|
48
|
+
return { kind: 'hook' };
|
|
49
|
+
if (pathname === `${base}/health`)
|
|
50
|
+
return { kind: 'health' };
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
function checkOptions(opts) {
|
|
54
|
+
const base = opts.base ?? HANDLER_BASE;
|
|
55
|
+
if (!PREFIX.test(base)) {
|
|
56
|
+
throw new TypeError(`base: an absolute app path of [a-z0-9-] segments, such as "${HANDLER_BASE}".`);
|
|
57
|
+
}
|
|
58
|
+
const authorize = opts.authorizePreview ?? false;
|
|
59
|
+
if (authorize !== false && typeof authorize !== 'function') {
|
|
60
|
+
throw new TypeError('authorizePreview: a function or false.');
|
|
61
|
+
}
|
|
62
|
+
if (opts.hook) {
|
|
63
|
+
if (opts.hook.secretEnv !== undefined)
|
|
64
|
+
checkEnvName(opts.hook.secretEnv, 'hook.secretEnv');
|
|
65
|
+
if (opts.hook.previousSecretEnv !== undefined)
|
|
66
|
+
checkEnvName(opts.hook.previousSecretEnv, 'hook.previousSecretEnv');
|
|
67
|
+
}
|
|
68
|
+
return base;
|
|
69
|
+
}
|
|
70
|
+
function defaultHook(config, opts, hook) {
|
|
71
|
+
const env = opts.env ?? process.env;
|
|
72
|
+
const log = opts.log ?? console;
|
|
73
|
+
const secretEnv = hook.secretEnv ?? HOOK_SECRET_ENV;
|
|
74
|
+
return createHookEndpoint({
|
|
75
|
+
site: config.site,
|
|
76
|
+
sdk: SERVER_SDK,
|
|
77
|
+
secrets: () => [env[secretEnv], hook.previousSecretEnv && env[hook.previousSecretEnv]],
|
|
78
|
+
liveTag: (path) => `foliwake:${config.site}:live${path === undefined ? '' : `:page:${path}`}`,
|
|
79
|
+
expire: () => { },
|
|
80
|
+
warm: async () => { },
|
|
81
|
+
schedule: (task) => void task().catch((error) => log.error('[foliwake] hook task failed', error)),
|
|
82
|
+
warmPages: false,
|
|
83
|
+
onDelivery: hook.onDelivery,
|
|
84
|
+
toleranceS: hook.toleranceS,
|
|
85
|
+
log,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function hookOf(config, opts) {
|
|
89
|
+
if (opts.hook === false)
|
|
90
|
+
return null;
|
|
91
|
+
const hook = opts.hook ?? {};
|
|
92
|
+
return hook.endpoint ?? defaultHook(config, opts, hook);
|
|
93
|
+
}
|
|
94
|
+
async function configOf(opts) {
|
|
95
|
+
if (typeof opts.config === 'function')
|
|
96
|
+
return opts.config();
|
|
97
|
+
if (opts.config)
|
|
98
|
+
return opts.config;
|
|
99
|
+
return loadAppConfig({ env: opts.env, fetch: opts.fetch });
|
|
100
|
+
}
|
|
101
|
+
async function prepare(opts) {
|
|
102
|
+
const config = await configOf(opts);
|
|
103
|
+
if (!config.app)
|
|
104
|
+
throw new TypeError(`${config.from}: "app" is required for an app.`);
|
|
105
|
+
const client = createOriginClient(config, opts.env ?? process.env, opts.fetch ? { fetch: opts.fetch } : {});
|
|
106
|
+
const proxy = { authorizePreview: opts.authorizePreview ?? false };
|
|
107
|
+
const code = codeHandler(config, client, proxy);
|
|
108
|
+
return { config, code, media: mediaHandler(config, client, proxy), hook: hookOf(config, opts) };
|
|
109
|
+
}
|
|
110
|
+
function health(request, config) {
|
|
111
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
112
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
113
|
+
}
|
|
114
|
+
const response = Response.json({ ok: true, site: config.site }, { headers: { 'Cache-Control': 'no-store' } });
|
|
115
|
+
return request.method === 'HEAD' ? new Response(null, { headers: response.headers }) : response;
|
|
116
|
+
}
|
|
117
|
+
async function dispatch(request, ready, base) {
|
|
118
|
+
const route = routeOf(new URL(request.url).pathname, ready.config, base);
|
|
119
|
+
if (route === null)
|
|
120
|
+
return text(404, 'Not found');
|
|
121
|
+
if (route.kind === 'code')
|
|
122
|
+
return ready.code(request, { path: route.path });
|
|
123
|
+
if (route.kind === 'media')
|
|
124
|
+
return ready.media(request, { path: route.path });
|
|
125
|
+
if (route.kind === 'health')
|
|
126
|
+
return health(request, ready.config);
|
|
127
|
+
return ready.hook ? ready.hook(request) : text(404, 'Not found');
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The Foliwake routes of an app as one `(request) => Promise<Response>`. The config is read on the first request
|
|
131
|
+
* (FOLIWAKE_URL and its discovery document, unless `config` is given) and kept; a failed read is tried again on the
|
|
132
|
+
* next request and answers 503 meanwhile.
|
|
133
|
+
*
|
|
134
|
+
* @param opts - `config`, `base`, `authorizePreview` (default false), `hook`, `env`, `fetch`, `log`.
|
|
135
|
+
*/
|
|
136
|
+
export function createFoliwakeHandler(opts = {}) {
|
|
137
|
+
const base = checkOptions(opts);
|
|
138
|
+
const log = opts.log ?? console;
|
|
139
|
+
let ready = null;
|
|
140
|
+
return async (request) => {
|
|
141
|
+
ready ??= prepare(opts);
|
|
142
|
+
let current;
|
|
143
|
+
try {
|
|
144
|
+
current = await ready;
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
ready = null;
|
|
148
|
+
log.error('[foliwake] the app config could not be read', error);
|
|
149
|
+
return text(503, 'Foliwake is not configured');
|
|
150
|
+
}
|
|
151
|
+
return dispatch(request, current, base);
|
|
152
|
+
};
|
|
153
|
+
}
|