@rsc-kit/core 0.42.1 → 0.43.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/apiPrerender.js +25 -12
- package/dist/apiPrerender.js.map +1 -1
- package/dist/buildProcess.d.ts +12 -0
- package/dist/buildProcess.js +202 -0
- package/dist/buildProcess.js.map +1 -0
- package/dist/buildScope.d.ts +61 -0
- package/dist/buildScope.js +172 -0
- package/dist/buildScope.js.map +1 -0
- package/dist/conformance.d.ts +3 -0
- package/dist/conformance.js +23 -3
- package/dist/conformance.js.map +1 -1
- package/dist/conformanceBuild.d.ts +5 -0
- package/dist/conformanceBuild.js +154 -0
- package/dist/conformanceBuild.js.map +1 -0
- package/dist/csp.d.ts +11 -2
- package/dist/csp.js +55 -6
- package/dist/csp.js.map +1 -1
- package/dist/formArgs.d.ts +10 -0
- package/dist/formArgs.js +41 -0
- package/dist/formArgs.js.map +1 -0
- package/dist/headers.d.ts +2 -0
- package/dist/headers.js +2 -0
- package/dist/headers.js.map +1 -1
- package/dist/host.js +47 -29
- package/dist/host.js.map +1 -1
- package/dist/hostCalls.d.ts +17 -0
- package/dist/hostCalls.js +103 -103
- package/dist/hostCalls.js.map +1 -1
- package/dist/hostSources.d.ts +23 -0
- package/dist/hostSources.js +65 -0
- package/dist/hostSources.js.map +1 -0
- package/dist/prerender.d.ts +18 -5
- package/dist/prerender.js +95 -16
- package/dist/prerender.js.map +1 -1
- package/dist/typegen.js +11 -2
- package/dist/typegen.js.map +1 -1
- package/dist/vite.d.ts +17 -2
- package/dist/vite.js +189 -105
- package/dist/vite.js.map +1 -1
- package/package.json +5 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conformanceBuild.js","sourceRoot":"","sources":["../src/conformanceBuild.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,uDAAuD;AACvD,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,4EAA4E;AAC5E,yEAA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A;QAEF,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAA;IAC5D,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["// The half of the contract a build uses: the adapter's command, answering\n// rpc() while pages are prerendered (buildProcess.ts).\n//\n// What it has to get right is the line between two answers. A function whose\n// answer is the same for everyone is answered, as the endpoint would; one that\n// read who is asking is said to have, because a build that stored a guest's\n// answer would show it to every visitor. Asked of the same Conformance.*\n// functions as the endpoint, so an adapter registers nothing more.\n\nimport { spawn } from 'node:child_process'\nimport { buildProcess } from './buildProcess.js'\nimport { visitorRead, type BuildAnswer } from './buildScope.js'\nimport type { ConformanceResult } from './conformance.js'\nimport { interpretReply } from './hostCalls.js'\nimport { isNotFoundSignal } from './notFound.js'\nimport { withRedirect } from './redirect.js'\n\n/** Every function that reads, or sets, something of one visitor's. */\nconst VISITORS: Record<string, string> = {\n 'Conformance.cookie': 'the Cookie header',\n 'Conformance.authorization': 'the Authorization header',\n 'Conformance.ip': \"the visitor's address\",\n 'Conformance.userAgent': \"the visitor's browser\",\n 'Conformance.login': 'setting a cookie',\n 'Conformance.flash': 'flashing a message',\n 'Conformance.unauthenticated': 'refusing who is not signed in',\n 'Conformance.unauthorized': 'refusing who may not',\n}\n\nexport async function buildConformance(\n command: string[],\n options: { cwd?: string; timeoutMs?: number } = {},\n): Promise<ConformanceResult[]> {\n const results: ConformanceResult[] = []\n const cwd = options.cwd ?? process.cwd()\n const timeoutMs = options.timeoutMs ?? 30_000\n const backend = buildProcess({ command, cwd, timeoutMs, print: () => {} })\n\n const expect = (ok: boolean, detail: string) => {\n if (!ok) throw new Error(detail)\n }\n\n const check = async (name: string, run: () => Promise<void>) => {\n try {\n await run()\n results.push({ case: 'a build: ' + name, ok: true })\n } catch (error) {\n results.push({ case: 'a build: ' + name, ok: false, detail: error instanceof Error ? error.message : String(error) })\n }\n }\n\n /** The answer as a render gets it: a value, or what is thrown. */\n const value = async (name: string, ...args: unknown[]): Promise<unknown> => {\n const answer = await backend.ask(name, args)\n\n expect(!visitorRead(answer), `${name} was said to need a visitor: ${JSON.stringify(answer)}`)\n\n return interpretReply(name, answer as Exclude<BuildAnswer, { visitor: string[] }>, () => {})\n }\n\n const thrown = async (name: string): Promise<unknown> => {\n let answered: unknown\n\n try {\n answered = await value(name)\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(name + ' was said to')) throw error\n\n return error\n }\n\n throw new Error(name + ' answered ' + JSON.stringify(answered))\n }\n\n try {\n await check('what is the same for everyone is answered', async () => {\n const shape = { list: [1, 'ü', null, true, { nested: [] }], text: 'a\\nb' }\n const echoed = await value('Conformance.echo', shape)\n\n expect(JSON.stringify(echoed) === JSON.stringify(shape), 'echo answered ' + JSON.stringify(echoed))\n\n const none = await value('Conformance.emptyList')\n\n expect(Array.isArray(none) && none.length === 0, 'emptyList answered ' + JSON.stringify(none))\n expect(Date.parse(String(await value('Conformance.time'))) === Date.parse('2026-01-02T03:04:05Z'), 'the time arrived as another')\n expect((await value('Conformance.double', 21)) === 42, 'double(21) is not 42')\n })\n\n for (const [name, what] of Object.entries(VISITORS)) {\n await check(`${what} needs a visitor (${name})`, async () => {\n const answer = await backend.ask(name, [])\n\n expect(visitorRead(answer) !== null, 'it was answered, and would be stored for everyone: ' + JSON.stringify(answer))\n })\n }\n\n await check('calls asked after one that needed a visitor are still answered', async () => {\n const [, after] = await Promise.all([backend.ask('Conformance.cookie', ['again']), value('Conformance.echo', 'after a visitor')])\n\n expect(after === 'after a visitor', 'got ' + JSON.stringify(after))\n })\n\n await check('many calls at once are each answered with their own', async () => {\n const answers = await Promise.all(Array.from({ length: 40 }, (_, i) => value('Conformance.double', 100 + i)))\n\n expect(answers.every((answer, i) => answer === 2 * (100 + i)), JSON.stringify(answers))\n })\n\n await check('a failure carries its message', async () => {\n const error = await thrown('Conformance.fail')\n\n expect(error instanceof Error && error.message.includes('boom'), 'got ' + String(error))\n })\n\n await check('not found, a refusal, refused input and a redirect keep their shape', async () => {\n expect(isNotFoundSignal(await thrown('Conformance.notFound')), 'notFound is not not-found')\n\n const refused = (await thrown('Conformance.refuse')) as { refusalStatus?: number }\n\n expect(refused.refusalStatus === 429, 'refuse came back as ' + String(refused))\n\n const invalid = (await thrown('Conformance.invalid')) as { errors?: Record<string, string[]> }\n\n expect(Array.isArray(invalid.errors?.name), 'invalid came back as ' + String(invalid))\n\n const taken = await withRedirect(async (seen) => {\n await thrown('Conformance.redirect')\n\n return seen()\n })\n\n expect(taken?.location === '/login', 'redirect ' + JSON.stringify(taken))\n })\n\n await check('a function nobody registered is an error, not a visitor', async () => {\n const error = await thrown('Conformance.nobodyRegisteredThis')\n\n expect(error instanceof Error, 'got ' + String(error))\n })\n } finally {\n backend.close()\n }\n\n // Over the wire, for what a well-behaved client never sends.\n await check('a line that is not a call does not end the process', async () => {\n const answers = await raw(command, cwd, timeoutMs, [\n 'not json',\n '{\"id\":1}',\n JSON.stringify({ id: 2, function: 'Conformance.echo', args: ['still here'] }),\n ])\n\n expect(\n answers.some((a) => a.id === 2 && a.result === 'still here'),\n 'the call after it was not answered: ' + JSON.stringify(answers),\n )\n })\n\n await check('the process ends when its input does', async () => {\n await raw(command, cwd, timeoutMs, [])\n })\n\n return results\n}\n\n/** Every answer to these lines, once the process ended by itself. */\nfunction raw(command: string[], cwd: string, timeoutMs: number, lines: string[]): Promise<Record<string, unknown>[]> {\n return new Promise((resolve, reject) => {\n const child = spawn(command[0]!, command.slice(1), { cwd, stdio: ['pipe', 'pipe', 'ignore'] })\n let out = ''\n const timer = setTimeout(() => {\n child.kill()\n reject(new Error(`still running ${Math.round(timeoutMs / 1000)}s after its input ended`))\n }, timeoutMs)\n\n child.stdout.setEncoding('utf-8')\n child.stdout.on('data', (text: string) => (out += text))\n child.stdin.on('error', () => {})\n child.on('error', (error) => {\n clearTimeout(timer)\n reject(error)\n })\n child.on('close', () => {\n clearTimeout(timer)\n resolve(\n out.split('\\n').flatMap((line) => {\n try {\n return line.trim() ? [JSON.parse(line) as Record<string, unknown>] : []\n } catch {\n return []\n }\n }),\n )\n })\n\n child.stdin.end(lines.map((line) => line + '\\n').join(''))\n })\n}\n"]}
|
package/dist/csp.d.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
/** What `rscKit({ contentSecurityPolicy })` accepts. */
|
|
2
2
|
export interface ContentSecurityPolicyOptions {
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Sources added to the default policy: `{ 'script-src': 'https://cdn.example' }`.
|
|
5
|
+
* A directive the default doesn't name starts from the one a browser would
|
|
6
|
+
* fall back to, so naming script-src never drops `'self'`. One that falls
|
|
7
|
+
* back to nothing (frame-ancestors, form-action) is what is written here.
|
|
8
|
+
* Not together with `directives`.
|
|
9
|
+
*/
|
|
10
|
+
extend?: Record<string, string | readonly string[]>;
|
|
11
|
+
/**
|
|
12
|
+
* The whole policy, one entry per directive, in place of the default:
|
|
13
|
+
* `{ 'img-src': ["'self'", 'data:'] }`. With neither, the default:
|
|
14
|
+
* `default-src 'self'; base-uri 'self'; object-src 'none';
|
|
6
15
|
* style-src-attr 'unsafe-inline'`.
|
|
7
16
|
*/
|
|
8
17
|
directives?: Record<string, string | readonly string[]>;
|
package/dist/csp.js
CHANGED
|
@@ -29,6 +29,29 @@ export const DEFAULT_DIRECTIVES = {
|
|
|
29
29
|
// no hash or nonce can allow. An attribute cannot run code.
|
|
30
30
|
"style-src-attr": ["'unsafe-inline'"],
|
|
31
31
|
};
|
|
32
|
+
/**
|
|
33
|
+
* What a browser reads in place of a directive a policy leaves out, nearest
|
|
34
|
+
* first. A name not here falls back to nothing: left out, it restricts nothing.
|
|
35
|
+
*/
|
|
36
|
+
const FALLBACKS = {
|
|
37
|
+
"child-src": ["default-src"],
|
|
38
|
+
"connect-src": ["default-src"],
|
|
39
|
+
"fenced-frame-src": ["frame-src", "child-src", "default-src"],
|
|
40
|
+
"font-src": ["default-src"],
|
|
41
|
+
"frame-src": ["child-src", "default-src"],
|
|
42
|
+
"img-src": ["default-src"],
|
|
43
|
+
"manifest-src": ["default-src"],
|
|
44
|
+
"media-src": ["default-src"],
|
|
45
|
+
"object-src": ["default-src"],
|
|
46
|
+
"prefetch-src": ["default-src"],
|
|
47
|
+
"script-src": ["default-src"],
|
|
48
|
+
"script-src-attr": ["script-src", "default-src"],
|
|
49
|
+
"script-src-elem": ["script-src", "default-src"],
|
|
50
|
+
"style-src": ["default-src"],
|
|
51
|
+
"style-src-attr": ["style-src", "default-src"],
|
|
52
|
+
"style-src-elem": ["style-src", "default-src"],
|
|
53
|
+
"worker-src": ["child-src", "script-src", "default-src"],
|
|
54
|
+
};
|
|
32
55
|
/**
|
|
33
56
|
* Directives a `<meta>` policy cannot carry: a browser ignores them there and
|
|
34
57
|
* says so in the console. Only a header delivers them.
|
|
@@ -47,14 +70,17 @@ export function normaliseContentSecurityPolicy(raw) {
|
|
|
47
70
|
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
48
71
|
fail("an object, as in { directives: { 'img-src': [\"'self'\", 'data:'] } }.");
|
|
49
72
|
for (const key of Object.keys(raw)) {
|
|
50
|
-
if (key !== "directives" && key !== "reportOnly")
|
|
51
|
-
fail(`${JSON.stringify(key)} is not an option. It takes directives and reportOnly.`);
|
|
73
|
+
if (key !== "extend" && key !== "directives" && key !== "reportOnly")
|
|
74
|
+
fail(`${JSON.stringify(key)} is not an option. It takes extend, directives and reportOnly.`);
|
|
52
75
|
}
|
|
53
76
|
if (raw.reportOnly !== undefined && typeof raw.reportOnly !== "boolean")
|
|
54
77
|
fail("reportOnly is true or false.");
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
78
|
+
if (raw.extend !== undefined && raw.directives !== undefined)
|
|
79
|
+
fail("extend adds to the default policy and directives replaces it. Keep one.");
|
|
80
|
+
const option = raw.extend !== undefined ? "extend" : "directives";
|
|
81
|
+
const given = raw.extend ?? raw.directives ?? DEFAULT_DIRECTIVES;
|
|
82
|
+
if (raw.extend === null || typeof given !== "object" || Array.isArray(given))
|
|
83
|
+
fail(`${option} is an object of directive names to sources.`);
|
|
58
84
|
const directives = [];
|
|
59
85
|
const seen = new Set();
|
|
60
86
|
for (const [rawName, value] of Object.entries(given)) {
|
|
@@ -78,7 +104,30 @@ export function normaliseContentSecurityPolicy(raw) {
|
|
|
78
104
|
}
|
|
79
105
|
directives.push([name, sources]);
|
|
80
106
|
}
|
|
81
|
-
return {
|
|
107
|
+
return {
|
|
108
|
+
directives: option === "extend" ? extendDefault(directives, fail) : directives,
|
|
109
|
+
reportOnly: raw.reportOnly === true,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The default policy with these sources added, so that nothing it allows is
|
|
114
|
+
* lost by naming a directive: one it doesn't have is seeded with what it would
|
|
115
|
+
* have fallen back to, as extended, whichever order they were written in.
|
|
116
|
+
*/
|
|
117
|
+
function extendDefault(added, fail) {
|
|
118
|
+
const extra = new Map(added);
|
|
119
|
+
const sourcesOf = (name) => {
|
|
120
|
+
const inherited = (FALLBACKS[name] ?? []).find((other) => DEFAULT_DIRECTIVES[other] || extra.has(other));
|
|
121
|
+
const base = DEFAULT_DIRECTIVES[name] ?? (inherited ? sourcesOf(inherited) : []);
|
|
122
|
+
const more = extra.get(name) ?? [];
|
|
123
|
+
const none = (source) => /^'none'$/i.test(source);
|
|
124
|
+
// 'none' means something only alone: beside a source, a browser ignores it.
|
|
125
|
+
if (more.some(none) && [...base, ...more].some((source) => !none(source)))
|
|
126
|
+
fail(`extend: ${name} 'none' closes a directive that allows ${[...base, ...more].filter((s) => !none(s)).join(" ")}. extend only adds; write the policy with directives.`);
|
|
127
|
+
const all = [...new Set([...base, ...more])];
|
|
128
|
+
return all.some((source) => !none(source)) ? all.filter((source) => !none(source)) : all;
|
|
129
|
+
};
|
|
130
|
+
return [...new Set([...Object.keys(DEFAULT_DIRECTIVES), ...extra.keys()])].map((name) => [name, sourcesOf(name)]);
|
|
82
131
|
}
|
|
83
132
|
/**
|
|
84
133
|
* The policy as `vite dev` sends it: the same one, so what it would refuse in
|
package/dist/csp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csp.js","sourceRoot":"","sources":["../src/csp.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,yDAAyD;AACzD,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,kBAAkB;AAClB,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,yEAAyE;AACzE,EAAE;AACF,sEAAsE;AA0BtE,MAAM,CAAC,MAAM,kBAAkB,GAA6B;IAC1D,aAAa,EAAE,CAAC,QAAQ,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,CAAC;IACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;IACxB,2EAA2E;IAC3E,4DAA4D;IAC5D,gBAAgB,EAAE,CAAC,iBAAiB,CAAC;CACtC,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC;AAEvF;;;GAGG;AACH,MAAM,UAAU,8BAA8B,CAC5C,GAA6C;IAE7C,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAExC,MAAM,IAAI,GAAG,CAAC,GAAW,EAAS,EAAE;QAClC,MAAM,IAAI,KAAK,CAAC,oCAAoC,GAAG,EAAE,CAAC,CAAC;IAC7D,CAAC,CAAC;IAEF,IAAI,GAAG,KAAK,IAAI,IAAI,OA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AAC;IACjC,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AACtE,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,QAAQ;IACtB,MAAM,KAAK,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzD,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["// A Content-Security-Policy that allows the page's own inline code and nothing\n// else, on every host - a process, a Worker, a function, an edge, a bucket.\n//\n// The author names the policy; the engine adds what only it knows: the inline\n// scripts and styles each document carries. Two ways, and which one is decided\n// by whether the body is known before the headers leave:\n//\n// - A body that is whole first - a page the build stored, a kept page, a\n// shell - gets the hash of each inline script and style in it. The same\n// bytes for everyone, so the same header for everyone, and a cache may\n// share both.\n// - A body that streams - a page rendered per request, the holes resumed\n// after a shell - gets a nonce, new for each response, which React puts on\n// every script it writes. A shell's own scripts are already hashed, so a\n// stored shell stays the same bytes for everyone.\n//\n// The payload a document carries is data blocks (see inlineFlight.ts), which\n// no policy judges, so a nonce is needed only for what React writes as a\n// stream fills in: `$RC(\"B:1\",\"S:1\")` and its like, which differ by the shape\n// of each render and which no hash can know in advance. A nonce is never put\n// on anything a cache may share: it would be a secret given to everyone.\n//\n// Nothing here imports `node:` anything: it runs where the host runs.\n\n/** What `rscKit({ contentSecurityPolicy })` accepts. */\nexport interface ContentSecurityPolicyOptions {\n /**\n * The policy, one entry per directive: `{ 'img-src': [\"'self'\", 'data:'] }`.\n * Left out, `default-src 'self'; base-uri 'self'; object-src 'none';\n * style-src-attr 'unsafe-inline'`.\n */\n directives?: Record<string, string | readonly string[]>;\n /** Sent as Content-Security-Policy-Report-Only: reported, never enforced. */\n reportOnly?: boolean;\n}\n\n/** The policy as the build hands it to the host. */\nexport interface ContentSecurityPolicy {\n directives: [string, string[]][];\n reportOnly: boolean;\n}\n\n/** What a document's own inline code hashes to, as CSP source expressions. */\nexport interface InlineHashes {\n scripts: string[];\n styles: string[];\n}\n\nexport const DEFAULT_DIRECTIVES: Record<string, string[]> = {\n \"default-src\": [\"'self'\"],\n \"base-uri\": [\"'self'\"],\n \"object-src\": [\"'none'\"],\n // A style={{...}} React rendered on the server is a style attribute, which\n // no hash or nonce can allow. An attribute cannot run code.\n \"style-src-attr\": [\"'unsafe-inline'\"],\n};\n\n/**\n * Directives a `<meta>` policy cannot carry: a browser ignores them there and\n * says so in the console. Only a header delivers them.\n */\nconst HEADER_ONLY = new Set([\"frame-ancestors\", \"report-uri\", \"report-to\", \"sandbox\"]);\n\n/**\n * The policy, checked. Refused at build, never trimmed at runtime: a policy\n * quietly not sent is a security header missing from every page.\n */\nexport function normaliseContentSecurityPolicy(\n raw: ContentSecurityPolicyOptions | undefined,\n): ContentSecurityPolicy | undefined {\n if (raw === undefined) return undefined;\n\n const fail = (why: string): never => {\n throw new Error(`[rsc-kit] contentSecurityPolicy: ${why}`);\n };\n\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw))\n fail(\"an object, as in { directives: { 'img-src': [\\\"'self'\\\", 'data:'] } }.\");\n\n for (const key of Object.keys(raw)) {\n if (key !== \"directives\" && key !== \"reportOnly\") fail(`${JSON.stringify(key)} is not an option. It takes directives and reportOnly.`);\n }\n\n if (raw.reportOnly !== undefined && typeof raw.reportOnly !== \"boolean\") fail(\"reportOnly is true or false.\");\n\n const given = raw.directives ?? DEFAULT_DIRECTIVES;\n\n if (given === null || typeof given !== \"object\" || Array.isArray(given))\n fail(\"directives is an object of directive names to sources.\");\n\n const directives: [string, string[]][] = [];\n const seen = new Set<string>();\n\n for (const [rawName, value] of Object.entries(given)) {\n const name = rawName.toLowerCase();\n\n if (!/^[a-z][a-z-]*$/.test(name)) fail(`${JSON.stringify(rawName)} is not a directive name.`);\n if (seen.has(name)) fail(`${name} is named twice.`);\n seen.add(name);\n\n const list = typeof value === \"string\" ? value.split(/\\s+/) : Array.isArray(value) ? [...value] : fail(`${name} takes a string or a list of sources.`);\n const sources = list.map((source) => {\n if (typeof source !== \"string\") fail(`${name} takes a string or a list of sources.`);\n\n return source.trim();\n }).filter(Boolean);\n\n for (const source of sources) {\n if (/[\\s;,]/.test(source)) fail(`${name}: ${JSON.stringify(source)} is not one source. Give each its own entry.`);\n if (/^'nonce-/i.test(source))\n fail(`${name}: a nonce written into the config is the same on every response, which is no nonce at all. The engine adds one to each response that streams.`);\n }\n\n directives.push([name, sources]);\n }\n\n return { directives, reportOnly: raw.reportOnly === true };\n}\n\n/**\n * The policy as `vite dev` sends it: the same one, so what it would refuse in\n * production is refused while you work, plus what only development needs.\n *\n * - `'unsafe-eval'` in script-src. React's development build evaluates code\n * for its debugging features (owner stacks, server logs replayed in the\n * browser) and says so in the console when it cannot. Never in a build.\n * - The dev server's origin, when the page is served from another one (a\n * backend in front, `devOrigin`): its modules, styles and fonts load from\n * there, and its HMR socket connects there.\n *\n * Every page renders per request in dev, so every page is allowed by its\n * nonce, where a build hashes the pages it stores. Vite's own inline styles -\n * a CSS update, the error overlay - take the nonce from a\n * `<meta property=\"csp-nonce\">` the page's boot script writes.\n */\nconst LOCAL_DEV_SOCKETS = [\"ws://localhost:*\", \"ws://127.0.0.1:*\", \"http://localhost:*\", \"http://127.0.0.1:*\"];\n\nexport function devContentSecurityPolicy(\n policy: ContentSecurityPolicy,\n options: { origin?: string } = {},\n): ContentSecurityPolicy {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const fallback = map.get(\"default-src\");\n const origin = options.origin ? new URL(options.origin).origin : \"\";\n const socket = origin ? origin.replace(/^http/, \"ws\") : \"\";\n // Only to a directive the policy has: one it leaves out falls back to\n // default-src, which gets the same. One the author closed with 'none' stays\n // closed: dev adds what it needs, never what the author refused.\n const plus = (name: string, sources: string[]) => {\n const list = map.get(name);\n\n if (!list || list.some((source) => /^'none'$/i.test(source))) return;\n\n for (const source of sources) if (!list.includes(source)) list.push(source);\n };\n\n // A script-src copied from default-src, as policyValue would, so eval has\n // somewhere to go; a policy restricting no scripts already allows it.\n if (!map.has(\"script-src\") && fallback) map.set(\"script-src\", [...fallback]);\n\n plus(\"script-src\", [\"'unsafe-eval'\"]);\n\n // Vite's HMR client, on a page the backend serves (my-app.test), tries the\n // page's own host first and then the dev server directly - ws://localhost:\n // <port>. The port is chosen at runtime, so any; local only, and dev only.\n if (!map.has(\"connect-src\") && fallback) map.set(\"connect-src\", [...fallback]);\n\n plus(\"connect-src\", [...LOCAL_DEV_SOCKETS]);\n\n if (origin) {\n for (const name of [\"default-src\", \"script-src\", \"script-src-elem\", \"style-src\", \"style-src-elem\", \"font-src\", \"img-src\"]) {\n plus(name, [origin]);\n }\n\n plus(\"connect-src\", [origin, socket]);\n }\n\n return { ...policy, directives: [...map] };\n}\n\n/** The header the policy goes out as. */\nexport function policyHeaderName(policy: ContentSecurityPolicy): string {\n return policy.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n}\n\n/**\n * The policy with what the document needs added: its hashes, and a nonce for\n * a response that streams.\n *\n * Added only where the policy restricts scripts (or styles) at all - a\n * script-src, or a default-src it falls back to. A policy that says nothing\n * about scripts allows every one, and a script-src with hashes in it would\n * take that away. And never where the author wrote 'unsafe-inline': a hash or\n * nonce beside it switches it off, which is the opposite of what they asked.\n */\nexport function policyValue(\n policy: ContentSecurityPolicy,\n extra: { hashes?: InlineHashes | null; nonce?: string | null; for?: \"header\" | \"meta\" } = {},\n): string {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const nonce = extra.nonce ? `'nonce-${extra.nonce}'` : null;\n\n const add = (kind: \"script\" | \"style\", hashes: readonly string[]) => {\n const own = `${kind}-src`;\n const fallback = map.get(\"default-src\");\n\n if (!map.has(own) && fallback) map.set(own, [...fallback]);\n\n for (const name of [own, `${own}-elem`]) {\n const sources = map.get(name);\n\n if (!sources) continue;\n if (sources.some((source) => /^'(unsafe-inline|none)'$/i.test(source))) continue;\n\n for (const source of [...hashes, ...(nonce ? [nonce] : [])]) {\n if (!sources.includes(source)) sources.push(source);\n }\n }\n };\n\n add(\"script\", extra.hashes?.scripts ?? []);\n add(\"style\", extra.hashes?.styles ?? []);\n\n return [...map]\n .filter(([name]) => extra.for !== \"meta\" || !HEADER_ONLY.has(name))\n .map(([name, sources]) => (sources.length ? `${name} ${sources.join(\" \")}` : name))\n .join(\"; \");\n}\n\n/**\n * The policy as a `<meta>`, for a page a host serves as a file and the engine\n * never answers - a static export. Without the directives only a header can\n * carry, and none at all for a report-only policy, which a `<meta>` cannot be.\n */\nexport function policyMeta(policy: ContentSecurityPolicy, hashes: InlineHashes): string {\n if (policy.reportOnly) return \"\";\n\n const value = policyValue(policy, { hashes, for: \"meta\" }).replace(/&/g, \"&\").replace(/\"/g, \""\");\n\n return `<meta http-equiv=\"Content-Security-Policy\" content=\"${value}\">`;\n}\n\n/**\n * The document with its policy in `<head>`: after the charset, which must\n * stay inside the first 1024 bytes, and ahead of every script and style the\n * policy judges.\n */\nexport function withPolicyMeta(html: string, meta: string): string {\n if (!meta) return html;\n\n const charset = /<meta\\s[^>]*charset[^>]*>/i.exec(html);\n\n if (charset && charset.index < 1024) {\n const at = charset.index + charset[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n }\n\n const head = /<head\\b[^>]*>/i.exec(html);\n\n if (!head) return html;\n\n const at = head.index + head[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n}\n\nconst ATTRIBUTES = `((?:[^>\"']|\"[^\"]*\"|'[^']*')*)`;\nconst SCRIPT = new RegExp(`<script\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</script\\\\s*>`, \"gi\");\nconst STYLE = new RegExp(`<style\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</style\\\\s*>`, \"gi\");\n\n/** The types a browser runs, or that a policy judges as a script anyway. */\nconst RUN = new Set([\n \"\",\n \"module\",\n \"text/javascript\",\n \"application/javascript\",\n \"text/ecmascript\",\n \"application/ecmascript\",\n \"importmap\",\n \"speculationrules\",\n]);\n\nfunction attribute(attributes: string, name: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s\"'=<>\\`]+))`, \"i\").exec(attributes);\n\n if (match) return match[1] ?? match[2] ?? match[3] ?? \"\";\n\n return new RegExp(`(?:^|\\\\s)${name}(?:\\\\s|$)`, \"i\").test(attributes) ? \"\" : null;\n}\n\nasync function sha256(text: string): Promise<string> {\n // The parser normalises line breaks before a browser hashes the element's text.\n const bytes = new TextEncoder().encode(text.replace(/\\r\\n?/g, \"\\n\"));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes));\n let binary = \"\";\n\n for (const byte of digest) binary += String.fromCharCode(byte);\n\n return `'sha256-${btoa(binary)}'`;\n}\n\n/**\n * The hash of every inline script and style in a document: what a policy\n * must name for the document to run as written. A script with a `src` is the\n * policy's origin rules' to judge, and a data block - JSON, a type no browser\n * runs - is not judged at all.\n */\nexport async function inlineHashes(html: string): Promise<InlineHashes> {\n const scripts = new Set<string>();\n const styles = new Set<string>();\n\n for (const [, attributes, body] of html.matchAll(SCRIPT)) {\n if (attribute(attributes, \"src\") !== null) continue;\n if (!RUN.has((attribute(attributes, \"type\") ?? \"\").trim().toLowerCase())) continue;\n if (body === \"\") continue;\n\n scripts.add(await sha256(body));\n }\n\n // Scripts out first: a style tag written inside a script's text is not one.\n for (const [, , body] of html.replace(SCRIPT, \"\").matchAll(STYLE)) {\n if (body === \"\") continue;\n\n styles.add(await sha256(body));\n }\n\n return { scripts: [...scripts].sort(), styles: [...styles].sort() };\n}\n\n/** A nonce: 128 random bits, base64. New for every response that streams. */\nexport function newNonce(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"csp.js","sourceRoot":"","sources":["../src/csp.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,yDAAyD;AACzD,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,kBAAkB;AAClB,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,yEAAyE;AACzE,EAAE;AACF,sEAAsE;AAmCtE,MAAM,CAAC,MAAM,kBAAkB,GAA6B;IAC1D,aAAa,EAAE,CAAC,QAAQ,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,CAAC;IACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;IACxB,2EAA2E;IAC3E,4DAA4D;IAC5D,gBAAgB,EAAE,CAAC,iBAAiB,CAAC;CACtC,CAAC;AAEF;;;GAGG;AACH,MAAM,SAAS,GAA6B;IAC1C,WAAW,EAAE,CAAC,aAAa,CAAC;IAC5B,aAAa,EAAE,CAAC,aAAa,CAAC;IAC9B,kBAAkB,EAAE,CAAC,WAAW,EAAE,WAAW,EAAE,aAAa,CAAC;IAC7D,UAAU,EAAE,CAAC,aAAa,CAAC;IAC3B,WAAW,EAAE,CAAC,WAAW,EAAE,aAAa,CAAC;IACzC,SAAS,EAAE,CAAC,aAAa,CAAC;IAC1B,cAAc,EAAE,CAAC,aAAa,CAAC;IAC/B,WAAW,EAAE,CAAC,aAAa,CAAC;IAC5B,YAAY,EAAE,CAAC,aAAa,CAAC;IAC7B,cAAc,EAAE,CAAC,aAA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IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;YAAE,SAAS;QACnF,IAAI,IAAI,KAAK,EAAE;YAAE,SAAS;QAE1B,OAAO,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IAClC,CAAC;IAED,4EAA4E;IAC5E,KAAK,MAAM,CAAC,EAAE,AAAD,EAAG,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAClE,IAAI,IAAI,KAAK,EAAE;YAAE,SAAS;QAE1B,MAAM,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AACtE,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,QAAQ;IACtB,MAAM,KAAK,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzD,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["// A Content-Security-Policy that allows the page's own inline code and nothing\n// else, on every host - a process, a Worker, a function, an edge, a bucket.\n//\n// The author names the policy; the engine adds what only it knows: the inline\n// scripts and styles each document carries. Two ways, and which one is decided\n// by whether the body is known before the headers leave:\n//\n// - A body that is whole first - a page the build stored, a kept page, a\n// shell - gets the hash of each inline script and style in it. The same\n// bytes for everyone, so the same header for everyone, and a cache may\n// share both.\n// - A body that streams - a page rendered per request, the holes resumed\n// after a shell - gets a nonce, new for each response, which React puts on\n// every script it writes. A shell's own scripts are already hashed, so a\n// stored shell stays the same bytes for everyone.\n//\n// The payload a document carries is data blocks (see inlineFlight.ts), which\n// no policy judges, so a nonce is needed only for what React writes as a\n// stream fills in: `$RC(\"B:1\",\"S:1\")` and its like, which differ by the shape\n// of each render and which no hash can know in advance. A nonce is never put\n// on anything a cache may share: it would be a secret given to everyone.\n//\n// Nothing here imports `node:` anything: it runs where the host runs.\n\n/** What `rscKit({ contentSecurityPolicy })` accepts. */\nexport interface ContentSecurityPolicyOptions {\n /**\n * Sources added to the default policy: `{ 'script-src': 'https://cdn.example' }`.\n * A directive the default doesn't name starts from the one a browser would\n * fall back to, so naming script-src never drops `'self'`. One that falls\n * back to nothing (frame-ancestors, form-action) is what is written here.\n * Not together with `directives`.\n */\n extend?: Record<string, string | readonly string[]>;\n /**\n * The whole policy, one entry per directive, in place of the default:\n * `{ 'img-src': [\"'self'\", 'data:'] }`. With neither, the default:\n * `default-src 'self'; base-uri 'self'; object-src 'none';\n * style-src-attr 'unsafe-inline'`.\n */\n directives?: Record<string, string | readonly string[]>;\n /** Sent as Content-Security-Policy-Report-Only: reported, never enforced. */\n reportOnly?: boolean;\n}\n\n/** The policy as the build hands it to the host. */\nexport interface ContentSecurityPolicy {\n directives: [string, string[]][];\n reportOnly: boolean;\n}\n\n/** What a document's own inline code hashes to, as CSP source expressions. */\nexport interface InlineHashes {\n scripts: string[];\n styles: string[];\n}\n\nexport const DEFAULT_DIRECTIVES: Record<string, string[]> = {\n \"default-src\": [\"'self'\"],\n \"base-uri\": [\"'self'\"],\n \"object-src\": [\"'none'\"],\n // A style={{...}} React rendered on the server is a style attribute, which\n // no hash or nonce can allow. An attribute cannot run code.\n \"style-src-attr\": [\"'unsafe-inline'\"],\n};\n\n/**\n * What a browser reads in place of a directive a policy leaves out, nearest\n * first. A name not here falls back to nothing: left out, it restricts nothing.\n */\nconst FALLBACKS: Record<string, string[]> = {\n \"child-src\": [\"default-src\"],\n \"connect-src\": [\"default-src\"],\n \"fenced-frame-src\": [\"frame-src\", \"child-src\", \"default-src\"],\n \"font-src\": [\"default-src\"],\n \"frame-src\": [\"child-src\", \"default-src\"],\n \"img-src\": [\"default-src\"],\n \"manifest-src\": [\"default-src\"],\n \"media-src\": [\"default-src\"],\n \"object-src\": [\"default-src\"],\n \"prefetch-src\": [\"default-src\"],\n \"script-src\": [\"default-src\"],\n \"script-src-attr\": [\"script-src\", \"default-src\"],\n \"script-src-elem\": [\"script-src\", \"default-src\"],\n \"style-src\": [\"default-src\"],\n \"style-src-attr\": [\"style-src\", \"default-src\"],\n \"style-src-elem\": [\"style-src\", \"default-src\"],\n \"worker-src\": [\"child-src\", \"script-src\", \"default-src\"],\n};\n\n/**\n * Directives a `<meta>` policy cannot carry: a browser ignores them there and\n * says so in the console. Only a header delivers them.\n */\nconst HEADER_ONLY = new Set([\"frame-ancestors\", \"report-uri\", \"report-to\", \"sandbox\"]);\n\n/**\n * The policy, checked. Refused at build, never trimmed at runtime: a policy\n * quietly not sent is a security header missing from every page.\n */\nexport function normaliseContentSecurityPolicy(\n raw: ContentSecurityPolicyOptions | undefined,\n): ContentSecurityPolicy | undefined {\n if (raw === undefined) return undefined;\n\n const fail = (why: string): never => {\n throw new Error(`[rsc-kit] contentSecurityPolicy: ${why}`);\n };\n\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw))\n fail(\"an object, as in { directives: { 'img-src': [\\\"'self'\\\", 'data:'] } }.\");\n\n for (const key of Object.keys(raw)) {\n if (key !== \"extend\" && key !== \"directives\" && key !== \"reportOnly\")\n fail(`${JSON.stringify(key)} is not an option. It takes extend, directives and reportOnly.`);\n }\n\n if (raw.reportOnly !== undefined && typeof raw.reportOnly !== \"boolean\") fail(\"reportOnly is true or false.\");\n\n if (raw.extend !== undefined && raw.directives !== undefined)\n fail(\"extend adds to the default policy and directives replaces it. Keep one.\");\n\n const option = raw.extend !== undefined ? \"extend\" : \"directives\";\n const given = raw.extend ?? raw.directives ?? DEFAULT_DIRECTIVES;\n\n if (raw.extend === null || typeof given !== \"object\" || Array.isArray(given))\n fail(`${option} is an object of directive names to sources.`);\n\n const directives: [string, string[]][] = [];\n const seen = new Set<string>();\n\n for (const [rawName, value] of Object.entries(given)) {\n const name = rawName.toLowerCase();\n\n if (!/^[a-z][a-z-]*$/.test(name)) fail(`${JSON.stringify(rawName)} is not a directive name.`);\n if (seen.has(name)) fail(`${name} is named twice.`);\n seen.add(name);\n\n const list = typeof value === \"string\" ? value.split(/\\s+/) : Array.isArray(value) ? [...value] : fail(`${name} takes a string or a list of sources.`);\n const sources = list.map((source) => {\n if (typeof source !== \"string\") fail(`${name} takes a string or a list of sources.`);\n\n return source.trim();\n }).filter(Boolean);\n\n for (const source of sources) {\n if (/[\\s;,]/.test(source)) fail(`${name}: ${JSON.stringify(source)} is not one source. Give each its own entry.`);\n if (/^'nonce-/i.test(source))\n fail(`${name}: a nonce written into the config is the same on every response, which is no nonce at all. The engine adds one to each response that streams.`);\n }\n\n directives.push([name, sources]);\n }\n\n return {\n directives: option === \"extend\" ? extendDefault(directives, fail) : directives,\n reportOnly: raw.reportOnly === true,\n };\n}\n\n/**\n * The default policy with these sources added, so that nothing it allows is\n * lost by naming a directive: one it doesn't have is seeded with what it would\n * have fallen back to, as extended, whichever order they were written in.\n */\nfunction extendDefault(added: [string, string[]][], fail: (why: string) => never): [string, string[]][] {\n const extra = new Map(added);\n\n const sourcesOf = (name: string): string[] => {\n const inherited = (FALLBACKS[name] ?? []).find((other) => DEFAULT_DIRECTIVES[other] || extra.has(other));\n const base = DEFAULT_DIRECTIVES[name] ?? (inherited ? sourcesOf(inherited) : []);\n const more = extra.get(name) ?? [];\n const none = (source: string) => /^'none'$/i.test(source);\n\n // 'none' means something only alone: beside a source, a browser ignores it.\n if (more.some(none) && [...base, ...more].some((source) => !none(source)))\n fail(`extend: ${name} 'none' closes a directive that allows ${[...base, ...more].filter((s) => !none(s)).join(\" \")}. extend only adds; write the policy with directives.`);\n\n const all = [...new Set([...base, ...more])];\n\n return all.some((source) => !none(source)) ? all.filter((source) => !none(source)) : all;\n };\n\n return [...new Set([...Object.keys(DEFAULT_DIRECTIVES), ...extra.keys()])].map((name) => [name, sourcesOf(name)]);\n}\n\n/**\n * The policy as `vite dev` sends it: the same one, so what it would refuse in\n * production is refused while you work, plus what only development needs.\n *\n * - `'unsafe-eval'` in script-src. React's development build evaluates code\n * for its debugging features (owner stacks, server logs replayed in the\n * browser) and says so in the console when it cannot. Never in a build.\n * - The dev server's origin, when the page is served from another one (a\n * backend in front, `devOrigin`): its modules, styles and fonts load from\n * there, and its HMR socket connects there.\n *\n * Every page renders per request in dev, so every page is allowed by its\n * nonce, where a build hashes the pages it stores. Vite's own inline styles -\n * a CSS update, the error overlay - take the nonce from a\n * `<meta property=\"csp-nonce\">` the page's boot script writes.\n */\nconst LOCAL_DEV_SOCKETS = [\"ws://localhost:*\", \"ws://127.0.0.1:*\", \"http://localhost:*\", \"http://127.0.0.1:*\"];\n\nexport function devContentSecurityPolicy(\n policy: ContentSecurityPolicy,\n options: { origin?: string } = {},\n): ContentSecurityPolicy {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const fallback = map.get(\"default-src\");\n const origin = options.origin ? new URL(options.origin).origin : \"\";\n const socket = origin ? origin.replace(/^http/, \"ws\") : \"\";\n // Only to a directive the policy has: one it leaves out falls back to\n // default-src, which gets the same. One the author closed with 'none' stays\n // closed: dev adds what it needs, never what the author refused.\n const plus = (name: string, sources: string[]) => {\n const list = map.get(name);\n\n if (!list || list.some((source) => /^'none'$/i.test(source))) return;\n\n for (const source of sources) if (!list.includes(source)) list.push(source);\n };\n\n // A script-src copied from default-src, as policyValue would, so eval has\n // somewhere to go; a policy restricting no scripts already allows it.\n if (!map.has(\"script-src\") && fallback) map.set(\"script-src\", [...fallback]);\n\n plus(\"script-src\", [\"'unsafe-eval'\"]);\n\n // Vite's HMR client, on a page the backend serves (my-app.test), tries the\n // page's own host first and then the dev server directly - ws://localhost:\n // <port>. The port is chosen at runtime, so any; local only, and dev only.\n if (!map.has(\"connect-src\") && fallback) map.set(\"connect-src\", [...fallback]);\n\n plus(\"connect-src\", [...LOCAL_DEV_SOCKETS]);\n\n if (origin) {\n for (const name of [\"default-src\", \"script-src\", \"script-src-elem\", \"style-src\", \"style-src-elem\", \"font-src\", \"img-src\"]) {\n plus(name, [origin]);\n }\n\n plus(\"connect-src\", [origin, socket]);\n }\n\n return { ...policy, directives: [...map] };\n}\n\n/** The header the policy goes out as. */\nexport function policyHeaderName(policy: ContentSecurityPolicy): string {\n return policy.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n}\n\n/**\n * The policy with what the document needs added: its hashes, and a nonce for\n * a response that streams.\n *\n * Added only where the policy restricts scripts (or styles) at all - a\n * script-src, or a default-src it falls back to. A policy that says nothing\n * about scripts allows every one, and a script-src with hashes in it would\n * take that away. And never where the author wrote 'unsafe-inline': a hash or\n * nonce beside it switches it off, which is the opposite of what they asked.\n */\nexport function policyValue(\n policy: ContentSecurityPolicy,\n extra: { hashes?: InlineHashes | null; nonce?: string | null; for?: \"header\" | \"meta\" } = {},\n): string {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const nonce = extra.nonce ? `'nonce-${extra.nonce}'` : null;\n\n const add = (kind: \"script\" | \"style\", hashes: readonly string[]) => {\n const own = `${kind}-src`;\n const fallback = map.get(\"default-src\");\n\n if (!map.has(own) && fallback) map.set(own, [...fallback]);\n\n for (const name of [own, `${own}-elem`]) {\n const sources = map.get(name);\n\n if (!sources) continue;\n if (sources.some((source) => /^'(unsafe-inline|none)'$/i.test(source))) continue;\n\n for (const source of [...hashes, ...(nonce ? [nonce] : [])]) {\n if (!sources.includes(source)) sources.push(source);\n }\n }\n };\n\n add(\"script\", extra.hashes?.scripts ?? []);\n add(\"style\", extra.hashes?.styles ?? []);\n\n return [...map]\n .filter(([name]) => extra.for !== \"meta\" || !HEADER_ONLY.has(name))\n .map(([name, sources]) => (sources.length ? `${name} ${sources.join(\" \")}` : name))\n .join(\"; \");\n}\n\n/**\n * The policy as a `<meta>`, for a page a host serves as a file and the engine\n * never answers - a static export. Without the directives only a header can\n * carry, and none at all for a report-only policy, which a `<meta>` cannot be.\n */\nexport function policyMeta(policy: ContentSecurityPolicy, hashes: InlineHashes): string {\n if (policy.reportOnly) return \"\";\n\n const value = policyValue(policy, { hashes, for: \"meta\" }).replace(/&/g, \"&\").replace(/\"/g, \""\");\n\n return `<meta http-equiv=\"Content-Security-Policy\" content=\"${value}\">`;\n}\n\n/**\n * The document with its policy in `<head>`: after the charset, which must\n * stay inside the first 1024 bytes, and ahead of every script and style the\n * policy judges.\n */\nexport function withPolicyMeta(html: string, meta: string): string {\n if (!meta) return html;\n\n const charset = /<meta\\s[^>]*charset[^>]*>/i.exec(html);\n\n if (charset && charset.index < 1024) {\n const at = charset.index + charset[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n }\n\n const head = /<head\\b[^>]*>/i.exec(html);\n\n if (!head) return html;\n\n const at = head.index + head[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n}\n\nconst ATTRIBUTES = `((?:[^>\"']|\"[^\"]*\"|'[^']*')*)`;\nconst SCRIPT = new RegExp(`<script\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</script\\\\s*>`, \"gi\");\nconst STYLE = new RegExp(`<style\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</style\\\\s*>`, \"gi\");\n\n/** The types a browser runs, or that a policy judges as a script anyway. */\nconst RUN = new Set([\n \"\",\n \"module\",\n \"text/javascript\",\n \"application/javascript\",\n \"text/ecmascript\",\n \"application/ecmascript\",\n \"importmap\",\n \"speculationrules\",\n]);\n\nfunction attribute(attributes: string, name: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s\"'=<>\\`]+))`, \"i\").exec(attributes);\n\n if (match) return match[1] ?? match[2] ?? match[3] ?? \"\";\n\n return new RegExp(`(?:^|\\\\s)${name}(?:\\\\s|$)`, \"i\").test(attributes) ? \"\" : null;\n}\n\nasync function sha256(text: string): Promise<string> {\n // The parser normalises line breaks before a browser hashes the element's text.\n const bytes = new TextEncoder().encode(text.replace(/\\r\\n?/g, \"\\n\"));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes));\n let binary = \"\";\n\n for (const byte of digest) binary += String.fromCharCode(byte);\n\n return `'sha256-${btoa(binary)}'`;\n}\n\n/**\n * The hash of every inline script and style in a document: what a policy\n * must name for the document to run as written. A script with a `src` is the\n * policy's origin rules' to judge, and a data block - JSON, a type no browser\n * runs - is not judged at all.\n */\nexport async function inlineHashes(html: string): Promise<InlineHashes> {\n const scripts = new Set<string>();\n const styles = new Set<string>();\n\n for (const [, attributes, body] of html.matchAll(SCRIPT)) {\n if (attribute(attributes, \"src\") !== null) continue;\n if (!RUN.has((attribute(attributes, \"type\") ?? \"\").trim().toLowerCase())) continue;\n if (body === \"\") continue;\n\n scripts.add(await sha256(body));\n }\n\n // Scripts out first: a style tag written inside a script's text is not one.\n for (const [, , body] of html.replace(SCRIPT, \"\").matchAll(STYLE)) {\n if (body === \"\") continue;\n\n styles.add(await sha256(body));\n }\n\n return { scripts: [...scripts].sort(), styles: [...styles].sort() };\n}\n\n/** A nonce: 128 random bits, base64. New for every response that streams. */\nexport function newNonce(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A form posted to a backend action. React hands the action a FormData; on
|
|
3
|
+
* the wire to the backend it is JSON, and JSON.stringify of a FormData is {} -
|
|
4
|
+
* so a form posting straight to a backend action used to send nothing. Its
|
|
5
|
+
* fields become one object, typed by the first parameter where the backend
|
|
6
|
+
* described it: numbers and booleans coerced, a repeated name a list.
|
|
7
|
+
*
|
|
8
|
+
* One copy, imported by every module the build writes under server-actions/.
|
|
9
|
+
*/
|
|
10
|
+
export declare function formArgs(args: unknown[], schemas: (Record<string, any> | null)[]): unknown[];
|
package/dist/formArgs.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A form posted to a backend action. React hands the action a FormData; on
|
|
3
|
+
* the wire to the backend it is JSON, and JSON.stringify of a FormData is {} -
|
|
4
|
+
* so a form posting straight to a backend action used to send nothing. Its
|
|
5
|
+
* fields become one object, typed by the first parameter where the backend
|
|
6
|
+
* described it: numbers and booleans coerced, a repeated name a list.
|
|
7
|
+
*
|
|
8
|
+
* One copy, imported by every module the build writes under server-actions/.
|
|
9
|
+
*/
|
|
10
|
+
export function formArgs(args, schemas) {
|
|
11
|
+
// The form is the last argument, and it fills the parameter it lands on: the
|
|
12
|
+
// first when the action takes nothing before it, the one after the team when
|
|
13
|
+
// that was bound with stub.bind(null, team).
|
|
14
|
+
const at = args.length - 1;
|
|
15
|
+
if (at < 0 || !(args[at] instanceof FormData))
|
|
16
|
+
return args;
|
|
17
|
+
const form = args[at];
|
|
18
|
+
const schema = schemas[at] ?? null;
|
|
19
|
+
const props = schema?.properties ?? {};
|
|
20
|
+
const coerce = (type, v) => type === 'integer' || type === 'number' ? (v === '' ? null : Number(v))
|
|
21
|
+
: type === 'boolean' ? v === 'on' || v === 'true' || v === '1'
|
|
22
|
+
: v;
|
|
23
|
+
const out = {};
|
|
24
|
+
for (const key of new Set(form.keys())) {
|
|
25
|
+
// React's own fields for a form action, not the form's.
|
|
26
|
+
if (key.startsWith('$ACTION_'))
|
|
27
|
+
continue;
|
|
28
|
+
const values = form.getAll(key).filter((v) => typeof v === 'string');
|
|
29
|
+
const prop = props[key];
|
|
30
|
+
out[key] = prop?.type === 'array' || (!prop && values.length > 1)
|
|
31
|
+
? values.map((v) => coerce(prop?.items?.type, v))
|
|
32
|
+
: coerce(prop?.type, values[0] ?? '');
|
|
33
|
+
}
|
|
34
|
+
// An unchecked checkbox sends nothing: false, not missing.
|
|
35
|
+
for (const [key, prop] of Object.entries(props)) {
|
|
36
|
+
if (!(key in out) && prop?.type === 'boolean')
|
|
37
|
+
out[key] = false;
|
|
38
|
+
}
|
|
39
|
+
return [...args.slice(0, at), out];
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=formArgs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formArgs.js","sourceRoot":"","sources":["../src/formArgs.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAe,EAAE,OAAuC;IAC/E,6EAA6E;IAC7E,6EAA6E;IAC7E,6CAA6C;IAC7C,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;IAE1B,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,YAAY,QAAQ,CAAC;QAAE,OAAO,IAAI,CAAA;IAE1D,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,CAAa,CAAA;IACjC,MAAM,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC,IAAI,IAAI,CAAA;IAClC,MAAM,KAAK,GAAwB,MAAM,EAAE,UAAU,IAAI,EAAE,CAAA;IAC3D,MAAM,MAAM,GAAG,CAAC,IAAa,EAAE,CAAS,EAAW,EAAE,CACnD,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACrE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,MAAM,IAAI,CAAC,KAAK,GAAG;YAC9D,CAAC,CAAC,CAAC,CAAA;IACP,MAAM,GAAG,GAA4B,EAAE,CAAA;IAEvC,KAAK,MAAM,GAAG,IAAI,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;QACvC,wDAAwD;QACxD,IAAI,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,SAAQ;QAExC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAA;QACjF,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,CAAA;QAEvB,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,IAAI,CAAC,CAAC,IAAI,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;YAC/D,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YACjD,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;IACzC,CAAC;IAED,2DAA2D;IAC3D,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAChD,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,IAAI,EAAE,IAAI,KAAK,SAAS;YAAE,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;IACjE,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,CAAA;AACpC,CAAC","sourcesContent":["/**\n * A form posted to a backend action. React hands the action a FormData; on\n * the wire to the backend it is JSON, and JSON.stringify of a FormData is {} -\n * so a form posting straight to a backend action used to send nothing. Its\n * fields become one object, typed by the first parameter where the backend\n * described it: numbers and booleans coerced, a repeated name a list.\n *\n * One copy, imported by every module the build writes under server-actions/.\n */\nexport function formArgs(args: unknown[], schemas: (Record<string, any> | null)[]): unknown[] {\n // The form is the last argument, and it fills the parameter it lands on: the\n // first when the action takes nothing before it, the one after the team when\n // that was bound with stub.bind(null, team).\n const at = args.length - 1\n\n if (at < 0 || !(args[at] instanceof FormData)) return args\n\n const form = args[at] as FormData\n const schema = schemas[at] ?? null\n const props: Record<string, any> = schema?.properties ?? {}\n const coerce = (type: unknown, v: string): unknown =>\n type === 'integer' || type === 'number' ? (v === '' ? null : Number(v))\n : type === 'boolean' ? v === 'on' || v === 'true' || v === '1'\n : v\n const out: Record<string, unknown> = {}\n\n for (const key of new Set(form.keys())) {\n // React's own fields for a form action, not the form's.\n if (key.startsWith('$ACTION_')) continue\n\n const values = form.getAll(key).filter((v): v is string => typeof v === 'string')\n const prop = props[key]\n\n out[key] = prop?.type === 'array' || (!prop && values.length > 1)\n ? values.map((v) => coerce(prop?.items?.type, v))\n : coerce(prop?.type, values[0] ?? '')\n }\n\n // An unchecked checkbox sends nothing: false, not missing.\n for (const [key, prop] of Object.entries(props)) {\n if (!(key in out) && prop?.type === 'boolean') out[key] = false\n }\n\n return [...args.slice(0, at), out]\n}\n"]}
|
package/dist/headers.d.ts
CHANGED
|
@@ -43,6 +43,8 @@ export declare const HEADER: {
|
|
|
43
43
|
* instead leaves an upload undecodable.
|
|
44
44
|
*/
|
|
45
45
|
readonly contentType: 'X-RSC-Content-Type';
|
|
46
|
+
/** What every address below begins with: this package's own, on any host, whatever routes the app has. */
|
|
47
|
+
readonly endpoints: '/_rsc/';
|
|
46
48
|
/**
|
|
47
49
|
* Where the browser posts server actions.
|
|
48
50
|
*
|
package/dist/headers.js
CHANGED
|
@@ -52,6 +52,8 @@ export const HEADER = {
|
|
|
52
52
|
* instead leaves an upload undecodable.
|
|
53
53
|
*/
|
|
54
54
|
contentType: 'X-RSC-Content-Type',
|
|
55
|
+
/** What every address below begins with: this package's own, on any host, whatever routes the app has. */
|
|
56
|
+
endpoints: '/_rsc/',
|
|
55
57
|
/**
|
|
56
58
|
* Where the browser posts server actions.
|
|
57
59
|
*
|
package/dist/headers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,wEAAwE;AACxE,2EAA2E;AAC3E,gCAAgC;AAChC,EAAE;AACF,gFAAgF;AAEhF,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB;;;OAGG;IACH,GAAG,EAAE,OAAO;IAEZ,iFAAiF;IACjF,QAAQ,EAAE,gBAAgB;IAE1B,kEAAkE;IAClE,YAAY,EAAE,qBAAqB;IAEnC,wCAAwC;IACxC,OAAO,EAAE,eAAe;IAExB;;;;OAIG;IACH,QAAQ,EAAE,iBAAiB;IAE3B,gFAAgF;IAChF,OAAO,EAAE,eAAe;IAExB,uDAAuD;IACvD,SAAS,EAAE,iBAAiB;IAE5B,gDAAgD;IAChD,OAAO,EAAE,eAAe;IAExB,uEAAuE;IACvE,UAAU,EAAE,kBAAkB;IAE9B,0CAA0C;IAC1C,MAAM,EAAE,cAAc;IAEtB;;;;;;;OAOG;IACH,QAAQ,EAAE,gBAAgB;IAE1B;;;;;;OAMG;IACH,WAAW,EAAE,oBAAoB;IAEjC;;;;;OAKG;IACH,UAAU,EAAE,cAAc;IAC1B;;;;;;;;;OASG;IACH;;;;;;;OAOG;IACH,KAAK,EAAE,aAAa;IAEpB,SAAS,EAAE,aAAa;IACxB;;;;OAIG;IACH,SAAS,EAAE,eAAe;IAC1B,+EAA+E;IAC/E,WAAW,EAAE,eAAe;IAC5B,8FAA8F;IAC9F,UAAU,EAAE,cAAc;CAClB,CAAA;AAEV,sBAAsB;AACtB,MAAM,CAAC,MAAM,WAAW,GAAG,iCAAiC,CAAA;AAE5D,2BAA2B;AAC3B,MAAM,CAAC,MAAM,SAAS,GAAG,0BAA0B,CAAA;AAEnD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,MAAM,CAAC,GAAG;IACV,MAAM,CAAC,QAAQ;IACf,MAAM,CAAC,UAAU;IACjB,MAAM,CAAC,SAAS;IAChB,MAAM,CAAC,OAAO;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,oCAAoC,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,qCAAqC,CAAA;AAEhE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,MAAM,EAAE,SAAS;IACjB,QAAQ,EAAE,aAAa;IACvB,UAAU,EAAE,eAAe;IAC3B,QAAQ,EAAE,YAAY;IACtB,KAAK,EAAE,YAAY;IACnB,KAAK,EAAE,YAAY;IACnB;;;;OAIG;IACH,MAAM,EAAE,aAAa;IACrB,iFAAiF;IACjF,KAAK,EAAE,YAAY;IACnB,iFAAiF;IACjF,gBAAgB,EAAE,cAAc;IAChC,uEAAuE;IACvE,YAAY,EAAE,YAAY;CAClB,CAAA;AAEV;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,kBAAkB;IAClB,MAAM;IACN,eAAe;IACf,cAAc;IACd,yBAAyB;IACzB,qCAAqC;IACrC,oBAAoB;IACpB,iBAAiB;IACjB,2BAA2B;IAC3B,iBAAiB;IACjB,wBAAwB;IACxB,4BAA4B;IAC5B,8BAA8B;IAC9B,8BAA8B;IAC9B,wBAAwB;CAChB,CAAA","sourcesContent":["// The wire protocol, as names rather than string literals.\n//\n// A host writing these out by hand is how they drift. Two of them are not\n// negotiable at all — the client sends them or asks for them at fixed\n// addresses, and a host that spells one differently fails silently: the\n// request falls through, the decoder never runs, and a button does nothing\n// with no error on either side.\n//\n// PROTOCOL.md describes what each one means. This is the same list, importable.\n\nexport const HEADER = {\n /**\n * Present on a request for a Flight payload rather than the document. One\n * url serves both, which is why every answer must Vary on it.\n */\n rsc: 'X-RSC',\n\n /** The layout chain the client has mounted, outermost first, comma-separated. */\n segments: 'X-RSC-Segments',\n\n /** The boundary the answer replaces. 0 means a whole document. */\n segmentDepth: 'X-RSC-Segment-Depth',\n\n /** The chain to send back next time. */\n layouts: 'X-RSC-Layouts',\n\n /**\n * On a payload request: this url's page said it does not exist, after the\n * shell went out, and the client is asking for the not-found page to put\n * where it was. RedirectBoundary sends it.\n */\n notFound: 'X-RSC-Not-Found',\n\n /** Identifies the build, so a client can notice it is talking to an old one. */\n version: 'X-RSC-Version',\n\n /** The slot an intercepted navigation is targeting. */\n intercept: 'X-RSC-Intercept',\n\n /** Where the navigation or action came from. */\n referer: 'X-RSC-Referer',\n\n /** One named region of the current page to render and return alone. */\n revalidate: 'X-RSC-Revalidate',\n\n /** The server reference being invoked. */\n action: 'X-RSC-Action',\n\n /**\n * Go here instead.\n *\n * Used for a redirect the client has to perform itself: a failed action, and\n * a navigation whose render redirected. Never a 3xx for those — `fetch`\n * follows one transparently, so the client would get the destination's HTML\n * where it expected a Flight payload and decode it as one.\n */\n redirect: 'X-RSC-Redirect',\n\n /**\n * The body's real type.\n *\n * The body itself goes out as application/octet-stream so a host that parses\n * multipart cannot consume it before the action does — reading Content-Type\n * instead leaves an upload undecodable.\n */\n contentType: 'X-RSC-Content-Type',\n\n /**\n * Where the browser posts server actions.\n *\n * Not a convention this can choose: the client runtime posts here\n * unconditionally.\n */\n actionPath: '/_rsc/action',\n /**\n * Where the browser reads queries.\n *\n * A GET, and that is the whole point of it being a separate address: a POST\n * is cacheable by nothing, so a read routed through the action endpoint can\n * never be kept by an HTTP cache, a CDN or a service worker. Only functions\n * declared with `query()` are reachable here — the endpoint checks the mark\n * before invoking anything, because otherwise this address would run any\n * registered action over GET.\n */\n /**\n * Sent on every read, and required by the query endpoint.\n *\n * A GET with no unusual header is a simple request, so any page could\n * trigger one with an <img> and the visitor's cookies would ride along.\n * This header is not CORS-safelisted, so the browser preflights it — the\n * same thing that makes a POST carrying X-RSC-Action safe.\n */\n query: 'X-RSC-Query',\n\n queryPath: '/_rsc/query',\n /**\n * On a refresh a change triggered: which names moved, to which versions\n * (`stock@5,orders@2`). A shared section renders once per such change, and\n * every tab asking with the same one gets that render.\n */\n changedBy: 'X-RSC-Changed',\n /** The stream a tab hears on when a name its page refreshes on has changed. */\n changesPath: '/_rsc/changes',\n /** Whether this renderer can serve: up, and its backend answering. GET only, never cached. */\n healthPath: '/_rsc/health',\n} as const\n\n/** Flight payload. */\nexport const FLIGHT_TYPE = 'text/x-component; charset=utf-8'\n\n/** A rendered document. */\nexport const HTML_TYPE = 'text/html; charset=utf-8'\n\n/**\n * Every request header that changes what a response body contains.\n *\n * One url answers with a whole document, a partial payload, a named region or\n * an interceptor depending on these — so a cache keyed on the url alone, or on\n * `X-RSC` alone, will hand one client another's answer. They are materially\n * different bodies, not variations in presentation.\n */\nexport const VARY_ON_RSC = [\n HEADER.rsc,\n HEADER.segments,\n HEADER.revalidate,\n HEADER.intercept,\n HEADER.referer,\n].join(', ')\n\n/**\n * What a response says about being stored, when it must not be.\n *\n * `Vary` alone is not enough on the platform this targets. Cloudflare ignores\n * `Vary` for everything except `Accept-Encoding`, and this package ships a\n * Workers story as a headline feature — so one url answering with a document,\n * a Flight payload, a segment and an interceptor, keyed only on the url, hands\n * one visitor another's body. Anything narrowed by a request header, and\n * anything behind a guard, says outright that it is not to be stored.\n */\nexport const PER_CLIENT = 'private, no-store'\n\n/**\n * And what a frozen, unguarded page says.\n *\n * Explicit rather than absent: with no directive at all, whether an\n * intermediary stores it comes down to that intermediary's heuristics, which\n * is not a decision this package should be leaving to chance in either\n * direction.\n */\nexport const REVALIDATE = 'public, max-age=0, must-revalidate'\n\n/**\n * And what a page rendered for one request says.\n *\n * It may have read the visitor's cookies, and nothing in the headers - which\n * leave before the render has finished - can know whether it did. So a shared\n * cache may not keep it; the visitor's own browser may, and must ask again.\n */\nexport const PER_REQUEST = 'private, max-age=0, must-revalidate'\n\n/**\n * The edge contract: one marker, one page endpoint, one resume, for any edge\n * and any framework that implements it. Vendor-neutral names on purpose: an\n * edge speaks the contract, and there is no second way in that is rsc-kit's\n * own. docs/reference/edge-contract.mdx is the specification.\n */\nexport const EDGE = {\n prefix: '/_edge/',\n pagePath: '/_edge/page',\n resumePath: '/_edge/resume',\n tokenEnv: 'EDGE_TOKEN',\n token: 'Edge-Token',\n build: 'Edge-Build',\n /**\n * On a page request, `nonce` says the edge mints a nonce per response: a\n * shell under a Content-Security-Policy is then answered, its policy naming\n * `nonce` (the placeholder below) where the edge puts its own.\n */\n accept: 'Edge-Accept',\n /** On a resume, the nonce the edge put in the policy, for the holes' scripts. */\n nonce: 'Edge-Nonce',\n /** What the edge replaces, in every header value of the page, with its nonce. */\n noncePlaceholder: '{edge-nonce}',\n /** The marker's copy beside the stored pages, which the host reads. */\n storedMarker: '_edge.json',\n} as const\n\n/**\n * The response headers an edge may send with a page it serves from its cache\n * (the contract's `headers`), and so the only ones rscKit({ headers }) sets:\n * one outside this list could not leave with a cached page, and the page would\n * go out without it.\n */\nexport const EDGE_HEADERS = [\n 'Content-Language',\n 'Link',\n 'Cache-Control',\n 'X-Robots-Tag',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Permissions-Policy',\n 'Referrer-Policy',\n 'Strict-Transport-Security',\n 'X-Frame-Options',\n 'X-Content-Type-Options',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Resource-Policy',\n 'X-DNS-Prefetch-Control',\n] as const\n"]}
|
|
1
|
+
{"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,2DAA2D;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;IAChB,MAAM,CAAC,OAAO;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,oCAAoC,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,qCAAqC,CAAA;AAEhE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,MAAM,EAAE,SAAS;IACjB,QAAQ,EAAE,aAAa;IACvB,UAAU,EAAE,eAAe;IAC3B,QAAQ,EAAE,YAAY;IACtB,KAAK,EAAE,YAAY;IACnB,KAAK,EAAE,YAAY;IACnB;;;;OAIG;IACH,MAAM,EAAE,aAAa;IACrB,iFAAiF;IACjF,KAAK,EAAE,YAAY;IACnB,iFAAiF;IACjF,gBAAgB,EAAE,cAAc;IAChC,uEAAuE;IACvE,YAAY,EAAE,YAAY;CAClB,CAAA;AAEV;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,kBAAkB;IAClB,MAAM;IACN,eAAe;IACf,cAAc;IACd,yBAAyB;IACzB,qCAAqC;IACrC,oBAAoB;IACpB,iBAAiB;IACjB,2BAA2B;IAC3B,iBAAiB;IACjB,wBAAwB;IACxB,4BAA4B;IAC5B,8BAA8B;IAC9B,8BAA8B;IAC9B,wBAAwB;CAChB,CAAA","sourcesContent":["// The wire protocol, as names rather than string literals.\n//\n// A host writing these out by hand is how they drift. Two of them are not\n// negotiable at all — the client sends them or asks for them at fixed\n// addresses, and a host that spells one differently fails silently: the\n// request falls through, the decoder never runs, and a button does nothing\n// with no error on either side.\n//\n// PROTOCOL.md describes what each one means. This is the same list, importable.\n\nexport const HEADER = {\n /**\n * Present on a request for a Flight payload rather than the document. One\n * url serves both, which is why every answer must Vary on it.\n */\n rsc: 'X-RSC',\n\n /** The layout chain the client has mounted, outermost first, comma-separated. */\n segments: 'X-RSC-Segments',\n\n /** The boundary the answer replaces. 0 means a whole document. */\n segmentDepth: 'X-RSC-Segment-Depth',\n\n /** The chain to send back next time. */\n layouts: 'X-RSC-Layouts',\n\n /**\n * On a payload request: this url's page said it does not exist, after the\n * shell went out, and the client is asking for the not-found page to put\n * where it was. RedirectBoundary sends it.\n */\n notFound: 'X-RSC-Not-Found',\n\n /** Identifies the build, so a client can notice it is talking to an old one. */\n version: 'X-RSC-Version',\n\n /** The slot an intercepted navigation is targeting. */\n intercept: 'X-RSC-Intercept',\n\n /** Where the navigation or action came from. */\n referer: 'X-RSC-Referer',\n\n /** One named region of the current page to render and return alone. */\n revalidate: 'X-RSC-Revalidate',\n\n /** The server reference being invoked. */\n action: 'X-RSC-Action',\n\n /**\n * Go here instead.\n *\n * Used for a redirect the client has to perform itself: a failed action, and\n * a navigation whose render redirected. Never a 3xx for those — `fetch`\n * follows one transparently, so the client would get the destination's HTML\n * where it expected a Flight payload and decode it as one.\n */\n redirect: 'X-RSC-Redirect',\n\n /**\n * The body's real type.\n *\n * The body itself goes out as application/octet-stream so a host that parses\n * multipart cannot consume it before the action does — reading Content-Type\n * instead leaves an upload undecodable.\n */\n contentType: 'X-RSC-Content-Type',\n\n /** What every address below begins with: this package's own, on any host, whatever routes the app has. */\n endpoints: '/_rsc/',\n\n /**\n * Where the browser posts server actions.\n *\n * Not a convention this can choose: the client runtime posts here\n * unconditionally.\n */\n actionPath: '/_rsc/action',\n /**\n * Where the browser reads queries.\n *\n * A GET, and that is the whole point of it being a separate address: a POST\n * is cacheable by nothing, so a read routed through the action endpoint can\n * never be kept by an HTTP cache, a CDN or a service worker. Only functions\n * declared with `query()` are reachable here — the endpoint checks the mark\n * before invoking anything, because otherwise this address would run any\n * registered action over GET.\n */\n /**\n * Sent on every read, and required by the query endpoint.\n *\n * A GET with no unusual header is a simple request, so any page could\n * trigger one with an <img> and the visitor's cookies would ride along.\n * This header is not CORS-safelisted, so the browser preflights it — the\n * same thing that makes a POST carrying X-RSC-Action safe.\n */\n query: 'X-RSC-Query',\n\n queryPath: '/_rsc/query',\n /**\n * On a refresh a change triggered: which names moved, to which versions\n * (`stock@5,orders@2`). A shared section renders once per such change, and\n * every tab asking with the same one gets that render.\n */\n changedBy: 'X-RSC-Changed',\n /** The stream a tab hears on when a name its page refreshes on has changed. */\n changesPath: '/_rsc/changes',\n /** Whether this renderer can serve: up, and its backend answering. GET only, never cached. */\n healthPath: '/_rsc/health',\n} as const\n\n/** Flight payload. */\nexport const FLIGHT_TYPE = 'text/x-component; charset=utf-8'\n\n/** A rendered document. */\nexport const HTML_TYPE = 'text/html; charset=utf-8'\n\n/**\n * Every request header that changes what a response body contains.\n *\n * One url answers with a whole document, a partial payload, a named region or\n * an interceptor depending on these — so a cache keyed on the url alone, or on\n * `X-RSC` alone, will hand one client another's answer. They are materially\n * different bodies, not variations in presentation.\n */\nexport const VARY_ON_RSC = [\n HEADER.rsc,\n HEADER.segments,\n HEADER.revalidate,\n HEADER.intercept,\n HEADER.referer,\n].join(', ')\n\n/**\n * What a response says about being stored, when it must not be.\n *\n * `Vary` alone is not enough on the platform this targets. Cloudflare ignores\n * `Vary` for everything except `Accept-Encoding`, and this package ships a\n * Workers story as a headline feature — so one url answering with a document,\n * a Flight payload, a segment and an interceptor, keyed only on the url, hands\n * one visitor another's body. Anything narrowed by a request header, and\n * anything behind a guard, says outright that it is not to be stored.\n */\nexport const PER_CLIENT = 'private, no-store'\n\n/**\n * And what a frozen, unguarded page says.\n *\n * Explicit rather than absent: with no directive at all, whether an\n * intermediary stores it comes down to that intermediary's heuristics, which\n * is not a decision this package should be leaving to chance in either\n * direction.\n */\nexport const REVALIDATE = 'public, max-age=0, must-revalidate'\n\n/**\n * And what a page rendered for one request says.\n *\n * It may have read the visitor's cookies, and nothing in the headers - which\n * leave before the render has finished - can know whether it did. So a shared\n * cache may not keep it; the visitor's own browser may, and must ask again.\n */\nexport const PER_REQUEST = 'private, max-age=0, must-revalidate'\n\n/**\n * The edge contract: one marker, one page endpoint, one resume, for any edge\n * and any framework that implements it. Vendor-neutral names on purpose: an\n * edge speaks the contract, and there is no second way in that is rsc-kit's\n * own. docs/reference/edge-contract.mdx is the specification.\n */\nexport const EDGE = {\n prefix: '/_edge/',\n pagePath: '/_edge/page',\n resumePath: '/_edge/resume',\n tokenEnv: 'EDGE_TOKEN',\n token: 'Edge-Token',\n build: 'Edge-Build',\n /**\n * On a page request, `nonce` says the edge mints a nonce per response: a\n * shell under a Content-Security-Policy is then answered, its policy naming\n * `nonce` (the placeholder below) where the edge puts its own.\n */\n accept: 'Edge-Accept',\n /** On a resume, the nonce the edge put in the policy, for the holes' scripts. */\n nonce: 'Edge-Nonce',\n /** What the edge replaces, in every header value of the page, with its nonce. */\n noncePlaceholder: '{edge-nonce}',\n /** The marker's copy beside the stored pages, which the host reads. */\n storedMarker: '_edge.json',\n} as const\n\n/**\n * The response headers an edge may send with a page it serves from its cache\n * (the contract's `headers`), and so the only ones rscKit({ headers }) sets:\n * one outside this list could not leave with a cached page, and the page would\n * go out without it.\n */\nexport const EDGE_HEADERS = [\n 'Content-Language',\n 'Link',\n 'Cache-Control',\n 'X-Robots-Tag',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Permissions-Policy',\n 'Referrer-Policy',\n 'Strict-Transport-Security',\n 'X-Frame-Options',\n 'X-Content-Type-Options',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Resource-Policy',\n 'X-DNS-Prefetch-Control',\n] as const\n"]}
|
package/dist/host.js
CHANGED
|
@@ -395,24 +395,6 @@ async function readBodyUpTo(request, limit) {
|
|
|
395
395
|
}
|
|
396
396
|
return body;
|
|
397
397
|
}
|
|
398
|
-
/**
|
|
399
|
-
* The page a client says it was on, as a path this router can match - or
|
|
400
|
-
* null. A header is a string anyone can send, and `new URL` throws on one
|
|
401
|
-
* that is not a url; that must not become a 500 on the action endpoint.
|
|
402
|
-
*/
|
|
403
|
-
function refererPath(referer, origin, hosts = []) {
|
|
404
|
-
if (!referer)
|
|
405
|
-
return null;
|
|
406
|
-
try {
|
|
407
|
-
const parsed = new URL(referer, origin);
|
|
408
|
-
// The page the action was invoked from is routed the way a request for
|
|
409
|
-
// it would be: on a tenant host, the referer's host names the segment.
|
|
410
|
-
return hostPath(parsed.host, parsed.pathname, hosts);
|
|
411
|
-
}
|
|
412
|
-
catch {
|
|
413
|
-
return null;
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
398
|
/**
|
|
417
399
|
* The url of the page an action was invoked from, query string included -
|
|
418
400
|
* or undefined. On this origin whatever the header names: it only ever
|
|
@@ -956,6 +938,41 @@ export function createRscHandler(options) {
|
|
|
956
938
|
headers.set("location", placed);
|
|
957
939
|
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
958
940
|
}
|
|
941
|
+
/** The host the visitor asked for. Behind a proxy the url names this process instead. */
|
|
942
|
+
function requestHost(request, url) {
|
|
943
|
+
return request.headers.get("x-forwarded-host") ?? request.headers.get("host") ?? url.host;
|
|
944
|
+
}
|
|
945
|
+
/** The url the router matches for this path on this host: the host's segment in front, when a route begins with it. */
|
|
946
|
+
function onHost(url, host) {
|
|
947
|
+
const segment = hostSegment(host, siteHosts);
|
|
948
|
+
if (segment === null || !routableHost(segment, routes.routes))
|
|
949
|
+
return url;
|
|
950
|
+
const routed = new URL(hostPath(host, url.pathname, siteHosts) + url.search, url.origin);
|
|
951
|
+
hostOf.set(routed, segment);
|
|
952
|
+
return routed;
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* The page a client says it was on, as a url this router can match - or
|
|
956
|
+
* null. A header is a string anyone can send, and `new URL` throws on one
|
|
957
|
+
* that is not a url; that must not become a 500 on the action endpoint.
|
|
958
|
+
*
|
|
959
|
+
* The client sends a path, so its host is the request's: behind a proxy the
|
|
960
|
+
* url names this process, and /login from merchant.example.com was looked
|
|
961
|
+
* up as the site's own /login.
|
|
962
|
+
*/
|
|
963
|
+
function refererUrl(request, url) {
|
|
964
|
+
const referer = request.headers.get(HEADER.referer);
|
|
965
|
+
if (!referer)
|
|
966
|
+
return null;
|
|
967
|
+
try {
|
|
968
|
+
const parsed = new URL(referer, url.origin);
|
|
969
|
+
const host = parsed.origin === url.origin ? requestHost(request, url) : parsed.host;
|
|
970
|
+
return onHost(new URL(parsed.pathname, url.origin), host);
|
|
971
|
+
}
|
|
972
|
+
catch {
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
959
976
|
async function routeOnHost(request) {
|
|
960
977
|
let url = new URL(request.url);
|
|
961
978
|
// rscKit({ subdomains }): a page under one of those directories has one
|
|
@@ -987,14 +1004,15 @@ export function createRscHandler(options) {
|
|
|
987
1004
|
// one named for the host - so an app with a metadataBase and no tenant
|
|
988
1005
|
// tree routes every host by path, and a proxy forwarding by an internal
|
|
989
1006
|
// name is not read as a tenant.
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
1007
|
+
//
|
|
1008
|
+
// Never this package's own endpoints. The browser posts to /_rsc/action
|
|
1009
|
+
// whatever host its page is on, and with the segment in front it is
|
|
1010
|
+
// /merchant/_rsc/action: no route, and a 404 for every action there.
|
|
1011
|
+
if (siteHosts.length > 0 && !url.pathname.startsWith(HEADER.endpoints)) {
|
|
1012
|
+
const host = requestHost(request, url);
|
|
994
1013
|
const segment = hostSegment(host, siteHosts);
|
|
995
1014
|
if (segment !== null && routableHost(segment, routes.routes)) {
|
|
996
|
-
url =
|
|
997
|
-
hostOf.set(url, segment);
|
|
1015
|
+
url = onHost(url, host);
|
|
998
1016
|
}
|
|
999
1017
|
else if (segment !== null && host && siteHosts.some((site) => bareHost(host).endsWith("." + site))) {
|
|
1000
1018
|
// A label under the site's own host, not a foreign one: a foreign
|
|
@@ -2114,8 +2132,8 @@ export function createRscHandler(options) {
|
|
|
2114
2132
|
return new Response("Not found", { status: 404 });
|
|
2115
2133
|
if (refusal)
|
|
2116
2134
|
return refusal;
|
|
2117
|
-
const from =
|
|
2118
|
-
const under = from ?
|
|
2135
|
+
const from = refererUrl(request, url);
|
|
2136
|
+
const under = from ? matchPage(routes, from) : null;
|
|
2119
2137
|
// Without a page to open over there is nothing to intercept: render the
|
|
2120
2138
|
// interceptor on its own rather than answering with the wrong page.
|
|
2121
2139
|
const component = under ? under.route.component : intercept.component;
|
|
@@ -2299,10 +2317,10 @@ export function createRscHandler(options) {
|
|
|
2299
2317
|
const contentType = request.headers.get(HEADER.contentType) ?? "text/plain;charset=UTF-8";
|
|
2300
2318
|
// Where it was invoked from, so anything the action invalidates can be
|
|
2301
2319
|
// re-rendered against the page that is actually on screen.
|
|
2302
|
-
const from =
|
|
2303
|
-
const match = from ?
|
|
2320
|
+
const from = refererUrl(request, url);
|
|
2321
|
+
const match = from ? matchPage(routes, from) : null;
|
|
2304
2322
|
const page = match
|
|
2305
|
-
? pageContext(match, await propsFor(match, request), from
|
|
2323
|
+
? pageContext(match, await propsFor(match, request), from?.pathname, pageHref(request.headers.get(HEADER.referer), url.origin))
|
|
2306
2324
|
: undefined;
|
|
2307
2325
|
// Scoped to this action: revalidate() called anywhere inside it, at any
|
|
2308
2326
|
// depth, marks here and nowhere else — two requests can be in flight and
|