@foliwake/server 0.0.0-stage → 0.3.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.
@@ -0,0 +1,111 @@
1
+ import type { ChannelName, ClientSettings } from '@foliwake/blocks-contract/page';
2
+ export { FoliwakeConfigError } from './errors.js';
3
+ export type { ClientSettings } from '@foliwake/blocks-contract/page';
4
+ /** The default config file name, looked up in the current directory. */
5
+ export declare const CONFIG_FILE = "foliwake.remote.json";
6
+ /** The environment variable that names another config file. */
7
+ export declare const CONFIG_ENV = "FOLIWAKE_REMOTE";
8
+ /** The channels a config can name. */
9
+ export declare const CHANNELS: readonly ChannelName[];
10
+ /** HTTP Basic credentials: a user name and the NAME of the variable holding the password. */
11
+ export interface BasicAuth {
12
+ type: 'basic';
13
+ username: string;
14
+ passwordEnv: string;
15
+ }
16
+ /**
17
+ * A service token: each request carries a fresh ES256 JWT for its exact path, signed with the private key
18
+ * in the variable `privateKeyEnv` (a JWK as JSON text). Delivery checks it with the public key of `kid`.
19
+ */
20
+ export interface ServiceTokenAuth {
21
+ type: 'service-token';
22
+ /** The `iss` the delivery expects (its TOKEN_ISSUER). */
23
+ issuer: string;
24
+ /** The key id the delivery looks the public key up by. */
25
+ kid: string;
26
+ /** The NAME of the variable holding the private key. */
27
+ privateKeyEnv: string;
28
+ }
29
+ /** The credential of an endpoint. */
30
+ export type RemoteAuth = BasicAuth | ServiceTokenAuth;
31
+ /** A channel's origin and its optional credential. */
32
+ export interface FoliwakeEndpoint {
33
+ /** Origin only: scheme, host, port. */
34
+ origin: string;
35
+ auth: RemoteAuth | null;
36
+ }
37
+ /** The `app` part of the config, with defaults applied. */
38
+ export interface FoliwakeAppSettings {
39
+ /** Page globs the app may read. */
40
+ pages: readonly string[];
41
+ /** App-origin URL prefixes of the proxies. */
42
+ proxies: {
43
+ code: string;
44
+ media: string;
45
+ pages: null;
46
+ };
47
+ /** Where `mountBlocks` lives in a code release; null: bodies stay static. */
48
+ blocks: {
49
+ entry: string | null;
50
+ contract: string;
51
+ major: number;
52
+ eventPrefix: string;
53
+ };
54
+ /** Live media through a transforming host; null: media through the proxy. */
55
+ media: {
56
+ base: string;
57
+ transform: 'cloudflare-images' | null;
58
+ } | null;
59
+ /** Seconds before a cached envelope is stale (stale-while-revalidate). */
60
+ revalidate: number;
61
+ }
62
+ /** A parsed and validated `foliwake.remote.json` (version 2). It holds credential variable names, never secrets. */
63
+ export interface FoliwakeAppConfig {
64
+ version: 2;
65
+ site: string;
66
+ live: FoliwakeEndpoint | null;
67
+ preview: FoliwakeEndpoint | null;
68
+ /** Null only when parsed with `requireApp: false` (the engine CLI). */
69
+ app: FoliwakeAppSettings | null;
70
+ /** Where the config came from, for messages. */
71
+ from: string;
72
+ }
73
+ /** Options of `parseFoliwakeConfig`. */
74
+ export interface ParseOptions {
75
+ /** For messages (default foliwake.remote.json). */
76
+ file?: string;
77
+ /** Refuse a file without `app` (default true; the CLI passes false). */
78
+ requireApp?: boolean;
79
+ /** An additional rule for credential variable names (the engine CLI passes its own). */
80
+ envNameProblem?: (name: string, what: string) => string | null;
81
+ }
82
+ /** True for 127.x, localhost, *.localhost and ::1. */
83
+ export declare function isLoopbackName(hostname: string): boolean;
84
+ /** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
85
+ export declare function parseRemoteUrl(value: unknown, where: string): string;
86
+ /** Validates an environment variable NAME (never a value). */
87
+ export declare function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): string;
88
+ /** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
89
+ export declare function checkUsername(value: unknown, where: string): string;
90
+ /** Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field. */
91
+ export declare function parseFoliwakeConfig(text: string, opts?: ParseOptions): FoliwakeAppConfig;
92
+ /** The endpoint of a channel; a missing one is an error, never replaced by the other channel. */
93
+ export declare function endpointOf(config: FoliwakeAppConfig, channel: ChannelName): FoliwakeEndpoint;
94
+ /** The app settings; throws when the config has none. */
95
+ export declare function appOf(config: FoliwakeAppConfig): FoliwakeAppSettings;
96
+ /** Whether the app may read this page path (`app.pages`). */
97
+ export declare function pageAllowed(config: FoliwakeAppConfig, pagePath: string): boolean;
98
+ /** Which file: an explicit `file` beats FOLIWAKE_REMOTE beats `<cwd>/foliwake.remote.json`. */
99
+ export declare function configFilePath(opts?: {
100
+ cwd?: string;
101
+ file?: string;
102
+ env?: NodeJS.ProcessEnv;
103
+ }): string;
104
+ /** Reads and parses the config file (see configFilePath). */
105
+ export declare function loadFoliwakeConfig(opts?: {
106
+ cwd?: string;
107
+ file?: string;
108
+ env?: NodeJS.ProcessEnv;
109
+ } & Omit<ParseOptions, 'file'>): Promise<FoliwakeAppConfig>;
110
+ /** The explicit browser projection: nothing else of the config reaches a browser. */
111
+ export declare function clientSettings(config: FoliwakeAppConfig): ClientSettings;
package/dist/config.js ADDED
@@ -0,0 +1,321 @@
1
+ // `foliwake.remote.json` version 2 (schema schemas/remote-2.schema.json):
2
+ // which Foliwake site an app reads, with which credential NAMES, and the app's settings. One parser for the
3
+ // engine CLI (`foliwake dev --remote`) and the app packages. Version 1 is no longer read.
4
+ //
5
+ // No secrets: anything that looks like a stored secret refuses the file; credentials are variable names,
6
+ // read on the server per origin request (./origin), never logged, never sent to a browser.
7
+ import { readFile } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { FoliwakeConfigError } from './errors.js';
10
+ import { basicEnvNameProblem } from './env-names.js';
11
+ import { compileGlob, globMatches, globProblem, GLOB_LIMITS } from './glob.js';
12
+ export { FoliwakeConfigError } from './errors.js';
13
+ /** The default config file name, looked up in the current directory. */
14
+ export const CONFIG_FILE = 'foliwake.remote.json';
15
+ /** The environment variable that names another config file. */
16
+ export const CONFIG_ENV = 'FOLIWAKE_REMOTE';
17
+ /** The channels a config can name. */
18
+ 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
+ /** Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field. */
239
+ export function parseFoliwakeConfig(text, opts = {}) {
240
+ const file = opts.file ?? CONFIG_FILE;
241
+ let parsed;
242
+ try {
243
+ parsed = JSON.parse(text);
244
+ }
245
+ catch (error) {
246
+ throw new FoliwakeConfigError(`${file} is not valid JSON: ${error.message}`);
247
+ }
248
+ if (!isObject(parsed))
249
+ throw new FoliwakeConfigError(`${file} must be a JSON object {"version": 2, "site": …, "live": …, "preview": …, "app": …}.`);
250
+ refuseSecrets(parsed, '', file);
251
+ onlyKeys(parsed, ['$schema', '$comment', 'version', 'site', 'live', 'preview', 'app'], file);
252
+ if (parsed.version === 1) {
253
+ throw new FoliwakeConfigError(`${file}: version 1 is no longer read. Rewrite it as version 2: add "version": 2 and "site": "<site name>" (docs: website/guide/embed-in-react.md, "The config file").`);
254
+ }
255
+ if (parsed.version !== 2)
256
+ throw new FoliwakeConfigError(`${file}: "version" must be 2.`);
257
+ if (typeof parsed.site !== 'string' || !SITE.test(parsed.site))
258
+ throw new FoliwakeConfigError(`${file} "site": the site name, [a-z0-9-], such as "my-site".`);
259
+ const live = parsed.live === undefined ? null : parseEndpoint(parsed.live, `${file} "live"`, opts);
260
+ const preview = parsed.preview === undefined ? null : parseEndpoint(parsed.preview, `${file} "preview"`, opts);
261
+ if (!live && !preview)
262
+ throw new FoliwakeConfigError(`${file}: give at least one of "live" and "preview".`);
263
+ const requireApp = opts.requireApp ?? true;
264
+ if (parsed.app === undefined && requireApp)
265
+ throw new FoliwakeConfigError(`${file}: "app" is required for an app (at least {"pages": ["/**"]}).`);
266
+ const app = parsed.app === undefined ? null : parseApp(parsed.app, `${file} "app"`);
267
+ return Object.freeze({ version: 2, site: parsed.site, live, preview, app, from: file });
268
+ }
269
+ /** The endpoint of a channel; a missing one is an error, never replaced by the other channel. */
270
+ export function endpointOf(config, channel) {
271
+ const endpoint = config[channel];
272
+ if (!endpoint) {
273
+ const other = channel === 'preview' ? 'live' : 'preview';
274
+ throw new FoliwakeConfigError(`${config.from} has no "${channel}" endpoint. ${channel === 'preview' ? 'Preview' : 'Live'} is never replaced by ${other}: add "${channel}".`);
275
+ }
276
+ return endpoint;
277
+ }
278
+ /** The app settings; throws when the config has none. */
279
+ export function appOf(config) {
280
+ if (!config.app)
281
+ throw new FoliwakeConfigError(`${config.from}: "app" is required for an app.`);
282
+ return config.app;
283
+ }
284
+ const compiled = new WeakMap();
285
+ /** Whether the app may read this page path (`app.pages`). */
286
+ export function pageAllowed(config, pagePath) {
287
+ const app = appOf(config);
288
+ let globs = compiled.get(app);
289
+ if (!globs)
290
+ compiled.set(app, (globs = app.pages.map(compileGlob)));
291
+ return globs.some((glob) => globMatches(glob, pagePath));
292
+ }
293
+ /** Which file: an explicit `file` beats FOLIWAKE_REMOTE beats `<cwd>/foliwake.remote.json`. */
294
+ export function configFilePath(opts = {}) {
295
+ const cwd = opts.cwd ?? process.cwd();
296
+ const env = opts.env ?? process.env;
297
+ return path.resolve(cwd, opts.file ?? env[CONFIG_ENV] ?? CONFIG_FILE);
298
+ }
299
+ /** Reads and parses the config file (see configFilePath). */
300
+ export async function loadFoliwakeConfig(opts = {}) {
301
+ const file = configFilePath(opts);
302
+ let text;
303
+ try {
304
+ text = await readFile(file, 'utf8');
305
+ }
306
+ catch (error) {
307
+ if (error.code === 'ENOENT')
308
+ throw new FoliwakeConfigError(`${file} does not exist. Create ${CONFIG_FILE} (or set ${CONFIG_ENV} to another file).`);
309
+ throw new FoliwakeConfigError(`Cannot read ${file}: ${error.message}`);
310
+ }
311
+ return parseFoliwakeConfig(text, { ...opts, file: path.basename(file) });
312
+ }
313
+ /** The explicit browser projection: nothing else of the config reaches a browser. */
314
+ export function clientSettings(config) {
315
+ const app = appOf(config);
316
+ return {
317
+ site: config.site,
318
+ proxies: { code: app.proxies.code, media: app.proxies.media, pages: app.proxies.pages },
319
+ blocks: { contract: app.blocks.contract, eventPrefix: app.blocks.eventPrefix },
320
+ };
321
+ }
@@ -0,0 +1,26 @@
1
+ /** A code release id (release-formats `CODE_ID_PATTERN`). */
2
+ export declare const CODE_ID_PATTERN: RegExp;
3
+ /** Every file type site code may have, with the content type the proxy requires (release-formats code-files). */
4
+ export declare const CODE_FILE_TYPES: Readonly<Record<string, string>>;
5
+ /** The sandbox an SVG code file is served with (release-formats `codeFileHeaders('.svg')`). */
6
+ export declare const SVG_CODE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
7
+ /** First segments of a path inside a code release the proxy serves. */
8
+ export declare const CODE_ROOTS: readonly string[];
9
+ /**
10
+ * A media key as the engine writes it: `<sha256>.<ext>`, images only. SVG (refused in 0.1) since 2026-11-16: the
11
+ * engine's inline reference images (content-components.md §3.7), served with SVG_CODE_CSP like a code SVG.
12
+ */
13
+ export declare const MEDIA_KEY_PATTERN: RegExp;
14
+ export declare const MEDIA_TYPES: Readonly<Record<string, string>>;
15
+ /** One segment of a path inside a code release, after a single decode. */
16
+ export declare const CODE_SEGMENT: RegExp;
17
+ /** A Foliwake page path: `/` or segments of lower-case letters and digits joined by single `-` or `_` (engine PATH_PATTERN). */
18
+ export declare const PAGE_PATH_PATTERN: RegExp;
19
+ /** Limits (bytes, ms). */
20
+ export declare const LIMITS: Readonly<{
21
+ body: number;
22
+ code: number;
23
+ media: number;
24
+ timeoutMs: 10000;
25
+ depth: 200;
26
+ }>;
@@ -0,0 +1,46 @@
1
+ // Engine constants this package needs. @foliwake/release-formats is not published, so they are copied;
2
+ // test/packages/server-constants.test.js asserts they equal the engine's.
3
+ /** A code release id (release-formats `CODE_ID_PATTERN`). */
4
+ export const CODE_ID_PATTERN = /^cd_[0-9a-f]{32,64}$/;
5
+ /** Every file type site code may have, with the content type the proxy requires (release-formats code-files). */
6
+ export const CODE_FILE_TYPES = Object.freeze({
7
+ '.js': 'text/javascript',
8
+ '.css': 'text/css',
9
+ '.json': 'application/json',
10
+ '.woff2': 'font/woff2',
11
+ '.woff': 'font/woff',
12
+ '.ttf': 'font/ttf',
13
+ '.otf': 'font/otf',
14
+ '.svg': 'image/svg+xml',
15
+ '.png': 'image/png',
16
+ '.jpg': 'image/jpeg',
17
+ '.jpeg': 'image/jpeg',
18
+ '.webp': 'image/webp',
19
+ '.avif': 'image/avif',
20
+ '.gif': 'image/gif',
21
+ });
22
+ /** The sandbox an SVG code file is served with (release-formats `codeFileHeaders('.svg')`). */
23
+ export const SVG_CODE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
24
+ /** First segments of a path inside a code release the proxy serves. */
25
+ export const CODE_ROOTS = Object.freeze(['components', 'scripts', 'styles', '_foliwake']);
26
+ /**
27
+ * A media key as the engine writes it: `<sha256>.<ext>`, images only. SVG (refused in 0.1) since 2026-11-16: the
28
+ * engine's inline reference images (content-components.md §3.7), served with SVG_CODE_CSP like a code SVG.
29
+ */
30
+ export const MEDIA_KEY_PATTERN = /^[0-9a-f]{64}\.(png|jpe?g|webp|gif|avif|svg)$/;
31
+ export const MEDIA_TYPES = Object.freeze({
32
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif', avif: 'image/avif',
33
+ svg: 'image/svg+xml',
34
+ });
35
+ /** One segment of a path inside a code release, after a single decode. */
36
+ export const CODE_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
37
+ /** A Foliwake page path: `/` or segments of lower-case letters and digits joined by single `-` or `_` (engine PATH_PATTERN). */
38
+ export const PAGE_PATH_PATTERN = /^\/(?:[a-z0-9]+(?:[-_][a-z0-9]+)*(?:\/[a-z0-9]+(?:[-_][a-z0-9]+)*)*)?$/;
39
+ /** Limits (bytes, ms). */
40
+ export const LIMITS = Object.freeze({
41
+ body: 2 * 1024 * 1024,
42
+ code: 5 * 1024 * 1024,
43
+ media: 25 * 1024 * 1024,
44
+ timeoutMs: 10_000,
45
+ depth: 200,
46
+ });
package/dist/csp.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /** React DOM 19.2's inline `requestAnimationFrame(function(){$RT=performance.now()});` in PPR static shells. */
2
+ export declare const REACT_SHELL_SCRIPT = "requestAnimationFrame(function(){$RT=performance.now()});";
3
+ /** The CSP hash source of `REACT_SHELL_SCRIPT` (used by the `nonce` strategy). */
4
+ export declare const REACT_SHELL_SCRIPT_HASH = "'sha256-7mu4H06fwDCjmnxxr/xNHyuQC6pLTHr4M2E4jXw5WZs='";
5
+ /** Options of `foliwakeCsp`. */
6
+ export interface CspOptions {
7
+ /** `self-inline` (recommended; works with partial prerendering) or `nonce` (experimental, not recommended). */
8
+ strategy: 'self-inline' | 'nonce';
9
+ /** Required with 'nonce'. */
10
+ nonce?: string;
11
+ /**
12
+ * The media host whose pictures pages show: `app.media.base` (live pictures through a transforming host),
13
+ * or the site's own CDN when the site resizes images on one (`media.resize: "cdn"`, whose `cdnBase` is in
14
+ * every live `srcset`). An https address; only its origin (scheme and host) is added to `img-src`.
15
+ */
16
+ mediaBase?: string | null;
17
+ /** Development: adds 'unsafe-eval' (React's debugging) and websocket connections for HMR. */
18
+ dev?: boolean;
19
+ /** Where browsers report violations (`report-uri`). */
20
+ reportUri?: string;
21
+ /** More sources per directive, e.g. { 'connect-src': ['https://api.example.org'] }. */
22
+ extra?: Partial<Record<string, string[]>>;
23
+ }
24
+ /** The policy as one header value. */
25
+ export declare function foliwakeCsp(opts: CspOptions): string;
package/dist/csp.js ADDED
@@ -0,0 +1,78 @@
1
+ // Content-Security-Policy for an app that embeds Foliwake pages (design §5; decision in §12, spike of
2
+ // 2026-11-10). Blocks load from the app's own origin (the code proxy), so no Foliwake host is ever named in
3
+ // `script-src`, and there is no 'strict-dynamic'.
4
+ //
5
+ // 'self-inline' (the decided strategy, A): `script-src 'self' 'unsafe-inline'`. Works with Cache Components /
6
+ // PPR static shells; measured with zero violations on Next 16.2.12 and 16.4.3.
7
+ // 'nonce' (B, experimental): nonce + the hash of React's constant inline timing script. Measured clean
8
+ // on Next 16.2.12 only for hard loads; broken on 16.4.3 (un-nonced Turbopack bootstrap). Not recommended.
9
+ /** React DOM 19.2's inline `requestAnimationFrame(function(){$RT=performance.now()});` in PPR static shells. */
10
+ export const REACT_SHELL_SCRIPT = 'requestAnimationFrame(function(){$RT=performance.now()});';
11
+ /** The CSP hash source of `REACT_SHELL_SCRIPT` (used by the `nonce` strategy). */
12
+ export const REACT_SHELL_SCRIPT_HASH = "'sha256-7mu4H06fwDCjmnxxr/xNHyuQC6pLTHr4M2E4jXw5WZs='";
13
+ const SOURCE = /^(?:'[a-z0-9-]+(?:-[A-Za-z0-9+/=_-]+)?'|[a-z][a-z0-9+.-]*:|https:\/\/[A-Za-z0-9.*-]+(?::\d+)?(?:\/[^\s;,]*)?|wss?:\/\/[A-Za-z0-9.*-]+(?::\d+)?)$/;
14
+ const DIRECTIVE = /^[a-z-]+$/;
15
+ const NONCE = /^[A-Za-z0-9+/=_-]{16,128}$/;
16
+ // The origin of an https media host; never a scheme, wildcard or credentials in the policy.
17
+ function mediaOrigin(value) {
18
+ let url = null;
19
+ try {
20
+ url = new URL(value);
21
+ }
22
+ catch {
23
+ // refused below
24
+ }
25
+ if (!url || url.protocol !== 'https:' || url.username || url.password || url.hostname.includes('*')) {
26
+ throw new TypeError('foliwakeCsp: mediaBase must be an https:// address such as https://media.example.org.');
27
+ }
28
+ return url.origin;
29
+ }
30
+ /** The policy as one header value. */
31
+ export function foliwakeCsp(opts) {
32
+ const d = new Map();
33
+ const add = (name, ...values) => d.set(name, [...(d.get(name) ?? []), ...values]);
34
+ add('default-src', "'self'");
35
+ if (opts.strategy === 'nonce') {
36
+ if (!opts.nonce || !NONCE.test(opts.nonce))
37
+ throw new TypeError('foliwakeCsp: a nonce of 16–128 base64 characters is required with strategy "nonce".');
38
+ add('script-src', "'self'", `'nonce-${opts.nonce}'`, REACT_SHELL_SCRIPT_HASH);
39
+ add('style-src', "'self'", `'nonce-${opts.nonce}'`);
40
+ add('style-src-attr', "'unsafe-inline'");
41
+ }
42
+ else if (opts.strategy === 'self-inline') {
43
+ add('script-src', "'self'", "'unsafe-inline'");
44
+ add('style-src', "'self'", "'unsafe-inline'");
45
+ }
46
+ else {
47
+ throw new TypeError('foliwakeCsp: strategy must be "self-inline" or "nonce".');
48
+ }
49
+ if (opts.dev)
50
+ add('script-src', "'unsafe-eval'");
51
+ add('img-src', "'self'", 'data:', 'blob:');
52
+ if (opts.mediaBase)
53
+ add('img-src', mediaOrigin(opts.mediaBase));
54
+ add('font-src', "'self'");
55
+ add('connect-src', "'self'");
56
+ if (opts.dev)
57
+ add('connect-src', 'ws:', 'wss:');
58
+ add('object-src', "'none'");
59
+ add('base-uri', "'self'");
60
+ add('form-action', "'self'");
61
+ add('frame-ancestors', "'none'");
62
+ for (const [name, values] of Object.entries(opts.extra ?? {})) {
63
+ if (!DIRECTIVE.test(name))
64
+ throw new TypeError(`foliwakeCsp: invalid directive ${JSON.stringify(name)}`);
65
+ for (const value of values ?? []) {
66
+ if (!SOURCE.test(value))
67
+ throw new TypeError(`foliwakeCsp: invalid source ${JSON.stringify(value)} for ${name}`);
68
+ add(name, value);
69
+ }
70
+ }
71
+ const parts = [...d].map(([name, values]) => `${name} ${[...new Set(values)].join(' ')}`);
72
+ if (opts.reportUri) {
73
+ if (!/^\/[A-Za-z0-9/_-]*$/.test(opts.reportUri))
74
+ throw new TypeError('foliwakeCsp: reportUri must be an app path such as /csp-report');
75
+ parts.push(`report-uri ${opts.reportUri}`);
76
+ }
77
+ return parts.join('; ');
78
+ }
@@ -0,0 +1,2 @@
1
+ /** Why `name` cannot name a credential, or null. Browser-exposed prefixes (NEXT_PUBLIC_, VITE_) are refused too. */
2
+ export declare function basicEnvNameProblem(name: unknown, what: string): string | null;
@@ -0,0 +1,20 @@
1
+ // Which environment variable names a config may give as a credential: the engine's rule
2
+ // (src/sites/credential-env.ts), reduced to what an app needs. The engine's CLI passes its full rule
3
+ // (`envNameProblem`) on top of this one.
4
+ const NAME = /^[A-Z_][A-Z0-9_]{0,127}$/;
5
+ const SYSTEM_NAMES = new Set([
6
+ 'PATH', 'HOME', 'USER', 'USERNAME', 'LOGNAME', 'SHELL', 'PWD', 'OLDPWD', 'TMPDIR', 'TMP', 'TEMP', 'TERM', 'TERM_PROGRAM', 'LANG', 'LANGUAGE', 'TZ',
7
+ 'EDITOR', 'VISUAL', 'PAGER', 'HOSTNAME', 'HOST', 'MAIL', 'DISPLAY', 'COLUMNS', 'LINES', 'SHLVL', 'CI', 'NODE_OPTIONS', 'NODE_PATH', 'NODE_ENV',
8
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY', 'ENV', 'PROMPT_COMMAND', 'IFS', 'CDPATH', 'MANPATH', 'INFOPATH', 'CLASSPATH', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'CURL_CA_BUNDLE',
9
+ ]);
10
+ const SYSTEM_PREFIXES = ['SSH_', 'LC_', 'XDG_', 'DYLD_', 'LD_', 'GIT_', 'NODE_', 'NPM_CONFIG_', 'YARN_', 'PNPM_', 'PYTHON', 'PIP_', 'RUBY', 'GEM_', 'BUNDLE_', 'PERL5', 'PERL_', 'JAVA_', '_JAVA_', 'JDK_', 'BASH_', 'ZSH', 'DOCKER_', 'KUBE', 'SUDO_', 'GPG_', 'GNUPG', 'NEXT_PUBLIC_', 'VITE_'];
11
+ /** Why `name` cannot name a credential, or null. Browser-exposed prefixes (NEXT_PUBLIC_, VITE_) are refused too. */
12
+ export function basicEnvNameProblem(name, what) {
13
+ if (typeof name !== 'string' || !NAME.test(name)) {
14
+ return `${what}: give the NAME of an environment variable (capital letters, digits and _), not the secret itself.`;
15
+ }
16
+ if (SYSTEM_NAMES.has(name) || SYSTEM_PREFIXES.some((prefix) => name.startsWith(prefix))) {
17
+ return `${what}: ${name} is a system or browser-exposed variable, not a credential; use a variable of its own.`;
18
+ }
19
+ return null;
20
+ }
@@ -0,0 +1,16 @@
1
+ /** A configuration problem; the message is shown as is (it never contains a secret). */
2
+ export declare class FoliwakeConfigError extends Error {
3
+ name: string;
4
+ }
5
+ /** Why a page cannot be shown (`FoliwakePageError.kind`). */
6
+ export type PageErrorKind = 'not_found' | 'not_allowed' | 'origin' | 'invalid' | 'unauthorized' | 'too_large';
7
+ /** A page that cannot be shown. `status`: the origin's HTTP status when there was one. */
8
+ export declare class FoliwakePageError extends Error {
9
+ name: string;
10
+ readonly kind: PageErrorKind;
11
+ readonly status?: number;
12
+ constructor(kind: PageErrorKind, message: string, opts?: {
13
+ status?: number;
14
+ cause?: unknown;
15
+ });
16
+ }