fondu 0.17.0 → 0.18.1
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/dist/client/form.d.ts +4 -0
- package/dist/client/form.js +43 -2
- package/dist/client/navigation.js +86 -20
- package/dist/client.d.ts +3 -3
- package/dist/form.d.ts +2 -1
- package/dist/form.js +9 -2
- package/dist/paths.d.ts +5 -0
- package/dist/paths.js +64 -4
- package/dist/server/app.d.ts +3 -2
- package/dist/server/app.js +29 -60
- package/dist/server/document.js +25 -8
- package/dist/server/flash.js +54 -15
- package/dist/server/http.d.ts +26 -2
- package/dist/server/http.js +61 -4
- package/dist/server/prerender.js +19 -2
- package/dist/server/protocol.js +21 -10
- package/dist/server/routes.js +21 -6
- package/dist/server/validate.d.ts +2 -2
- package/dist/server/validate.js +4 -3
- package/dist/virtual.d.ts +2 -0
- package/dist/vite/index.d.ts +8 -1
- package/dist/vite/index.js +96 -54
- package/dist/vite/node-server.d.ts +10 -0
- package/dist/vite/node-server.js +49 -0
- package/dist/vite/options.d.ts +8 -0
- package/dist/vite/options.js +72 -0
- package/dist/vite/prerender.d.ts +13 -2
- package/dist/vite/prerender.js +103 -17
- package/dist/vite/strip.d.ts +1 -1
- package/dist/vite/strip.js +70 -11
- package/package.json +1 -1
package/dist/server/app.js
CHANGED
|
@@ -4,11 +4,11 @@ import { every } from 'hono/combine';
|
|
|
4
4
|
import { csrf } from 'hono/csrf';
|
|
5
5
|
import { HTTPException } from 'hono/http-exception';
|
|
6
6
|
import { NONCE, secureHeaders } from 'hono/secure-headers';
|
|
7
|
-
import { appendTrailingSlash, trimTrailingSlash } from 'hono/trailing-slash';
|
|
8
7
|
import { prerender, version } from 'virtual:fondu/assets';
|
|
9
|
-
import {
|
|
8
|
+
import { checkExportNames, isPageFile, isRouteFile, METHODS, pageId } from '../paths.js';
|
|
10
9
|
import { settings } from './document.js';
|
|
11
10
|
import { errorResponse } from './errors.js';
|
|
11
|
+
import { csrfOrigin, trailingSlash } from './http.js';
|
|
12
12
|
import { prerenderRoutes } from './prerender.js';
|
|
13
13
|
import { protocol, registerPage, renderPage, routePage } from './protocol.js';
|
|
14
14
|
import { routeTable } from './routes.js';
|
|
@@ -24,49 +24,8 @@ const CSP = {
|
|
|
24
24
|
baseUri: ["'self'"],
|
|
25
25
|
};
|
|
26
26
|
const ROOT = '/app/routes/';
|
|
27
|
-
/**
|
|
28
|
-
* What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
|
|
29
|
-
* page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
|
|
30
|
-
* HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
|
|
31
|
-
*/
|
|
32
|
-
function exportsOf(file) {
|
|
33
|
-
const name = file.split('/').at(-1);
|
|
34
|
-
if (name === '_middleware.ts')
|
|
35
|
-
return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
|
|
36
|
-
if (/^_(?:layout|error)\.tsx$/.test(name))
|
|
37
|
-
return { allowed: ['default'], hint: 'its component only (default)' };
|
|
38
|
-
if (file.endsWith('.mdx'))
|
|
39
|
-
return {
|
|
40
|
-
allowed: [],
|
|
41
|
-
hint: "its content: an MDX page has no handlers (a _middleware.ts's prerender, params)",
|
|
42
|
-
};
|
|
43
|
-
if (file.endsWith('.ts'))
|
|
44
|
-
return {
|
|
45
|
-
allowed: [...METHODS, ...CONFIG],
|
|
46
|
-
hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
|
|
47
|
-
};
|
|
48
|
-
return {
|
|
49
|
-
allowed: ['default', ...HANDLERS, ...CONFIG],
|
|
50
|
-
hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
/** what a page's handler is called in a `.ts` file */
|
|
54
|
-
const INSTEAD = {
|
|
55
|
-
loader: 'in a .ts file it is `GET`',
|
|
56
|
-
action: 'in a .ts file it is `POST`',
|
|
57
|
-
actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
|
|
58
|
-
};
|
|
59
27
|
export function checkExports(file, mod) {
|
|
60
|
-
|
|
61
|
-
const mdx = file.endsWith('.mdx');
|
|
62
|
-
const extra = Object.keys(mod).filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
|
|
63
|
-
if (extra.length) {
|
|
64
|
-
const renamed = file.endsWith('.ts')
|
|
65
|
-
? extra.filter((k) => k in INSTEAD)
|
|
66
|
-
: [];
|
|
67
|
-
throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
|
|
68
|
-
(renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
|
|
69
|
-
}
|
|
28
|
+
checkExportNames(file, Object.keys(mod));
|
|
70
29
|
if (/\.(?:tsx|mdx)$/.test(file) && typeof mod.default !== 'function')
|
|
71
30
|
throw new Error(`fondu: routes/${file} is a page: its default export is the component (code for the server only: a .ts file)`);
|
|
72
31
|
}
|
|
@@ -95,7 +54,8 @@ function actionName(url) {
|
|
|
95
54
|
* `action`, `actions`: those are a page's)
|
|
96
55
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
97
56
|
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page, and a request body
|
|
98
|
-
* limit (413, after
|
|
57
|
+
* limit (413, in each route that takes a body, after its directories' `_middleware.ts`, so its error page has the
|
|
58
|
+
* shared props; CSRF's 403 is plain text).
|
|
99
59
|
* Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
|
100
60
|
*/
|
|
101
61
|
export function createApp(options = {}) {
|
|
@@ -133,13 +93,17 @@ export function createApp(options = {}) {
|
|
|
133
93
|
}));
|
|
134
94
|
}
|
|
135
95
|
if (options.csrf !== false)
|
|
136
|
-
app.use(csrf(options.csrf));
|
|
96
|
+
app.use(csrf({ ...options.csrf, origin: options.csrf?.origin ?? csrfOrigin }));
|
|
137
97
|
const prerendered = [];
|
|
138
98
|
if (prerender)
|
|
139
99
|
prerenderRoutes(app, () => prerendered, version);
|
|
140
|
-
app.use(append
|
|
100
|
+
app.use(trailingSlash(append), ...protocol);
|
|
141
101
|
app.notFound((c) => errorResponse(c, 404));
|
|
142
102
|
app.onError((error, c) => {
|
|
103
|
+
// the client left (a body cut off mid-upload, a handler that read it): nobody is there to answer, so no 500 is
|
|
104
|
+
// logged. Recognised by the request's own signal, not by the error's type or message (they differ by runtime)
|
|
105
|
+
if (!(error instanceof HTTPException) && c.req.raw.signal.aborted)
|
|
106
|
+
return new Response(null, { status: 499 });
|
|
143
107
|
if (error instanceof HTTPException && error.res)
|
|
144
108
|
return error.getResponse();
|
|
145
109
|
return errorResponse(c, error instanceof HTTPException ? error.status : 500, error);
|
|
@@ -148,18 +112,22 @@ export function createApp(options = {}) {
|
|
|
148
112
|
const rootMiddleware = modules['_middleware.ts']?.default;
|
|
149
113
|
if (rootMiddleware)
|
|
150
114
|
app.use(...chain(rootMiddleware));
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
115
|
+
// One limit, in the chain of each route for the methods that take a body, after its directories' middleware (so a 413
|
|
116
|
+
// has their shared props, and a request they refuse is not read) and before its handler. Not for a GET, a HEAD or a
|
|
117
|
+
// URL that is no route: none of them reads a body. With a Content-Length the header is checked, without one the body
|
|
118
|
+
// is counted as it is read. A directory's middleware must not read the body itself. CSRF stays above: Hono's 403 has
|
|
119
|
+
// its own plain response, so no page is rendered for it.
|
|
120
|
+
const limit = options.bodyLimit === false
|
|
121
|
+
? []
|
|
122
|
+
: [
|
|
123
|
+
bodyLimit({
|
|
124
|
+
maxSize: options.bodyLimit ?? 10 * 1024 * 1024,
|
|
125
|
+
// Fondu's own answer: the error page for a visitor, the status alone for an API client
|
|
126
|
+
onError: () => {
|
|
127
|
+
throw new HTTPException(413);
|
|
128
|
+
},
|
|
129
|
+
}),
|
|
130
|
+
];
|
|
163
131
|
for (const { file, pattern, path, middleware } of routeTable(modules, append)) {
|
|
164
132
|
const mod = modules[file];
|
|
165
133
|
const page = isPageFile(file) ? pageId(file) : undefined;
|
|
@@ -191,6 +159,7 @@ export function createApp(options = {}) {
|
|
|
191
159
|
const actions = mod.actions ?? {};
|
|
192
160
|
add('POST', [
|
|
193
161
|
...mws,
|
|
162
|
+
...limit,
|
|
194
163
|
async (c, next) => {
|
|
195
164
|
const name = actionName(c.req.url);
|
|
196
165
|
// actions: the one named (?name), else none; otherwise the one action
|
|
@@ -210,7 +179,7 @@ export function createApp(options = {}) {
|
|
|
210
179
|
continue;
|
|
211
180
|
const h = mod[method];
|
|
212
181
|
if (h)
|
|
213
|
-
add(method, [...mws, ...chain(h)]);
|
|
182
|
+
add(method, [...mws, ...(method === 'OPTIONS' ? [] : limit), ...chain(h)]);
|
|
214
183
|
}
|
|
215
184
|
}
|
|
216
185
|
return app;
|
package/dist/server/document.js
CHANGED
|
@@ -15,8 +15,12 @@ export const withoutSsr = () => async (c, next) => {
|
|
|
15
15
|
browserOnly.add(c);
|
|
16
16
|
await next();
|
|
17
17
|
};
|
|
18
|
-
/**
|
|
19
|
-
|
|
18
|
+
/**
|
|
19
|
+
* The page data as the document carries it, from the JSON of the page: `<` escaped, so nothing in it is `</script>` or
|
|
20
|
+
* `<!--` (the only ways out of a script's data); no HTML entities. U+2028 and U+2029 are fine in JSON, and the data is
|
|
21
|
+
* not run as JavaScript.
|
|
22
|
+
*/
|
|
23
|
+
const pageScript = (json) => `<script data-page="app" type="application/json">${json.replace(/</g, '\\u003c')}</script>`;
|
|
20
24
|
/**
|
|
21
25
|
* A reload, Back to a page of another site: this entry's position, where fondu/client left it, before the first
|
|
22
26
|
* paint (the stylesheets are in: the page is laid out), and again once the page has loaded: browsers scroll on
|
|
@@ -65,6 +69,8 @@ export async function renderDocument(c, page, whole = false) {
|
|
|
65
69
|
const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
|
|
66
70
|
if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
|
|
67
71
|
throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
|
|
72
|
+
// the page once as JSON: the document's data, and what the render gets a fresh copy of
|
|
73
|
+
const json = JSON.stringify(page);
|
|
68
74
|
let ssr = null;
|
|
69
75
|
// per request: nothing the page renders can be it
|
|
70
76
|
const marker = crypto.randomUUID();
|
|
@@ -72,13 +78,22 @@ export async function renderDocument(c, page, whole = false) {
|
|
|
72
78
|
// React reports it to `onError` too, so what it reports is held until the shell is known to be there
|
|
73
79
|
const pending = [];
|
|
74
80
|
let live = false;
|
|
75
|
-
|
|
81
|
+
// The client left: React is given the request's signal, stops, and reports the signal's reason to `onError` (what
|
|
82
|
+
// `abort()` was given: an AbortError, or Node's string). That is not an error of the page, and nothing else is left out
|
|
83
|
+
const { signal } = c.req.raw;
|
|
84
|
+
const clientLeft = (error) => signal.aborted && error === signal.reason;
|
|
85
|
+
const late = (error) => {
|
|
86
|
+
if (!clientLeft(error))
|
|
87
|
+
console.error(`[fondu] a Suspense boundary of "${page.component}" failed on the server, the browser renders it:`, error);
|
|
88
|
+
};
|
|
76
89
|
try {
|
|
77
90
|
// a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
|
|
78
91
|
if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
|
|
79
|
-
// the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
|
|
80
|
-
|
|
92
|
+
// the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides. A copy
|
|
93
|
+
// of its own: what the render changes in its props is not in the page data
|
|
94
|
+
const stream = await renderPage(JSON.parse(json), {
|
|
81
95
|
nonce,
|
|
96
|
+
signal,
|
|
82
97
|
onError: (error) => (live ? late(error) : void pending.push(error)),
|
|
83
98
|
// React writes this as a script right after the shell, before what the boundaries add: where `restoreScroll`
|
|
84
99
|
// goes. Not as React's own script (it adds an `id`, and follows its `$RT` one), and not as a sibling of the
|
|
@@ -98,12 +113,14 @@ export async function renderDocument(c, page, whole = false) {
|
|
|
98
113
|
// same props and most likely fail again, and a visitor without JavaScript would get nothing)
|
|
99
114
|
if (page.component === '_error')
|
|
100
115
|
throw error;
|
|
101
|
-
// like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
|
|
102
|
-
|
|
116
|
+
// like Laravel: a page that fails to render on the server is still sent, and rendered in the browser. Not logged if
|
|
117
|
+
// the client left before the shell was there
|
|
118
|
+
if (!clientLeft(error))
|
|
119
|
+
console.error(`[fondu] server render of "${page.component}" failed, sending it to render in the browser:`, error);
|
|
103
120
|
}
|
|
104
121
|
// the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
|
|
105
122
|
// content can come before it
|
|
106
|
-
const data = pageScript(
|
|
123
|
+
const data = pageScript(json);
|
|
107
124
|
// the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
|
|
108
125
|
// document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
|
|
109
126
|
// the page out early (Firefox's, with its tools open) has them sooner
|
package/dist/server/flash.js
CHANGED
|
@@ -1,5 +1,47 @@
|
|
|
1
1
|
import { generateCookie, getCookie } from 'hono/cookie';
|
|
2
|
-
import { appendHeader } from './http.js';
|
|
2
|
+
import { appendHeader, isSecure } from './http.js';
|
|
3
|
+
/** what fits in a cookie (browsers drop one over ~4 KB, name and attributes included, without a word) */
|
|
4
|
+
const COOKIE_LIMIT = 4000;
|
|
5
|
+
const cookieSize = (value) => encodeURIComponent(JSON.stringify(value)).length;
|
|
6
|
+
const isPlain = (value) => typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype;
|
|
7
|
+
/**
|
|
8
|
+
* The cookie comes back from the client: anyone can write it. What is not `{ flash?, errors? }` is ignored: `flash` a
|
|
9
|
+
* plain object (its values any JSON: an app's flash data can be an object), `errors` a plain object of strings
|
|
10
|
+
* (`ValidationError`'s).
|
|
11
|
+
*/
|
|
12
|
+
function parseCarried(raw) {
|
|
13
|
+
try {
|
|
14
|
+
const value = JSON.parse(raw ?? 'null');
|
|
15
|
+
if (!isPlain(value))
|
|
16
|
+
return undefined;
|
|
17
|
+
const { flash, errors } = value;
|
|
18
|
+
return (flash === undefined || isPlain(flash)) &&
|
|
19
|
+
(errors === undefined ||
|
|
20
|
+
(isPlain(errors) && Object.values(errors).every((v) => typeof v === 'string')))
|
|
21
|
+
? { flash, errors }
|
|
22
|
+
: undefined;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** `outgoing` as a cookie's value: whole if it fits, else without the flash data, else the errors that fit, in order */
|
|
29
|
+
function fit(outgoing) {
|
|
30
|
+
const whole = JSON.stringify(outgoing);
|
|
31
|
+
if (encodeURIComponent(whole).length <= COOKIE_LIMIT)
|
|
32
|
+
return { value: whole };
|
|
33
|
+
const errors = {};
|
|
34
|
+
for (const [key, message] of Object.entries(outgoing.errors ?? {}))
|
|
35
|
+
if (cookieSize({ errors: { ...errors, [key]: message } }) <= COOKIE_LIMIT)
|
|
36
|
+
errors[key] = message;
|
|
37
|
+
const kept = Object.keys(errors).length;
|
|
38
|
+
const all = Object.keys(outgoing.errors ?? {}).length;
|
|
39
|
+
const dropped = [
|
|
40
|
+
...(outgoing.flash ? ['the flash data'] : []),
|
|
41
|
+
...(kept < all ? [`${all - kept} of ${all} errors`] : []),
|
|
42
|
+
];
|
|
43
|
+
return { value: kept ? JSON.stringify({ errors }) : undefined, dropped: dropped.join(' and ') };
|
|
44
|
+
}
|
|
3
45
|
const states = new WeakMap();
|
|
4
46
|
const state = (c) => {
|
|
5
47
|
let s = states.get(c);
|
|
@@ -7,9 +49,6 @@ const state = (c) => {
|
|
|
7
49
|
states.set(c, (s = { outgoing: {}, incoming: undefined, read: false }));
|
|
8
50
|
return s;
|
|
9
51
|
};
|
|
10
|
-
/** https, directly or behind a proxy that says so */
|
|
11
|
-
const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
|
|
12
|
-
c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
|
|
13
52
|
const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
|
|
14
53
|
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
|
15
54
|
export function flash(c, data) {
|
|
@@ -25,12 +64,7 @@ export function takeCarried(c) {
|
|
|
25
64
|
const s = state(c);
|
|
26
65
|
if (!s.read) {
|
|
27
66
|
s.read = true;
|
|
28
|
-
|
|
29
|
-
s.incoming = JSON.parse(getCookie(c, cookieName(c)) ?? 'null') ?? undefined;
|
|
30
|
-
}
|
|
31
|
-
catch {
|
|
32
|
-
s.incoming = undefined;
|
|
33
|
-
}
|
|
67
|
+
s.incoming = parseCarried(getCookie(c, cookieName(c)));
|
|
34
68
|
}
|
|
35
69
|
const carried = {
|
|
36
70
|
flash: { ...s.incoming?.flash, ...s.outgoing.flash },
|
|
@@ -45,15 +79,20 @@ export const flashCookie = async (c, next) => {
|
|
|
45
79
|
const s = states.get(c);
|
|
46
80
|
if (!s)
|
|
47
81
|
return;
|
|
82
|
+
// a HEAD request is a GET's headers: it leaves the flash for the page the browser asks for
|
|
83
|
+
if (c.req.method === 'HEAD')
|
|
84
|
+
return;
|
|
48
85
|
const name = cookieName(c);
|
|
49
86
|
const options = { path: '/', httpOnly: true, sameSite: 'Lax', secure: isSecure(c) };
|
|
87
|
+
let value;
|
|
50
88
|
if (s.outgoing.flash || s.outgoing.errors) {
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
if (
|
|
54
|
-
console.
|
|
55
|
-
appendHeader(c, 'Set-Cookie', generateCookie(name, value, { ...options, maxAge: 60 }));
|
|
89
|
+
const result = fit(s.outgoing);
|
|
90
|
+
value = result.value;
|
|
91
|
+
if (result.dropped)
|
|
92
|
+
console.warn(`[fondu] flash data and errors are too large for a cookie (about ${COOKIE_LIMIT} bytes fit, the browser drops more): dropped ${result.dropped}`);
|
|
56
93
|
}
|
|
94
|
+
if (value)
|
|
95
|
+
appendHeader(c, 'Set-Cookie', generateCookie(name, value, { ...options, maxAge: 60 }));
|
|
57
96
|
else if (s.read && s.incoming)
|
|
58
97
|
appendHeader(c, 'Set-Cookie', generateCookie(name, '', { ...options, maxAge: 0 }));
|
|
59
98
|
};
|
package/dist/server/http.d.ts
CHANGED
|
@@ -1,14 +1,38 @@
|
|
|
1
|
-
import type { Context } from 'hono';
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
2
|
/** a navigation of fondu/client: it wants the page as JSON */
|
|
3
3
|
export declare const isPageRequest: (c: Context) => boolean;
|
|
4
4
|
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
5
5
|
export declare const wantsPage: (c: Context) => boolean;
|
|
6
6
|
/** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
|
|
7
7
|
export declare const nonceOf: (c: Context) => string | undefined;
|
|
8
|
-
/**
|
|
8
|
+
/** https, directly or behind a proxy that says so (`X-Forwarded-Proto`; the proxy's word is read, never `X-Forwarded-Host`) */
|
|
9
|
+
export declare const isSecure: (c: Context) => boolean;
|
|
10
|
+
/** the path and query of a URL, as a redirect to this site: one leading slash (`//evil.com` is another site's) */
|
|
11
|
+
export declare const pathAndQuery: (url: URL) => string;
|
|
12
|
+
/**
|
|
13
|
+
* `url` as a URL of this site, or null (another site, unparsable). Hosts are compared, not origins: behind a proxy
|
|
14
|
+
* that terminates TLS the request's URL is `http://` while the browser's `Referer` is `https://`.
|
|
15
|
+
*/
|
|
9
16
|
export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
|
|
17
|
+
/**
|
|
18
|
+
* The page the request came from (its `Referer`) as a URL: only its path and query are ever used. A request the
|
|
19
|
+
* browser says is `Sec-Fetch-Site: same-origin` came from a page of this site; else its host must be this site's.
|
|
20
|
+
*/
|
|
21
|
+
export declare function referer(c: Context): URL | null;
|
|
10
22
|
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
|
11
23
|
export declare const back: (c: Context, fallback?: string) => Response & import("hono").TypedResponse<undefined, 303, "redirect">;
|
|
24
|
+
/**
|
|
25
|
+
* The trailing-slash redirect, for a GET or HEAD no route answered (404): a 301 to the path with its slash taken off
|
|
26
|
+
* (`'trim'`) or put on (`'append'`). Its Location is relative, the path as it was asked (encoded) and the query:
|
|
27
|
+
* behind a proxy the request's URL has another scheme than the browser's. One leading slash (`//evil.com/` is
|
|
28
|
+
* `/evil.com`, never another site).
|
|
29
|
+
*/
|
|
30
|
+
export declare const trailingSlash: (append: boolean) => MiddlewareHandler;
|
|
31
|
+
/**
|
|
32
|
+
* `hono/csrf`'s fallback for a browser without `Sec-Fetch-Site`: an `Origin` with this request's `Host`, and its scheme
|
|
33
|
+
* (`https` too when a proxy says so). Hono compares it with the request's URL, `http://` behind a proxy.
|
|
34
|
+
*/
|
|
35
|
+
export declare const csrfOrigin: (origin: string, c: Context) => boolean;
|
|
12
36
|
/**
|
|
13
37
|
* A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
|
|
14
38
|
* the copy of `new Response('text')` (`c.text()`) has no Content-Type: browsers download it. Its own headers, then,
|
package/dist/server/http.js
CHANGED
|
@@ -4,13 +4,38 @@ export const isPageRequest = (c) => c.req.header('x-fondu') === 'true';
|
|
|
4
4
|
export const wantsPage = (c) => isPageRequest(c) || (c.req.header('accept') ?? '').includes('text/html');
|
|
5
5
|
/** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
|
|
6
6
|
export const nonceOf = (c) => c.get('secureHeadersNonce');
|
|
7
|
-
/**
|
|
7
|
+
/** https, directly or behind a proxy that says so (`X-Forwarded-Proto`; the proxy's word is read, never `X-Forwarded-Host`) */
|
|
8
|
+
export const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
|
|
9
|
+
c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
|
|
10
|
+
/** the `Host` the browser asked for: behind a proxy that terminates TLS, the request's URL has the scheme of the hop */
|
|
11
|
+
const hostOf = (c) => (c.req.header('host') ?? new URL(c.req.url).host).toLowerCase();
|
|
12
|
+
/** the path and query of a URL, as a redirect to this site: one leading slash (`//evil.com` is another site's) */
|
|
13
|
+
export const pathAndQuery = (url) => url.pathname.replace(/^\/+/, '/') + url.search;
|
|
14
|
+
/**
|
|
15
|
+
* `url` as a URL of this site, or null (another site, unparsable). Hosts are compared, not origins: behind a proxy
|
|
16
|
+
* that terminates TLS the request's URL is `http://` while the browser's `Referer` is `https://`.
|
|
17
|
+
*/
|
|
8
18
|
export function sameOrigin(c, url) {
|
|
9
19
|
if (!url)
|
|
10
20
|
return null;
|
|
11
21
|
try {
|
|
12
22
|
const parsed = new URL(url, c.req.url);
|
|
13
|
-
return parsed.
|
|
23
|
+
return parsed.host === new URL(c.req.url).host || parsed.host === hostOf(c) ? parsed : null;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The page the request came from (its `Referer`) as a URL: only its path and query are ever used. A request the
|
|
31
|
+
* browser says is `Sec-Fetch-Site: same-origin` came from a page of this site; else its host must be this site's.
|
|
32
|
+
*/
|
|
33
|
+
export function referer(c) {
|
|
34
|
+
const url = c.req.header('referer');
|
|
35
|
+
if (c.req.header('sec-fetch-site') !== 'same-origin')
|
|
36
|
+
return sameOrigin(c, url);
|
|
37
|
+
try {
|
|
38
|
+
return url ? new URL(url, c.req.url) : null;
|
|
14
39
|
}
|
|
15
40
|
catch {
|
|
16
41
|
return null;
|
|
@@ -18,8 +43,40 @@ export function sameOrigin(c, url) {
|
|
|
18
43
|
}
|
|
19
44
|
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
|
20
45
|
export const back = (c, fallback = '/') => {
|
|
21
|
-
const from =
|
|
22
|
-
return c.redirect(from ? from
|
|
46
|
+
const from = referer(c);
|
|
47
|
+
return c.redirect(from ? pathAndQuery(from) : fallback, 303);
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* The trailing-slash redirect, for a GET or HEAD no route answered (404): a 301 to the path with its slash taken off
|
|
51
|
+
* (`'trim'`) or put on (`'append'`). Its Location is relative, the path as it was asked (encoded) and the query:
|
|
52
|
+
* behind a proxy the request's URL has another scheme than the browser's. One leading slash (`//evil.com/` is
|
|
53
|
+
* `/evil.com`, never another site).
|
|
54
|
+
*/
|
|
55
|
+
export const trailingSlash = (append) => async (c, next) => {
|
|
56
|
+
await next();
|
|
57
|
+
if (c.res.status !== 404 || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
|
|
58
|
+
return;
|
|
59
|
+
const url = new URL(c.req.url);
|
|
60
|
+
if (url.pathname === '/' || url.pathname.endsWith('/') === append)
|
|
61
|
+
return;
|
|
62
|
+
url.pathname = append ? `${url.pathname}/` : url.pathname.slice(0, -1);
|
|
63
|
+
c.res = c.redirect(pathAndQuery(url), 301);
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* `hono/csrf`'s fallback for a browser without `Sec-Fetch-Site`: an `Origin` with this request's `Host`, and its scheme
|
|
67
|
+
* (`https` too when a proxy says so). Hono compares it with the request's URL, `http://` behind a proxy.
|
|
68
|
+
*/
|
|
69
|
+
export const csrfOrigin = (origin, c) => {
|
|
70
|
+
try {
|
|
71
|
+
const parsed = new URL(origin);
|
|
72
|
+
return (parsed.origin === origin &&
|
|
73
|
+
parsed.host === hostOf(c) &&
|
|
74
|
+
(parsed.protocol === new URL(c.req.url).protocol ||
|
|
75
|
+
(parsed.protocol === 'https:' && isSecure(c))));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
23
80
|
};
|
|
24
81
|
/**
|
|
25
82
|
* A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
|
package/dist/server/prerender.js
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData } from '../paths.js';
|
|
2
2
|
import { isPrerendering } from './http.js';
|
|
3
|
+
/**
|
|
4
|
+
* A param's value becomes a file name (`/items/:id` → `items/<id>.html`): not a path of its own. A `/` or a `\`
|
|
5
|
+
* in it (Windows' separator) would make a directory of it, or leave the build's directory (`../../x`); a catch-all
|
|
6
|
+
* is the path of its segments, each of which is a name. Throws, naming the value.
|
|
7
|
+
*/
|
|
8
|
+
function fileNames(pattern, params) {
|
|
9
|
+
for (const [, name, catchAll] of pattern.matchAll(/:(\w+)(\{[^}]*\})?/g)) {
|
|
10
|
+
const value = String(params[name]);
|
|
11
|
+
for (const part of catchAll ? value.split('/') : [value])
|
|
12
|
+
if (part === '.' || part === '..' || part.includes('\\') || (!catchAll && part.includes('/')))
|
|
13
|
+
throw new Error(`param "${name}" is ${JSON.stringify(value)}: a prerendered URL is a file, and its names have no ` +
|
|
14
|
+
`separators (/ or \\) and are not . or ..`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
3
17
|
/** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
|
|
4
18
|
export async function prerenderPaths(routes) {
|
|
5
19
|
const paths = new Set();
|
|
@@ -28,8 +42,11 @@ export async function prerenderPaths(routes) {
|
|
|
28
42
|
continue;
|
|
29
43
|
}
|
|
30
44
|
try {
|
|
31
|
-
for (const params of await setting())
|
|
32
|
-
|
|
45
|
+
for (const params of await setting()) {
|
|
46
|
+
const path = fillPattern(route.pattern, params);
|
|
47
|
+
fileNames(route.pattern, params);
|
|
48
|
+
add(path);
|
|
49
|
+
}
|
|
33
50
|
}
|
|
34
51
|
catch (error) {
|
|
35
52
|
problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
|
package/dist/server/protocol.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { version } from 'virtual:fondu/assets';
|
|
2
2
|
import { renderDocument } from './document.js';
|
|
3
3
|
import { flashCookie, takeCarried } from './flash.js';
|
|
4
|
-
import { appendHeader, back, isPageRequest, isPrerendering, sameOrigin } from './http.js';
|
|
4
|
+
import { appendHeader, back, isPageRequest, isPrerendering, pathAndQuery, referer, sameOrigin, } from './http.js';
|
|
5
5
|
const shared = new WeakMap();
|
|
6
6
|
/** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
|
|
7
7
|
export function share(c, props) {
|
|
@@ -44,8 +44,8 @@ export const routePage = (id) => async (c, next) => {
|
|
|
44
44
|
/** This URL as the page's: the request's for a GET, the page the request came from otherwise. */
|
|
45
45
|
function pageUrl(c) {
|
|
46
46
|
const here = new URL(c.req.url);
|
|
47
|
-
const from = c.req.method === 'GET' ? here : (
|
|
48
|
-
return from
|
|
47
|
+
const from = c.req.method === 'GET' ? here : (referer(c) ?? here);
|
|
48
|
+
return pathAndQuery(from);
|
|
49
49
|
}
|
|
50
50
|
/**
|
|
51
51
|
* The route file's page (its default export) with these props: JSON for a navigation, the HTML document
|
|
@@ -135,10 +135,13 @@ function askedFor(c, id) {
|
|
|
135
135
|
!isPageRequest(c) ||
|
|
136
136
|
c.req.header('x-fondu-component') !== id)
|
|
137
137
|
return;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
138
|
+
// each name once, in the order first given: a name asked twice does not run its loader twice
|
|
139
|
+
return [
|
|
140
|
+
...new Set(only
|
|
141
|
+
.split(',')
|
|
142
|
+
.map((name) => name.trim())
|
|
143
|
+
.filter(Boolean)),
|
|
144
|
+
];
|
|
142
145
|
}
|
|
143
146
|
/** an http(s) URL, as `to` resolves from the request's */
|
|
144
147
|
function webUrl(c, to) {
|
|
@@ -150,17 +153,25 @@ function webUrl(c, to) {
|
|
|
150
153
|
}
|
|
151
154
|
}
|
|
152
155
|
// ---- the protocol middleware (installed by createApp)
|
|
156
|
+
/**
|
|
157
|
+
* Every header that selects what a navigation answers: the page object (`X-Fondu`), the 409 of an old build
|
|
158
|
+
* (`X-Fondu-Version`), a partial answer (`X-Fondu-Only`, for `X-Fondu-Component`'s page)
|
|
159
|
+
*/
|
|
160
|
+
const NAVIGATION_VARY = 'X-Fondu, X-Fondu-Version, X-Fondu-Only, X-Fondu-Component';
|
|
153
161
|
const versionCheck = async (c, next) => {
|
|
154
162
|
// a navigation of a client built from other assets: the page loads as a document
|
|
155
163
|
if (version &&
|
|
156
164
|
c.req.method === 'GET' &&
|
|
157
165
|
isPageRequest(c) &&
|
|
158
166
|
c.req.header('x-fondu-version') !== version) {
|
|
159
|
-
return c.body(null, 409, {
|
|
167
|
+
return c.body(null, 409, {
|
|
168
|
+
'X-Fondu-Location': pathAndQuery(new URL(c.req.url)),
|
|
169
|
+
Vary: NAVIGATION_VARY,
|
|
170
|
+
});
|
|
160
171
|
}
|
|
161
172
|
await next();
|
|
162
173
|
// a URL answers a navigation and a document differently: caches keep them apart
|
|
163
|
-
appendHeader(c, 'Vary', isPageRequest(c) ?
|
|
174
|
+
appendHeader(c, 'Vary', isPageRequest(c) ? NAVIGATION_VARY : 'X-Fondu');
|
|
164
175
|
// an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
|
|
165
176
|
// isn't read to tell (a stream's would be, to its end)
|
|
166
177
|
if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
|
|
@@ -178,7 +189,7 @@ const versionCheck = async (c, next) => {
|
|
|
178
189
|
// this site's root (a relative Location is the request's, not the page's on the screen)
|
|
179
190
|
else if (to.includes('#'))
|
|
180
191
|
c.res = c.body(null, 200, {
|
|
181
|
-
'X-Fondu-Redirect': here
|
|
192
|
+
'X-Fondu-Redirect': pathAndQuery(here) + here.hash,
|
|
182
193
|
});
|
|
183
194
|
}
|
|
184
195
|
};
|
package/dist/server/routes.js
CHANGED
|
@@ -65,7 +65,7 @@ export function routeTable(modules, append) {
|
|
|
65
65
|
: 'Move one, or list the values of a param: `export const params = { name: [...] }`'));
|
|
66
66
|
byKey.set(key, route);
|
|
67
67
|
}
|
|
68
|
-
return routes.sort((a, b) =>
|
|
68
|
+
return routes.sort((a, b) => compare(a.pattern, b.pattern));
|
|
69
69
|
}
|
|
70
70
|
function paramsOf(file, mod) {
|
|
71
71
|
const params = mod?.params;
|
|
@@ -81,8 +81,23 @@ function paramsOf(file, mod) {
|
|
|
81
81
|
}
|
|
82
82
|
// a catch-all takes the rest of the path: never a trailing slash
|
|
83
83
|
const withSlash = (pattern, append) => append && pattern !== '/' && !pattern.endsWith('{.+}') ? pattern + '/' : pattern;
|
|
84
|
-
/**
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
84
|
+
/** a segment's specificity: static, then a param with listed values, then a param, then a catch-all */
|
|
85
|
+
const priority = (s) => s.endsWith('{.+}') ? 3 : s.includes('{') ? 1 : s.startsWith(':') ? 2 : 0;
|
|
86
|
+
/**
|
|
87
|
+
* Hono's order: the specificity of each segment, from the first (static segments of another spelling are other
|
|
88
|
+
* URLs: alphabetical); a param's name decides only between patterns equally specific at every segment, so
|
|
89
|
+
* renaming a param never changes which route answers
|
|
90
|
+
*/
|
|
91
|
+
function compare(a, b) {
|
|
92
|
+
const x = a.split('/');
|
|
93
|
+
const y = b.split('/');
|
|
94
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
95
|
+
const d = priority(x[i]) - priority(y[i]);
|
|
96
|
+
if (d)
|
|
97
|
+
return d;
|
|
98
|
+
// two static segments that differ: the routes are apart, any order is right (the alphabetical one is steady)
|
|
99
|
+
if (priority(x[i]) === 0 && x[i] !== y[i])
|
|
100
|
+
return x[i] < y[i] ? -1 : 1;
|
|
101
|
+
}
|
|
102
|
+
return x.length - y.length || (a < b ? -1 : a > b ? 1 : 0);
|
|
103
|
+
}
|
|
@@ -31,8 +31,8 @@ export declare class ValidationError extends Error {
|
|
|
31
31
|
export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
|
|
32
32
|
/**
|
|
33
33
|
* A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
|
|
34
|
-
* that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32
|
|
35
|
-
* 400.
|
|
34
|
+
* that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32, more than 10,000
|
|
35
|
+
* entries) is a 400.
|
|
36
36
|
*/
|
|
37
37
|
export declare function readBody(c: Context): Promise<unknown>;
|
|
38
38
|
/** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
|
package/dist/server/validate.js
CHANGED
|
@@ -23,13 +23,14 @@ export function validationErrorResponse(c, error) {
|
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
25
|
* A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
|
|
26
|
-
* that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32
|
|
27
|
-
* 400.
|
|
26
|
+
* that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32, more than 10,000
|
|
27
|
+
* entries) is a 400.
|
|
28
28
|
*/
|
|
29
29
|
export async function readBody(c) {
|
|
30
30
|
const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
|
|
31
31
|
const type = (c.req.header('content-type') ?? '').toLowerCase();
|
|
32
|
-
|
|
32
|
+
// `application/json`, and any `application/*+json` (`merge-patch+json`, `vnd.api+json`), as the client reads an answer
|
|
33
|
+
if (type.includes('application/json') || /^application\/[^;\s]+\+json\s*(?:;|$)/.test(type))
|
|
33
34
|
return c.req.json().catch(() => Promise.reject(malformed('invalid JSON')));
|
|
34
35
|
if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
|
|
35
36
|
return {};
|
package/dist/virtual.d.ts
CHANGED
|
@@ -14,6 +14,8 @@ declare module 'virtual:fondu/ssr' {
|
|
|
14
14
|
page: import('./client/navigation.js').Page,
|
|
15
15
|
options: {
|
|
16
16
|
nonce?: string
|
|
17
|
+
/** the request's: React stops rendering when it aborts */
|
|
18
|
+
signal?: AbortSignal
|
|
17
19
|
onError?: (error: unknown) => void
|
|
18
20
|
bootstrapScriptContent?: string
|
|
19
21
|
},
|