@foliwake/server 0.9.0 → 0.10.2
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 +55 -0
- package/README.md +388 -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/constants.d.ts +4 -1
- package/dist/constants.js +5 -2
- 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 +50 -0
- package/dist/hook-endpoint.js +167 -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 +26 -10
- 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 +22 -4
- package/schemas/remote-2.schema.json +1 -1
- package/schemas/remote-3.schema.json +204 -0
|
@@ -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, hookSecretsFrom } 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: hookSecretsFrom({ names: [secretEnv, hook.previousSecretEnv], env, log }),
|
|
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
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type FoliwakeDeliveryPayload } from './hook.js';
|
|
2
|
+
/** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
|
|
3
|
+
export declare const WARM_LIMIT = 20;
|
|
4
|
+
/** What the endpoint needs from the framework and from the app. */
|
|
5
|
+
export interface HookEndpointDeps {
|
|
6
|
+
/** The configured site. */
|
|
7
|
+
site: string;
|
|
8
|
+
/** What a `ping` answers as `sdk`: the package and its version (`@foliwake/next/0.9.0`). */
|
|
9
|
+
sdk: string;
|
|
10
|
+
/** The accepted secrets, read per request (current, then previous). */
|
|
11
|
+
secrets(): (string | undefined)[];
|
|
12
|
+
/** The live tag of the site (no path) or of one path. */
|
|
13
|
+
liveTag(path?: string): string;
|
|
14
|
+
/** Expires one tag (revalidateTag with the chosen profile). */
|
|
15
|
+
expire(tag: string): void;
|
|
16
|
+
/** Reads one page into the cache again. */
|
|
17
|
+
warm(path: string): Promise<unknown>;
|
|
18
|
+
/** Runs work after the response is sent. */
|
|
19
|
+
schedule(task: () => Promise<void>): void;
|
|
20
|
+
/** Whether pages are read again after a delivery. */
|
|
21
|
+
warmPages: boolean;
|
|
22
|
+
onDelivery?: (payload: FoliwakeDeliveryPayload) => void | Promise<void>;
|
|
23
|
+
toleranceS?: number;
|
|
24
|
+
now?: () => number;
|
|
25
|
+
log: Pick<Console, 'warn' | 'error'>;
|
|
26
|
+
}
|
|
27
|
+
/** Where `hookSecretsFrom` reads and what it warns on. */
|
|
28
|
+
export interface HookSecretSource {
|
|
29
|
+
/** The variables, current first, then the previous one while it is rotated; undefined entries are skipped. */
|
|
30
|
+
names: readonly (string | undefined)[];
|
|
31
|
+
/** Where the variables are read, per call; default process.env. */
|
|
32
|
+
env?: NodeJS.ProcessEnv;
|
|
33
|
+
log: Pick<Console, 'warn'>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The `secrets()` of the hook endpoint read from environment variables: each value is trimmed of leading and
|
|
37
|
+
* trailing whitespace and newlines (a secret pasted from `openssl rand -hex 32` often ends in one), and an
|
|
38
|
+
* all-whitespace value counts as unset. The first time trimming changes a variable's value, one warning names
|
|
39
|
+
* the variable, never the value.
|
|
40
|
+
*/
|
|
41
|
+
export declare function hookSecretsFrom(source: HookSecretSource): () => (string | undefined)[];
|
|
42
|
+
/** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
|
|
43
|
+
export declare function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[];
|
|
44
|
+
/** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
|
|
45
|
+
export declare function warmPaths(payload: FoliwakeDeliveryPayload): string[];
|
|
46
|
+
/**
|
|
47
|
+
* The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
|
|
48
|
+
* body that is not a payload or names another site, 200 otherwise.
|
|
49
|
+
*/
|
|
50
|
+
export declare function createHookEndpoint(deps: HookEndpointDeps): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// The hook endpoint without a framework: verify, parse, expire tags, answer. `@foliwake/next/revalidate` wires it to
|
|
2
|
+
// next/cache and next/server; `@foliwake/server/handler` uses it with the app's own callbacks; tests drive it with
|
|
3
|
+
// plain Request objects.
|
|
4
|
+
import { FoliwakeHookError, HOOK_BODY_LIMIT, isFoliwakePagePath, parseFoliwakeHook, verifyFoliwakeSignature, } from './hook.js';
|
|
5
|
+
/** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
|
|
6
|
+
export const WARM_LIMIT = 20;
|
|
7
|
+
/** The value with surrounding whitespace removed; an all-whitespace value is unset. */
|
|
8
|
+
function trimmedSecret(value) {
|
|
9
|
+
const trimmed = value?.trim();
|
|
10
|
+
return trimmed ? trimmed : undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The `secrets()` of the hook endpoint read from environment variables: each value is trimmed of leading and
|
|
14
|
+
* trailing whitespace and newlines (a secret pasted from `openssl rand -hex 32` often ends in one), and an
|
|
15
|
+
* all-whitespace value counts as unset. The first time trimming changes a variable's value, one warning names
|
|
16
|
+
* the variable, never the value.
|
|
17
|
+
*/
|
|
18
|
+
export function hookSecretsFrom(source) {
|
|
19
|
+
const warned = new Set();
|
|
20
|
+
const read = (name) => {
|
|
21
|
+
const raw = (source.env ?? process.env)[name];
|
|
22
|
+
const secret = trimmedSecret(raw);
|
|
23
|
+
if (raw !== undefined && raw !== secret && !warned.has(name)) {
|
|
24
|
+
warned.add(name);
|
|
25
|
+
source.log.warn(`[foliwake] hook: ${name} has surrounding whitespace; it is trimmed. Store it without.`);
|
|
26
|
+
}
|
|
27
|
+
return secret;
|
|
28
|
+
};
|
|
29
|
+
return () => source.names.map((name) => (name ? read(name) : undefined));
|
|
30
|
+
}
|
|
31
|
+
class TooLarge extends Error {
|
|
32
|
+
}
|
|
33
|
+
function answer(status, body) {
|
|
34
|
+
return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
|
|
35
|
+
}
|
|
36
|
+
function refuse(status, error) {
|
|
37
|
+
return answer(status, { ok: false, error });
|
|
38
|
+
}
|
|
39
|
+
function declaredTooLarge(request) {
|
|
40
|
+
const length = Number(request.headers.get('content-length') ?? '0');
|
|
41
|
+
return Number.isFinite(length) && length > HOOK_BODY_LIMIT;
|
|
42
|
+
}
|
|
43
|
+
function joined(chunks, total) {
|
|
44
|
+
const out = new Uint8Array(total);
|
|
45
|
+
let at = 0;
|
|
46
|
+
for (const chunk of chunks) {
|
|
47
|
+
out.set(chunk, at);
|
|
48
|
+
at += chunk.byteLength;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** The body, cut at HOOK_BODY_LIMIT whatever Content-Length says. */
|
|
53
|
+
async function readBody(request) {
|
|
54
|
+
if (declaredTooLarge(request))
|
|
55
|
+
throw new TooLarge();
|
|
56
|
+
if (!request.body)
|
|
57
|
+
return new Uint8Array();
|
|
58
|
+
const reader = request.body.getReader();
|
|
59
|
+
const chunks = [];
|
|
60
|
+
let total = 0;
|
|
61
|
+
for (let read = await reader.read(); !read.done; read = await reader.read()) {
|
|
62
|
+
total += read.value.byteLength;
|
|
63
|
+
if (total > HOOK_BODY_LIMIT) {
|
|
64
|
+
await reader.cancel().catch(() => { });
|
|
65
|
+
throw new TooLarge();
|
|
66
|
+
}
|
|
67
|
+
chunks.push(read.value);
|
|
68
|
+
}
|
|
69
|
+
return joined(chunks, total);
|
|
70
|
+
}
|
|
71
|
+
/** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
|
|
72
|
+
export function deliveryTags(payload, liveTag) {
|
|
73
|
+
if (payload.all)
|
|
74
|
+
return [liveTag()];
|
|
75
|
+
return (payload.pages ?? []).map((path) => liveTag(path));
|
|
76
|
+
}
|
|
77
|
+
/** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
|
|
78
|
+
export function warmPaths(payload) {
|
|
79
|
+
if (payload.all)
|
|
80
|
+
return [];
|
|
81
|
+
return (payload.pages ?? []).filter(isFoliwakePagePath).slice(0, WARM_LIMIT);
|
|
82
|
+
}
|
|
83
|
+
function scheduleWarm(deps, payload) {
|
|
84
|
+
const paths = warmPaths(payload);
|
|
85
|
+
if (!deps.warmPages || paths.length === 0)
|
|
86
|
+
return;
|
|
87
|
+
deps.schedule(async () => {
|
|
88
|
+
const results = await Promise.allSettled(paths.map((path) => deps.warm(path)));
|
|
89
|
+
const failed = results.filter((r) => r.status === 'rejected').length;
|
|
90
|
+
if (failed > 0)
|
|
91
|
+
deps.log.warn(`[foliwake] hook: ${failed} of ${paths.length} pages were not read again`);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
async function deliver(deps, payload) {
|
|
95
|
+
const tags = deliveryTags(payload, deps.liveTag);
|
|
96
|
+
for (const tag of tags)
|
|
97
|
+
deps.expire(tag);
|
|
98
|
+
try {
|
|
99
|
+
await deps.onDelivery?.(payload);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
deps.log.error('[foliwake] hook: onDelivery failed; the server will send the delivery again', error);
|
|
103
|
+
return refuse(500, 'on_delivery_failed');
|
|
104
|
+
}
|
|
105
|
+
scheduleWarm(deps, payload);
|
|
106
|
+
return answer(200, { ok: true, revalidated: tags });
|
|
107
|
+
}
|
|
108
|
+
function verified(deps, body, request) {
|
|
109
|
+
const check = verifyFoliwakeSignature(body, request.headers.get('foliwake-signature'), deps.secrets(), {
|
|
110
|
+
now: deps.now?.(),
|
|
111
|
+
toleranceS: deps.toleranceS,
|
|
112
|
+
});
|
|
113
|
+
if (check.ok)
|
|
114
|
+
return null;
|
|
115
|
+
if (check.reason !== 'no_secret')
|
|
116
|
+
return refuse(401, `signature_${check.reason}`);
|
|
117
|
+
deps.log.error('[foliwake] hook: no secret is set; every delivery is refused');
|
|
118
|
+
return refuse(500, 'no_secret');
|
|
119
|
+
}
|
|
120
|
+
function payloadOf(body) {
|
|
121
|
+
try {
|
|
122
|
+
return parseFoliwakeHook(body);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (error instanceof FoliwakeHookError)
|
|
126
|
+
return refuse(400, error.message);
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function eventMismatch(request, payload) {
|
|
131
|
+
const event = request.headers.get('foliwake-event');
|
|
132
|
+
return event !== null && event !== payload.event;
|
|
133
|
+
}
|
|
134
|
+
async function handle(deps, request) {
|
|
135
|
+
if (request.method !== 'POST')
|
|
136
|
+
return refuse(405, 'method_not_allowed');
|
|
137
|
+
const body = await readBody(request);
|
|
138
|
+
const refused = verified(deps, body, request);
|
|
139
|
+
if (refused)
|
|
140
|
+
return refused;
|
|
141
|
+
const payload = payloadOf(body);
|
|
142
|
+
if (payload instanceof Response)
|
|
143
|
+
return payload;
|
|
144
|
+
if (eventMismatch(request, payload))
|
|
145
|
+
return refuse(400, 'Foliwake-Event does not match the body');
|
|
146
|
+
if (payload.site !== deps.site)
|
|
147
|
+
return refuse(400, `this app serves the site ${deps.site}`);
|
|
148
|
+
if (payload.event === 'ping')
|
|
149
|
+
return answer(200, { ok: true, site: deps.site, sdk: deps.sdk });
|
|
150
|
+
return deliver(deps, payload);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
|
|
154
|
+
* body that is not a payload or names another site, 200 otherwise.
|
|
155
|
+
*/
|
|
156
|
+
export function createHookEndpoint(deps) {
|
|
157
|
+
return async (request) => {
|
|
158
|
+
try {
|
|
159
|
+
return await handle(deps, request);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (error instanceof TooLarge)
|
|
163
|
+
return refuse(413, 'body_too_large');
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The title of a prepared body: the text of its first <h1>, whitespace collapsed, at most 200 characters.
|
|
2
|
+
import { elements } from './html.js';
|
|
3
|
+
const MAX_TITLE = 200;
|
|
4
|
+
function textOf(nodes) {
|
|
5
|
+
return nodes.map((node) => (node.type === 'text' ? node.data : textOf(node.children))).join('');
|
|
6
|
+
}
|
|
7
|
+
/** The first `<h1>`'s text, or null when there is none or it is empty. */
|
|
8
|
+
export function firstHeading(nodes) {
|
|
9
|
+
for (const element of elements(nodes)) {
|
|
10
|
+
if (element.name !== 'h1')
|
|
11
|
+
continue;
|
|
12
|
+
const text = textOf(element.children).replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE);
|
|
13
|
+
return text === '' ? null : text;
|
|
14
|
+
}
|
|
15
|
+
return null;
|
|
16
|
+
}
|
package/dist/page.d.ts
CHANGED
|
@@ -28,11 +28,21 @@ export interface PrepareOptions {
|
|
|
28
28
|
/** The app's own change of the body (allow-list, artwork, …); its output is checked again. */
|
|
29
29
|
transform?: (html: string, envelope: PageEnvelope) => string;
|
|
30
30
|
}
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The same-origin URL of the blocks module, or null without an entry.
|
|
33
|
+
*
|
|
34
|
+
* @param entry - The module inside the code release; default the config's `app.blocks.entry`.
|
|
35
|
+
*/
|
|
36
|
+
export declare function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId, entry?: string | null): {
|
|
33
37
|
base: string;
|
|
34
38
|
url: string;
|
|
35
39
|
} | null;
|
|
40
|
+
/** The blocks a page mounts: the config's, or (version 3 without `app.blocks`) the ones its code release names. */
|
|
41
|
+
export declare function pageBlocksOf(config: FoliwakeAppConfig, envelope: PageEnvelope): {
|
|
42
|
+
entry: string | null;
|
|
43
|
+
major: number;
|
|
44
|
+
eventPrefix: string;
|
|
45
|
+
};
|
|
36
46
|
/**
|
|
37
47
|
* Per request, after the cache: check → rewrite media/links → transform → check again → serialise.
|
|
38
48
|
*
|