@rsc-kit/core 0.30.54 → 0.31.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/vite.js CHANGED
@@ -26,6 +26,7 @@ import { stampDisplayNames } from "./stableNames.js";
26
26
  import { REPORT_FILE, buildReport } from "./buildReport.js";
27
27
  import { contractPath, edgeGuarded, edgeMarker, edgeShells, edgeStatic } from "./edgeShells.js";
28
28
  import { EDGE, EDGE_HEADERS } from "./headers.js";
29
+ import { devContentSecurityPolicy, normaliseContentSecurityPolicy, } from "./csp.js";
29
30
  import { MANIFEST_PATH, manifestWarning, webManifest } from "./webManifest.js";
30
31
  import { ASSET_BASE, allAppAssets, assetFile, appAssets, headTags, shareImageUrls, typeOf, } from "./appAssets.js";
31
32
  import { reactCacheImports } from "./reactCache.js";
@@ -250,6 +251,18 @@ let barrelImports = true;
250
251
  let identify = true;
251
252
  /** RscKitOptions.headers, checked against the edge contract's allow list. */
252
253
  let pageHeaders = {};
254
+ let contentSecurityPolicy;
255
+ /** Whether this is `vite dev`, where the policy is devPolicy()'s. */
256
+ let devServer = false;
257
+ /**
258
+ * The policy the host is handed: in dev, the same one with what development
259
+ * needs - see devContentSecurityPolicy - so a refusal shows while you work.
260
+ */
261
+ function devPolicy() {
262
+ if (!contentSecurityPolicy || !devServer)
263
+ return contentSecurityPolicy;
264
+ return devContentSecurityPolicy(contentSecurityPolicy, { origin: devOrigin || undefined });
265
+ }
253
266
  /** Resolved from RscKitOptions.openapi; null when off. */
254
267
  let openapi = null;
