@krate/runtime 0.5.0-rc.5 → 0.5.0-rc.6
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/actions.js +10 -1
- package/dist/cache-scope.d.ts +2 -0
- package/dist/cache-scope.js +6 -1
- package/dist/context.d.ts +5 -0
- package/dist/context.js +28 -17
- package/dist/flight-props.d.ts +7 -0
- package/dist/flight-props.js +105 -0
- package/dist/hints.d.ts +25 -2
- package/dist/hints.js +148 -74
- package/dist/index.d.ts +1 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-features.json +24 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.d.ts +14 -4
- package/dist/list.js +4 -5
- package/dist/navigation-react.d.ts +13 -0
- package/dist/navigation-react.js +86 -0
- package/dist/navigation.d.ts +19 -0
- package/dist/navigation.js +35 -0
- package/dist/react-compat.d.ts +26 -0
- package/dist/react-compat.js +292 -0
- package/dist/server-handler.js +74 -6
- package/dist/server.d.ts +17 -10
- package/dist/server.js +400 -94
- package/package.json +15 -2
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -75
- package/dist/after.test.d.ts +0 -1
- package/dist/after.test.js +0 -58
- package/dist/builtin-tags.test.d.ts +0 -1
- package/dist/builtin-tags.test.js +0 -12
- package/dist/cache-adapter.test.d.ts +0 -1
- package/dist/cache-adapter.test.js +0 -45
- package/dist/cache.test.d.ts +0 -1
- package/dist/cache.test.js +0 -37
- package/dist/events.test.d.ts +0 -1
- package/dist/events.test.js +0 -42
- package/dist/handler-html.test.d.ts +0 -1
- package/dist/handler-html.test.js +0 -55
- package/dist/handler-segments.test.d.ts +0 -1
- package/dist/handler-segments.test.js +0 -25
- package/dist/head-tags.test.d.ts +0 -1
- package/dist/head-tags.test.js +0 -24
- package/dist/inline-action-token.test.d.ts +0 -1
- package/dist/inline-action-token.test.js +0 -31
- package/dist/jsx-svg-types.test.d.ts +0 -1
- package/dist/jsx-svg-types.test.js +0 -58
- package/dist/link-base-path.test.d.ts +0 -1
- package/dist/link-base-path.test.js +0 -28
- package/dist/node-server.test.d.ts +0 -1
- package/dist/node-server.test.js +0 -138
- package/dist/platform.test.d.ts +0 -1
- package/dist/platform.test.js +0 -44
- package/dist/router-nav.test.d.ts +0 -1
- package/dist/router-nav.test.js +0 -130
- package/dist/server-handler.test.d.ts +0 -1
- package/dist/server-handler.test.js +0 -338
- package/dist/server-renderer.test.d.ts +0 -1
- package/dist/server-renderer.test.js +0 -162
- package/dist/server.test.d.ts +0 -1
- package/dist/server.test.js +0 -91
- package/dist/sha256.test.d.ts +0 -1
- package/dist/sha256.test.js +0 -13
- package/dist/signal.test.d.ts +0 -1
- package/dist/signal.test.js +0 -68
- package/dist/site-config.test.d.ts +0 -1
- package/dist/site-config.test.js +0 -30
- package/dist/slot.test.d.ts +0 -1
- package/dist/slot.test.js +0 -25
- package/dist/ssr-core-behavior.test.d.ts +0 -1
- package/dist/ssr-core-behavior.test.js +0 -108
- package/dist/testing.test.d.ts +0 -1
- package/dist/testing.test.js +0 -73
package/dist/node-server.test.js
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
// @vitest-environment node
|
|
2
|
-
import fs from "node:fs";
|
|
3
|
-
import http from "node:http";
|
|
4
|
-
import os from "node:os";
|
|
5
|
-
import path from "node:path";
|
|
6
|
-
import zlib from "node:zlib";
|
|
7
|
-
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
8
|
-
import { createNodeStaticLayer, nodeRequestListener } from "./node-server.js";
|
|
9
|
-
let tmp;
|
|
10
|
-
let dist;
|
|
11
|
-
function write(rel, data) {
|
|
12
|
-
const f = path.join(dist, rel);
|
|
13
|
-
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
14
|
-
fs.writeFileSync(f, data);
|
|
15
|
-
}
|
|
16
|
-
beforeAll(() => {
|
|
17
|
-
tmp = fs.mkdtempSync(path.join(os.tmpdir(), "krate-node-server-"));
|
|
18
|
-
dist = path.join(tmp, "dist");
|
|
19
|
-
write("index.html", "<h1>home</h1>");
|
|
20
|
-
write("about/index.html", "<h1>about</h1>");
|
|
21
|
-
write("empty/readme.txt", "no index here");
|
|
22
|
-
write("app.abc123.js", "console.log('0123456789');");
|
|
23
|
-
write("app.abc123.js.gz", zlib.gzipSync("gz-body"));
|
|
24
|
-
write("app.abc123.js.br", zlib.brotliCompressSync("br-body"));
|
|
25
|
-
write("data.bin", Buffer.from("0123456789"));
|
|
26
|
-
write("logo.png", Buffer.from("not really a png"));
|
|
27
|
-
write("page.html", "<p>page</p>");
|
|
28
|
-
write(".env", "SECRET=1");
|
|
29
|
-
write(".well-known/security.txt", "Contact: a@example.com");
|
|
30
|
-
write(".krate/manifest.json", "{}");
|
|
31
|
-
write("server-manifest.json", "{}");
|
|
32
|
-
write("api-node/hello.mjs", "export {}");
|
|
33
|
-
fs.writeFileSync(path.join(tmp, "outside.txt"), "outside the site");
|
|
34
|
-
fs.symlinkSync(path.join(tmp, "outside.txt"), path.join(dist, "escape.txt"));
|
|
35
|
-
});
|
|
36
|
-
afterAll(() => {
|
|
37
|
-
fs.rmSync(tmp, { recursive: true, force: true });
|
|
38
|
-
});
|
|
39
|
-
function req(url, init = {}) {
|
|
40
|
-
return new Request("http://localhost" + url, init);
|
|
41
|
-
}
|
|
42
|
-
describe("createNodeStaticLayer", () => {
|
|
43
|
-
const layer = () => createNodeStaticLayer(dist);
|
|
44
|
-
it("serves a file with type, length, validators and range support", async () => {
|
|
45
|
-
const r = (await layer().serve(req("/data.bin"), "/data.bin"));
|
|
46
|
-
expect(r.status).toBe(200);
|
|
47
|
-
expect(r.headers.get("content-type")).toBe("application/octet-stream");
|
|
48
|
-
expect(r.headers.get("content-length")).toBe("10");
|
|
49
|
-
expect(r.headers.get("accept-ranges")).toBe("bytes");
|
|
50
|
-
expect(r.headers.get("last-modified")).toMatch(/GMT$/);
|
|
51
|
-
expect(await r.text()).toBe("0123456789");
|
|
52
|
-
});
|
|
53
|
-
it.each([
|
|
54
|
-
["dotfile", "/.env"],
|
|
55
|
-
["encoded dotfile", "/%2eenv"],
|
|
56
|
-
["dotfile inside a path", "/about/../.env"],
|
|
57
|
-
["krate internals", "/.krate/manifest.json"],
|
|
58
|
-
["server manifest", "/server-manifest.json"],
|
|
59
|
-
["api bundles", "/api-node/hello.mjs"],
|
|
60
|
-
["parent traversal", "/../outside.txt"],
|
|
61
|
-
["encoded traversal", "/%2e%2e/outside.txt"],
|
|
62
|
-
["backslash traversal", "/..%5coutside.txt"],
|
|
63
|
-
["symlink out of the site", "/escape.txt"],
|
|
64
|
-
["null byte", "/data.bin%00.html"],
|
|
65
|
-
])("does not serve %s", async (_name, p) => {
|
|
66
|
-
const l = layer();
|
|
67
|
-
expect(await l.serve(req(p), decodeURIComponentSafe(p))).toBeNull();
|
|
68
|
-
expect(await l.exists(decodeURIComponentSafe(p))).toBe(false);
|
|
69
|
-
});
|
|
70
|
-
});
|
|
71
|
-
function decodeURIComponentSafe(p) {
|
|
72
|
-
try {
|
|
73
|
-
return decodeURIComponent(p);
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
return p;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
function listen(server) {
|
|
80
|
-
return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port)));
|
|
81
|
-
}
|
|
82
|
-
function call(port, p, headers = {}, opts = {}) {
|
|
83
|
-
return new Promise((resolve, reject) => {
|
|
84
|
-
const r = http.request({ host: "127.0.0.1", port, path: p, method: opts.method || "GET", headers }, (res) => {
|
|
85
|
-
const chunks = [];
|
|
86
|
-
res.on("data", (c) => chunks.push(c));
|
|
87
|
-
res.on("end", () => resolve({ status: res.statusCode || 0, headers: res.headers, rawHeaders: res.rawHeaders, body: Buffer.concat(chunks) }));
|
|
88
|
-
res.on("error", reject);
|
|
89
|
-
});
|
|
90
|
-
r.on("error", reject);
|
|
91
|
-
if (opts.body !== undefined)
|
|
92
|
-
r.write(opts.body);
|
|
93
|
-
r.end();
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
async function withServer(handler, trustProxy, fn) {
|
|
97
|
-
const server = http.createServer(nodeRequestListener(handler, trustProxy));
|
|
98
|
-
const port = await listen(server);
|
|
99
|
-
try {
|
|
100
|
-
return await fn(port);
|
|
101
|
-
}
|
|
102
|
-
finally {
|
|
103
|
-
server.closeAllConnections();
|
|
104
|
-
await new Promise((ok) => server.close(ok));
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
describe("requestFromNode", () => {
|
|
108
|
-
const echo = async (request) => Response.json({
|
|
109
|
-
url: request.url,
|
|
110
|
-
method: request.method,
|
|
111
|
-
xff: request.headers.get("x-forwarded-for"),
|
|
112
|
-
host: request.headers.get("x-forwarded-host"),
|
|
113
|
-
proto: request.headers.get("x-forwarded-proto"),
|
|
114
|
-
forwarded: request.headers.get("forwarded"),
|
|
115
|
-
realIp: request.headers.get("x-real-ip"),
|
|
116
|
-
body: request.method === "POST" ? await request.text() : null,
|
|
117
|
-
cookie: request.headers.get("cookie"),
|
|
118
|
-
});
|
|
119
|
-
it("replaces client-supplied forwarding headers with what the socket shows", async () => {
|
|
120
|
-
await withServer(echo, false, async (port) => {
|
|
121
|
-
const r = await call(port, "/p?q=1", {
|
|
122
|
-
"x-forwarded-for": "1.2.3.4",
|
|
123
|
-
"x-forwarded-host": "evil.example",
|
|
124
|
-
"x-forwarded-proto": "https",
|
|
125
|
-
forwarded: "for=1.2.3.4",
|
|
126
|
-
"x-real-ip": "1.2.3.4",
|
|
127
|
-
host: "site.test",
|
|
128
|
-
});
|
|
129
|
-
const j = JSON.parse(r.body.toString());
|
|
130
|
-
expect(j.xff).toBe("127.0.0.1");
|
|
131
|
-
expect(j.host).toBe("site.test");
|
|
132
|
-
expect(j.proto).toBe("http");
|
|
133
|
-
expect(j.forwarded).toBeNull();
|
|
134
|
-
expect(j.realIp).toBeNull();
|
|
135
|
-
expect(j.url).toBe("http://site.test/p?q=1");
|
|
136
|
-
});
|
|
137
|
-
});
|
|
138
|
-
});
|
package/dist/platform.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/platform.test.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { after } from './after.js';
|
|
3
|
-
import { env as shimEnv } from './cloudflare-workers.js';
|
|
4
|
-
import { getCloudflareContext, getPlatform } from './platform.js';
|
|
5
|
-
import { runWithPlatform } from './server-handler.js';
|
|
6
|
-
function fakeContext() {
|
|
7
|
-
const waited = [];
|
|
8
|
-
return { waited, ctx: { env: { DB: 'db-binding', GREETING: 'hi' }, cf: { country: 'NL' }, waitUntil: (p) => waited.push(p) } };
|
|
9
|
-
}
|
|
10
|
-
describe('platform access', () => {
|
|
11
|
-
it('returns an empty environment outside a request', () => {
|
|
12
|
-
const p = getPlatform();
|
|
13
|
-
expect(p.target).toBe('none');
|
|
14
|
-
expect(p.env).toEqual({});
|
|
15
|
-
expect(() => getCloudflareContext()).toThrow(/outside|no request|cloudflare target/);
|
|
16
|
-
});
|
|
17
|
-
it('exposes env, ctx and cf of the request being served', async () => {
|
|
18
|
-
const { ctx } = fakeContext();
|
|
19
|
-
const seen = await runWithPlatform('cloudflare', ctx, async () => {
|
|
20
|
-
await Promise.resolve();
|
|
21
|
-
const cf = getCloudflareContext();
|
|
22
|
-
return { db: cf.env.DB, country: cf.cf?.country, target: getPlatform().target };
|
|
23
|
-
});
|
|
24
|
-
expect(seen).toEqual({ db: 'db-binding', country: 'NL', target: 'cloudflare' });
|
|
25
|
-
expect(getPlatform().target).toBe('none');
|
|
26
|
-
});
|
|
27
|
-
it('refuses getCloudflareContext on other targets', () => {
|
|
28
|
-
const { ctx } = fakeContext();
|
|
29
|
-
expect(() => runWithPlatform('node', ctx, () => getCloudflareContext())).toThrow(/"node"/);
|
|
30
|
-
});
|
|
31
|
-
it('backs after() with ctx.waitUntil', async () => {
|
|
32
|
-
const { ctx, waited } = fakeContext();
|
|
33
|
-
let ran = false;
|
|
34
|
-
runWithPlatform('cloudflare', ctx, () => after(() => { ran = true; }));
|
|
35
|
-
expect(waited).toHaveLength(1);
|
|
36
|
-
await waited[0];
|
|
37
|
-
expect(ran).toBe(true);
|
|
38
|
-
});
|
|
39
|
-
it('serves the cloudflare:workers stand-in from the same request env', () => {
|
|
40
|
-
const { ctx } = fakeContext();
|
|
41
|
-
expect(runWithPlatform('cloudflare', ctx, () => shimEnv.DB)).toBe('db-binding');
|
|
42
|
-
expect(() => shimEnv.DB).toThrow(/cloudflare target/);
|
|
43
|
-
});
|
|
44
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/router-nav.test.js
DELETED
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
2
|
-
import { initRouter, destroyRouter, krateRouter, } from './router';
|
|
3
|
-
function page(title, body, head = '') {
|
|
4
|
-
return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
|
|
5
|
-
}
|
|
6
|
-
let routes;
|
|
7
|
-
let fetchMock;
|
|
8
|
-
let hardNavs;
|
|
9
|
-
function installFetch() {
|
|
10
|
-
fetchMock = vi.fn(async (input, init) => {
|
|
11
|
-
const u = new URL(input, location.href);
|
|
12
|
-
const r = routes[u.pathname + u.search] ?? routes[u.pathname];
|
|
13
|
-
if (!r) {
|
|
14
|
-
return mockResponse({ status: 404, body: 'nope', type: 'text/plain' }, u.href);
|
|
15
|
-
}
|
|
16
|
-
if (r.gate)
|
|
17
|
-
await r.gate;
|
|
18
|
-
if (init?.signal?.aborted) {
|
|
19
|
-
const e = new Error('aborted');
|
|
20
|
-
e.name = 'AbortError';
|
|
21
|
-
throw e;
|
|
22
|
-
}
|
|
23
|
-
if (r.fail)
|
|
24
|
-
throw r.fail;
|
|
25
|
-
return mockResponse(r, r.redirect ? new URL(r.redirect, location.href).href : u.href);
|
|
26
|
-
});
|
|
27
|
-
vi.stubGlobal('fetch', fetchMock);
|
|
28
|
-
}
|
|
29
|
-
function mockResponse(r, url) {
|
|
30
|
-
const status = r.status ?? 200;
|
|
31
|
-
return {
|
|
32
|
-
ok: status >= 200 && status < 300,
|
|
33
|
-
status,
|
|
34
|
-
url,
|
|
35
|
-
redirected: !!r.redirect,
|
|
36
|
-
headers: new Headers({ 'content-type': r.type ?? 'text/html; charset=utf-8' }),
|
|
37
|
-
text: async () => r.body ?? '',
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
function link(href, text, attrs = '') {
|
|
41
|
-
return `<a data-krate-link href="${href}" ${attrs}>${text}</a>`;
|
|
42
|
-
}
|
|
43
|
-
function click(el) {
|
|
44
|
-
el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }));
|
|
45
|
-
}
|
|
46
|
-
async function settle() {
|
|
47
|
-
for (let i = 0; i < 10; i++)
|
|
48
|
-
await Promise.resolve();
|
|
49
|
-
await new Promise((r) => setTimeout(r, 0));
|
|
50
|
-
for (let i = 0; i < 10; i++)
|
|
51
|
-
await Promise.resolve();
|
|
52
|
-
}
|
|
53
|
-
function events(name) {
|
|
54
|
-
const got = [];
|
|
55
|
-
window.addEventListener(name, (e) => got.push(e.detail));
|
|
56
|
-
return got;
|
|
57
|
-
}
|
|
58
|
-
beforeEach(() => {
|
|
59
|
-
destroyRouter();
|
|
60
|
-
globalThis.__KRATE_CFG__ = { viewTransitions: false };
|
|
61
|
-
history.replaceState(null, '', '/');
|
|
62
|
-
document.title = 'Home';
|
|
63
|
-
document.head.innerHTML = '<title>Home</title>';
|
|
64
|
-
document.body.innerHTML = `<div id="root"><h1>Home</h1>${link('/about', 'About')}${link('/docs', 'Docs')}${link('/docs-old', 'Old')}</div>`;
|
|
65
|
-
routes = {
|
|
66
|
-
'/about': { body: page('About', `<h1>About</h1>${link('/', 'Home')}`) },
|
|
67
|
-
'/docs': { body: page('Docs', `<h1>Docs</h1>${link('/docs', 'Docs')}${link('/docs/intro', 'Intro')}`) },
|
|
68
|
-
'/docs/intro': { body: page('Intro', `<h1>Intro</h1>${link('/docs', 'Docs')}${link('/docs-old', 'Old')}`) },
|
|
69
|
-
};
|
|
70
|
-
installFetch();
|
|
71
|
-
hardNavs = [];
|
|
72
|
-
globalThis.__krateHardNavigate = (url, replace) => hardNavs.push([url, replace]);
|
|
73
|
-
initRouter();
|
|
74
|
-
});
|
|
75
|
-
afterEach(() => {
|
|
76
|
-
destroyRouter();
|
|
77
|
-
vi.unstubAllGlobals();
|
|
78
|
-
delete globalThis.__krateHardNavigate;
|
|
79
|
-
delete globalThis.__KRATE_CFG__;
|
|
80
|
-
delete document.startViewTransition;
|
|
81
|
-
});
|
|
82
|
-
describe('SPA navigation', () => {
|
|
83
|
-
it('swaps the app root, title, history and announces the route', async () => {
|
|
84
|
-
const nav = events('krate:navigate');
|
|
85
|
-
click(document.querySelector('a[href="/about"]'));
|
|
86
|
-
await settle();
|
|
87
|
-
expect(location.pathname).toBe('/about');
|
|
88
|
-
expect(document.querySelector('#root h1').textContent).toBe('About');
|
|
89
|
-
expect(document.title).toBe('About');
|
|
90
|
-
expect(nav.length).toBe(1);
|
|
91
|
-
expect(document.getElementById('__krate-route-announcer').textContent).toBe('About');
|
|
92
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
93
|
-
});
|
|
94
|
-
it('follows html and body attribute changes and keeps runtime-set ones', async () => {
|
|
95
|
-
routes['/themed'] = {
|
|
96
|
-
body: '<!doctype html><html class="dark" lang="fr"><head><title>T</title></head><body data-x="1"><div id="root"><h1>T</h1></div></body></html>',
|
|
97
|
-
};
|
|
98
|
-
document.documentElement.setAttribute('data-runtime', '1');
|
|
99
|
-
await krateRouter.push('/themed');
|
|
100
|
-
await settle();
|
|
101
|
-
expect(document.documentElement.getAttribute('class')).toBe('dark');
|
|
102
|
-
expect(document.documentElement.getAttribute('lang')).toBe('fr');
|
|
103
|
-
expect(document.body.getAttribute('data-x')).toBe('1');
|
|
104
|
-
expect(document.documentElement.getAttribute('data-runtime')).toBe('1');
|
|
105
|
-
await krateRouter.push('/about');
|
|
106
|
-
await settle();
|
|
107
|
-
expect(document.documentElement.hasAttribute('class')).toBe(false);
|
|
108
|
-
expect(document.body.hasAttribute('data-x')).toBe(false);
|
|
109
|
-
expect(document.documentElement.getAttribute('data-runtime')).toBe('1');
|
|
110
|
-
});
|
|
111
|
-
it('hard-navigates when a redirect leaves the origin', async () => {
|
|
112
|
-
routes['/out'] = { body: page('x', ''), redirect: 'https://example.com/elsewhere' };
|
|
113
|
-
await krateRouter.push('/out');
|
|
114
|
-
expect(hardNavs[0][0]).toBe('https://example.com/elsewhere');
|
|
115
|
-
});
|
|
116
|
-
});
|
|
117
|
-
describe('races', () => {
|
|
118
|
-
it('a slower superseded navigation never overwrites a newer one', async () => {
|
|
119
|
-
let open;
|
|
120
|
-
routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
|
|
121
|
-
const first = krateRouter.push('/slow');
|
|
122
|
-
const second = krateRouter.push('/about');
|
|
123
|
-
await second;
|
|
124
|
-
open();
|
|
125
|
-
await first;
|
|
126
|
-
await settle();
|
|
127
|
-
expect(document.title).toBe('About');
|
|
128
|
-
expect(location.pathname).toBe('/about');
|
|
129
|
-
});
|
|
130
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,338 +0,0 @@
|
|
|
1
|
-
// @vitest-environment node
|
|
2
|
-
import { describe, expect, it, vi } from "vitest";
|
|
3
|
-
import { createKrateHandler, matchMetaRoute } from "./server-handler.js";
|
|
4
|
-
import { jsx, ServerErrorBoundary } from "./server.js";
|
|
5
|
-
const config = {
|
|
6
|
-
basePath: "",
|
|
7
|
-
trustProxy: true,
|
|
8
|
-
maxBodyBytes: 1 << 20,
|
|
9
|
-
maxAPIBodyBytes: 1 << 20,
|
|
10
|
-
redirects: [{ source: "/old", destination: "/new", permanent: true }],
|
|
11
|
-
rewrites: [],
|
|
12
|
-
headers: [{ source: "/new", headers: { "X-Rule": "yes" } }],
|
|
13
|
-
security: { nosniff: true, frameOptions: "DENY", referrerPolicy: "no-referrer", permissionsPolicy: "", hsts: "", csp: "" },
|
|
14
|
-
cors: { enabled: false, origins: [], methods: [], headers: [], credentials: false, maxAge: 0 },
|
|
15
|
-
ssr: { timeout: 2000, maxCacheSize: 16, ppr: false, pprRevalidate: 60 },
|
|
16
|
-
};
|
|
17
|
-
function data(extra = {}) {
|
|
18
|
-
return {
|
|
19
|
-
version: 1,
|
|
20
|
-
config,
|
|
21
|
-
pages: [{ route: "/live", mode: "isr", revalidate: 30, bundlePath: "live" }],
|
|
22
|
-
regions: {},
|
|
23
|
-
allPages: [{ route: "/live", mode: "isr" }, { route: "/static", mode: "ssg" }],
|
|
24
|
-
shells: { "/live": "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>" },
|
|
25
|
-
templates: [],
|
|
26
|
-
staticOnlyRoutes: [],
|
|
27
|
-
hashedAssets: [],
|
|
28
|
-
html404: "<h1>custom 404</h1>",
|
|
29
|
-
html500: "",
|
|
30
|
-
apiRoutes: ["hello", "items/[id]"],
|
|
31
|
-
actions: [{ id: "act1", export: "add", file: "acts" }],
|
|
32
|
-
hasMiddleware: true,
|
|
33
|
-
...extra,
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
let renders = 0;
|
|
37
|
-
const modules = {
|
|
38
|
-
pages: { live: { default: () => jsx("main", { children: "render " + ++renders }) } },
|
|
39
|
-
api: {
|
|
40
|
-
hello: { GET: () => Response.json({ ok: true }), POST: async (r) => new Response(await r.text(), { status: 201 }) },
|
|
41
|
-
"items/[id]": { GET: (_r, ctx) => Response.json(ctx.params) },
|
|
42
|
-
},
|
|
43
|
-
actions: { acts: { add: (a, b) => ({ sum: a + b }) } },
|
|
44
|
-
middleware: {
|
|
45
|
-
middleware: (req) => {
|
|
46
|
-
if (new URL(req.url).pathname === "/blocked")
|
|
47
|
-
return new Response("no", { status: 403 });
|
|
48
|
-
return new Response(null, { headers: { "x-middleware-next": "1", "x-mw": "1" } });
|
|
49
|
-
},
|
|
50
|
-
config: { matcher: ["/blocked", "/api/:path*", "/live"] },
|
|
51
|
-
},
|
|
52
|
-
};
|
|
53
|
-
describe("createKrateHandler", () => {
|
|
54
|
-
const handler = createKrateHandler({ target: "node", data: data(), modules });
|
|
55
|
-
const get = (path, init) => handler(new Request("http://localhost" + path, init));
|
|
56
|
-
it("applies config redirects, header rules and security headers", async () => {
|
|
57
|
-
const r = await get("/old");
|
|
58
|
-
expect(r.status).toBe(301);
|
|
59
|
-
expect(r.headers.get("location")).toBe("/new");
|
|
60
|
-
expect(r.headers.get("x-frame-options")).toBe("DENY");
|
|
61
|
-
expect(r.headers.get("permissions-policy")).toBeNull();
|
|
62
|
-
expect((await get("/new")).headers.get("x-rule")).toBe("yes");
|
|
63
|
-
});
|
|
64
|
-
it("routes API requests with 404, 405 and params", async () => {
|
|
65
|
-
expect(await (await get("/api/items/7")).json()).toEqual({ id: "7" });
|
|
66
|
-
expect((await get("/api/none")).status).toBe(404);
|
|
67
|
-
const r = await get("/api/hello", { method: "DELETE" });
|
|
68
|
-
expect(r.status).toBe(405);
|
|
69
|
-
expect(r.headers.get("allow")).toBe("GET, POST, HEAD, OPTIONS");
|
|
70
|
-
expect((await get("/api/hello", { method: "POST", body: "abc" })).status).toBe(201);
|
|
71
|
-
});
|
|
72
|
-
it("runs server actions and rejects cross-site posts", async () => {
|
|
73
|
-
const headers = { "content-type": "application/json", "x-krate-action": "fetch", "sec-fetch-site": "same-origin" };
|
|
74
|
-
const ok = await get("/__krate/action/act1", { method: "POST", headers, body: '{"args":[2,3]}' });
|
|
75
|
-
expect(await ok.json()).toEqual({ ok: true, result: { sum: 5 } });
|
|
76
|
-
const bad = await get("/__krate/action/act1", { method: "POST", headers: { ...headers, "sec-fetch-site": "cross-site" }, body: "{}" });
|
|
77
|
-
expect(bad.status).toBe(403);
|
|
78
|
-
});
|
|
79
|
-
});
|
|
80
|
-
describe("API maxDuration", () => {
|
|
81
|
-
const sleep = (ms, signal) => new Promise((resolve) => {
|
|
82
|
-
const t = setTimeout(() => resolve(false), ms);
|
|
83
|
-
signal.addEventListener("abort", () => (clearTimeout(t), resolve(true)), { once: true });
|
|
84
|
-
});
|
|
85
|
-
let sawAbort = false;
|
|
86
|
-
const mods = {
|
|
87
|
-
...modules,
|
|
88
|
-
api: {
|
|
89
|
-
...modules.api,
|
|
90
|
-
slow: { GET: async (r) => ((sawAbort = await sleep(2000, r.signal)), Response.json({ late: true })) },
|
|
91
|
-
ok: { GET: async (r) => (await sleep(50, r.signal), Response.json({ done: true })) },
|
|
92
|
-
},
|
|
93
|
-
};
|
|
94
|
-
const h = createKrateHandler({
|
|
95
|
-
target: "node",
|
|
96
|
-
data: data({ hasMiddleware: false, apiRoutes: ["slow", "ok"], apiMaxDuration: { slow: 0.1, ok: 5 } }),
|
|
97
|
-
modules: mods,
|
|
98
|
-
});
|
|
99
|
-
const get = (path) => h(new Request("http://localhost" + path));
|
|
100
|
-
it("answers 504 and aborts request.signal at the deadline", async () => {
|
|
101
|
-
const err = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
102
|
-
const r = await get("/api/slow");
|
|
103
|
-
expect(r.status).toBe(504);
|
|
104
|
-
expect(await r.json()).toEqual({ error: "Gateway Timeout" });
|
|
105
|
-
expect(sawAbort).toBe(true);
|
|
106
|
-
err.mockRestore();
|
|
107
|
-
});
|
|
108
|
-
it("lets a handler that finishes inside its budget through", async () => {
|
|
109
|
-
const r = await get("/api/ok");
|
|
110
|
-
expect(r.status).toBe(200);
|
|
111
|
-
expect(await r.json()).toEqual({ done: true });
|
|
112
|
-
});
|
|
113
|
-
});
|
|
114
|
-
describe("canonical slash redirect", () => {
|
|
115
|
-
const h = createKrateHandler({
|
|
116
|
-
target: "node",
|
|
117
|
-
data: data({ hasMiddleware: false, templates: [{ pattern: "plain/[id]", html: "<p>[id]</p>" }] }),
|
|
118
|
-
modules,
|
|
119
|
-
});
|
|
120
|
-
const get = (path) => h(new Request("http://localhost" + path, { redirect: "manual" }));
|
|
121
|
-
it("never emits a Location that can parse as an absolute URL", async () => {
|
|
122
|
-
for (const seg of ["ftp:3232235777", "https:3232235777", "http:1"]) {
|
|
123
|
-
const r = await get("/plain/" + seg);
|
|
124
|
-
expect(r.status, seg).toBe(301);
|
|
125
|
-
const loc = r.headers.get("location");
|
|
126
|
-
expect(loc, seg).toBe("./" + seg + "/");
|
|
127
|
-
expect(new URL(loc, "http://localhost/plain/" + seg).origin, seg).toBe("http://localhost");
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
});
|
|
131
|
-
describe("signed flash cookies", () => {
|
|
132
|
-
const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
|
|
133
|
-
const mk = (target, flashSecret) => createKrateHandler({
|
|
134
|
-
target,
|
|
135
|
-
flashSecret,
|
|
136
|
-
data: data({
|
|
137
|
-
hasMiddleware: false,
|
|
138
|
-
pages: [{ route: "/form", mode: "ssr", bundlePath: "form" }],
|
|
139
|
-
allPages: [{ route: "/form", mode: "ssr" }],
|
|
140
|
-
shells: { "/form": shell },
|
|
141
|
-
actions: [{ id: "act9", export: "bad", file: "acts" }],
|
|
142
|
-
}),
|
|
143
|
-
modules: {
|
|
144
|
-
pages: {
|
|
145
|
-
form: {
|
|
146
|
-
default: () => jsx("main", { children: jsx("form", { action: "/__krate/action/act9", method: "post", children: jsx("button", { children: "go" }) }) }),
|
|
147
|
-
},
|
|
148
|
-
},
|
|
149
|
-
actions: { acts: { bad: () => ({ error: "Name is required" }) } },
|
|
150
|
-
},
|
|
151
|
-
});
|
|
152
|
-
const page = (h, cookie) => h(new Request("http://localhost/form/", { headers: { cookie } }));
|
|
153
|
-
it("ignores a cookie planted without a valid signature", async () => {
|
|
154
|
-
const h = mk("node", "a-shared-flash-secret-for-this-test");
|
|
155
|
-
const planted = Buffer.from(JSON.stringify({ a: "act9", r: { error: "Your account was suspended" } })).toString("base64url");
|
|
156
|
-
for (const cookie of [planted, planted + ".", planted + ".AAAA", "x." + planted]) {
|
|
157
|
-
const body = await (await page(h, "krate_flash=" + cookie)).text();
|
|
158
|
-
expect(body, cookie).not.toContain("suspended");
|
|
159
|
-
expect(body, cookie).not.toContain("krate-flash");
|
|
160
|
-
}
|
|
161
|
-
});
|
|
162
|
-
});
|
|
163
|
-
describe("forwarded headers per platform", () => {
|
|
164
|
-
const mk = (target, trustProxy) => {
|
|
165
|
-
const base = data({ hasMiddleware: false });
|
|
166
|
-
return createKrateHandler({
|
|
167
|
-
target,
|
|
168
|
-
data: { ...base, config: { ...config, trustProxy: trustProxy === undefined ? null : trustProxy }, apiRoutes: ["echo"], actions: [{ id: "act1", export: "add", file: "acts" }] },
|
|
169
|
-
modules: {
|
|
170
|
-
api: {
|
|
171
|
-
echo: {
|
|
172
|
-
GET: (r) => Response.json({
|
|
173
|
-
url: r.url,
|
|
174
|
-
xff: r.headers.get("x-forwarded-for"),
|
|
175
|
-
realIp: r.headers.get("x-real-ip"),
|
|
176
|
-
forwarded: r.headers.get("forwarded"),
|
|
177
|
-
host: r.headers.get("x-forwarded-host"),
|
|
178
|
-
proto: r.headers.get("x-forwarded-proto"),
|
|
179
|
-
}),
|
|
180
|
-
},
|
|
181
|
-
},
|
|
182
|
-
actions: { acts: { add: (a, b) => ({ sum: a + b }) } },
|
|
183
|
-
},
|
|
184
|
-
});
|
|
185
|
-
};
|
|
186
|
-
const echo = async (h, headers) => (await h(new Request("http://app.internal/api/echo", { headers }))).json();
|
|
187
|
-
// What a hostile client adds on top of whatever the platform sets.
|
|
188
|
-
const spoof = { "x-forwarded-host": "evil.example", "x-forwarded-proto": "https", "x-forwarded-for": "6.6.6.6, 7.7.7.7", "x-real-ip": "6.6.6.6", forwarded: "for=6.6.6.6;host=evil.example" };
|
|
189
|
-
it("vercel: a client-written forwarded chain never becomes the client address", async () => {
|
|
190
|
-
const out = await echo(mk("vercel"), { ...spoof, "x-forwarded-host": "shop.example", "x-real-ip": "203.0.113.9" });
|
|
191
|
-
expect(out.xff).toBe("203.0.113.9");
|
|
192
|
-
expect(out.forwarded).toBeNull();
|
|
193
|
-
});
|
|
194
|
-
it("the server-action origin check is not fooled by a spoofed X-Forwarded-Host", async () => {
|
|
195
|
-
const post = (h) => h(new Request("http://app.internal/__krate/action/act1", {
|
|
196
|
-
method: "POST",
|
|
197
|
-
headers: { origin: "https://evil.example", "x-forwarded-host": "evil.example", "x-krate-action": "fetch", "content-type": "application/json" },
|
|
198
|
-
body: '{"args":[1,2]}',
|
|
199
|
-
}));
|
|
200
|
-
for (const target of ["netlify", "cloudflare"]) {
|
|
201
|
-
expect((await post(mk(target))).status, target + " unset").toBe(403);
|
|
202
|
-
expect((await post(mk(target, false))).status, target + " false").toBe(403);
|
|
203
|
-
}
|
|
204
|
-
expect((await post(mk("vercel", false))).status).toBe(403);
|
|
205
|
-
// Behind a proxy of yours that sets the header, it is the real host.
|
|
206
|
-
expect((await post(mk("cloudflare", true))).status).toBe(200);
|
|
207
|
-
});
|
|
208
|
-
});
|
|
209
|
-
describe("middleware exports", () => {
|
|
210
|
-
const run = (middleware) => createKrateHandler({ target: "node", data: data(), modules: { ...modules, middleware } })(new Request("http://localhost/live"));
|
|
211
|
-
it("fails closed when the module has no handler", async () => {
|
|
212
|
-
const error = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
213
|
-
expect((await run({ other: 1 })).status).toBe(503);
|
|
214
|
-
expect((await run(undefined)).status).toBe(503);
|
|
215
|
-
error.mockRestore();
|
|
216
|
-
});
|
|
217
|
-
});
|
|
218
|
-
describe("per-request metadata routes", () => {
|
|
219
|
-
const metaRoutes = [
|
|
220
|
-
{ path: "/robots.txt", key: "__krate_meta/robots" },
|
|
221
|
-
{ prefix: "/sitemap/", suffix: ".xml", key: "__krate_meta/sitemap/[id]" },
|
|
222
|
-
];
|
|
223
|
-
it("maps public URLs to API route keys", () => {
|
|
224
|
-
expect(matchMetaRoute(metaRoutes, "/robots.txt")).toBe("__krate_meta/robots");
|
|
225
|
-
expect(matchMetaRoute(metaRoutes, "/sitemap/3.xml")).toBe("__krate_meta/sitemap/3");
|
|
226
|
-
for (const p of ["/sitemap/.xml", "/sitemap/a/b.xml", "/robots.txt/x", "/other"])
|
|
227
|
-
expect(matchMetaRoute(metaRoutes, p)).toBe("");
|
|
228
|
-
expect(matchMetaRoute(undefined, "/robots.txt")).toBe("");
|
|
229
|
-
});
|
|
230
|
-
it("serves them through the API handler after middleware", async () => {
|
|
231
|
-
const handler = createKrateHandler({
|
|
232
|
-
target: "node",
|
|
233
|
-
data: data({ metaRoutes, apiRoutes: ["__krate_meta/robots", "__krate_meta/sitemap/[id]"], hasMiddleware: false }),
|
|
234
|
-
modules: {
|
|
235
|
-
api: {
|
|
236
|
-
"__krate_meta/robots": { GET: (r) => new Response("User-agent: *\n# " + new URL(r.url).pathname, { headers: { "content-type": "text/plain" } }) },
|
|
237
|
-
"__krate_meta/sitemap/[id]": { GET: (_r, ctx) => new Response("sitemap " + ctx.params.id) },
|
|
238
|
-
},
|
|
239
|
-
},
|
|
240
|
-
});
|
|
241
|
-
const robots = await handler(new Request("http://localhost/robots.txt"));
|
|
242
|
-
expect(robots.status).toBe(200);
|
|
243
|
-
expect(await robots.text()).toContain("User-agent: *");
|
|
244
|
-
expect(await (await handler(new Request("http://localhost/sitemap/7.xml"))).text()).toBe("sitemap 7");
|
|
245
|
-
expect((await handler(new Request("http://localhost/robots.txt", { method: "POST" }))).status).not.toBe(200);
|
|
246
|
-
});
|
|
247
|
-
});
|
|
248
|
-
describe("Cache-Control on request-time pages", () => {
|
|
249
|
-
const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
|
|
250
|
-
const mk = (target) => createKrateHandler({
|
|
251
|
-
target,
|
|
252
|
-
data: data({
|
|
253
|
-
hasMiddleware: true,
|
|
254
|
-
pages: [
|
|
255
|
-
{ route: "/cached", mode: "ssr", bundlePath: "page" },
|
|
256
|
-
{ route: "/plain", mode: "ssr", bundlePath: "page" },
|
|
257
|
-
],
|
|
258
|
-
allPages: [{ route: "/cached", mode: "ssr" }, { route: "/plain", mode: "ssr" }],
|
|
259
|
-
shells: { "/cached": shell, "/plain": shell },
|
|
260
|
-
}),
|
|
261
|
-
modules: {
|
|
262
|
-
pages: { page: { default: () => jsx("main", { children: "ssr" }) } },
|
|
263
|
-
middleware: {
|
|
264
|
-
middleware: (req) => {
|
|
265
|
-
const headers = { "x-middleware-next": "1" };
|
|
266
|
-
if (new URL(req.url).pathname.startsWith("/cached"))
|
|
267
|
-
headers["cache-control"] = "public, s-maxage=60";
|
|
268
|
-
return new Response(null, { headers });
|
|
269
|
-
},
|
|
270
|
-
},
|
|
271
|
-
},
|
|
272
|
-
});
|
|
273
|
-
it("lets middleware set it and defaults to no-store", async () => {
|
|
274
|
-
for (const target of ["node", "cloudflare", "vercel"]) {
|
|
275
|
-
const h = mk(target);
|
|
276
|
-
const cached = await h(new Request("http://localhost/cached/"));
|
|
277
|
-
expect(cached.headers.get("cache-control"), target).toBe("public, s-maxage=60");
|
|
278
|
-
expect(await cached.text()).toContain("ssr");
|
|
279
|
-
expect((await h(new Request("http://localhost/plain/"))).headers.get("cache-control"), target).toBe("no-store");
|
|
280
|
-
}
|
|
281
|
-
});
|
|
282
|
-
});
|
|
283
|
-
describe("error boundary under a request-time page", () => {
|
|
284
|
-
const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
|
|
285
|
-
const boom = async () => {
|
|
286
|
-
throw new Error("db down");
|
|
287
|
-
};
|
|
288
|
-
const h = createKrateHandler({
|
|
289
|
-
target: "node",
|
|
290
|
-
data: data({
|
|
291
|
-
hasMiddleware: false,
|
|
292
|
-
pages: [{ route: "/boom", mode: "ssr", bundlePath: "boom" }],
|
|
293
|
-
allPages: [{ route: "/boom", mode: "ssr" }],
|
|
294
|
-
shells: { "/boom": shell },
|
|
295
|
-
}),
|
|
296
|
-
modules: {
|
|
297
|
-
pages: {
|
|
298
|
-
boom: {
|
|
299
|
-
default: () => jsx("div", {
|
|
300
|
-
children: jsx(ServerErrorBoundary, { fallback: (p) => jsx("p", { children: "failed " + p.error.digest }), children: jsx(boom, {}) }),
|
|
301
|
-
}),
|
|
302
|
-
},
|
|
303
|
-
},
|
|
304
|
-
},
|
|
305
|
-
});
|
|
306
|
-
it("answers 500 with no-store and the fallback in place", async () => {
|
|
307
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
308
|
-
const r = await h(new Request("http://localhost/boom/"));
|
|
309
|
-
const body = await r.text();
|
|
310
|
-
expect(r.status).toBe(500);
|
|
311
|
-
expect(r.headers.get("cache-control")).toBe("no-store");
|
|
312
|
-
expect(body).toMatch(/<p>failed [0-9a-f]{10}<\/p>/);
|
|
313
|
-
expect(body).not.toContain("db down");
|
|
314
|
-
});
|
|
315
|
-
it("keeps no-store when middleware asked for public caching", async () => {
|
|
316
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
317
|
-
const cached = createKrateHandler({
|
|
318
|
-
target: "cloudflare",
|
|
319
|
-
data: data({
|
|
320
|
-
hasMiddleware: true,
|
|
321
|
-
pages: [{ route: "/boom", mode: "ssr", bundlePath: "boom" }],
|
|
322
|
-
allPages: [{ route: "/boom", mode: "ssr" }],
|
|
323
|
-
shells: { "/boom": shell },
|
|
324
|
-
}),
|
|
325
|
-
modules: {
|
|
326
|
-
pages: {
|
|
327
|
-
boom: {
|
|
328
|
-
default: () => jsx("div", { children: jsx(ServerErrorBoundary, { fallback: () => jsx("p", { children: "failed" }), children: jsx(boom, {}) }) }),
|
|
329
|
-
},
|
|
330
|
-
},
|
|
331
|
-
middleware: { middleware: () => new Response(null, { headers: { "x-middleware-next": "1", "cache-control": "public, s-maxage=60" } }) },
|
|
332
|
-
},
|
|
333
|
-
});
|
|
334
|
-
const r = await cached(new Request("http://localhost/boom/"));
|
|
335
|
-
expect(r.status).toBe(500);
|
|
336
|
-
expect(r.headers.get("cache-control")).toBe("no-store");
|
|
337
|
-
});
|
|
338
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|