Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: unstable_subResourceIntegrity #13163

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
6 changes: 6 additions & 0 deletions .changeset/late-falcons-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@react-router/dev": patch
"react-router": patch
---

Introduce `unstable_subResourceIntegrity` future flag that enables generation of an importmap with integrity for the scripts that will be loaded by the browser.
3 changes: 3 additions & 0 deletions packages/react-router-dev/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ interface FutureConfig {
* Automatically split route modules into multiple chunks when possible.
*/
unstable_splitRouteModules: boolean | "enforce";
unstable_subResourceIntegrity: boolean;
/**
* Use Vite Environment API (experimental)
*/
Expand Down Expand Up @@ -497,6 +498,8 @@ async function resolveConfig({
reactRouterUserConfig.future?.unstable_optimizeDeps ?? false,
unstable_splitRouteModules:
reactRouterUserConfig.future?.unstable_splitRouteModules ?? false,
unstable_subResourceIntegrity:
reactRouterUserConfig.future?.unstable_subResourceIntegrity ?? false,
unstable_viteEnvironmentApi:
reactRouterUserConfig.future?.unstable_viteEnvironmentApi ?? false,
};
Expand Down
1 change: 1 addition & 0 deletions packages/react-router-dev/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export type Manifest = {
routes: {
[routeId: string]: ManifestRoute;
};
sri: Record<string, string> | undefined;
hmr?: {
timestamp?: number;
runtime: string;
Expand Down
62 changes: 62 additions & 0 deletions packages/react-router-dev/vite/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// context but want to use Vite's ESM build to avoid deprecation warnings
import type * as Vite from "vite";
import { type BinaryLike, createHash } from "node:crypto";
import * as fs from "node:fs";
import * as path from "node:path";
import * as url from "node:url";
import * as fse from "fs-extra";
Expand Down Expand Up @@ -816,6 +817,39 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
return new Set([...cssUrlPaths, ...chunkAssetPaths]);
};

let generateSriManifest = async (ctx: ReactRouterPluginContext) => {
let clientBuildDirectory = getClientBuildDirectory(ctx.reactRouterConfig);
// walk the client build directory and generate SRI hashes for all .js files
let entries = fs.readdirSync(clientBuildDirectory, {
withFileTypes: true,
recursive: true,
});
let sriManifest: ReactRouterManifest["sri"] = {};
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith(".js")) {
let contents;
try {
contents = await fse.readFile(
path.join(entry.path, entry.name),
"utf-8"
);
} catch (e) {
logger.error(`Failed to read file for SRI generation: ${entry.name}`);
throw e;
}
let hash = createHash("sha384")
.update(contents)
.digest()
.toString("base64");
let filepath = getVite().normalizePath(
path.relative(clientBuildDirectory, path.join(entry.path, entry.name))
);
sriManifest[`${ctx.publicPath}${filepath}`] = `sha384-${hash}`;
}
}
return sriManifest;
};

let generateReactRouterManifestsForBuild = async ({
routeIds,
}: {
Expand Down Expand Up @@ -938,6 +972,7 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
let reactRouterBrowserManifest: ReactRouterManifest = {
...fingerprintedValues,
...nonFingerprintedValues,
sri: undefined,
};

// Write the browser manifest to disk as part of the build process
Expand All @@ -948,12 +983,18 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
)};`
);

let sri: ReactRouterManifest["sri"] = undefined;
if (ctx.reactRouterConfig.future.unstable_subResourceIntegrity) {
sri = await generateSriManifest(ctx);
}

// The server manifest is the same as the browser manifest, except for
// server bundle builds which only includes routes for the current bundle,
// otherwise the server and client have the same routes
let reactRouterServerManifest: ReactRouterManifest = {
...reactRouterBrowserManifest,
routes: serverRoutes,
sri,
};

return {
Expand Down Expand Up @@ -1031,6 +1072,8 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
};
}

let sri: ReactRouterManifest["sri"] = undefined;

let reactRouterManifestForDev = {
version: String(Math.random()),
url: combineURLs(ctx.publicPath, virtual.browserManifest.url),
Expand All @@ -1044,6 +1087,7 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
),
imports: [],
},
sri,
routes,
};

Expand Down Expand Up @@ -3497,3 +3541,21 @@ async function getEnvironmentsOptions(
function isNonNullable<T>(x: T): x is NonNullable<T> {
return x != null;
}

function createSubResourceIntegrityMap(
viteManifest: Vite.Manifest,
algorithm: string,
outdir: string,
publicPath: string
) {
let map: Record<string, string> = {};
for (let value of Object.values(viteManifest)) {
let file = path.resolve(outdir, value.file);
if (!fse.existsSync(file)) continue;
let source = fse.readFileSync(file);
let hash = createHash("sha384").update(source).digest().toString("base64");
let url = `${publicPath}${value.file}`;
map[url] = `${algorithm.toLowerCase()}-${hash}`;
}
return map;
}
13 changes: 13 additions & 0 deletions packages/react-router/lib/dom/ssr/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -784,24 +784,37 @@ import(${JSON.stringify(manifest.entry.module)});`;

return isHydrated ? null : (
<>
{manifest.sri ? (
<script
type="importmap"
dangerouslySetInnerHTML={{
__html: JSON.stringify({
integrity: manifest.sri,
}),
}}
/>
) : null}
{!enableFogOfWar ? (
<link
rel="modulepreload"
href={manifest.url}
crossOrigin={props.crossOrigin}
integrity={manifest.sri?.[manifest.url]}
/>
) : null}
<link
rel="modulepreload"
href={manifest.entry.module}
crossOrigin={props.crossOrigin}
integrity={manifest.sri?.[manifest.entry.module]}
/>
{dedupe(preloads).map((path) => (
<link
key={path}
rel="modulepreload"
href={path}
crossOrigin={props.crossOrigin}
integrity={manifest.sri?.[path]}
/>
))}
{initialScripts}
Expand Down
2 changes: 2 additions & 0 deletions packages/react-router/lib/dom/ssr/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface EntryContext extends FrameworkContextObject {
}

export interface FutureConfig {
unstable_subResourceIntegrity: boolean;
unstable_middleware: boolean;
}

Expand All @@ -59,4 +60,5 @@ export interface AssetsManifest {
timestamp?: number;
runtime: string;
};
sri?: Record<string, string>;
}
1 change: 1 addition & 0 deletions packages/react-router/lib/dom/ssr/routes-test-stub.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export function createRoutesStub(
if (routerRef.current == null) {
remixContextRef.current = {
future: {
unstable_subResourceIntegrity: future?.unstable_subResourceIntegrity === true,
unstable_middleware: future?.unstable_middleware === true,
},
manifest: {
Expand Down
1 change: 1 addition & 0 deletions playground/framework/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<Meta />
<Links />
</head>
Expand Down
6 changes: 5 additions & 1 deletion playground/framework/react-router.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import type { Config } from "@react-router/dev/config";

export default {} satisfies Config;
export default {
future: {
unstable_subResourceIntegrity: true,
},
} satisfies Config;
15 changes: 4 additions & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading