@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.11

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.
Files changed (214) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +470 -77
  22. package/dist/dom.js +18 -3
  23. package/dist/effects.js +2 -2
  24. package/dist/flight-props.d.ts +7 -0
  25. package/dist/flight-props.js +105 -0
  26. package/dist/handler-html.js +4 -4
  27. package/dist/handler-routing.d.ts +2 -23
  28. package/dist/handler-routing.js +9 -190
  29. package/dist/handler-segments.d.ts +6 -0
  30. package/dist/handler-segments.js +18 -4
  31. package/dist/head-tags.d.ts +9 -0
  32. package/dist/head-tags.js +93 -6
  33. package/dist/highlight-bind.js +1 -1
  34. package/dist/highlight.d.ts +3 -2
  35. package/dist/highlight.js +17 -12
  36. package/dist/hints.d.ts +25 -2
  37. package/dist/hints.js +147 -74
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +3 -0
  40. package/dist/island-swap.d.ts +47 -0
  41. package/dist/island-swap.js +635 -0
  42. package/dist/jsx-dev-runtime.d.ts +1 -1
  43. package/dist/jsx-types.d.ts +99 -3
  44. package/dist/krate-core.js +1 -1
  45. package/dist/krate-dev.js +385 -66
  46. package/dist/krate-f-actions.js +1 -1
  47. package/dist/krate-f-classes.js +1 -1
  48. package/dist/krate-f-highlight.js +1 -1
  49. package/dist/krate-f-list.js +1 -1
  50. package/dist/krate-f-navigation.js +1 -1
  51. package/dist/krate-f-router-lite.js +1 -1
  52. package/dist/krate-f-router.js +1 -1
  53. package/dist/krate-features.json +454 -0
  54. package/dist/krate-hydrate-lite.js +5 -5
  55. package/dist/krate-hydrate.js +5 -5
  56. package/dist/krate-island-swap.js +1 -0
  57. package/dist/krate-runtime.js +5 -5
  58. package/dist/list.d.ts +14 -4
  59. package/dist/list.js +4 -5
  60. package/dist/metadata.js +5 -2
  61. package/dist/navigation-react.d.ts +13 -0
  62. package/dist/navigation-react.js +86 -0
  63. package/dist/navigation.d.ts +19 -0
  64. package/dist/navigation.js +35 -0
  65. package/dist/node-server.js +3 -3
  66. package/dist/og.js +1 -1
  67. package/dist/platform.d.ts +52 -0
  68. package/dist/platform.js +57 -0
  69. package/dist/react-compat.d.ts +39 -0
  70. package/dist/react-compat.js +359 -0
  71. package/dist/react-server.d.ts +63 -0
  72. package/dist/react-server.js +125 -0
  73. package/dist/region-wire.d.ts +10 -0
  74. package/dist/region-wire.js +154 -0
  75. package/dist/request-context.js +1 -1
  76. package/dist/request-extras.d.ts +4 -0
  77. package/dist/request-extras.js +51 -0
  78. package/dist/resp.js +1 -1
  79. package/dist/route-source.d.ts +39 -0
  80. package/dist/route-source.js +532 -0
  81. package/dist/router-lite.js +3 -9
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +628 -98
  84. package/dist/server-handler.d.ts +69 -1
  85. package/dist/server-handler.js +515 -96
  86. package/dist/server-renderer.js +16 -7
  87. package/dist/server.d.ts +73 -16
  88. package/dist/server.js +619 -102
  89. package/dist/sha256.js +9 -9
  90. package/dist/signal.js +0 -6
  91. package/dist/site-config.d.ts +15 -0
  92. package/dist/site-config.js +28 -0
  93. package/dist/slot.d.ts +12 -0
  94. package/dist/slot.js +23 -0
  95. package/dist/ssr-core.d.ts +2 -0
  96. package/dist/ssr-core.js +12 -4
  97. package/dist/testing.d.ts +62 -0
  98. package/dist/testing.js +90 -0
  99. package/dist/use-id.js +1 -1
  100. package/package.json +28 -3
  101. package/dist/action-context.test.d.ts +0 -1
  102. package/dist/action-context.test.js +0 -72
  103. package/dist/actions.test.d.ts +0 -1
  104. package/dist/actions.test.js +0 -477
  105. package/dist/cache-adapter.test.d.ts +0 -1
  106. package/dist/cache-adapter.test.js +0 -244
  107. package/dist/cache.test.d.ts +0 -1
  108. package/dist/cache.test.js +0 -233
  109. package/dist/class-component.test.d.ts +0 -1
  110. package/dist/class-component.test.js +0 -462
  111. package/dist/class-helpers.test.d.ts +0 -1
  112. package/dist/class-helpers.test.js +0 -169
  113. package/dist/context.test.d.ts +0 -1
  114. package/dist/context.test.js +0 -57
  115. package/dist/derived.test.d.ts +0 -1
  116. package/dist/derived.test.js +0 -140
  117. package/dist/dev-overlay.test.d.ts +0 -1
  118. package/dist/dev-overlay.test.js +0 -165
  119. package/dist/discrete.test.d.ts +0 -1
  120. package/dist/discrete.test.js +0 -100
  121. package/dist/dom.test.d.ts +0 -1
  122. package/dist/dom.test.js +0 -39
  123. package/dist/effect-errors.test.d.ts +0 -1
  124. package/dist/effect-errors.test.js +0 -199
  125. package/dist/effects.test.d.ts +0 -1
  126. package/dist/effects.test.js +0 -485
  127. package/dist/events.test.d.ts +0 -1
  128. package/dist/events.test.js +0 -447
  129. package/dist/handler-html.test.d.ts +0 -1
  130. package/dist/handler-html.test.js +0 -256
  131. package/dist/handler-routing.test.d.ts +0 -1
  132. package/dist/handler-routing.test.js +0 -99
  133. package/dist/handler-segments.test.d.ts +0 -1
  134. package/dist/handler-segments.test.js +0 -217
  135. package/dist/head-tags.test.d.ts +0 -1
  136. package/dist/head-tags.test.js +0 -131
  137. package/dist/highlight-bind.test.d.ts +0 -1
  138. package/dist/highlight-bind.test.js +0 -124
  139. package/dist/highlight.test.d.ts +0 -1
  140. package/dist/highlight.test.js +0 -56
  141. package/dist/lanes.test.d.ts +0 -1
  142. package/dist/lanes.test.js +0 -59
  143. package/dist/list.test.d.ts +0 -1
  144. package/dist/list.test.js +0 -435
  145. package/dist/metadata.test.d.ts +0 -1
  146. package/dist/metadata.test.js +0 -167
  147. package/dist/navigation.test.d.ts +0 -1
  148. package/dist/navigation.test.js +0 -130
  149. package/dist/node-server.test.d.ts +0 -1
  150. package/dist/node-server.test.js +0 -492
  151. package/dist/optimistic-lanes.test.d.ts +0 -1
  152. package/dist/optimistic-lanes.test.js +0 -45
  153. package/dist/patterns.test.d.ts +0 -1
  154. package/dist/patterns.test.js +0 -125
  155. package/dist/portal.test.d.ts +0 -1
  156. package/dist/portal.test.js +0 -99
  157. package/dist/react-effects.test.d.ts +0 -1
  158. package/dist/react-effects.test.js +0 -133
  159. package/dist/react-suspense.test.d.ts +0 -1
  160. package/dist/react-suspense.test.js +0 -194
  161. package/dist/react.test.d.ts +0 -1
  162. package/dist/react.test.js +0 -60
  163. package/dist/react19.test.d.ts +0 -1
  164. package/dist/react19.test.js +0 -176
  165. package/dist/reactivity-core.test.d.ts +0 -1
  166. package/dist/reactivity-core.test.js +0 -152
  167. package/dist/reconcile.test.d.ts +0 -1
  168. package/dist/reconcile.test.js +0 -110
  169. package/dist/refs.test.d.ts +0 -1
  170. package/dist/refs.test.js +0 -257
  171. package/dist/router-layout.test.d.ts +0 -1
  172. package/dist/router-layout.test.js +0 -249
  173. package/dist/router-nav.test.d.ts +0 -1
  174. package/dist/router-nav.test.js +0 -559
  175. package/dist/router-slots.test.d.ts +0 -1
  176. package/dist/router-slots.test.js +0 -144
  177. package/dist/router-speculation.test.d.ts +0 -1
  178. package/dist/router-speculation.test.js +0 -25
  179. package/dist/router-styles.test.d.ts +0 -1
  180. package/dist/router-styles.test.js +0 -98
  181. package/dist/router.test.d.ts +0 -1
  182. package/dist/router.test.js +0 -36
  183. package/dist/server-async.test.d.ts +0 -1
  184. package/dist/server-async.test.js +0 -216
  185. package/dist/server-handler.test.d.ts +0 -1
  186. package/dist/server-handler.test.js +0 -535
  187. package/dist/server-highlight.test.d.ts +0 -1
  188. package/dist/server-highlight.test.js +0 -32
  189. package/dist/server-renderer.test.d.ts +0 -1
  190. package/dist/server-renderer.test.js +0 -266
  191. package/dist/server.test.d.ts +0 -1
  192. package/dist/server.test.js +0 -88
  193. package/dist/sha256.test.d.ts +0 -1
  194. package/dist/sha256.test.js +0 -13
  195. package/dist/signal-lanes.test.d.ts +0 -1
  196. package/dist/signal-lanes.test.js +0 -32
  197. package/dist/signal.test.d.ts +0 -1
  198. package/dist/signal.test.js +0 -68
  199. package/dist/slots.test.d.ts +0 -1
  200. package/dist/slots.test.js +0 -187
  201. package/dist/snapshots.test.d.ts +0 -1
  202. package/dist/snapshots.test.js +0 -208
  203. package/dist/ssr-core-behavior.test.d.ts +0 -1
  204. package/dist/ssr-core-behavior.test.js +0 -620
  205. package/dist/ssr-core.test.d.ts +0 -1
  206. package/dist/ssr-core.test.js +0 -324
  207. package/dist/static-memory.test.d.ts +0 -1
  208. package/dist/static-memory.test.js +0 -26
  209. package/dist/storage.test.d.ts +0 -1
  210. package/dist/storage.test.js +0 -46
  211. package/dist/suspense-actions.test.d.ts +0 -1
  212. package/dist/suspense-actions.test.js +0 -72
  213. package/dist/suspense.test.d.ts +0 -1
  214. package/dist/suspense.test.js +0 -556
@@ -1,535 +0,0 @@
1
- // @vitest-environment node
2
- import { describe, expect, it, vi } from "vitest";
3
- import { createKrateHandler } from "./server-handler.js";
4
- import { jsx } 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("serves ISR pages from the cache with the CDN policy", async () => {
65
- const a = await get("/live/");
66
- const b = await get("/live/");
67
- expect(a.headers.get("cache-control")).toBe("public, s-maxage=30, stale-while-revalidate=60");
68
- expect(a.headers.get("x-krate-cache")).toBe("MISS");
69
- expect(b.headers.get("x-krate-cache")).toBe("HIT");
70
- expect(await b.text()).toContain("render 1");
71
- expect(renders).toBe(1);
72
- });
73
- it("runs middleware and answers its responses", async () => {
74
- expect((await get("/blocked")).status).toBe(403);
75
- expect((await get("/api/hello")).headers.get("x-mw")).toBe("1");
76
- });
77
- it("routes API requests with 404, 405 and params", async () => {
78
- expect(await (await get("/api/items/7")).json()).toEqual({ id: "7" });
79
- expect((await get("/api/none")).status).toBe(404);
80
- const r = await get("/api/hello", { method: "DELETE" });
81
- expect(r.status).toBe(405);
82
- expect(r.headers.get("allow")).toBe("GET, POST, HEAD, OPTIONS");
83
- expect((await get("/api/hello", { method: "POST", body: "abc" })).status).toBe(201);
84
- });
85
- it("runs server actions and rejects cross-site posts", async () => {
86
- const headers = { "content-type": "application/json", "x-krate-action": "fetch", "sec-fetch-site": "same-origin" };
87
- const ok = await get("/__krate/action/act1", { method: "POST", headers, body: '{"args":[2,3]}' });
88
- expect(await ok.json()).toEqual({ ok: true, result: { sum: 5 } });
89
- const bad = await get("/__krate/action/act1", { method: "POST", headers: { ...headers, "sec-fetch-site": "cross-site" }, body: "{}" });
90
- expect(bad.status).toBe(403);
91
- });
92
- it("answers unknown pages with the custom 404 and hides internals", async () => {
93
- const r = await get("/nope/");
94
- expect(r.status).toBe(404);
95
- expect(await r.text()).toContain("custom 404");
96
- expect((await get("/.krate/x")).status).toBe(404);
97
- });
98
- it("reports revalidation honestly on multi-instance targets", async () => {
99
- let seen;
100
- const h = createKrateHandler({
101
- target: "vercel",
102
- data: data({ actions: [{ id: "rv", export: "rv", file: "acts" }] }),
103
- modules: {
104
- ...modules,
105
- actions: { acts: { rv: async () => { const { revalidatePath } = await import("./cache.js"); revalidatePath("/live"); return 1; } } },
106
- },
107
- });
108
- const res = await h(new Request("http://localhost/__krate/action/rv", { method: "POST", headers: { "x-krate-action": "fetch", "content-type": "application/json", "sec-fetch-site": "same-origin" }, body: '{"args":[]}' }));
109
- seen = await res.json();
110
- expect(seen.revalidated).toBe(true);
111
- expect(seen.revalidation.paths).toEqual([{ path: "/live", type: "page" }]);
112
- });
113
- });
114
- describe("middleware without a matcher", () => {
115
- const seen = [];
116
- const mw = {
117
- middleware: (req) => {
118
- const p = new URL(req.url).pathname;
119
- seen.push(p);
120
- if (req.headers.get("x-auth") !== "yes")
121
- return new Response("denied", { status: 401 });
122
- return new Response(null, { headers: { "x-middleware-next": "1" } });
123
- },
124
- };
125
- const staticLayer = {
126
- exists: (p) => p === "/doc.pdf",
127
- isAsset: (p) => p === "/doc.pdf",
128
- serve: async (_r, p) => (p === "/doc.pdf" ? new Response("pdf") : null),
129
- };
130
- const h = createKrateHandler({
131
- target: "node",
132
- data: data({ apiRoutes: ["files/[name]"] }),
133
- modules: { ...modules, api: { "files/[name]": { GET: () => Response.json({ secret: "TOP" }) } }, middleware: mw },
134
- static: staticLayer,
135
- });
136
- const get = (path) => h(new Request("http://localhost" + path));
137
- it("does not skip dynamic API routes that end in a static extension", async () => {
138
- for (const ext of ["pdf", "txt", "xml", "zip", "js", "css"]) {
139
- const r = await get("/api/files/report." + ext);
140
- expect(r.status, ext).toBe(401);
141
- }
142
- });
143
- it("still skips a real static file", async () => {
144
- seen.length = 0;
145
- const r = await get("/doc.pdf");
146
- expect(r.status).toBe(200);
147
- expect(seen).not.toContain("/doc.pdf");
148
- });
149
- it("runs middleware for a static-looking page path that is not a file", async () => {
150
- expect((await get("/missing.pdf")).status).toBe(401);
151
- });
152
- });
153
- describe("canonical slash redirect", () => {
154
- const h = createKrateHandler({
155
- target: "node",
156
- data: data({ hasMiddleware: false, templates: [{ pattern: "plain/[id]", html: "<p>[id]</p>" }] }),
157
- modules,
158
- });
159
- const get = (path) => h(new Request("http://localhost" + path, { redirect: "manual" }));
160
- it("never emits a Location that can parse as an absolute URL", async () => {
161
- for (const seg of ["ftp:3232235777", "https:3232235777", "http:1"]) {
162
- const r = await get("/plain/" + seg);
163
- expect(r.status, seg).toBe(301);
164
- const loc = r.headers.get("location");
165
- expect(loc, seg).toBe("./" + seg + "/");
166
- expect(new URL(loc, "http://localhost/plain/" + seg).origin, seg).toBe("http://localhost");
167
- }
168
- });
169
- it("keeps the query on an ordinary segment", async () => {
170
- const r = await get("/plain/7?a=1");
171
- expect(r.headers.get("location")).toBe("./7/?a=1");
172
- });
173
- });
174
- describe("action cookies", () => {
175
- const h = createKrateHandler({
176
- target: "node",
177
- data: data({ hasMiddleware: false, actions: [{ id: "setc", export: "setc", file: "acts" }, { id: "flash", export: "flash", file: "acts" }] }),
178
- modules: {
179
- ...modules,
180
- actions: {
181
- acts: {
182
- setc: async () => {
183
- const { cookies } = await import("./action-context.js");
184
- cookies().set("none", "1", { sameSite: "None" });
185
- cookies().set("plain", "2");
186
- cookies().set("optout", "3", { secure: false });
187
- return 1;
188
- },
189
- flash: () => ({ error: "bad" }),
190
- },
191
- },
192
- },
193
- });
194
- const post = (id, headers) => h(new Request("http://localhost/__krate/action/" + id, { method: "POST", headers: { "sec-fetch-site": "same-origin", ...headers }, body: "{}" }));
195
- const cookiesOf = (r) => r.headers.getSetCookie();
196
- it("marks SameSite=None cookies Secure and defaults Secure on https", async () => {
197
- const insecure = cookiesOf(await post("setc", { "x-krate-action": "fetch", "content-type": "application/json" }));
198
- expect(insecure.find((c) => c.startsWith("none="))).toContain("; Secure");
199
- expect(insecure.find((c) => c.startsWith("plain="))).not.toContain("Secure");
200
- const https = cookiesOf(await post("setc", { "x-krate-action": "fetch", "content-type": "application/json", "x-forwarded-proto": "https" }));
201
- expect(https.find((c) => c.startsWith("plain="))).toContain("; Secure");
202
- expect(https.find((c) => c.startsWith("optout="))).not.toContain("Secure");
203
- });
204
- it("marks the flash cookie Secure on https", async () => {
205
- const r = await post("flash", { "content-type": "application/x-www-form-urlencoded", "x-forwarded-proto": "https", referer: "http://localhost/form" });
206
- const flash = cookiesOf(r).find((c) => c.startsWith("krate_flash="));
207
- expect(flash).toContain("; Secure");
208
- });
209
- });
210
- describe("rewrites to a slashless page path", () => {
211
- const h = createKrateHandler({
212
- target: "node",
213
- data: data({
214
- hasMiddleware: true,
215
- templates: [{ pattern: "feedback", html: "<p>feedback form</p>" }],
216
- config: { ...config, rewrites: [{ source: "/contact", destination: "/feedback" }] },
217
- }),
218
- modules: {
219
- ...modules,
220
- middleware: {
221
- middleware: (req) => {
222
- if (new URL(req.url).pathname === "/go")
223
- return new Response(null, { headers: { "x-middleware-rewrite": "/feedback" } });
224
- return undefined;
225
- },
226
- config: { matcher: ["/go"] },
227
- },
228
- },
229
- static: {
230
- exists: (p) => p === "/feedback/",
231
- isAsset: () => false,
232
- serve: async (_r, p) => (p === "/feedback/" ? new Response("<p>feedback form</p>", { headers: { "content-type": "text/html" } }) : null),
233
- },
234
- });
235
- const get = (path) => h(new Request("http://localhost" + path, { redirect: "manual" }));
236
- it("serves a middleware rewrite in place (no 301)", async () => {
237
- const r = await get("/go");
238
- expect(r.status).toBe(200);
239
- expect(await r.text()).toContain("feedback form");
240
- });
241
- it("serves a config rewrite in place (no 301)", async () => {
242
- const r = await get("/contact");
243
- expect(r.status).toBe(200);
244
- expect(await r.text()).toContain("feedback form");
245
- });
246
- });
247
- describe("page region title swap", () => {
248
- it("keeps the page markers intact when the title length changes", async () => {
249
- const h = createKrateHandler({
250
- target: "node",
251
- data: data({
252
- pages: [{ route: "/titled", mode: "ssr", bundlePath: "titled" }],
253
- allPages: [{ route: "/titled", mode: "ssr" }],
254
- shells: { "/titled": "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>" },
255
- hasMiddleware: false,
256
- }),
257
- modules: {
258
- ...modules,
259
- pages: {
260
- titled: {
261
- default: () => jsx("div", { children: [jsx("title", { children: "A much longer title" }), jsx("h1", { children: "hello" })] }),
262
- },
263
- },
264
- },
265
- });
266
- const r = await h(new Request("http://localhost/titled/"));
267
- const body = await r.text();
268
- expect(body).toContain("<title>A much longer title</title></head><body><!--suspense:page--><div><h1>hello</h1></div><!--/suspense:page--></body>");
269
- expect(body.match(/<title/g)?.length).toBe(1);
270
- });
271
- });
272
- describe("signed flash cookies", () => {
273
- const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
274
- const mk = (target, flashSecret) => createKrateHandler({
275
- target,
276
- flashSecret,
277
- data: data({
278
- hasMiddleware: false,
279
- pages: [{ route: "/form", mode: "ssr", bundlePath: "form" }],
280
- allPages: [{ route: "/form", mode: "ssr" }],
281
- shells: { "/form": shell },
282
- actions: [{ id: "act9", export: "bad", file: "acts" }],
283
- }),
284
- modules: {
285
- pages: {
286
- form: {
287
- default: () => jsx("main", { children: jsx("form", { action: "/__krate/action/act9", method: "post", children: jsx("button", { children: "go" }) }) }),
288
- },
289
- },
290
- actions: { acts: { bad: () => ({ error: "Name is required" }) } },
291
- },
292
- });
293
- const submit = (h) => h(new Request("http://localhost/__krate/action/act9", {
294
- method: "POST",
295
- headers: { "sec-fetch-site": "same-origin", "content-type": "application/x-www-form-urlencoded", referer: "http://localhost/form/" },
296
- body: "x=1",
297
- }));
298
- const flashOf = (r) => r.headers.getSetCookie().find((c) => c.startsWith("krate_flash="));
299
- const page = (h, cookie) => h(new Request("http://localhost/form/", { headers: { cookie } }));
300
- it("signs the cookie and shows the notice when it comes back", async () => {
301
- const h = mk("node", "a-shared-flash-secret-for-this-test");
302
- const set = flashOf(await submit(h));
303
- expect(set).toBeDefined();
304
- const value = set.split(";")[0].slice("krate_flash=".length);
305
- expect(value).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/);
306
- const body = await (await page(h, "krate_flash=" + value)).text();
307
- expect(body).toContain("krate-flash");
308
- expect(body).toContain("Name is required");
309
- });
310
- it("ignores a cookie planted without a valid signature", async () => {
311
- const h = mk("node", "a-shared-flash-secret-for-this-test");
312
- const planted = Buffer.from(JSON.stringify({ a: "act9", r: { error: "Your account was suspended" } })).toString("base64url");
313
- for (const cookie of [planted, planted + ".", planted + ".AAAA", "x." + planted]) {
314
- const body = await (await page(h, "krate_flash=" + cookie)).text();
315
- expect(body, cookie).not.toContain("suspended");
316
- expect(body, cookie).not.toContain("krate-flash");
317
- }
318
- });
319
- it("serverless instances that share the secret accept each other's cookies, others do not", async () => {
320
- const a = mk("vercel", "a-shared-flash-secret-for-this-test");
321
- const b = mk("vercel", "a-shared-flash-secret-for-this-test");
322
- const stranger = mk("vercel", "some-other-deployments-secret-value");
323
- const value = flashOf(await submit(a)).split(";")[0].slice("krate_flash=".length);
324
- expect(await (await page(b, "krate_flash=" + value)).text()).toContain("Name is required");
325
- expect(await (await page(stranger, "krate_flash=" + value)).text()).not.toContain("Name is required");
326
- });
327
- it("the node target without a secret signs with a per-process key", async () => {
328
- const saved = process.env.KRATE_FLASH_SECRET;
329
- delete process.env.KRATE_FLASH_SECRET;
330
- try {
331
- const one = mk("node");
332
- const other = mk("node");
333
- const value = flashOf(await submit(one)).split(";")[0].slice("krate_flash=".length);
334
- expect(value).toContain(".");
335
- expect(await (await page(one, "krate_flash=" + value)).text()).toContain("Name is required");
336
- expect(await (await page(other, "krate_flash=" + value)).text()).not.toContain("Name is required");
337
- }
338
- finally {
339
- if (saved !== undefined)
340
- process.env.KRATE_FLASH_SECRET = saved;
341
- }
342
- });
343
- it("a serverless target without a secret carries no flash and says why", async () => {
344
- const saved = process.env.KRATE_FLASH_SECRET;
345
- delete process.env.KRATE_FLASH_SECRET;
346
- const warn = vi.spyOn(console, "warn").mockImplementation(() => { });
347
- try {
348
- const h = mk("cloudflare");
349
- const r = await submit(h);
350
- expect(r.status).toBe(303);
351
- expect(flashOf(r)).toBeUndefined();
352
- expect(warn).toHaveBeenCalledWith(expect.stringContaining("KRATE_FLASH_SECRET"));
353
- // A cookie from anywhere is not read either.
354
- const planted = Buffer.from(JSON.stringify({ a: "act9", r: { error: "planted" } })).toString("base64url");
355
- expect(await (await page(h, "krate_flash=" + planted)).text()).not.toContain("planted");
356
- }
357
- finally {
358
- warn.mockRestore();
359
- if (saved !== undefined)
360
- process.env.KRATE_FLASH_SECRET = saved;
361
- }
362
- });
363
- it("reads the key from KRATE_FLASH_SECRET", async () => {
364
- const saved = process.env.KRATE_FLASH_SECRET;
365
- process.env.KRATE_FLASH_SECRET = "env-flash-secret-env-flash-secret";
366
- try {
367
- const h = mk("vercel");
368
- const value = flashOf(await submit(h)).split(";")[0].slice("krate_flash=".length);
369
- expect(await (await page(mk("vercel"), "krate_flash=" + value)).text()).toContain("Name is required");
370
- }
371
- finally {
372
- if (saved === undefined)
373
- delete process.env.KRATE_FLASH_SECRET;
374
- else
375
- process.env.KRATE_FLASH_SECRET = saved;
376
- }
377
- });
378
- });
379
- describe("forwarded headers per platform", () => {
380
- const mk = (target, trustProxy) => {
381
- const base = data({ hasMiddleware: false });
382
- return createKrateHandler({
383
- target,
384
- data: { ...base, config: { ...config, trustProxy: trustProxy === undefined ? null : trustProxy }, apiRoutes: ["echo"], actions: [{ id: "act1", export: "add", file: "acts" }] },
385
- modules: {
386
- api: {
387
- echo: {
388
- GET: (r) => Response.json({
389
- url: r.url,
390
- xff: r.headers.get("x-forwarded-for"),
391
- realIp: r.headers.get("x-real-ip"),
392
- forwarded: r.headers.get("forwarded"),
393
- host: r.headers.get("x-forwarded-host"),
394
- proto: r.headers.get("x-forwarded-proto"),
395
- }),
396
- },
397
- },
398
- actions: { acts: { add: (a, b) => ({ sum: a + b }) } },
399
- },
400
- });
401
- };
402
- const echo = async (h, headers) => (await h(new Request("http://app.internal/api/echo", { headers }))).json();
403
- // What a hostile client adds on top of whatever the platform sets.
404
- 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" };
405
- it("vercel: uses the host, protocol and client address Vercel sets", async () => {
406
- const out = await echo(mk("vercel"), { "x-forwarded-host": "shop.example", "x-forwarded-proto": "https", "x-forwarded-for": "203.0.113.9", "x-real-ip": "203.0.113.9", forwarded: "for=6.6.6.6" });
407
- expect(out.url).toBe("https://shop.example/api/echo");
408
- expect(out.xff).toBe("203.0.113.9");
409
- expect(out.realIp).toBe("203.0.113.9");
410
- expect(out.forwarded).toBeNull();
411
- });
412
- it("vercel: a client-written forwarded chain never becomes the client address", async () => {
413
- const out = await echo(mk("vercel"), { ...spoof, "x-forwarded-host": "shop.example", "x-real-ip": "203.0.113.9" });
414
- expect(out.xff).toBe("203.0.113.9");
415
- expect(out.forwarded).toBeNull();
416
- });
417
- it("vercel with server.trustProxy: false trusts no forwarded header", async () => {
418
- const out = await echo(mk("vercel", false), { "x-forwarded-host": "shop.example", "x-forwarded-proto": "https", "x-forwarded-for": "203.0.113.9", "x-real-ip": "203.0.113.9" });
419
- expect(out.url).toBe("http://app.internal/api/echo");
420
- expect(out.host).toBe("app.internal");
421
- expect(out.proto).toBe("http");
422
- expect(out.xff).toBeNull();
423
- expect(out.realIp).toBeNull();
424
- });
425
- for (const [target, ipHeader] of [["netlify", "x-nf-client-connection-ip"], ["cloudflare", "cf-connecting-ip"]]) {
426
- it(`${target}: host and protocol come from the request URL, the address from ${ipHeader}`, async () => {
427
- const out = await echo(mk(target), { ...spoof, [ipHeader]: "203.0.113.9" });
428
- expect(out.url).toBe("http://app.internal/api/echo");
429
- expect(out.host).toBe("app.internal");
430
- expect(out.proto).toBe("http");
431
- expect(out.xff).toBe("203.0.113.9");
432
- expect(out.realIp).toBe("203.0.113.9");
433
- expect(out.forwarded).toBeNull();
434
- });
435
- it(`${target}: without the platform address header there is no client address`, async () => {
436
- const out = await echo(mk(target), spoof);
437
- expect(out.xff).toBeNull();
438
- expect(out.realIp).toBeNull();
439
- });
440
- it(`${target} with server.trustProxy: true trusts the proxy of yours in front`, async () => {
441
- const out = await echo(mk(target, true), { ...spoof, [ipHeader]: "203.0.113.9" });
442
- expect(out.url).toBe("https://evil.example/api/echo");
443
- expect(out.xff).toBe("6.6.6.6, 7.7.7.7");
444
- });
445
- it(`${target} with server.trustProxy: false ignores everything forwarded, the platform address included`, async () => {
446
- const out = await echo(mk(target, false), { ...spoof, [ipHeader]: "203.0.113.9" });
447
- expect(out.url).toBe("http://app.internal/api/echo");
448
- expect(out.xff).toBeNull();
449
- expect(out.realIp).toBeNull();
450
- });
451
- }
452
- it("the server-action origin check is not fooled by a spoofed X-Forwarded-Host", async () => {
453
- const post = (h) => h(new Request("http://app.internal/__krate/action/act1", {
454
- method: "POST",
455
- headers: { origin: "https://evil.example", "x-forwarded-host": "evil.example", "x-krate-action": "fetch", "content-type": "application/json" },
456
- body: '{"args":[1,2]}',
457
- }));
458
- for (const target of ["netlify", "cloudflare"]) {
459
- expect((await post(mk(target))).status, target + " unset").toBe(403);
460
- expect((await post(mk(target, false))).status, target + " false").toBe(403);
461
- }
462
- expect((await post(mk("vercel", false))).status).toBe(403);
463
- // Behind a proxy of yours that sets the header, it is the real host.
464
- expect((await post(mk("cloudflare", true))).status).toBe(200);
465
- });
466
- it("node: forwarded headers are read only with trustProxy: true", async () => {
467
- const headers = { "x-forwarded-host": "shop.example", "x-forwarded-proto": "https" };
468
- expect((await echo(mk("node"), headers)).url).toBe("http://app.internal/api/echo");
469
- expect((await echo(mk("node", true), headers)).url).toBe("https://shop.example/api/echo");
470
- });
471
- });
472
- // Serverless targets run many instances. Passing a cache adapter to
473
- // createKrateHandler (or setting cache.adapter in krate.config) shares the ISR
474
- // and data caches between them, and revalidateTag on one reaches the others.
475
- describe("createKrateHandler with a shared cache adapter", () => {
476
- it("serves one instance's page from another and revalidates for both", async () => {
477
- const { MemoryAdapter } = await import("./cache-adapter.js");
478
- const { revalidateTag } = await import("./cache.js");
479
- let renders = 0;
480
- const shared = new MemoryAdapter();
481
- const make = () => createKrateHandler({
482
- target: "vercel",
483
- data: data({
484
- apiRoutes: ["bump"],
485
- pages: [{ route: "/tagged", mode: "isr", revalidate: 300, bundlePath: "tagged" }],
486
- allPages: [{ route: "/tagged", mode: "isr" }],
487
- shells: { "/tagged": "<html><head></head><body><!--suspense:page-->x<!--/suspense:page--></body></html>" },
488
- hasMiddleware: false,
489
- }),
490
- modules: {
491
- pages: {
492
- tagged: {
493
- default: async () => {
494
- // A tagged read: revalidateTag("posts") must drop this page everywhere.
495
- const { recordCacheRead } = await import("./cache-scope.js");
496
- recordCacheRead(["posts"], undefined);
497
- return jsx("main", { children: "render " + ++renders });
498
- },
499
- },
500
- },
501
- api: { bump: { POST: () => (revalidateTag("posts"), Response.json({ ok: true })) } },
502
- actions: {},
503
- },
504
- cache: shared,
505
- });
506
- const a = make();
507
- const b = make();
508
- const get = (h, path, init) => h(new Request("http://localhost" + path, init));
509
- const first = await get(a, "/tagged/");
510
- expect(first.headers.get("x-krate-cache")).toBe("MISS");
511
- const other = await get(b, "/tagged/");
512
- expect(other.headers.get("x-krate-cache")).toBe("HIT");
513
- expect(await other.text()).toContain("render 1");
514
- expect(renders).toBe(1);
515
- const bump = await get(a, "/api/bump", { method: "POST" });
516
- expect(bump.status).toBe(200);
517
- const after = await get(b, "/tagged/");
518
- expect(after.headers.get("x-krate-cache")).toBe("MISS");
519
- expect(await after.text()).toContain("render 2");
520
- expect(renders).toBe(2);
521
- });
522
- });
523
- describe("middleware exports", () => {
524
- const deny = () => new Response("no", { status: 403 });
525
- const run = (middleware) => createKrateHandler({ target: "node", data: data(), modules: { ...modules, middleware } })(new Request("http://localhost/live"));
526
- it("runs a default export", async () => {
527
- expect((await run({ default: deny })).status).toBe(403);
528
- });
529
- it("fails closed when the module has no handler", async () => {
530
- const error = vi.spyOn(console, "error").mockImplementation(() => { });
531
- expect((await run({ other: 1 })).status).toBe(503);
532
- expect((await run(undefined)).status).toBe(503);
533
- error.mockRestore();
534
- });
535
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,32 +0,0 @@
1
- import { beforeAll, describe, expect, it } from "vitest";
2
- import { SyntaxHighlight, renderToString } from "./server";
3
- import { registerLanguage } from "./highlight";
4
- const table = {
5
- n: "Toy",
6
- t: ["nx", "mi", ""],
7
- s: [[["[a-z]+", 0], ["[0-9]+", 1], ["[ \\n]+", 2]]],
8
- };
9
- beforeAll(() => registerLanguage(table, ["toy"]));
10
- const html = (n) => renderToString(n);
11
- describe("SyntaxHighlight on the server", () => {
12
- it("highlights a language whose tables are loaded", () => {
13
- const out = html(SyntaxHighlight({ lang: "toy", children: "ab 12" }));
14
- expect(out).toContain('<pre class="chroma"><code class="language-toy">');
15
- expect(out).toContain('<span class="nx">ab</span>');
16
- expect(out).toContain('<span class="mi">12</span>');
17
- });
18
- it("marks lines and keeps the attribute the compiler writes", () => {
19
- const out = html(SyntaxHighlight({ lang: "toy", children: "a\nb", highlight: "2" }));
20
- expect(out).toContain('data-highlight-lines="2"');
21
- expect(out).toContain('<span class="line hl">');
22
- });
23
- it("writes plain escaped text for other languages and for unsafe input", () => {
24
- expect(html(SyntaxHighlight({ lang: "cobol", children: "<b>" }))).toContain("&lt;b&gt;");
25
- expect(html(SyntaxHighlight({ children: "a & b" }))).toContain("a &amp; b");
26
- const big = html(SyntaxHighlight({ lang: "toy", children: "a".repeat(70000) }));
27
- expect(big).not.toContain('class="line"');
28
- expect(big.length).toBeGreaterThan(70000);
29
- const long = html(SyntaxHighlight({ lang: "toy", children: "a".repeat(3000) }));
30
- expect(long).not.toContain('class="line"');
31
- });
32
- });
@@ -1 +0,0 @@
1
- export {};