Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/stable-subresource-integrity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'rsbuild-plugin-react-router': patch
---

Support React Router's stable `subResourceIntegrity` config and keep it in sync
with `future.unstable_subResourceIntegrity` when merging presets and user
configuration.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,12 @@ export default {
*/
serverBundles: async ({ branch }) => branch[0]?.id ?? "main",

/**
* Enable Subresource Integrity for browser assets.
* @default false
*/
subResourceIntegrity: true,

/**
* Hook called after the build completes.
*/
Expand Down Expand Up @@ -283,10 +289,17 @@ If no configuration is provided, the following defaults will be used:
ssr: true,
buildDirectory: 'build',
appDirectory: 'app',
basename: '/'
basename: '/',
subResourceIntegrity: false
}
```

Subresource Integrity is disabled by default. Enable it with
`subResourceIntegrity: true` in `react-router.config.*` when the deployed app
should emit integrity metadata for browser scripts. The legacy
`future.unstable_subResourceIntegrity` flag is still accepted and is normalized
to the stable option.

### Route Configuration

Routes can be defined in `app/routes.ts` using the helper functions from `@react-router/dev/routes`:
Expand Down
96 changes: 90 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ import {
getReactRouterManifestForDev,
configRoutesToRouteManifest,
} from './manifest.js';
import { createModifyBrowserManifestPlugin } from './modify-browser-manifest.js';
import {
collectSubresourceIntegrity,
createModifyBrowserManifestPlugin,
} from './modify-browser-manifest.js';
import { createRequestHandler, matchRoutes } from 'react-router';
import {
getExportNames,
Expand Down Expand Up @@ -229,6 +232,7 @@ export const pluginReactRouter = (
serverBuildFile,
serverModuleFormat,
serverBundles,
subResourceIntegrity,
buildEnd,
} = resolvedConfig;

Expand Down Expand Up @@ -407,6 +411,27 @@ export const pluginReactRouter = (
let latestServerManifest: ReactRouterManifest | null = null;
const latestServerManifestsByBundleId: Record<string, ReactRouterManifest> =
{};
const updateLatestServerManifestSri = (
sri: Record<string, string> | undefined
) => {
if (!latestServerManifest) {
return;
}

latestServerManifest = {
...latestServerManifest,
sri,
};

for (const [bundleId, manifest] of Object.entries(
latestServerManifestsByBundleId
)) {
latestServerManifestsByBundleId[bundleId] = {
...manifest,
sri,
};
}
};

const routeByFilePath = new Map(
Object.values(routes).map(route => [
Expand Down Expand Up @@ -467,9 +492,45 @@ export const pluginReactRouter = (
const assetsBuildDirectory = relative(process.cwd(), outputClientPath);

let clientStats: Rspack.StatsCompilation | undefined;
let clientSri: Record<string, string> | undefined;
let resolveClientStatsReady: (
stats: Rspack.StatsCompilation | undefined
) => void = () => {};
let clientStatsReadyResolved = false;
const clientStatsReady = new Promise<Rspack.StatsCompilation | undefined>(
resolve => {
resolveClientStatsReady = resolve;
}
);
const resolveClientStatsOnce = (
stats: Rspack.StatsCompilation | undefined
) => {
if (clientStatsReadyResolved) {
return;
}
clientStatsReadyResolved = true;
resolveClientStatsReady(stats);
};
const toClientManifestStats = (
stats: Rspack.Stats | undefined
): Rspack.StatsCompilation | undefined =>
stats?.toJson({
all: false,
assets: true,
});

api.onAfterEnvironmentCompile(({ stats, environment }) => {
if (environment.name === 'web') {
clientStats = stats?.toJson();
clientStats = toClientManifestStats(stats);
if (isBuild && subResourceIntegrity) {
clientSri = collectSubresourceIntegrity(
clientStats,
undefined,
assetPrefix
);
updateLatestServerManifestSri(clientSri);
}
resolveClientStatsOnce(clientStats);
}
if (pluginOptions.federation && ssr) {
const serverBuildDir = resolve(buildDirectory, 'server');
Expand Down Expand Up @@ -1128,6 +1189,15 @@ export const pluginReactRouter = (
},
environments: {
web: {
...(subResourceIntegrity
? {
security: {
sri: {
enable: true,
},
},
}
: {}),
source: {
entry: {
// no query needed when federation is disabled
Expand Down Expand Up @@ -1254,9 +1324,8 @@ export const pluginReactRouter = (
assetPrefix,
routeChunkOptions,
{
subResourceIntegrity:
resolvedConfigWithRoutes.subResourceIntegrity,
future,
subResourceIntegrity,
onManifest: (manifest, sri) => {
const baseServerManifest = {
...manifest,
Expand Down Expand Up @@ -1325,8 +1394,10 @@ export const pluginReactRouter = (
/virtual\/react-router\/server-manifest(?:-([^?]+))?/
);
const bundleId = bundleMatch?.[1]?.replace(/\\.js$/, '');
const manifestStats =
isBuild && subResourceIntegrity ? await clientStatsReady : clientStats;

const manifest =
const manifestBase =
(isBuild && latestServerManifest
? bundleId && latestServerManifestsByBundleId[bundleId]
? latestServerManifestsByBundleId[bundleId]
Expand All @@ -1335,11 +1406,24 @@ export const pluginReactRouter = (
(await getReactRouterManifestForDev(
routes,
pluginOptions,
clientStats,
manifestStats ?? clientStats,
appDirectory,
assetPrefix,
routeChunkOptions
));
const manifest =
isBuild && subResourceIntegrity
? {
...manifestBase,
sri:
clientSri ??
collectSubresourceIntegrity(
manifestStats,
undefined,
assetPrefix
),
}
: manifestBase;
return {
code: `export default ${jsesc(manifest, { es6: true })};`,
};
Expand Down
2 changes: 1 addition & 1 deletion src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export async function getReactRouterManifestForDev(
imports: string[];
css: string[];
};
sri?: Record<string, string>;
sri?: Record<string, string> | true;
routes: Record<string, RouteManifestItem>;
}> {
const result: Record<string, RouteManifestItem> = {};
Expand Down
110 changes: 80 additions & 30 deletions src/modify-browser-manifest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { createHash } from 'node:crypto';
import type { Route, PluginOptions } from './types.js';
import { rspack } from '@rsbuild/core';
import type { Rspack } from '@rsbuild/core';
Expand All @@ -9,6 +8,70 @@ import {
import { combineURLs } from './plugin-utils.js';
import jsesc from 'jsesc';

type StatsAssetWithIntegrity = {
name?: string;
integrity?: unknown;
};

type StatsWithIntegrity = {
assets?: StatsAssetWithIntegrity[];
};

type CompilationAssetWithIntegrity = {
name: string;
info?: {
integrity?: unknown;
};
};

const ABSOLUTE_URL_RE = /^[a-zA-Z][a-zA-Z\d+\-.]*:/;

const toManifestAssetUrl = (assetPrefix: string, assetName: string) => {
if (
ABSOLUTE_URL_RE.test(assetName) ||
assetName.startsWith('//') ||
assetName.startsWith('/')
) {
return assetName;
}
return combineURLs(assetPrefix, assetName);
};

const addIntegrity = (
sri: Record<string, string>,
assetPrefix: string,
assetName: unknown,
integrity: unknown
) => {
if (typeof assetName !== 'string' || typeof integrity !== 'string') {
return;
}
sri[toManifestAssetUrl(assetPrefix, assetName)] = integrity;
};

export const collectSubresourceIntegrity = (
stats: StatsWithIntegrity | undefined,
compilation:
| Pick<Rspack.Compilation, 'getAssets'>
| { getAssets?: () => CompilationAssetWithIntegrity[] }
| undefined,
assetPrefix = '/'
): Record<string, string> | undefined => {
const sri: Record<string, string> = {};

for (const asset of stats?.assets ?? []) {
addIntegrity(sri, assetPrefix, asset.name, asset.integrity);
}

if (typeof compilation?.getAssets === 'function') {
for (const asset of compilation.getAssets()) {
addIntegrity(sri, assetPrefix, asset.name, asset.info?.integrity);
}
}

return Object.keys(sri).length > 0 ? sri : undefined;
};

/**
* Creates a Webpack/Rspack plugin that modifies the browser manifest
* @param routes - The routes configuration
Expand All @@ -23,11 +86,11 @@ export function createModifyBrowserManifestPlugin(
assetPrefix = '/',
routeChunkOptions?: Parameters<typeof getReactRouterManifestForDev>[5],
options?: {
subResourceIntegrity?: boolean;
future?: { unstable_subResourceIntegrity?: boolean };
subResourceIntegrity?: boolean;
onManifest?: (
manifest: Awaited<ReturnType<typeof getReactRouterManifestForDev>>,
sri: Record<string, string> | undefined
sri: Record<string, string> | true | undefined
) => void;
}
) {
Expand All @@ -45,6 +108,17 @@ export function createModifyBrowserManifestPlugin(
assetPrefix,
routeChunkOptions
);
const shouldUseSri =
routeChunkOptions?.isBuild &&
(options?.subResourceIntegrity ??
options?.future?.unstable_subResourceIntegrity);
const manifestForBrowser = shouldUseSri
? { ...manifest, sri: true as const }
: manifest;
const sri = shouldUseSri
? (collectSubresourceIntegrity(stats, compilation, assetPrefix) ??
true)
: undefined;

const virtualManifestPath =
'static/js/virtual/react-router/browser-manifest.js';
Expand All @@ -54,7 +128,7 @@ export function createModifyBrowserManifestPlugin(
.toString();
const newSource = originalSource.replace(
/["'`]PLACEHOLDER["'`]/,
jsesc(manifest, { es6: true })
jsesc(manifestForBrowser, { es6: true })
);
compilation.assets[virtualManifestPath] = {
source: () => newSource,
Expand Down Expand Up @@ -93,39 +167,15 @@ export function createModifyBrowserManifestPlugin(
entryModulePath: entryJsAssets[0],
});
const manifestSource = `window.__reactRouterManifest=${jsesc(
manifest,
manifestForBrowser,
{ es6: true }
)};`;
compilation.assets[manifestPath] = new rspack.sources.RawSource(
manifestSource
);
}

let sri: Record<string, string> | undefined;
if (
routeChunkOptions?.isBuild &&
(options?.subResourceIntegrity ??
options?.future?.unstable_subResourceIntegrity)
) {
const assets =
typeof compilation.getAssets === 'function'
? compilation.getAssets()
: Object.entries(compilation.assets).map(([name, asset]) => ({
name,
source: asset,
}));
sri = {};
for (const asset of assets) {
if (!asset.name.endsWith('.js')) {
continue;
}
const source = asset.source.source().toString();
const hash = createHash('sha384').update(source).digest('base64');
sri[combineURLs(assetPrefix, asset.name)] = `sha384-${hash}`;
}
}

options?.onManifest?.(manifest, sri);
options?.onManifest?.(manifestForBrowser, sri);
callback();
}
);
Expand Down
Loading
Loading