@rsc-kit/core 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,yEAAyE;AACzE,mEAAmE;AAEnE,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAChD,OAAO,EAAE,WAAW,EAAoB,MAAM,iBAAiB,CAAA;AAE/D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAE5C,sEAAsE;AACtE,MAAM,QAAQ,GAA2B;IACvC,oBAAoB,EAAE,mBAAmB;IACzC,2BAA2B,EAAE,0BAA0B;IACvD,gBAAgB,EAAE,uBAAuB;IACzC,uBAAuB,EAAE,uBAAuB;IAChD,mBAAmB,EAAE,kBAAkB;IACvC,mBAAmB,EAAE,oBAAoB;IACzC,6BAA6B,EAAE,+BAA+B;IAC9D,0BAA0B,EAAE,sBAAsB;CACnD,CAAA;AAED,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,OAAiB,EACjB,OAAO,GAAyC,EAAE;IAElD,MAAM,OAAO,GAAwB,EAAE,CAAA;IACvC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAA;IACxC,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,MAAM,CAAA;IAC7C,MAAM,OAAO,GAAG,YAAY,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE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O,CAAC,CAAC,IAAI,EAAE,EAAE;gBAC/B,IAAI,CAAC;oBACH,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAA4B,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;gBACzE,CAAC;gBAAC,MAAM,CAAC;oBACP,OAAO,EAAE,CAAA;gBACX,CAAC;YACH,CAAC,CAAC,CACH,CAAA;QACH,CAAC,CAAC,CAAA;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
- * The policy, one entry per directive: `{ 'img-src': ["'self'", 'data:'] }`.
5
- * Left out, `default-src 'self'; base-uri 'self'; object-src 'none';
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
- const given = raw.directives ?? DEFAULT_DIRECTIVES;
56
- if (given === null || typeof given !== "object" || Array.isArray(given))
57
- fail("directives is an object of directive names to sources.");
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 { directives, reportOnly: raw.reportOnly === true };
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+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AU,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, \"&amp;\").replace(/\"/g, \"&quot;\");\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,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,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, \"&amp;\").replace(/\"/g, \"&quot;\");\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[];
@@ -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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AC,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"]}
@@ -157,6 +157,12 @@ export type HostCallBatchLine = HostCallReply & {
157
157
  index: number;
158
158
  status?: number;
159
159
  };
160
+ type Settled = {
161
+ status: number;
162
+ reply: HostCallReply | null;
163
+ text: string;
164
+ setCookies?: string[];
165
+ };
160
166
  /**
161
167
  * The fixed headers sent on every request to the backend - host calls, and
162
168
  * the urls forwarded to it - from RSC_BACKEND_HEADERS, a JSON object:
@@ -169,3 +175,14 @@ export type HostCallBatchLine = HostCallReply & {
169
175
  */
170
176
  export declare function backendHeaders(value: string | Record<string, string> | undefined): Record<string, string>;
171
177
  export declare function httpHostCalls(options: HttpHostCallsOptions): (name: string, ...args: unknown[]) => Promise<unknown>;
178
+ /**
179
+ * What a reply means, in the caller's own async context.
180
+ *
181
+ * Deliberately not done where the response arrives: a batch is answered in
182
+ * a timer, outside every caller's request scope, and `redirect()` and
183
+ * `revalidate()` both write to that scope. Interpreting here, after the
184
+ * caller's await resumed, puts each reply back inside the render it belongs
185
+ * to.
186
+ */
187
+ export declare function interpretReply(name: string, { status, reply, text, setCookies }: Settled, onRevalidate?: (targets: string[]) => void): unknown;
188
+ export {};
package/dist/hostCalls.js CHANGED
@@ -369,108 +369,6 @@ export function httpHostCalls(options) {
369
369
  }
370
370
  });
371
371
  }
372
- /**
373
- * What a reply means, in the caller's own async context.
374
- *
375
- * Deliberately not done where the response arrives: a batch is answered in
376
- * a timer, outside every caller's request scope, and `redirect()` and
377
- * `revalidate()` both write to that scope. Interpreting here, after the
378
- * caller's await resumed, puts each reply back inside the render it belongs
379
- * to.
380
- */
381
- function interpret(name, { status, reply, text, setCookies }) {
382
- // First, whatever the outcome: a login that then redirects still logged
383
- // the visitor in. In the caller's context, where the page's response is.
384
- // Dropped as nobody: a cookie on a page kept for everyone is handed to
385
- // everyone - and its Set-Cookie alone would make the page private.
386
- if (setCookies?.length && !renderingAsNobody())
387
- passSetCookies(setCookies);
388
- // Refusing the input is not the call failing — it is the call answering.
389
- //
390
- // Thrown rather than returned, so a handler stops where it is instead of
391
- // carrying on with data the host rejected. createActionClient catches this
392
- // on the way out and returns { validationErrors }, which is the shape
393
- // useForm reads: React serialises a REJECTED server action opaquely, so a
394
- // validation error that stays thrown reaches the browser as "an error
395
- // occurred" with every field it named gone.
396
- //
397
- // Checked before `error`, so a host that sends both is read as a refusal
398
- // rather than as a failure with no fields.
399
- //
400
- // One error for both places a call is made. In an action, the mark is
401
- // what returns the fields to the form. In a page's render there is no
402
- // form: refusalStatus makes the page answer 422 rather than 500, and the
403
- // message says which call refused which fields, where "Validation failed"
404
- // read like an action had run.
405
- if (reply?.validationErrors) {
406
- const refused = new ActionValidationError(reply.validationErrors);
407
- const fields = Object.keys(reply.validationErrors).map((field) => field || '(the input as a whole)');
408
- refused.message = `Host call ${JSON.stringify(name)} refused its input: ${fields.join(', ')}`;
409
- refused.refusalStatus = 422;
410
- throw refused;
411
- }
412
- // Raised as the engine's own redirect, so it travels the path every other
413
- // redirect travels — a real 3xx above a Suspense boundary, the digest
414
- // below one — rather than becoming an error the page has to interpret.
415
- //
416
- // What it revalidated is marked first: a backend that switched the team
417
- // and redirected - Rsc::revalidate('all') then redirect() in PHP - goes
418
- // to a page whose layout reads the team, and the redirect carries the
419
- // revalidation to the client only if it was marked before the throw.
420
- if (reply?.redirect) {
421
- markRevalidated(reply.revalidate);
422
- redirect(reply.redirect, reply.redirectStatus ?? 307);
423
- }
424
- if (reply?.unauthenticated) {
425
- throw new ServerAuthenticationError(reply.error ?? 'Unauthenticated.');
426
- }
427
- if (reply?.unauthorized) {
428
- throw new ServerAuthorizationError(reply.error ?? 'This action is unauthorized.');
429
- }
430
- // The backend says there is no such thing - Go's Refuse(404), Laravel's
431
- // abort(404), a record this caller cannot see. Raised as the engine's
432
- // own notFound(), so the page answers with not-found.tsx and a 404,
433
- // exactly as a component calling notFound() would; as an error it
434
- // reached the page as "something went wrong". The backend's message rides
435
- // on it for an action, which has no not-found page and shows the message.
436
- if (reply?.refusalStatus === 404)
437
- throw new NotFoundSignal(reply.error ?? 'Not found');
438
- // A status is what makes a reply a refusal rather than a failure: the
439
- // backend's refuse(), Go's Refuse, Laravel's abort(). Its message was
440
- // written for the person asking - Laravel shows an HttpException's in its
441
- // own production JSON - so it is raised as one, with or without data, and
442
- // onError never replaces it. Only refusals carried data at first, and
443
- // Refuse(503, "busy") reached the form as "Something went wrong.".
444
- if (reply?.error !== undefined && (reply.refusalStatus !== undefined || reply.refusalData !== undefined)) {
445
- throw new ActionRefusal(reply.error, reply.refusalData, reply.refusalStatus ?? 409);
446
- }
447
- if (reply?.error !== undefined) {
448
- const failure = new Error(`Host call ${JSON.stringify(name)} failed: ${reply.error}`);
449
- if (reply.debug)
450
- withBackendTrace(failure, reply.debug);
451
- throw failure;
452
- }
453
- if (status >= 400) {
454
- throw new Error(`Host call ${JSON.stringify(name)} failed: ${status}`.trim() +
455
- (text ? ` — ${text.slice(0, 200)}` : ''));
456
- }
457
- if (reply === null) {
458
- throw new Error(`Host call ${JSON.stringify(name)} returned a body that is not JSON: ${text.slice(0, 200)}`);
459
- }
460
- markRevalidated(reply.revalidate);
461
- return reply.result ?? null;
462
- }
463
- function markRevalidated(targets) {
464
- if (!targets?.length)
465
- return;
466
- if (onRevalidate)
467
- onRevalidate(targets);
468
- // Named by the host over the wire - Rsc::revalidate('orders') in PHP -
469
- // so nothing here can check it; the renderer refuses an unknown name.
470
- else
471
- for (const target of targets)
472
- revalidate(target);
473
- }
474
372
  return async function hostCall(name, ...args) {
475
373
  const headers = await forwardedHeaders();
476
374
  // A check rather than a run: the backend validates the fields named and
@@ -479,7 +377,109 @@ export function httpHostCalls(options) {
479
377
  // is one call by definition.
480
378
  const validate = checkedCall(name);
481
379
  const settled = validate ? await single(name, args, headers, validate) : await enqueue(name, args, headers);
482
- return interpret(name, settled);
380
+ return interpretReply(name, settled, onRevalidate);
483
381
  };
484
382
  }
383
+ /**
384
+ * What a reply means, in the caller's own async context.
385
+ *
386
+ * Deliberately not done where the response arrives: a batch is answered in
387
+ * a timer, outside every caller's request scope, and `redirect()` and
388
+ * `revalidate()` both write to that scope. Interpreting here, after the
389
+ * caller's await resumed, puts each reply back inside the render it belongs
390
+ * to.
391
+ */
392
+ export function interpretReply(name, { status, reply, text, setCookies }, onRevalidate) {
393
+ // First, whatever the outcome: a login that then redirects still logged
394
+ // the visitor in. In the caller's context, where the page's response is.
395
+ // Dropped as nobody: a cookie on a page kept for everyone is handed to
396
+ // everyone - and its Set-Cookie alone would make the page private.
397
+ if (setCookies?.length && !renderingAsNobody())
398
+ passSetCookies(setCookies);
399
+ // Refusing the input is not the call failing — it is the call answering.
400
+ //
401
+ // Thrown rather than returned, so a handler stops where it is instead of
402
+ // carrying on with data the host rejected. createActionClient catches this
403
+ // on the way out and returns { validationErrors }, which is the shape
404
+ // useForm reads: React serialises a REJECTED server action opaquely, so a
405
+ // validation error that stays thrown reaches the browser as "an error
406
+ // occurred" with every field it named gone.
407
+ //
408
+ // Checked before `error`, so a host that sends both is read as a refusal
409
+ // rather than as a failure with no fields.
410
+ //
411
+ // One error for both places a call is made. In an action, the mark is
412
+ // what returns the fields to the form. In a page's render there is no
413
+ // form: refusalStatus makes the page answer 422 rather than 500, and the
414
+ // message says which call refused which fields, where "Validation failed"
415
+ // read like an action had run.
416
+ if (reply?.validationErrors) {
417
+ const refused = new ActionValidationError(reply.validationErrors);
418
+ const fields = Object.keys(reply.validationErrors).map((field) => field || '(the input as a whole)');
419
+ refused.message = `Host call ${JSON.stringify(name)} refused its input: ${fields.join(', ')}`;
420
+ refused.refusalStatus = 422;
421
+ throw refused;
422
+ }
423
+ // Raised as the engine's own redirect, so it travels the path every other
424
+ // redirect travels — a real 3xx above a Suspense boundary, the digest
425
+ // below one — rather than becoming an error the page has to interpret.
426
+ //
427
+ // What it revalidated is marked first: a backend that switched the team
428
+ // and redirected - Rsc::revalidate('all') then redirect() in PHP - goes
429
+ // to a page whose layout reads the team, and the redirect carries the
430
+ // revalidation to the client only if it was marked before the throw.
431
+ if (reply?.redirect) {
432
+ markRevalidated(reply.revalidate, onRevalidate);
433
+ redirect(reply.redirect, reply.redirectStatus ?? 307);
434
+ }
435
+ if (reply?.unauthenticated) {
436
+ throw new ServerAuthenticationError(reply.error ?? 'Unauthenticated.');
437
+ }
438
+ if (reply?.unauthorized) {
439
+ throw new ServerAuthorizationError(reply.error ?? 'This action is unauthorized.');
440
+ }
441
+ // The backend says there is no such thing - Go's Refuse(404), Laravel's
442
+ // abort(404), a record this caller cannot see. Raised as the engine's
443
+ // own notFound(), so the page answers with not-found.tsx and a 404,
444
+ // exactly as a component calling notFound() would; as an error it
445
+ // reached the page as "something went wrong". The backend's message rides
446
+ // on it for an action, which has no not-found page and shows the message.
447
+ if (reply?.refusalStatus === 404)
448
+ throw new NotFoundSignal(reply.error ?? 'Not found');
449
+ // A status is what makes a reply a refusal rather than a failure: the
450
+ // backend's refuse(), Go's Refuse, Laravel's abort(). Its message was
451
+ // written for the person asking - Laravel shows an HttpException's in its
452
+ // own production JSON - so it is raised as one, with or without data, and
453
+ // onError never replaces it. Only refusals carried data at first, and
454
+ // Refuse(503, "busy") reached the form as "Something went wrong.".
455
+ if (reply?.error !== undefined && (reply.refusalStatus !== undefined || reply.refusalData !== undefined)) {
456
+ throw new ActionRefusal(reply.error, reply.refusalData, reply.refusalStatus ?? 409);
457
+ }
458
+ if (reply?.error !== undefined) {
459
+ const failure = new Error(`Host call ${JSON.stringify(name)} failed: ${reply.error}`);
460
+ if (reply.debug)
461
+ withBackendTrace(failure, reply.debug);
462
+ throw failure;
463
+ }
464
+ if (status >= 400) {
465
+ throw new Error(`Host call ${JSON.stringify(name)} failed: ${status}`.trim() +
466
+ (text ? ` — ${text.slice(0, 200)}` : ''));
467
+ }
468
+ if (reply === null) {
469
+ throw new Error(`Host call ${JSON.stringify(name)} returned a body that is not JSON: ${text.slice(0, 200)}`);
470
+ }
471
+ markRevalidated(reply.revalidate, onRevalidate);
472
+ return reply.result ?? null;
473
+ }
474
+ function markRevalidated(targets, onRevalidate) {
475
+ if (!targets?.length)
476
+ return;
477
+ if (onRevalidate)
478
+ onRevalidate(targets);
479
+ // Named by the host over the wire - Rsc::revalidate('orders') in PHP -
480
+ // so nothing here can check it; the renderer refuses an unknown name.
481
+ else
482
+ for (const target of targets)
483
+ revalidate(target);
484
+ }
485
485
  //# sourceMappingURL=hostCalls.js.map