@foliwake/server 0.0.0-stage → 0.4.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 +94 -0
- package/LICENSE +202 -0
- package/README.md +1000 -2
- package/dist/config.d.ts +111 -0
- package/dist/config.js +321 -0
- package/dist/constants.d.ts +26 -0
- package/dist/constants.js +46 -0
- package/dist/csp.d.ts +25 -0
- package/dist/csp.js +78 -0
- package/dist/env-names.d.ts +2 -0
- package/dist/env-names.js +20 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.js +16 -0
- package/dist/glob.d.ts +10 -0
- package/dist/glob.js +68 -0
- package/dist/handlers.d.ts +17 -0
- package/dist/handlers.js +118 -0
- package/dist/html-parse.d.ts +25 -0
- package/dist/html-parse.js +147 -0
- package/dist/html.d.ts +27 -0
- package/dist/html.js +148 -0
- package/dist/media-rewrite.d.ts +9 -0
- package/dist/media-rewrite.js +37 -0
- package/dist/origin.d.ts +36 -0
- package/dist/origin.js +129 -0
- package/dist/page.d.ts +43 -0
- package/dist/page.js +188 -0
- package/dist/preload.d.ts +14 -0
- package/dist/preload.js +139 -0
- package/dist/stream.d.ts +9 -0
- package/dist/stream.js +59 -0
- package/package.json +82 -3
- package/schemas/remote-2.schema.json +110 -0
package/dist/origin.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ChannelName } from '@foliwake/blocks-contract/page';
|
|
2
|
+
import { type FoliwakeAppConfig } from './config.js';
|
|
3
|
+
/** Seconds a service token lives: `exp = iat + 60`. Delivery accepts at most 120, with 5 s of clock skew. */
|
|
4
|
+
export declare const SERVICE_TOKEN_LIFETIME_SECONDS = 60;
|
|
5
|
+
/** Options of one origin request. */
|
|
6
|
+
export interface OriginRequestOptions {
|
|
7
|
+
method?: 'GET' | 'HEAD';
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
/** Only these headers are sent (never a browser's). */
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
}
|
|
12
|
+
/** Requests to the configured live and preview origins, with the credential added per request. */
|
|
13
|
+
export interface OriginClient {
|
|
14
|
+
readonly config: FoliwakeAppConfig;
|
|
15
|
+
/** The origin of a channel (for messages and loopback checks). */
|
|
16
|
+
originOf(channel: ChannelName): string;
|
|
17
|
+
/** GET/HEAD `<origin><path>`; `redirect: 'manual'`, 10 s timeout unless `signal` is given. */
|
|
18
|
+
request(channel: ChannelName, path: string, opts?: OriginRequestOptions): Promise<Response>;
|
|
19
|
+
}
|
|
20
|
+
/** Options of `createOriginClient`. */
|
|
21
|
+
export interface OriginClientOptions {
|
|
22
|
+
/** A fetch implementation (tests); default globalThis.fetch. */
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
/** The clock of service tokens, in milliseconds (tests); default Date.now. */
|
|
26
|
+
now?: () => number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The client for the config's origins. The secret is read from the environment at each request (a rotated
|
|
30
|
+
* secret takes effect without a restart) and goes only into the Authorization header: `basic` sends the
|
|
31
|
+
* password of `passwordEnv`; `service-token` signs a fresh token for the request's exact path with the
|
|
32
|
+
* private key of `privateKeyEnv`.
|
|
33
|
+
*
|
|
34
|
+
* @param env - Where secrets are read (default `process.env`).
|
|
35
|
+
*/
|
|
36
|
+
export declare function createOriginClient(config: FoliwakeAppConfig, env?: NodeJS.ProcessEnv, opts?: OriginClientOptions): OriginClient;
|
package/dist/origin.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { SignJWT, importJWK } from 'jose';
|
|
2
|
+
import { endpointOf } from './config.js';
|
|
3
|
+
import { LIMITS } from './constants.js';
|
|
4
|
+
import { FoliwakeConfigError } from './errors.js';
|
|
5
|
+
/** Seconds a service token lives: `exp = iat + 60`. Delivery accepts at most 120, with 5 s of clock skew. */
|
|
6
|
+
export const SERVICE_TOKEN_LIFETIME_SECONDS = 60;
|
|
7
|
+
function basicAuthorization(auth, channel, config, env) {
|
|
8
|
+
const password = env[auth.passwordEnv];
|
|
9
|
+
if (password === undefined || password === '') {
|
|
10
|
+
throw new FoliwakeConfigError(`The ${channel} site needs the password in the environment variable ${auth.passwordEnv} ` +
|
|
11
|
+
`(named in ${config.from}); it is not set on this server.`);
|
|
12
|
+
}
|
|
13
|
+
return `Basic ${Buffer.from(`${auth.username}:${password}`, 'utf8').toString('base64')}`;
|
|
14
|
+
}
|
|
15
|
+
const PRIVATE_KEY_SHAPE = 'an ES256 private key as JWK JSON text ({"kty": "EC", "crv": "P-256", "x", "y", "d"})';
|
|
16
|
+
function isEs256PrivateKey(key) {
|
|
17
|
+
if (key === null || typeof key !== 'object' || Array.isArray(key))
|
|
18
|
+
return false;
|
|
19
|
+
const jwk = key;
|
|
20
|
+
return jwk.kty === 'EC' && jwk.crv === 'P-256' && typeof jwk.d === 'string';
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The private key JWK in `text`, checked against the config's `kid`. `where` names the variable in
|
|
24
|
+
* messages, which never contain the value or a parse error of it.
|
|
25
|
+
*/
|
|
26
|
+
function parsePrivateKey(text, auth, where) {
|
|
27
|
+
let key;
|
|
28
|
+
try {
|
|
29
|
+
key = JSON.parse(text);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw new FoliwakeConfigError(`${where} is not valid JSON: it must be ${PRIVATE_KEY_SHAPE}.`);
|
|
33
|
+
}
|
|
34
|
+
if (!isEs256PrivateKey(key))
|
|
35
|
+
throw new FoliwakeConfigError(`${where} must be ${PRIVATE_KEY_SHAPE}.`);
|
|
36
|
+
if (key.alg !== undefined && key.alg !== 'ES256') {
|
|
37
|
+
throw new FoliwakeConfigError(`${where}: "alg" must be "ES256" when given.`);
|
|
38
|
+
}
|
|
39
|
+
if (key.kid !== undefined && key.kid !== auth.kid) {
|
|
40
|
+
const found = String(key.kid).slice(0, 128);
|
|
41
|
+
throw new FoliwakeConfigError(`${where} has kid "${found}", but the config names kid "${auth.kid}": ` +
|
|
42
|
+
'the delivery would look up the wrong public key.');
|
|
43
|
+
}
|
|
44
|
+
return key;
|
|
45
|
+
}
|
|
46
|
+
// The private key of a variable's current text. The parsed key is kept for the same text only, so a
|
|
47
|
+
// rotated value takes effect at the next request. Messages never contain the value or a parse error of it.
|
|
48
|
+
function createPrivateKeyReader() {
|
|
49
|
+
let last = null;
|
|
50
|
+
return (auth, channel, config, env) => {
|
|
51
|
+
const text = env[auth.privateKeyEnv];
|
|
52
|
+
const where = `The ${channel} site's signing key in ${auth.privateKeyEnv} (named in ${config.from})`;
|
|
53
|
+
if (text === undefined || text === '') {
|
|
54
|
+
throw new FoliwakeConfigError(`The ${channel} site needs ${PRIVATE_KEY_SHAPE} in the environment variable ${auth.privateKeyEnv} ` +
|
|
55
|
+
`(named in ${config.from}); it is not set on this server.`);
|
|
56
|
+
}
|
|
57
|
+
if (last && last.text === text && last.kid === auth.kid)
|
|
58
|
+
return last.key;
|
|
59
|
+
const key = parsePrivateKey(text, auth, where);
|
|
60
|
+
const imported = importJWK(key, 'ES256').catch(() => {
|
|
61
|
+
throw new FoliwakeConfigError(`${where} could not be read as ${PRIVATE_KEY_SHAPE}.`);
|
|
62
|
+
});
|
|
63
|
+
last = { text, kid: auth.kid, key: imported };
|
|
64
|
+
imported.catch(() => {
|
|
65
|
+
if (last?.key === imported)
|
|
66
|
+
last = null;
|
|
67
|
+
});
|
|
68
|
+
return imported;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The service token of one request: ES256, header `kid`, claims `iss`, `aud: site:<site>`, `iat`,
|
|
73
|
+
* `exp = iat + 60` and `path`, the exact path of the request as it goes on the wire (no query).
|
|
74
|
+
*/
|
|
75
|
+
async function serviceTokenAuthorization(auth, site, path, key, nowMs) {
|
|
76
|
+
const iat = Math.floor(nowMs / 1000);
|
|
77
|
+
const token = await new SignJWT({ path })
|
|
78
|
+
.setProtectedHeader({ alg: 'ES256', kid: auth.kid, typ: 'JWT' })
|
|
79
|
+
.setIssuer(auth.issuer)
|
|
80
|
+
.setAudience(`site:${site}`)
|
|
81
|
+
.setIssuedAt(iat)
|
|
82
|
+
.setExpirationTime(iat + SERVICE_TOKEN_LIFETIME_SECONDS)
|
|
83
|
+
.sign(key);
|
|
84
|
+
return `Bearer ${token}`;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The client for the config's origins. The secret is read from the environment at each request (a rotated
|
|
88
|
+
* secret takes effect without a restart) and goes only into the Authorization header: `basic` sends the
|
|
89
|
+
* password of `passwordEnv`; `service-token` signs a fresh token for the request's exact path with the
|
|
90
|
+
* private key of `privateKeyEnv`.
|
|
91
|
+
*
|
|
92
|
+
* @param env - Where secrets are read (default `process.env`).
|
|
93
|
+
*/
|
|
94
|
+
export function createOriginClient(config, env = process.env, opts = {}) {
|
|
95
|
+
const doFetch = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
96
|
+
const timeoutMs = opts.timeoutMs ?? LIMITS.timeoutMs;
|
|
97
|
+
const now = opts.now ?? Date.now;
|
|
98
|
+
const privateKeyOf = createPrivateKeyReader();
|
|
99
|
+
async function authorization(channel, url) {
|
|
100
|
+
const { auth } = endpointOf(config, channel);
|
|
101
|
+
if (!auth)
|
|
102
|
+
return null;
|
|
103
|
+
if (auth.type === 'basic')
|
|
104
|
+
return basicAuthorization(auth, channel, config, env);
|
|
105
|
+
const key = await privateKeyOf(auth, channel, config, env);
|
|
106
|
+
return serviceTokenAuthorization(auth, config.site, url.pathname, key, now());
|
|
107
|
+
}
|
|
108
|
+
return Object.freeze({
|
|
109
|
+
config,
|
|
110
|
+
originOf: (channel) => endpointOf(config, channel).origin,
|
|
111
|
+
async request(channel, path, ropts = {}) {
|
|
112
|
+
if (!path.startsWith('/') || path.startsWith('//'))
|
|
113
|
+
throw new TypeError('origin path must be absolute');
|
|
114
|
+
const { origin } = endpointOf(config, channel);
|
|
115
|
+
// Parsed once: the token names the path exactly as this URL sends it.
|
|
116
|
+
const url = new URL(`${origin}${path}`);
|
|
117
|
+
const headers = { ...(ropts.headers ?? {}) };
|
|
118
|
+
const auth = await authorization(channel, url);
|
|
119
|
+
if (auth)
|
|
120
|
+
headers.Authorization = auth;
|
|
121
|
+
return doFetch(url.href, {
|
|
122
|
+
method: ropts.method ?? 'GET',
|
|
123
|
+
headers,
|
|
124
|
+
redirect: 'manual',
|
|
125
|
+
signal: ropts.signal ?? AbortSignal.timeout(timeoutMs),
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ChannelName, CodeReleaseId, FoliwakePageData, PageEnvelope } from '@foliwake/blocks-contract/page';
|
|
2
|
+
import { type FoliwakeAppConfig } from './config.js';
|
|
3
|
+
import type { OriginClient } from './origin.js';
|
|
4
|
+
export { FoliwakePageError, type PageErrorKind } from './errors.js';
|
|
5
|
+
export { pageImportMap } from '@foliwake/blocks-contract/import-map';
|
|
6
|
+
export type { PageEnvelope, FoliwakePageData } from '@foliwake/blocks-contract/page';
|
|
7
|
+
/** The origin URL path of a page's body (`/` → `/index.plain.html`). */
|
|
8
|
+
export declare function plainPath(pagePath: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* Reads `<path>.plain.html` from the channel's origin. Primitive inputs only, no callbacks and no signal
|
|
11
|
+
* (an internal 10 s timeout), so it can run inside a cache function. Refuses paths outside `app.pages`.
|
|
12
|
+
*
|
|
13
|
+
* @param site - The config's site (`config.site`); another site is refused.
|
|
14
|
+
* @param path - The page path (`/`, `/lessons/a`).
|
|
15
|
+
* @returns The envelope; throws FoliwakePageError (`not_found`, `not_allowed`, `origin`, `unauthorized`, …).
|
|
16
|
+
*/
|
|
17
|
+
export declare function readEnvelope(config: FoliwakeAppConfig, client: OriginClient, site: string, channel: ChannelName, path: string): Promise<PageEnvelope>;
|
|
18
|
+
/** Options of `preparePage`. */
|
|
19
|
+
export interface PrepareOptions {
|
|
20
|
+
/**
|
|
21
|
+
* The site's mode of the page (a token, `[a-z][a-z0-9-]`, at most 32 characters), given to the blocks as
|
|
22
|
+
* `host.mode`; absent → none. `exam` is refused: the assessment extension's exam needs answers stripped by the
|
|
23
|
+
* origin, which does not exist yet, so an exam body would carry its answers.
|
|
24
|
+
*/
|
|
25
|
+
mode?: string;
|
|
26
|
+
/** Root-relative links (`/x`) of `<a href>`; returns the app's URL. */
|
|
27
|
+
rewriteLink?: (href: string) => string;
|
|
28
|
+
/** The app's own change of the body (allow-list, artwork, …); its output is checked again. */
|
|
29
|
+
transform?: (html: string, envelope: PageEnvelope) => string;
|
|
30
|
+
}
|
|
31
|
+
/** The same-origin URL of the blocks module, or null when the config names no blocks entry. */
|
|
32
|
+
export declare function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId): {
|
|
33
|
+
base: string;
|
|
34
|
+
url: string;
|
|
35
|
+
} | null;
|
|
36
|
+
/**
|
|
37
|
+
* Per request, after the cache: check → rewrite media/links → transform → check again → serialise.
|
|
38
|
+
*
|
|
39
|
+
* @param envelope - What readEnvelope (or a cached copy of it) returned.
|
|
40
|
+
* @returns The serialisable page for a client component (`preload` is empty; readPage of the Next package
|
|
41
|
+
* fills it). Throws FoliwakePageError('invalid') when the body or the transform's output is refused.
|
|
42
|
+
*/
|
|
43
|
+
export declare function preparePage(config: FoliwakeAppConfig, envelope: PageEnvelope, opts?: PrepareOptions): FoliwakePageData;
|
package/dist/page.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// Reading a page from the origin (the envelope: the only thing an app caches) and preparing it per request
|
|
2
|
+
// (design §6.5, §9.4): check → rewrite media and links → the app's transform → check again.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { appOf, isLoopbackName, pageAllowed } from './config.js';
|
|
5
|
+
import { CODE_ID_PATTERN, LIMITS, PAGE_PATH_PATTERN } from './constants.js';
|
|
6
|
+
import { FoliwakePageError } from './errors.js';
|
|
7
|
+
import { checkBody, componentNames, elements, serialize } from './html.js';
|
|
8
|
+
import { mediaRewriter } from './media-rewrite.js';
|
|
9
|
+
import { readLimited, TooLargeError } from './stream.js';
|
|
10
|
+
export { FoliwakePageError } from './errors.js';
|
|
11
|
+
export { pageImportMap } from '@foliwake/blocks-contract/import-map';
|
|
12
|
+
const HTML_CONTRACT = /^\d{1,4}$/;
|
|
13
|
+
const LANG = /^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;
|
|
14
|
+
const PAGE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
15
|
+
const GENERATION = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
16
|
+
const MODE = /^[a-z][a-z0-9-]{0,31}$/;
|
|
17
|
+
/** The origin URL path of a page's body (`/` → `/index.plain.html`). */
|
|
18
|
+
export function plainPath(pagePath) {
|
|
19
|
+
return `${pagePath === '/' ? '/index' : pagePath}.plain.html`;
|
|
20
|
+
}
|
|
21
|
+
function header(response, name, pattern, required = false) {
|
|
22
|
+
const value = response.headers.get(name);
|
|
23
|
+
if (value === null) {
|
|
24
|
+
if (required)
|
|
25
|
+
throw new FoliwakePageError('invalid', `The origin answered without ${name}.`);
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
if (!pattern.test(value))
|
|
29
|
+
throw new FoliwakePageError('invalid', `The origin answered an invalid ${name}.`);
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
const NO_CODE_RELEASE = 'The origin answered without X-Code-Release: it is not a plain/2 Foliwake origin.';
|
|
33
|
+
function codeReleaseOf(response, client, channel) {
|
|
34
|
+
const value = response.headers.get('x-code-release');
|
|
35
|
+
if (value === null)
|
|
36
|
+
throw new FoliwakePageError('invalid', NO_CODE_RELEASE);
|
|
37
|
+
if (CODE_ID_PATTERN.test(value))
|
|
38
|
+
return value;
|
|
39
|
+
if (value === 'local' && isLoopbackName(new URL(client.originOf(channel)).hostname))
|
|
40
|
+
return 'local';
|
|
41
|
+
throw new FoliwakePageError('invalid', 'The origin answered an invalid X-Code-Release.');
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Reads `<path>.plain.html` from the channel's origin. Primitive inputs only, no callbacks and no signal
|
|
45
|
+
* (an internal 10 s timeout), so it can run inside a cache function. Refuses paths outside `app.pages`.
|
|
46
|
+
*
|
|
47
|
+
* @param site - The config's site (`config.site`); another site is refused.
|
|
48
|
+
* @param path - The page path (`/`, `/lessons/a`).
|
|
49
|
+
* @returns The envelope; throws FoliwakePageError (`not_found`, `not_allowed`, `origin`, `unauthorized`, …).
|
|
50
|
+
*/
|
|
51
|
+
export async function readEnvelope(config, client, site, channel, path) {
|
|
52
|
+
if (site !== config.site)
|
|
53
|
+
throw new FoliwakePageError('not_allowed', `This app reads the site ${config.site}, not ${site}.`);
|
|
54
|
+
if (channel !== 'live' && channel !== 'preview')
|
|
55
|
+
throw new FoliwakePageError('not_allowed', 'channel must be live or preview');
|
|
56
|
+
if (typeof path !== 'string' || !PAGE_PATH_PATTERN.test(path))
|
|
57
|
+
throw new FoliwakePageError('not_found', 'Not a page path.');
|
|
58
|
+
if (!pageAllowed(config, path))
|
|
59
|
+
throw new FoliwakePageError('not_allowed', `${path} is outside app.pages in ${config.from}.`);
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await client.request(channel, plainPath(path), { headers: { Accept: 'text/html' } });
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error instanceof Error && error.name === 'FoliwakeConfigError')
|
|
66
|
+
throw error;
|
|
67
|
+
throw new FoliwakePageError('origin', `The ${channel} site did not answer.`, { cause: error });
|
|
68
|
+
}
|
|
69
|
+
const discard = () => response.body?.cancel().catch(() => { });
|
|
70
|
+
if (response.status === 404) {
|
|
71
|
+
await discard();
|
|
72
|
+
throw new FoliwakePageError('not_found', `${path} does not exist on the ${channel} site.`, { status: 404 });
|
|
73
|
+
}
|
|
74
|
+
if (response.status === 401 || response.status === 403) {
|
|
75
|
+
await discard();
|
|
76
|
+
throw new FoliwakePageError('unauthorized', `The ${channel} site refused the credentials (HTTP ${response.status}).`, { status: response.status });
|
|
77
|
+
}
|
|
78
|
+
if (response.status !== 200) {
|
|
79
|
+
await discard();
|
|
80
|
+
throw new FoliwakePageError('origin', `The ${channel} site answered HTTP ${response.status}.`, { status: response.status });
|
|
81
|
+
}
|
|
82
|
+
if (!/^text\/html\s*(;|$)/i.test(response.headers.get('content-type') ?? '')) {
|
|
83
|
+
await discard();
|
|
84
|
+
throw new FoliwakePageError('invalid', 'The origin answered a body that is not text/html.');
|
|
85
|
+
}
|
|
86
|
+
const codeRelease = codeReleaseOf(response, client, channel);
|
|
87
|
+
const htmlContract = header(response, 'x-html-contract', HTML_CONTRACT, true);
|
|
88
|
+
const lang = header(response, 'content-language', LANG);
|
|
89
|
+
const pageId = header(response, 'x-page-id', PAGE_ID);
|
|
90
|
+
const generation = header(response, 'x-site-generation', GENERATION);
|
|
91
|
+
const etag = response.headers.get('etag');
|
|
92
|
+
let bytes;
|
|
93
|
+
try {
|
|
94
|
+
bytes = await readLimited(response, LIMITS.body);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (error instanceof TooLargeError)
|
|
98
|
+
throw new FoliwakePageError('too_large', `${path} is larger than ${LIMITS.body} bytes.`);
|
|
99
|
+
throw new FoliwakePageError('origin', `Reading ${path} from the ${channel} site failed.`, { cause: error });
|
|
100
|
+
}
|
|
101
|
+
let html;
|
|
102
|
+
try {
|
|
103
|
+
html = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new FoliwakePageError('invalid', 'The body is not UTF-8.');
|
|
107
|
+
}
|
|
108
|
+
checkBody(html, path); // an invalid body is refused before anything caches it
|
|
109
|
+
return { site, channel, path, html, codeRelease, htmlContract, lang, pageId, etag: etag && etag.length <= 200 ? etag : null, generation };
|
|
110
|
+
}
|
|
111
|
+
function rewrite(nodes, config, channel, rewriteLink) {
|
|
112
|
+
const media = mediaRewriter(appOf(config), channel);
|
|
113
|
+
for (const element of elements(nodes)) {
|
|
114
|
+
const a = element.attribs;
|
|
115
|
+
if (a.srcset !== undefined)
|
|
116
|
+
a.srcset = media.srcset(a.srcset);
|
|
117
|
+
if (a.src !== undefined)
|
|
118
|
+
a.src = element.name === 'img' ? media.src(a.src, element.attribs.srcset) : media.url(a.src);
|
|
119
|
+
if (a.poster !== undefined)
|
|
120
|
+
a.poster = media.url(a.poster);
|
|
121
|
+
if (a.href !== undefined) {
|
|
122
|
+
const rewritten = media.url(a.href);
|
|
123
|
+
if (rewritten !== a.href)
|
|
124
|
+
a.href = rewritten;
|
|
125
|
+
else if (rewriteLink && element.name === 'a' && a.href.startsWith('/') && !a.href.startsWith('//'))
|
|
126
|
+
a.href = rewriteLink(a.href);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** The same-origin URL of the blocks module, or null when the config names no blocks entry. */
|
|
131
|
+
export function blocksUrlOf(config, channel, codeRelease) {
|
|
132
|
+
const app = appOf(config);
|
|
133
|
+
if (!app.blocks.entry)
|
|
134
|
+
return null;
|
|
135
|
+
const base = `${app.proxies.code}${channel === 'preview' ? '/preview' : ''}/${codeRelease}/`;
|
|
136
|
+
return { base, url: `${base}${app.blocks.entry}` };
|
|
137
|
+
}
|
|
138
|
+
/** The React key of a prepared page: see `FoliwakePageData.identity`. */
|
|
139
|
+
function identityOf(envelope, mode, digest) {
|
|
140
|
+
const { site, channel, path, etag, codeRelease } = envelope;
|
|
141
|
+
return [site, channel, path, etag ?? '', codeRelease, mode ?? '', digest].join('|');
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Per request, after the cache: check → rewrite media/links → transform → check again → serialise.
|
|
145
|
+
*
|
|
146
|
+
* @param envelope - What readEnvelope (or a cached copy of it) returned.
|
|
147
|
+
* @returns The serialisable page for a client component (`preload` is empty; readPage of the Next package
|
|
148
|
+
* fills it). Throws FoliwakePageError('invalid') when the body or the transform's output is refused.
|
|
149
|
+
*/
|
|
150
|
+
export function preparePage(config, envelope, opts = {}) {
|
|
151
|
+
const app = appOf(config);
|
|
152
|
+
const mode = opts.mode ?? null;
|
|
153
|
+
if (mode !== null && (typeof mode !== 'string' || !MODE.test(mode)))
|
|
154
|
+
throw new FoliwakePageError('invalid', `mode must be a token [a-z][a-z0-9-], at most 32 characters`);
|
|
155
|
+
if (mode === 'exam')
|
|
156
|
+
throw new FoliwakePageError('not_allowed', 'mode exam is not available (the origin does not strip answers yet)');
|
|
157
|
+
const nodes = checkBody(envelope.html, envelope.path);
|
|
158
|
+
rewrite(nodes, config, envelope.channel, opts.rewriteLink);
|
|
159
|
+
let html = serialize(nodes);
|
|
160
|
+
if (opts.transform)
|
|
161
|
+
html = opts.transform(html, envelope);
|
|
162
|
+
const final = checkBody(html, envelope.path); // a transform cannot add what the first check refused
|
|
163
|
+
html = serialize(final);
|
|
164
|
+
const blocks = blocksUrlOf(config, envelope.channel, envelope.codeRelease);
|
|
165
|
+
const contract = { major: app.blocks.major, eventPrefix: app.blocks.eventPrefix };
|
|
166
|
+
// The digest covers what the browser mounts: the final prepared body (after the app's transform, so two
|
|
167
|
+
// transforms of one envelope differ, and a missing ETag cannot collide) and every mount-defining setting.
|
|
168
|
+
const digest = createHash('sha256')
|
|
169
|
+
.update(JSON.stringify([html, blocks?.url ?? null, contract.major, contract.eventPrefix, envelope.htmlContract, envelope.lang]))
|
|
170
|
+
.digest('base64url')
|
|
171
|
+
.slice(0, 22);
|
|
172
|
+
return {
|
|
173
|
+
identity: identityOf(envelope, mode, digest),
|
|
174
|
+
site: envelope.site,
|
|
175
|
+
channel: envelope.channel,
|
|
176
|
+
path: envelope.path,
|
|
177
|
+
mode,
|
|
178
|
+
html,
|
|
179
|
+
codeRelease: envelope.codeRelease,
|
|
180
|
+
htmlContract: envelope.htmlContract,
|
|
181
|
+
lang: envelope.lang,
|
|
182
|
+
blocks: componentNames(final),
|
|
183
|
+
blocksUrl: blocks?.url ?? null,
|
|
184
|
+
codeBase: blocks?.base ?? null,
|
|
185
|
+
contract,
|
|
186
|
+
preload: [],
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { FoliwakePageData, PreloadHint } from '@foliwake/blocks-contract/page';
|
|
2
|
+
import { type FoliwakeAppConfig } from './config.js';
|
|
3
|
+
import type { OriginClient } from './origin.js';
|
|
4
|
+
export type { PreloadHint } from '@foliwake/blocks-contract/page';
|
|
5
|
+
/** A path inside the code release the proxy would serve, or null. */
|
|
6
|
+
export declare function codePath(relative: string): string | null;
|
|
7
|
+
/** Resolves `specifier` against the module at `from` (both inside the release), or null when it leaves it. */
|
|
8
|
+
export declare function resolveInRelease(from: string, specifier: string): string | null;
|
|
9
|
+
/** The relative static import specifiers of an ES module's text, and the kit's (KIT_SPECIFIER). */
|
|
10
|
+
export declare function staticImports(source: string): string[];
|
|
11
|
+
/** Hints for a prepared page: modulepreload for its modules, preload as=style for its block stylesheets. */
|
|
12
|
+
export declare function preloadHints(config: FoliwakeAppConfig, client: OriginClient, page: FoliwakePageData): Promise<PreloadHint[]>;
|
|
13
|
+
/** Forgets every remembered code file (tests). */
|
|
14
|
+
export declare function clearPreloadCache(): void;
|
package/dist/preload.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Preload hints for a page's blocks: the browser should fetch the blocks module,
|
|
2
|
+
// the modules of the blocks actually on the page, their static imports (the block-kit, the shared React chunk)
|
|
3
|
+
// and their stylesheets in parallel with the HTML, not as an import waterfall.
|
|
4
|
+
//
|
|
5
|
+
// Everything comes from the page's own code release, read on the server through the origin client:
|
|
6
|
+
// - `components/components.json` says which blocks have a .js and a .css;
|
|
7
|
+
// - each module's static relative imports are followed (`import … from "./x.js"`, `import "./x.js"`,
|
|
8
|
+
// `export … from "./x.js"`; dynamic import() is not followed), depth ≤ 4, at most 48 modules. The kit's
|
|
9
|
+
// specifier (`@foliwake/block-kit`) is the release's block-kit (the page's import map maps it to
|
|
10
|
+
// `_foliwake/block-kit.js`).
|
|
11
|
+
// A code release is immutable, so results are kept in memory per (channel, code release, file). Hints are an
|
|
12
|
+
// optimisation: a failed read gives fewer hints, never an error. Every href is a same-origin proxy URL
|
|
13
|
+
// (`<proxies.code>[/preview]/<cd>/<path>`) that the code proxy's allow-list accepts, so CSP 'self' covers it.
|
|
14
|
+
import { KIT_PATH, KIT_SPECIFIER } from '@foliwake/blocks-contract/import-map';
|
|
15
|
+
import { appOf } from './config.js';
|
|
16
|
+
import { CODE_ROOTS, CODE_SEGMENT } from './constants.js';
|
|
17
|
+
import { readLimited } from './stream.js';
|
|
18
|
+
const MAX_MODULES = 48;
|
|
19
|
+
const MAX_DEPTH = 4;
|
|
20
|
+
const FILE_LIMIT = 1024 * 1024;
|
|
21
|
+
const CACHE_LIMIT = 2048;
|
|
22
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
23
|
+
/** A static `import`/`export … from` of a relative module or of the kit. */
|
|
24
|
+
const IMPORT_HEAD = '(?:^|[;\\s}])(?:import|export)\\s*(?:[\\w$*{}\\s,]*?\\s*from\\s*)?';
|
|
25
|
+
const STATIC_IMPORT = new RegExp(`${IMPORT_HEAD}["'](\\.{1,2}\\/[^"'\\s]+|${escapeRegExp(KIT_SPECIFIER)})["']`, 'g');
|
|
26
|
+
const files = new Map();
|
|
27
|
+
function remember(key, value) {
|
|
28
|
+
if (files.size >= CACHE_LIMIT)
|
|
29
|
+
files.delete(files.keys().next().value);
|
|
30
|
+
files.set(key, value);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
/** A path inside the code release the proxy would serve, or null. */
|
|
34
|
+
export function codePath(relative) {
|
|
35
|
+
const segments = relative.split('/');
|
|
36
|
+
if (segments.length < 2 || segments.length > 9 || !CODE_ROOTS.includes(segments[0]))
|
|
37
|
+
return null;
|
|
38
|
+
if (segments.some((s) => !CODE_SEGMENT.test(s) || s === '..' || s === '.'))
|
|
39
|
+
return null;
|
|
40
|
+
return relative;
|
|
41
|
+
}
|
|
42
|
+
/** Resolves `specifier` against the module at `from` (both inside the release), or null when it leaves it. */
|
|
43
|
+
export function resolveInRelease(from, specifier) {
|
|
44
|
+
if (specifier === KIT_SPECIFIER)
|
|
45
|
+
return KIT_PATH;
|
|
46
|
+
const url = new URL(specifier, `https://release.invalid/${from}`);
|
|
47
|
+
if (url.origin !== 'https://release.invalid' || url.search || url.hash)
|
|
48
|
+
return null;
|
|
49
|
+
return codePath(url.pathname.slice(1));
|
|
50
|
+
}
|
|
51
|
+
/** The relative static import specifiers of an ES module's text, and the kit's (KIT_SPECIFIER). */
|
|
52
|
+
export function staticImports(source) {
|
|
53
|
+
const out = new Set();
|
|
54
|
+
for (const match of source.matchAll(STATIC_IMPORT))
|
|
55
|
+
out.add(match[1]);
|
|
56
|
+
return [...out];
|
|
57
|
+
}
|
|
58
|
+
async function readText(client, channel, cd, file) {
|
|
59
|
+
const key = `${channel}|${cd}|${file}`;
|
|
60
|
+
const known = files.get(key);
|
|
61
|
+
if (known)
|
|
62
|
+
return known;
|
|
63
|
+
const read = (async () => {
|
|
64
|
+
try {
|
|
65
|
+
const response = await client.request(channel, `/code/${cd}/${file}`);
|
|
66
|
+
if (response.status !== 200) {
|
|
67
|
+
await response.body?.cancel().catch(() => { });
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
return new TextDecoder().decode(await readLimited(response, FILE_LIMIT));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
})();
|
|
76
|
+
// A failure is not remembered (the next request tries again); 'local' code changes, so it is never kept.
|
|
77
|
+
void read.then((text) => {
|
|
78
|
+
if (text === null || cd === 'local')
|
|
79
|
+
files.delete(key);
|
|
80
|
+
});
|
|
81
|
+
return remember(key, read);
|
|
82
|
+
}
|
|
83
|
+
/** Hints for a prepared page: modulepreload for its modules, preload as=style for its block stylesheets. */
|
|
84
|
+
export async function preloadHints(config, client, page) {
|
|
85
|
+
const app = appOf(config);
|
|
86
|
+
if (!page.codeBase || !page.codeRelease || !app.blocks.entry)
|
|
87
|
+
return [];
|
|
88
|
+
const cd = page.codeRelease;
|
|
89
|
+
const descriptorText = await readText(client, page.channel, cd, 'components/components.json');
|
|
90
|
+
let declared = {};
|
|
91
|
+
try {
|
|
92
|
+
const parsed = descriptorText ? JSON.parse(descriptorText) : null;
|
|
93
|
+
if (parsed && typeof parsed.components === 'object' && parsed.components !== null)
|
|
94
|
+
declared = parsed.components;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
declared = {};
|
|
98
|
+
}
|
|
99
|
+
const roots = [app.blocks.entry];
|
|
100
|
+
const styles = [];
|
|
101
|
+
for (const name of page.blocks) {
|
|
102
|
+
const entry = declared[name];
|
|
103
|
+
if (!entry)
|
|
104
|
+
continue;
|
|
105
|
+
if (entry.js === true)
|
|
106
|
+
roots.push(`components/${name}/${name}.js`);
|
|
107
|
+
if (entry.css === true)
|
|
108
|
+
styles.push(`components/${name}/${name}.css`);
|
|
109
|
+
}
|
|
110
|
+
const modules = new Set();
|
|
111
|
+
let frontier = roots.map(codePath).filter((p) => p !== null);
|
|
112
|
+
for (let depth = 0; depth <= MAX_DEPTH && frontier.length > 0; depth++) {
|
|
113
|
+
const fresh = frontier.filter((p) => !modules.has(p)).slice(0, MAX_MODULES - modules.size);
|
|
114
|
+
for (const p of fresh)
|
|
115
|
+
modules.add(p);
|
|
116
|
+
if (depth === MAX_DEPTH || modules.size >= MAX_MODULES)
|
|
117
|
+
break;
|
|
118
|
+
const texts = await Promise.all(fresh.map((p) => readText(client, page.channel, cd, p)));
|
|
119
|
+
const next = new Set();
|
|
120
|
+
texts.forEach((text, i) => {
|
|
121
|
+
if (!text)
|
|
122
|
+
return;
|
|
123
|
+
for (const specifier of staticImports(text)) {
|
|
124
|
+
const resolved = resolveInRelease(fresh[i], specifier);
|
|
125
|
+
if (resolved && resolved.endsWith('.js') && !modules.has(resolved))
|
|
126
|
+
next.add(resolved);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
frontier = [...next];
|
|
130
|
+
}
|
|
131
|
+
return [
|
|
132
|
+
...[...modules].map((p) => ({ rel: 'modulepreload', href: `${page.codeBase}${p}` })),
|
|
133
|
+
...styles.map((p) => ({ rel: 'preload', as: 'style', href: `${page.codeBase}${p}` })),
|
|
134
|
+
];
|
|
135
|
+
}
|
|
136
|
+
/** Forgets every remembered code file (tests). */
|
|
137
|
+
export function clearPreloadCache() {
|
|
138
|
+
files.clear();
|
|
139
|
+
}
|
package/dist/stream.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare class TooLargeError extends Error {
|
|
2
|
+
name: string;
|
|
3
|
+
}
|
|
4
|
+
/** Whether the declared Content-Length is already over the limit. */
|
|
5
|
+
export declare function declaredTooLarge(response: Response, limit: number): boolean;
|
|
6
|
+
/** Reads the whole body, throwing TooLargeError (and cancelling) past `limit` bytes. */
|
|
7
|
+
export declare function readLimited(response: Response, limit: number): Promise<Uint8Array>;
|
|
8
|
+
/** The body passed through with a byte counter: the stream errors (the client sees a cut response) past `limit`. */
|
|
9
|
+
export declare function limitStream(body: ReadableStream<Uint8Array>, limit: number): ReadableStream<Uint8Array>;
|
package/dist/stream.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Streamed size limits: Content-Length is checked first, then every chunk is counted, so a response that
|
|
2
|
+
// lies about (or omits) its length is still cut at the limit.
|
|
3
|
+
export class TooLargeError extends Error {
|
|
4
|
+
name = 'TooLargeError';
|
|
5
|
+
}
|
|
6
|
+
function declaredLength(response) {
|
|
7
|
+
const value = response.headers.get('content-length');
|
|
8
|
+
if (value === null || !/^\d+$/.test(value))
|
|
9
|
+
return null;
|
|
10
|
+
return Number(value);
|
|
11
|
+
}
|
|
12
|
+
/** Whether the declared Content-Length is already over the limit. */
|
|
13
|
+
export function declaredTooLarge(response, limit) {
|
|
14
|
+
const length = declaredLength(response);
|
|
15
|
+
return length !== null && length > limit;
|
|
16
|
+
}
|
|
17
|
+
/** Reads the whole body, throwing TooLargeError (and cancelling) past `limit` bytes. */
|
|
18
|
+
export async function readLimited(response, limit) {
|
|
19
|
+
if (declaredTooLarge(response, limit)) {
|
|
20
|
+
await response.body?.cancel().catch(() => { });
|
|
21
|
+
throw new TooLargeError(`larger than ${limit} bytes`);
|
|
22
|
+
}
|
|
23
|
+
if (!response.body)
|
|
24
|
+
return new Uint8Array();
|
|
25
|
+
const reader = response.body.getReader();
|
|
26
|
+
const chunks = [];
|
|
27
|
+
let total = 0;
|
|
28
|
+
for (;;) {
|
|
29
|
+
const { done, value } = await reader.read();
|
|
30
|
+
if (done)
|
|
31
|
+
break;
|
|
32
|
+
total += value.byteLength;
|
|
33
|
+
if (total > limit) {
|
|
34
|
+
await reader.cancel().catch(() => { });
|
|
35
|
+
throw new TooLargeError(`larger than ${limit} bytes`);
|
|
36
|
+
}
|
|
37
|
+
chunks.push(value);
|
|
38
|
+
}
|
|
39
|
+
const out = new Uint8Array(total);
|
|
40
|
+
let at = 0;
|
|
41
|
+
for (const chunk of chunks) {
|
|
42
|
+
out.set(chunk, at);
|
|
43
|
+
at += chunk.byteLength;
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
/** The body passed through with a byte counter: the stream errors (the client sees a cut response) past `limit`. */
|
|
48
|
+
export function limitStream(body, limit) {
|
|
49
|
+
let total = 0;
|
|
50
|
+
return body.pipeThrough(new TransformStream({
|
|
51
|
+
transform(chunk, controller) {
|
|
52
|
+
total += chunk.byteLength;
|
|
53
|
+
if (total > limit)
|
|
54
|
+
controller.error(new TooLargeError(`larger than ${limit} bytes`));
|
|
55
|
+
else
|
|
56
|
+
controller.enqueue(chunk);
|
|
57
|
+
},
|
|
58
|
+
}));
|
|
59
|
+
}
|