@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/errors.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** A configuration problem; the message is shown as is (it never contains a secret). */
|
|
2
|
+
export class FoliwakeConfigError extends Error {
|
|
3
|
+
name = 'FoliwakeConfigError';
|
|
4
|
+
}
|
|
5
|
+
/** A page that cannot be shown. `status`: the origin's HTTP status when there was one. */
|
|
6
|
+
export class FoliwakePageError extends Error {
|
|
7
|
+
name = 'FoliwakePageError';
|
|
8
|
+
kind;
|
|
9
|
+
status;
|
|
10
|
+
constructor(kind, message, opts = {}) {
|
|
11
|
+
super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
|
|
12
|
+
this.kind = kind;
|
|
13
|
+
if (opts.status !== undefined)
|
|
14
|
+
this.status = opts.status;
|
|
15
|
+
}
|
|
16
|
+
}
|
package/dist/glob.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const GLOB_LIMITS: Readonly<{
|
|
2
|
+
globsPerList: 20;
|
|
3
|
+
globLength: 200;
|
|
4
|
+
}>;
|
|
5
|
+
/** Why `glob` is not a valid bounded glob (null: it is). */
|
|
6
|
+
export declare function globProblem(glob: string): string | null;
|
|
7
|
+
export type CompiledGlob = ReadonlyArray<'**' | readonly string[]>;
|
|
8
|
+
export declare function compileGlob(glob: string): CompiledGlob;
|
|
9
|
+
/** Whether the page path matches the compiled glob. */
|
|
10
|
+
export declare function globMatches(glob: CompiledGlob, pagePath: string): boolean;
|
package/dist/glob.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Page globs of `app.pages`: the query-index glob grammar (release-formats query.ts, copied; an equality test
|
|
2
|
+
// keeps them in step). `/`-separated segments of [a-z0-9_-] literals, `*` within a segment, `**` as a whole
|
|
3
|
+
// segment (zero or more segments; `/x/**` also matches `/x`).
|
|
4
|
+
const GLOB_SEGMENT = /^[a-z0-9_*-]+$/;
|
|
5
|
+
export const GLOB_LIMITS = Object.freeze({ globsPerList: 20, globLength: 200 });
|
|
6
|
+
/** Why `glob` is not a valid bounded glob (null: it is). */
|
|
7
|
+
export function globProblem(glob) {
|
|
8
|
+
if (glob.length > GLOB_LIMITS.globLength)
|
|
9
|
+
return `is longer than ${GLOB_LIMITS.globLength} characters`;
|
|
10
|
+
if (!glob.startsWith('/'))
|
|
11
|
+
return 'must start with /';
|
|
12
|
+
if (glob === '/')
|
|
13
|
+
return null;
|
|
14
|
+
for (const segment of glob.slice(1).split('/')) {
|
|
15
|
+
if (segment === '')
|
|
16
|
+
return 'has an empty segment (// or a trailing /)';
|
|
17
|
+
if (segment === '**')
|
|
18
|
+
continue;
|
|
19
|
+
if (!GLOB_SEGMENT.test(segment))
|
|
20
|
+
return 'may only use a-z, 0-9, -, _, * (within a segment) and ** (a whole segment)';
|
|
21
|
+
if (segment.includes('**'))
|
|
22
|
+
return 'uses ** inside a segment; ** must be a whole segment';
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
export function compileGlob(glob) {
|
|
27
|
+
if (glob === '/')
|
|
28
|
+
return [];
|
|
29
|
+
return glob.slice(1).split('/').map((segment) => (segment === '**' ? '**' : segment.split('*')));
|
|
30
|
+
}
|
|
31
|
+
function segmentMatches(parts, segment) {
|
|
32
|
+
if (parts.length === 1)
|
|
33
|
+
return parts[0] === segment;
|
|
34
|
+
const first = parts[0];
|
|
35
|
+
const last = parts[parts.length - 1];
|
|
36
|
+
if (!segment.startsWith(first) || segment.length < first.length + last.length || !segment.endsWith(last))
|
|
37
|
+
return false;
|
|
38
|
+
let at = first.length;
|
|
39
|
+
const end = segment.length - last.length;
|
|
40
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
41
|
+
const found = segment.indexOf(parts[i], at);
|
|
42
|
+
if (found === -1 || found + parts[i].length > end)
|
|
43
|
+
return false;
|
|
44
|
+
at = found + parts[i].length;
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
/** Whether the page path matches the compiled glob. */
|
|
49
|
+
export function globMatches(glob, pagePath) {
|
|
50
|
+
const segments = pagePath === '/' ? [] : pagePath.slice(1).split('/');
|
|
51
|
+
const s = segments.length;
|
|
52
|
+
let next = new Array(s + 1).fill(false);
|
|
53
|
+
next[s] = true;
|
|
54
|
+
for (let i = glob.length - 1; i >= 0; i--) {
|
|
55
|
+
const current = new Array(s + 1).fill(false);
|
|
56
|
+
const part = glob[i];
|
|
57
|
+
if (part === '**') {
|
|
58
|
+
for (let j = s; j >= 0; j--)
|
|
59
|
+
current[j] = next[j] || (j < s && current[j + 1]);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
for (let j = 0; j < s; j++)
|
|
63
|
+
current[j] = next[j + 1] && segmentMatches(part, segments[j]);
|
|
64
|
+
}
|
|
65
|
+
next = current;
|
|
66
|
+
}
|
|
67
|
+
return next[0];
|
|
68
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type FoliwakeAppConfig } from './config.js';
|
|
2
|
+
import type { OriginClient } from './origin.js';
|
|
3
|
+
/** A proxy handler: the request and the path segments after the proxy prefix. */
|
|
4
|
+
export type Handler = (request: Request, params: {
|
|
5
|
+
path: string[];
|
|
6
|
+
}) => Promise<Response>;
|
|
7
|
+
/** The app's author check for preview requests, or `false` (preview answers 404). */
|
|
8
|
+
export type AuthorizePreview = ((request: Request) => boolean | Promise<boolean>) | false;
|
|
9
|
+
/** Options of `codeHandler` and `mediaHandler`. */
|
|
10
|
+
export interface ProxyOptions {
|
|
11
|
+
/** The app's author check for `preview/…` requests, or `false` to answer them 404. Required. */
|
|
12
|
+
authorizePreview: AuthorizePreview;
|
|
13
|
+
}
|
|
14
|
+
/** `GET|HEAD <proxies.code>/[preview/]<cd>/<path inside the code release>`. */
|
|
15
|
+
export declare function codeHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): Handler;
|
|
16
|
+
/** `GET|HEAD <proxies.media>/[preview/]<sha256>.<ext>`: images only, one hashed segment. */
|
|
17
|
+
export declare function mediaHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): Handler;
|
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { isLoopbackName } from './config.js';
|
|
2
|
+
import { CODE_FILE_TYPES, CODE_ID_PATTERN, CODE_ROOTS, CODE_SEGMENT, LIMITS, MEDIA_KEY_PATTERN, MEDIA_TYPES, SVG_CODE_CSP } from './constants.js';
|
|
3
|
+
import { declaredTooLarge, limitStream } from './stream.js';
|
|
4
|
+
const IMMUTABLE = 'public, max-age=31536000, immutable';
|
|
5
|
+
const PRIVATE = 'private, no-store';
|
|
6
|
+
function plain(status, text, cacheControl = 'no-store') {
|
|
7
|
+
return new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': cacheControl, 'X-Content-Type-Options': 'nosniff' } });
|
|
8
|
+
}
|
|
9
|
+
const notFound = (cc) => plain(404, 'Not found', cc);
|
|
10
|
+
const badGateway = (cc) => plain(502, 'Bad gateway', cc);
|
|
11
|
+
function requireOptions(opts, what) {
|
|
12
|
+
if (!opts || (opts.authorizePreview !== false && typeof opts.authorizePreview !== 'function')) {
|
|
13
|
+
throw new TypeError(`${what}: pass { authorizePreview: <the app's author check> } or { authorizePreview: false }; no default serves preview.`);
|
|
14
|
+
}
|
|
15
|
+
return opts.authorizePreview;
|
|
16
|
+
}
|
|
17
|
+
async function channelOf(request, path, authorize) {
|
|
18
|
+
if (path[0] !== 'preview')
|
|
19
|
+
return { channel: 'live', rest: path };
|
|
20
|
+
if (authorize === false)
|
|
21
|
+
return null;
|
|
22
|
+
let allowed = false;
|
|
23
|
+
try {
|
|
24
|
+
allowed = (await authorize(request)) === true;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
allowed = false;
|
|
28
|
+
}
|
|
29
|
+
return allowed ? { channel: 'preview', rest: path.slice(1) } : null;
|
|
30
|
+
}
|
|
31
|
+
const baseType = (value) => (value ?? '').split(';')[0].trim().toLowerCase();
|
|
32
|
+
function typeMatches(expected, got) {
|
|
33
|
+
if (expected === 'text/javascript')
|
|
34
|
+
return got === 'text/javascript' || got === 'application/javascript';
|
|
35
|
+
return expected === got;
|
|
36
|
+
}
|
|
37
|
+
async function forward(request, client, channel, upstreamPath, expectedType, limit, extra, immutable) {
|
|
38
|
+
const cacheControl = channel === 'preview' ? PRIVATE : immutable ? IMMUTABLE : 'no-store';
|
|
39
|
+
const errorCc = channel === 'preview' ? PRIVATE : 'no-store';
|
|
40
|
+
const head = request.method === 'HEAD';
|
|
41
|
+
let upstream;
|
|
42
|
+
try {
|
|
43
|
+
upstream = await client.request(channel, upstreamPath, { method: head ? 'HEAD' : 'GET' });
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return badGateway(errorCc);
|
|
47
|
+
}
|
|
48
|
+
const discard = () => upstream.body?.cancel().catch(() => { });
|
|
49
|
+
if (upstream.status === 404) {
|
|
50
|
+
await discard();
|
|
51
|
+
return notFound(errorCc);
|
|
52
|
+
}
|
|
53
|
+
if (upstream.status !== 200 || !typeMatches(expectedType, baseType(upstream.headers.get('content-type'))) || declaredTooLarge(upstream, limit)) {
|
|
54
|
+
await discard();
|
|
55
|
+
return badGateway(errorCc);
|
|
56
|
+
}
|
|
57
|
+
const headers = { 'Content-Type': expectedType === 'text/javascript' ? 'text/javascript; charset=utf-8' : expectedType === 'text/css' ? 'text/css; charset=utf-8' : expectedType, 'Cache-Control': cacheControl, 'X-Content-Type-Options': 'nosniff', ...extra };
|
|
58
|
+
// No Content-Length: fetch decodes a gzip/br/deflate body but keeps the encoded length, so the upstream value
|
|
59
|
+
// may not describe what is sent (the platform sets the length or chunks the body itself). The ETag is passed on
|
|
60
|
+
// only for an unencoded body: it names the encoded representation otherwise.
|
|
61
|
+
const encoded = (upstream.headers.get('content-encoding') ?? 'identity').trim().toLowerCase() !== 'identity';
|
|
62
|
+
const etag = upstream.headers.get('etag');
|
|
63
|
+
if (etag && etag.length <= 200 && !encoded)
|
|
64
|
+
headers.ETag = etag;
|
|
65
|
+
if (head || !upstream.body)
|
|
66
|
+
return new Response(null, { status: 200, headers });
|
|
67
|
+
return new Response(limitStream(upstream.body, limit), { status: 200, headers });
|
|
68
|
+
}
|
|
69
|
+
/** `GET|HEAD <proxies.code>/[preview/]<cd>/<path inside the code release>`. */
|
|
70
|
+
export function codeHandler(config, client, opts) {
|
|
71
|
+
const authorize = requireOptions(opts, 'codeHandler');
|
|
72
|
+
return async (request, params) => {
|
|
73
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
74
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
75
|
+
const target = await channelOf(request, params.path, authorize);
|
|
76
|
+
if (!target)
|
|
77
|
+
return notFound(PRIVATE);
|
|
78
|
+
const [cd, ...rest] = target.rest;
|
|
79
|
+
const errorCc = target.channel === 'preview' ? PRIVATE : 'no-store';
|
|
80
|
+
const local = cd === 'local' && isLoopbackName(new URL(client.originOf(target.channel)).hostname);
|
|
81
|
+
if (cd === undefined || (!CODE_ID_PATTERN.test(cd) && !local))
|
|
82
|
+
return notFound(errorCc);
|
|
83
|
+
if (rest.length < 1 || rest.length > 8 || !CODE_ROOTS.includes(rest[0]))
|
|
84
|
+
return notFound(errorCc);
|
|
85
|
+
if (rest.some((s) => !CODE_SEGMENT.test(s) || s === '.' || s === '..'))
|
|
86
|
+
return notFound(errorCc);
|
|
87
|
+
const last = rest[rest.length - 1];
|
|
88
|
+
const dot = last.lastIndexOf('.');
|
|
89
|
+
const extension = dot > 0 ? last.slice(dot) : '';
|
|
90
|
+
const expected = CODE_FILE_TYPES[extension];
|
|
91
|
+
if (!expected)
|
|
92
|
+
return notFound(errorCc);
|
|
93
|
+
const extra = extension === '.svg' ? { 'Content-Security-Policy': SVG_CODE_CSP } : {};
|
|
94
|
+
return forward(request, client, target.channel, `/code/${cd}/${rest.join('/')}`, expected, LIMITS.code, extra, !local);
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** `GET|HEAD <proxies.media>/[preview/]<sha256>.<ext>`: images only, one hashed segment. */
|
|
98
|
+
export function mediaHandler(config, client, opts) {
|
|
99
|
+
const authorize = requireOptions(opts, 'mediaHandler');
|
|
100
|
+
return async (request, params) => {
|
|
101
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
102
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
103
|
+
const target = await channelOf(request, params.path, authorize);
|
|
104
|
+
if (!target)
|
|
105
|
+
return notFound(PRIVATE);
|
|
106
|
+
const errorCc = target.channel === 'preview' ? PRIVATE : 'no-store';
|
|
107
|
+
if (target.rest.length !== 1)
|
|
108
|
+
return notFound(errorCc);
|
|
109
|
+
const match = MEDIA_KEY_PATTERN.exec(target.rest[0]);
|
|
110
|
+
if (!match)
|
|
111
|
+
return notFound(errorCc);
|
|
112
|
+
const extension = match[1];
|
|
113
|
+
// A reference image (SVG media) is sandboxed like a code SVG.
|
|
114
|
+
const extra = extension === 'svg' ? { 'Content-Security-Policy': SVG_CODE_CSP } : {};
|
|
115
|
+
const mediaPath = `/media/${target.rest[0]}`;
|
|
116
|
+
return forward(request, client, target.channel, mediaPath, MEDIA_TYPES[extension], LIMITS.media, extra, true);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** A text node of a parsed body. */
|
|
2
|
+
export type HtmlText = {
|
|
3
|
+
type: 'text';
|
|
4
|
+
data: string;
|
|
5
|
+
};
|
|
6
|
+
/** An element of a parsed body. */
|
|
7
|
+
export type HtmlElement = {
|
|
8
|
+
type: 'tag';
|
|
9
|
+
name: string;
|
|
10
|
+
attribs: Record<string, string>;
|
|
11
|
+
children: HtmlNode[];
|
|
12
|
+
};
|
|
13
|
+
/** A node of a parsed body. */
|
|
14
|
+
export type HtmlNode = HtmlText | HtmlElement;
|
|
15
|
+
/** A body that cannot be parsed strictly. */
|
|
16
|
+
export declare class HtmlParseError extends Error {
|
|
17
|
+
name: string;
|
|
18
|
+
}
|
|
19
|
+
export declare const VOID: Set<string>;
|
|
20
|
+
/** Parses a body strictly. Comments are dropped; a doctype or processing instruction is an error. */
|
|
21
|
+
export declare function parseStrict(html: string): HtmlNode[];
|
|
22
|
+
/** Serialises the tree as HTML (the WHATWG fragment serialisation rules for the elements a body may hold). */
|
|
23
|
+
export declare function serialize(nodes: readonly HtmlNode[]): string;
|
|
24
|
+
/** Every element below `nodes`, depth first. */
|
|
25
|
+
export declare function elements(nodes: readonly HtmlNode[]): Generator<HtmlElement>;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// A strict htmlparser2 reader for Foliwake bodies (ported from a host app's HTML fragment reader):
|
|
2
|
+
// bodies are serialiser output, so anything the parser would have to REPAIR is an error (fail closed):
|
|
3
|
+
// an implied end or start tag, an end tag with nothing to close, a tag or comment cut off by the end of
|
|
4
|
+
// the document, an attribute given twice. Void elements and `/>` are the only closings without an end tag.
|
|
5
|
+
// Entities are decoded (text and attribute values), as a browser does.
|
|
6
|
+
import { Parser } from 'htmlparser2';
|
|
7
|
+
import { LIMITS } from './constants.js';
|
|
8
|
+
/** A body that cannot be parsed strictly. */
|
|
9
|
+
export class HtmlParseError extends Error {
|
|
10
|
+
name = 'HtmlParseError';
|
|
11
|
+
}
|
|
12
|
+
const RAW_NEWLINE = new Set(['pre', 'textarea', 'listing']);
|
|
13
|
+
export const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
14
|
+
class StrictParser extends Parser {
|
|
15
|
+
selfClosing = false;
|
|
16
|
+
closed = 0;
|
|
17
|
+
inStartTag = false;
|
|
18
|
+
onopentagname(start, endIndex) {
|
|
19
|
+
this.inStartTag = true;
|
|
20
|
+
super.onopentagname(start, endIndex);
|
|
21
|
+
}
|
|
22
|
+
onopentagend(endIndex) {
|
|
23
|
+
this.inStartTag = false;
|
|
24
|
+
super.onopentagend(endIndex);
|
|
25
|
+
}
|
|
26
|
+
onselfclosingtag(endIndex) {
|
|
27
|
+
this.inStartTag = false;
|
|
28
|
+
this.selfClosing = true;
|
|
29
|
+
super.onselfclosingtag(endIndex);
|
|
30
|
+
this.selfClosing = false;
|
|
31
|
+
}
|
|
32
|
+
oncomment(start, endIndex, offset) {
|
|
33
|
+
if (offset === 0)
|
|
34
|
+
throw new HtmlParseError('unterminated comment');
|
|
35
|
+
super.oncomment(start, endIndex, offset);
|
|
36
|
+
}
|
|
37
|
+
onclosetag(start, endIndex) {
|
|
38
|
+
const before = this.closed;
|
|
39
|
+
super.onclosetag(start, endIndex);
|
|
40
|
+
if (this.closed === before)
|
|
41
|
+
throw new HtmlParseError('an end tag without a start tag');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Parses a body strictly. Comments are dropped; a doctype or processing instruction is an error. */
|
|
45
|
+
export function parseStrict(html) {
|
|
46
|
+
if (html.length > LIMITS.body)
|
|
47
|
+
throw new HtmlParseError('document too large');
|
|
48
|
+
const root = { type: 'tag', name: '#root', attribs: {}, children: [] };
|
|
49
|
+
const stack = [root];
|
|
50
|
+
const top = () => stack[stack.length - 1];
|
|
51
|
+
let openText = null;
|
|
52
|
+
let attributes = new Set();
|
|
53
|
+
// The HTML parser drops one newline right after <pre>, <textarea> and <listing>; so does this reader.
|
|
54
|
+
let dropNewline = false;
|
|
55
|
+
const parser = new StrictParser({
|
|
56
|
+
onopentagname() {
|
|
57
|
+
attributes = new Set();
|
|
58
|
+
},
|
|
59
|
+
onattribute(name) {
|
|
60
|
+
if (attributes.has(name))
|
|
61
|
+
throw new HtmlParseError(`attribute ${name} given twice`);
|
|
62
|
+
attributes.add(name);
|
|
63
|
+
},
|
|
64
|
+
onopentag(name, attribs, isImplied) {
|
|
65
|
+
if (isImplied)
|
|
66
|
+
throw new HtmlParseError(`</${name}> without <${name}>`);
|
|
67
|
+
openText = null;
|
|
68
|
+
const element = { type: 'tag', name, attribs, children: [] };
|
|
69
|
+
top().children.push(element);
|
|
70
|
+
if (stack.length > LIMITS.depth)
|
|
71
|
+
throw new HtmlParseError('nested too deeply');
|
|
72
|
+
stack.push(element);
|
|
73
|
+
dropNewline = RAW_NEWLINE.has(name);
|
|
74
|
+
},
|
|
75
|
+
onclosetag(name, isImplied) {
|
|
76
|
+
dropNewline = false;
|
|
77
|
+
if (isImplied && !VOID.has(name) && !parser.selfClosing)
|
|
78
|
+
throw new HtmlParseError(`unclosed <${name}>`);
|
|
79
|
+
if (!isImplied)
|
|
80
|
+
parser.closed += 1;
|
|
81
|
+
openText = null;
|
|
82
|
+
stack.pop();
|
|
83
|
+
},
|
|
84
|
+
ontext(data) {
|
|
85
|
+
if (dropNewline) {
|
|
86
|
+
dropNewline = false;
|
|
87
|
+
if (data.startsWith('\n'))
|
|
88
|
+
data = data.slice(1);
|
|
89
|
+
if (data === '')
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (openText) {
|
|
93
|
+
openText.data += data;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
openText = { type: 'text', data };
|
|
97
|
+
top().children.push(openText);
|
|
98
|
+
},
|
|
99
|
+
oncomment() {
|
|
100
|
+
dropNewline = false;
|
|
101
|
+
openText = null;
|
|
102
|
+
},
|
|
103
|
+
onprocessinginstruction(name) {
|
|
104
|
+
throw new HtmlParseError(`<${name.slice(0, 20)}> is not allowed in a body`);
|
|
105
|
+
},
|
|
106
|
+
}, { recognizeSelfClosing: true });
|
|
107
|
+
parser.write(html);
|
|
108
|
+
parser.end();
|
|
109
|
+
if (parser.inStartTag)
|
|
110
|
+
throw new HtmlParseError('unterminated start tag');
|
|
111
|
+
if (/<[/!?][^>]*$/.test(html))
|
|
112
|
+
throw new HtmlParseError('unterminated tag at the end of the document');
|
|
113
|
+
return root.children;
|
|
114
|
+
}
|
|
115
|
+
const escapeText = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/ /g, ' ');
|
|
116
|
+
const escapeAttr = (s) => s.replace(/&/g, '&').replace(/"/g, '"').replace(/ /g, ' ');
|
|
117
|
+
/** Serialises the tree as HTML (the WHATWG fragment serialisation rules for the elements a body may hold). */
|
|
118
|
+
export function serialize(nodes) {
|
|
119
|
+
let out = '';
|
|
120
|
+
for (const node of nodes) {
|
|
121
|
+
if (node.type === 'text') {
|
|
122
|
+
out += escapeText(node.data);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
out += `<${node.name}`;
|
|
126
|
+
for (const [name, value] of Object.entries(node.attribs))
|
|
127
|
+
out += ` ${name}="${escapeAttr(value)}"`;
|
|
128
|
+
out += '>';
|
|
129
|
+
if (VOID.has(node.name))
|
|
130
|
+
continue;
|
|
131
|
+
const first = node.children[0];
|
|
132
|
+
if (RAW_NEWLINE.has(node.name) && first?.type === 'text' && first.data.startsWith('\n'))
|
|
133
|
+
out += '\n';
|
|
134
|
+
out += serialize(node.children);
|
|
135
|
+
out += `</${node.name}>`;
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/** Every element below `nodes`, depth first. */
|
|
140
|
+
export function* elements(nodes) {
|
|
141
|
+
for (const node of nodes) {
|
|
142
|
+
if (node.type !== 'tag')
|
|
143
|
+
continue;
|
|
144
|
+
yield node;
|
|
145
|
+
yield* elements(node.children);
|
|
146
|
+
}
|
|
147
|
+
}
|
package/dist/html.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type HtmlNode } from './html-parse.js';
|
|
2
|
+
export { HtmlParseError, parseStrict, serialize, elements } from './html-parse.js';
|
|
3
|
+
export type { HtmlElement, HtmlNode, HtmlText } from './html-parse.js';
|
|
4
|
+
/**
|
|
5
|
+
* Elements a body may not hold (incl. foreign content: no inline SVG or MathML in 0.1). `<form>` is allowed only
|
|
6
|
+
* as the engine writes it for the question block: an explicit `method="dialog"`, no `action`, `target` or
|
|
7
|
+
* `enctype`; no control may override the submission (`formmethod`, `formaction`, `formtarget`, `formenctype`)
|
|
8
|
+
* or associate itself with another form (`form`). Such a form closes a dialog at most; it submits nowhere.
|
|
9
|
+
*/
|
|
10
|
+
export declare const REFUSED_ELEMENTS: ReadonlySet<string>;
|
|
11
|
+
/** A valid `data-component` name. */
|
|
12
|
+
export declare const COMPONENT_NAME: RegExp;
|
|
13
|
+
/** Why a URL value is not allowed for this element/attribute, or null. Values are entity-decoded already. */
|
|
14
|
+
export declare function urlProblem(element: string, attribute: string, value: string, pagePath?: string): string | null;
|
|
15
|
+
/** Splits a srcset into candidates: the URL ends at whitespace; descriptors run to the next comma. */
|
|
16
|
+
export declare function srcsetCandidates(srcset: string): {
|
|
17
|
+
url: string;
|
|
18
|
+
descriptor: string;
|
|
19
|
+
}[];
|
|
20
|
+
/** Parses and checks a body; returns the checked tree. Throws FoliwakePageError('invalid'). */
|
|
21
|
+
export declare function checkBody(html: string, pagePath?: string): HtmlNode[];
|
|
22
|
+
/** Checks a body (the strict body check); throws FoliwakePageError('invalid'). */
|
|
23
|
+
export declare function checkPlainBody(html: string, pagePath?: string): void;
|
|
24
|
+
/** Distinct `data-component` names, sorted. */
|
|
25
|
+
export declare function componentNames(nodes: readonly HtmlNode[]): string[];
|
|
26
|
+
/** The checked body, serialised from its tree. */
|
|
27
|
+
export declare function sanitizedHtml(nodes: readonly HtmlNode[]): string;
|
package/dist/html.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// The page check (design §9.4): a body is trusted Foliwake output from the configured origin, and still
|
|
2
|
+
// checked, before and after the app's preparation, failing closed. What passes is serialised again from
|
|
3
|
+
// the checked tree, so the browser parses exactly what was checked.
|
|
4
|
+
import { FoliwakePageError } from './errors.js';
|
|
5
|
+
import { elements, HtmlParseError, parseStrict, serialize } from './html-parse.js';
|
|
6
|
+
export { HtmlParseError, parseStrict, serialize, elements } from './html-parse.js';
|
|
7
|
+
/**
|
|
8
|
+
* Elements a body may not hold (incl. foreign content: no inline SVG or MathML in 0.1). `<form>` is allowed only
|
|
9
|
+
* as the engine writes it for the question block: an explicit `method="dialog"`, no `action`, `target` or
|
|
10
|
+
* `enctype`; no control may override the submission (`formmethod`, `formaction`, `formtarget`, `formenctype`)
|
|
11
|
+
* or associate itself with another form (`form`). Such a form closes a dialog at most; it submits nowhere.
|
|
12
|
+
*/
|
|
13
|
+
export const REFUSED_ELEMENTS = new Set([
|
|
14
|
+
'script', 'style', 'iframe', 'frame', 'frameset', 'object', 'embed', 'applet', 'base', 'meta', 'link',
|
|
15
|
+
'noscript', 'template', 'svg', 'math', 'xmp', 'plaintext', 'noembed', 'noframes', 'portal', 'fencedframe',
|
|
16
|
+
]);
|
|
17
|
+
const REFUSED_ATTRIBUTES = new Set(['srcdoc', 'formaction', 'formmethod', 'formtarget', 'formenctype', 'form', 'style', 'is', 'ping']);
|
|
18
|
+
const ELEMENT_NAME = /^[a-z][a-z0-9-]*$/;
|
|
19
|
+
const ATTRIBUTE_NAME = /^[a-z_][a-z0-9_.-]*$/;
|
|
20
|
+
/** Attributes holding one URL. */
|
|
21
|
+
const URL_ATTRIBUTES = new Set(['href', 'src', 'poster', 'cite', 'background', 'longdesc', 'action', 'data', 'lowsrc', 'dynsrc', 'manifest', 'codebase', 'xlink']);
|
|
22
|
+
const DATA_IMAGE = /^data:image\/(png|jpeg|webp|gif)[;,]/i;
|
|
23
|
+
const BASE = 'https://page.invalid';
|
|
24
|
+
const DESCRIPTOR = /^(?:\d+w|\d+(?:\.\d+)?x)$/;
|
|
25
|
+
/** A valid `data-component` name. */
|
|
26
|
+
export const COMPONENT_NAME = /^[a-z][a-z0-9-]*$/;
|
|
27
|
+
function invalid(message, cause) {
|
|
28
|
+
return new FoliwakePageError('invalid', `The page body was refused: ${message}`, { cause });
|
|
29
|
+
}
|
|
30
|
+
/** Why a URL value is not allowed for this element/attribute, or null. Values are entity-decoded already. */
|
|
31
|
+
export function urlProblem(element, attribute, value, pagePath = '/') {
|
|
32
|
+
if (attribute === 'src' && element === 'img' && DATA_IMAGE.test(value.trim()))
|
|
33
|
+
return null;
|
|
34
|
+
// As the URL parser sees it: tabs and newlines removed, leading C0 controls and spaces stripped.
|
|
35
|
+
const stripped = value.replace(/[\t\n\r]/g, '').replace(/^[\u0000-\u0020]+/, '');
|
|
36
|
+
if (/^[\\/]{2}/.test(stripped))
|
|
37
|
+
return `<${element} ${attribute}> is a scheme-relative URL (another host)`;
|
|
38
|
+
let url;
|
|
39
|
+
try {
|
|
40
|
+
url = new URL(value, `${BASE}${pagePath}`);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return `<${element} ${attribute}> is not a valid URL`;
|
|
44
|
+
}
|
|
45
|
+
if (url.origin === BASE)
|
|
46
|
+
return null; // relative (or root-relative) on the app's own origin
|
|
47
|
+
if (url.protocol === 'https:')
|
|
48
|
+
return null;
|
|
49
|
+
if (attribute === 'href' && (url.protocol === 'mailto:' || url.protocol === 'tel:'))
|
|
50
|
+
return null;
|
|
51
|
+
return `<${element} ${attribute}> uses ${url.protocol === 'https:' ? 'another host' : `the scheme ${url.protocol}`} (allowed: relative, https:${attribute === 'href' ? ', mailto:, tel:' : ''})`;
|
|
52
|
+
}
|
|
53
|
+
/** Splits a srcset into candidates: the URL ends at whitespace; descriptors run to the next comma. */
|
|
54
|
+
export function srcsetCandidates(srcset) {
|
|
55
|
+
const out = [];
|
|
56
|
+
let i = 0;
|
|
57
|
+
const n = srcset.length;
|
|
58
|
+
const space = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f';
|
|
59
|
+
while (i < n) {
|
|
60
|
+
while (i < n && (space(srcset[i]) || srcset[i] === ','))
|
|
61
|
+
i++;
|
|
62
|
+
if (i >= n)
|
|
63
|
+
break;
|
|
64
|
+
let url = '';
|
|
65
|
+
while (i < n && !space(srcset[i]))
|
|
66
|
+
url += srcset[i++];
|
|
67
|
+
let descriptor = '';
|
|
68
|
+
if (url.endsWith(',')) {
|
|
69
|
+
url = url.replace(/,+$/, '');
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
while (i < n && srcset[i] !== ',')
|
|
73
|
+
descriptor += srcset[i++];
|
|
74
|
+
descriptor = descriptor.trim();
|
|
75
|
+
}
|
|
76
|
+
out.push({ url, descriptor });
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function checkElement(element, pagePath) {
|
|
81
|
+
if (!ELEMENT_NAME.test(element.name))
|
|
82
|
+
throw invalid(`the element <${element.name.slice(0, 30)}> is not allowed`);
|
|
83
|
+
if (REFUSED_ELEMENTS.has(element.name))
|
|
84
|
+
throw invalid(`the element <${element.name}> is not allowed`);
|
|
85
|
+
if (element.name === 'form') {
|
|
86
|
+
const a = element.attribs;
|
|
87
|
+
// Exactly `dialog` (ASCII case-insensitive, as HTML matches enumerated keywords). No trimming: HTML does not
|
|
88
|
+
// trim either, so `method=" dialog "` is an invalid value that falls back to GET.
|
|
89
|
+
if (a.method?.toLowerCase() !== 'dialog' || 'action' in a || 'target' in a || 'enctype' in a) {
|
|
90
|
+
throw invalid('a <form> may only be <form method="dialog"> without action, target or enctype');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for (const [name, value] of Object.entries(element.attribs)) {
|
|
94
|
+
if (!ATTRIBUTE_NAME.test(name))
|
|
95
|
+
throw invalid(`the attribute ${JSON.stringify(name.slice(0, 30))} on <${element.name}> is not allowed`);
|
|
96
|
+
if (name.startsWith('on') || name.startsWith('xmlns') || REFUSED_ATTRIBUTES.has(name))
|
|
97
|
+
throw invalid(`the attribute ${name} on <${element.name}> is not allowed`);
|
|
98
|
+
if (URL_ATTRIBUTES.has(name)) {
|
|
99
|
+
const problem = urlProblem(element.name, name, value, pagePath);
|
|
100
|
+
if (problem)
|
|
101
|
+
throw invalid(problem);
|
|
102
|
+
}
|
|
103
|
+
if (name === 'srcset' || name === 'imagesrcset') {
|
|
104
|
+
for (const candidate of srcsetCandidates(value)) {
|
|
105
|
+
if (candidate.descriptor !== '' && !DESCRIPTOR.test(candidate.descriptor))
|
|
106
|
+
throw invalid(`<${element.name} srcset> has the descriptor ${JSON.stringify(candidate.descriptor.slice(0, 20))}`);
|
|
107
|
+
const problem = urlProblem(element.name, 'srcset', candidate.url, pagePath);
|
|
108
|
+
if (problem)
|
|
109
|
+
throw invalid(problem);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (name === 'data-component' && !COMPONENT_NAME.test(value))
|
|
113
|
+
throw invalid(`the component name ${JSON.stringify(value.slice(0, 40))} is not valid`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Parses and checks a body; returns the checked tree. Throws FoliwakePageError('invalid'). */
|
|
117
|
+
export function checkBody(html, pagePath = '/') {
|
|
118
|
+
let nodes;
|
|
119
|
+
try {
|
|
120
|
+
nodes = parseStrict(html);
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (error instanceof HtmlParseError)
|
|
124
|
+
throw invalid(error.message, error);
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
for (const element of elements(nodes))
|
|
128
|
+
checkElement(element, pagePath);
|
|
129
|
+
return nodes;
|
|
130
|
+
}
|
|
131
|
+
/** Checks a body (the strict body check); throws FoliwakePageError('invalid'). */
|
|
132
|
+
export function checkPlainBody(html, pagePath = '/') {
|
|
133
|
+
checkBody(html, pagePath);
|
|
134
|
+
}
|
|
135
|
+
/** Distinct `data-component` names, sorted. */
|
|
136
|
+
export function componentNames(nodes) {
|
|
137
|
+
const names = new Set();
|
|
138
|
+
for (const element of elements(nodes)) {
|
|
139
|
+
const name = element.attribs['data-component'];
|
|
140
|
+
if (name !== undefined)
|
|
141
|
+
names.add(name);
|
|
142
|
+
}
|
|
143
|
+
return [...names].sort();
|
|
144
|
+
}
|
|
145
|
+
/** The checked body, serialised from its tree. */
|
|
146
|
+
export function sanitizedHtml(nodes) {
|
|
147
|
+
return serialize(nodes);
|
|
148
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ChannelName } from '@foliwake/blocks-contract/page';
|
|
2
|
+
import type { FoliwakeAppSettings } from './config.js';
|
|
3
|
+
export interface MediaRewriter {
|
|
4
|
+
url(value: string, width?: number | null): string;
|
|
5
|
+
srcset(value: string): string;
|
|
6
|
+
/** The `src` of an <img>, given its srcset (for the transform width). */
|
|
7
|
+
src(value: string, srcset: string | undefined): string;
|
|
8
|
+
}
|
|
9
|
+
export declare function mediaRewriter(app: FoliwakeAppSettings, channel: ChannelName): MediaRewriter;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { srcsetCandidates } from './html.js';
|
|
2
|
+
// `.svg`: inline reference images (engine content-components.md §3.7); never transformed.
|
|
3
|
+
const ENGINE_MEDIA = /^\/media\/([0-9a-f]{64}\.(?:png|jpe?g|webp|gif|avif|svg))$/;
|
|
4
|
+
const TRANSFORMABLE = /\.(?:png|jpe?g|webp|gif)$/;
|
|
5
|
+
const TRANSFORM_OPTIONS = 'format=auto,quality=80,metadata=none';
|
|
6
|
+
const WIDTH = /^(\d{1,5})w$/;
|
|
7
|
+
const MAX_WIDTH = 4096;
|
|
8
|
+
const DEFAULT_SRC_WIDTH = 1448;
|
|
9
|
+
export function mediaRewriter(app, channel) {
|
|
10
|
+
const proxied = (key) => (channel === 'preview' ? `${app.proxies.media}/preview/${key}` : `${app.proxies.media}/${key}`);
|
|
11
|
+
const transform = channel === 'live' && app.media?.transform === 'cloudflare-images' ? app.media.base : null;
|
|
12
|
+
const url = (value, width) => {
|
|
13
|
+
const match = ENGINE_MEDIA.exec(value);
|
|
14
|
+
if (!match)
|
|
15
|
+
return value;
|
|
16
|
+
const key = match[1];
|
|
17
|
+
if (transform && TRANSFORMABLE.test(key) && width && Number.isInteger(width) && width >= 1 && width <= MAX_WIDTH) {
|
|
18
|
+
return `${transform}/cdn-cgi/image/width=${width},${TRANSFORM_OPTIONS}/media/${key}`;
|
|
19
|
+
}
|
|
20
|
+
return proxied(key);
|
|
21
|
+
};
|
|
22
|
+
const largest = (srcset) => {
|
|
23
|
+
const widths = srcsetCandidates(srcset).map((c) => WIDTH.exec(c.descriptor)).filter((m) => m !== null).map((m) => Number(m[1]));
|
|
24
|
+
return widths.length ? Math.max(...widths) : null;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
url,
|
|
28
|
+
srcset: (value) => srcsetCandidates(value)
|
|
29
|
+
.map(({ url: u, descriptor }) => {
|
|
30
|
+
const w = WIDTH.exec(descriptor);
|
|
31
|
+
const out = url(u, w ? Number(w[1]) : null);
|
|
32
|
+
return descriptor ? `${out} ${descriptor}` : out;
|
|
33
|
+
})
|
|
34
|
+
.join(', '),
|
|
35
|
+
src: (value, srcset) => url(value, (srcset ? largest(srcset) : null) ?? DEFAULT_SRC_WIDTH),
|
|
36
|
+
};
|
|
37
|
+
}
|