255
268
  let foundAssets = {
@@ -564,6 +577,9 @@ function resolvePaths(options) {
564
577
  barrelImports = options.barrelImports !== false;
565
578
  identify = options.identify !== false;
566
579
  pageHeaders = normalisePageHeaders(options.headers);
580
+ contentSecurityPolicy = normaliseContentSecurityPolicy(options.contentSecurityPolicy);
581
+ if (contentSecurityPolicy && Object.keys(pageHeaders).some((name) => name.startsWith("Content-Security-Policy")))
582
+ throw new Error("[rsc-kit] contentSecurityPolicy and a Content-Security-Policy in headers are the same header twice. Keep contentSecurityPolicy: it adds what each page's inline code needs, which a fixed header cannot.");
567
583
  openapi = options.openapi
568
584
  ? (() => {
569
585
  const { path, ...document } = typeof options.openapi === "object" ? options.openapi : {};
@@ -888,6 +904,7 @@ function routeManifest() {
888
904
  identify,
889
905
  refreshOn: usesRefreshOn() || undefined,
890
906
  headers: Object.keys(pageHeaders).length ? pageHeaders : undefined,
907
+ contentSecurityPolicy: devPolicy(),
891
908
  // Always written, [] when none: a reader can tell "none" from a build
892
909
  // too old to say.
893
910
  backendPaths,
@@ -3515,7 +3532,8 @@ import { noteRequestRead, notePageProps, urlOf } from ${JSON.stringify(join(pack
3515
3532
  import { redirectDigest } from ${JSON.stringify(join(packageDir, "redirectDigest"))}
3516
3533
  import { cancelledByConsumer } from ${JSON.stringify(join(packageDir, "js/fallbackReport"))}
3517
3534
  import { withoutPayloadKey } from ${JSON.stringify(join(packageDir, "js/payloadKey"))}
3518
- import { cachingOf, finishCacheable } from ${JSON.stringify(join(packageDir, "pageCache"))}
3535
+ import { cachingOf, finishCacheable, keptBodyOf } from ${JSON.stringify(join(packageDir, "pageCache"))}
3536
+ import { inlineHashes, newNonce, policyHeaderName, policyValue } from ${JSON.stringify(join(packageDir, "csp"))}
3519
3537
  import { createRscHandler, notFoundRouteOf, pageSaidNotFound, queryAndParams } from ${JSON.stringify(join(packageDir, "host"))}
3520
3538
  import { backendHeaders, httpHostCalls } from ${JSON.stringify(join(packageDir, "hostCalls"))}
3521
3539
  import { backendVersions, installBackendVersionSource } from ${JSON.stringify(join(packageDir, "changed"))}
@@ -6352,14 +6370,34 @@ async function notFound(request: Request): Promise<Response> {
6352
6370
  const caching = cachingOf(seen)
6353
6371
 
6354
6372
  return await withRequest(seen, async () => {
6355
- if (!caching) return await renderNotFound(seen)
6373
+ // Rendered for this request: a nonce, as every page that streams gets.
6374
+ if (!caching || caching.refused) {
6375
+ const nonce = NOT_FOUND_POLICY ? newNonce() : undefined
6376
+
6377
+ return await withNotFoundPolicy(await renderNotFound(seen, nonce), nonce)
6378
+ }
6356
6379
 
6357
6380
  renderAsNobody()
6358
6381
 
6359
- return await finishCacheable(seen, await renderNotFound(seen), caching, () => true)
6382
+ // Kept: hashed from the body that is kept, as the host does for a page.
6383
+ return await withNotFoundPolicy(await finishCacheable(seen, await renderNotFound(seen), caching, () => true))
6360
6384
  })
6361
6385
  }
6362
6386
 
6387
+ /** rscKit({ contentSecurityPolicy }), for the 404 the host left to this entry. */
6388
+ const NOT_FOUND_POLICY: any = ${JSON.stringify(devPolicy() || null)}
6389
+
6390
+ async function withNotFoundPolicy(response: Response, nonce?: string): Promise<Response> {
6391
+ if (!NOT_FOUND_POLICY || !(response.headers.get('Content-Type') ?? '').startsWith('text/html')) return response
6392
+
6393
+ const kept = keptBodyOf(response)
6394
+ const hashes = nonce ? null : await inlineHashes(kept ? new TextDecoder().decode(kept) : await response.clone().text())
6395
+
6396
+ response.headers.set(policyHeaderName(NOT_FOUND_POLICY), policyValue(NOT_FOUND_POLICY, { hashes, nonce }))
6397
+
6398
+ return response
6399
+ }
6400
+
6363
6401
  /**
6364
6402
  * Whether the request can display a page: a navigation, an iframe, the
6365
6403
  * router's own payload request, or - from a client that does not say where
@@ -6390,7 +6428,7 @@ function nearestNotFound(request: Request): string | null {
6390
6428
 
6391
6429
  const NOT_FOUND_LAYOUTS: Record<string, string[]> = ${JSON.stringify(notFoundLayouts)}
6392
6430
 
6393
- async function renderNotFound(request: Request): Promise<Response> {
6431
+ async function renderNotFound(request: Request, nonce?: string): Promise<Response> {
6394
6432
  const target = nearestNotFound(request)
6395
6433
  ${notFoundFiles.length
6396
6434
  ? `
@@ -6438,7 +6476,7 @@ async function renderNotFound(request: Request): Promise<Response> {
6438
6476
  [],
6439
6477
  {},
6440
6478
  {},
6441
- undefined,
6479
+ nonce,
6442
6480
  new URL(request.url).pathname,
6443
6481
  )
6444
6482
 
@@ -6467,6 +6505,7 @@ function generateEntrySsr() {
6467
6505
  const redirectDigestModule = join(packageDir, "redirectDigest");
6468
6506
  const notFoundModule = join(packageDir, "notFound");
6469
6507
  const earlyClicks = join(packageDir, "js/earlyClicks");
6508
+ const inlineFlightModule = join(packageDir, "inlineFlight");
6470
6509
  const installCapture = join(packageDir, "js/installCapture");
6471
6510
  return `// GENERATED by rscKit() — do not edit.
6472
6511
  import { createFromReadableStream } from '@vitejs/plugin-rsc/ssr'
@@ -6478,19 +6517,29 @@ import { cancelledByConsumer, caughtByLoading } from ${JSON.stringify(fallbackRe
6478
6517
  import { parseRedirectDigest } from ${JSON.stringify(redirectDigestModule)}
6479
6518
  import { isNotFoundDigest } from ${JSON.stringify(notFoundModule)}
6480
6519
  import { EARLY_CLICKS } from ${JSON.stringify(earlyClicks)}
6520
+ import { READ_BLOCKS } from ${JSON.stringify(inlineFlightModule)}
6481
6521
  import { searchSnapshotContext } from ${JSON.stringify(join(packageDir, "js/useSearchParams"))}
6482
6522
  import { createElement as h } from 'react'
6483
6523
  ${webManifestOptions ? `import { INSTALL_CAPTURE } from ${JSON.stringify(installCapture)}` : ""}
6484
6524
 
6485
- // What runs ahead of the runtime: held taps, and - in an app that can be
6486
- // installed at all - the browser's offer to install it. See installCapture.ts.
6487
- const EARLY = EARLY_CLICKS${webManifestOptions ? " + INSTALL_CAPTURE" : ""}
6525
+ // What runs ahead of the runtime: held taps, the reader that hands the
6526
+ // document's payload blocks to it (see inlineFlight.ts), and - in an app that
6527
+ // can be installed at all - the browser's offer to install it. See
6528
+ // installCapture.ts. The same bytes on every page of a build, which is what
6529
+ // lets one hash in a Content-Security-Policy allow it.
6530
+ const EARLY = EARLY_CLICKS + READ_BLOCKS${webManifestOptions ? " + INSTALL_CAPTURE" : ""}
6488
6531
 
6489
6532
  // Set only by the dev server. @vitejs/plugin-rsc emits its bootstrap and CSS
6490
6533
  // links root-relative in dev, which would send the browser to the host for
6491
6534
  // modules only Vite can answer — see devUrls.ts.
6492
6535
  const DEV_ORIGIN = ${JSON.stringify(devOrigin)}
6493
6536
 
6537
+ // Dev under a Content-Security-Policy: Vite's client gives the styles it
6538
+ // injects - CSS updates, the error overlay - the nonce of a
6539
+ // <meta property="csp-nonce">, as laravel-vite-plugin's @vite writes it. The
6540
+ // boot script writes that tag from its own nonce, before the client loads.
6541
+ const DEV_NONCE_META = ${JSON.stringify(devServer && contentSecurityPolicy ? "(function(s){if(!s||!s.nonce)return;var m=document.createElement('meta');m.setAttribute('property','csp-nonce');m.nonce=s.nonce;document.head.appendChild(m)})(document.currentScript);" : "")}
6542
+
6494
6543
  /**
6495
6544
  * The payload, decoded by the render it is the tree of.
6496
6545
  *
@@ -6554,7 +6603,7 @@ export async function handleSsr(
6554
6603
  // seconds before the runtime hydrates is held for it rather than given
6555
6604
  // to the browser as a document load. See earlyClicks.ts.
6556
6605
  const bootstrapScriptContent = bootstrap
6557
- ? (inline ? 'self.__rsc_f=self.__rsc_f||[];' : '') +
6606
+ ? DEV_NONCE_META + (inline ? 'self.__rsc_f=self.__rsc_f||[];' : '') +
6558
6607
  EARLY + (await (import.meta as any).viteRsc.loadBootstrapScriptContent('index'))
6559
6608
  : undefined
6560
6609
 
@@ -6563,7 +6612,9 @@ export async function handleSsr(
6563
6612
  // which aborts on purpose once it has the shell.
6564
6613
  const html = await renderToReadableStream(root as any, {
6565
6614
  bootstrapScriptContent,
6566
- nonce,
6615
+ // Scripts and the styles React hoists (a <style precedence>) alike: a
6616
+ // policy with a nonce in style-src refuses a style without one.
6617
+ nonce: nonce ? { script: nonce, style: nonce } : undefined,
6567
6618
  onError: onError ?? reportRenderError('ssr'),
6568
6619
  // What a posted form's action returned, for the useActionState that
6569
6620
  // asked: React seats it in the form it belongs to.
@@ -6711,7 +6762,7 @@ export async function handleSsrResume(
6711
6762
  const root = withSearch(decodedBy(rscStream), search)
6712
6763
 
6713
6764
  const html = await resume(root as any, postponed as any, {
6714
- nonce,
6765
+ nonce: nonce ? { script: nonce, style: nonce } : undefined,
6715
6766
  // The same reading of an error the first render has. This used to log
6716
6767
  // every error raw, so a query read the developer's own boundary caught -
6717
6768
  // the designed path, on every resume of a shell whose hole holds one -
@@ -7995,6 +8046,9 @@ export function rscKit(options = {}) {
7995
8046
  },
7996
8047
  },
7997
8048
  config(_config, env) {
8049
+ // Here and not only in configResolved: the entries below are written
8050
+ // in this hook, and the 404's policy in them is dev's or the build's.
8051
+ devServer = env.command === "serve";
7998
8052
  runHostManifest(options, env.command === "build");
7999
8053
  if (!existsSync(appDir)) {
8000
8054
  throw new Error(`[rsc-kit] No app directory at ${appDir} — nothing to build.`);
@@ -8572,7 +8626,11 @@ export function rscKit(options = {}) {
8572
8626
  ? storedPayloadAssets(staticDir, clientOut, listed.static.map((path) => ({ path, key: keyOf.get(path) })).filter((page) => page.key))
8573
8627
  : [];
8574
8628
  const build = clientBuild ? edgeBuildId(clientBuild, staticDir) : undefined;
8575
- const marker = build ? edgeMarker(build, shells.shells, statics) : null;
8629
+ // No shells under a policy: the holes an edge resumes into one are
8630
+ // React's inline scripts, written per request, which only a nonce can
8631
+ // allow - and an edge sends the policy with its copy. Those pages are
8632
+ // answered by the app, shell and all, with the nonce it writes.
8633
+ const marker = build ? edgeMarker(build, contentSecurityPolicy ? [] : shells.shells, statics, contentSecurityPolicy ? shells.shells : undefined) : null;
8576
8634
  // Beside the pages too, so the host finds the build and the static
8577
8635
  // list wherever it reads the pages from.
8578
8636
  if (marker && output !== "export" && existsSync(staticDir)) {
@@ -8661,6 +8719,7 @@ export function rscKit(options = {}) {
8661
8719
  }
8662
8720
  },
8663
8721
  configResolved(config) {
8722
+ devServer = config.command === "serve";
8664
8723
  // A build that is not a production build cannot work here, and the
8665
8724
  // way it fails is opaque: plugin-react emits the development JSX
8666
8725
  // runtime (jsxDEV), the server bundles resolve React's production