Unverified Commit 3e015884 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

feat: add NEXT_HASH_SALT env var for content-hash filename salting (#91871)

### What?

Adds a `NEXT_HASH_SALT` environment variable **and** a
`experimental.outputHashSalt` config option that mix a user-supplied
string into every content-addressed hash used to generate chunk
filenames and static asset filenames. This works for both Webpack and
Turbopack.

When both are set, the values are concatenated (`outputHashSalt +
NEXT_HASH_SALT`), so a per-project salt can be baked into
`next.config.js` while a per-deployment salt is injected at build time
via the environment variable.

### Why?

Content-addressed filenames (e.g. `chunk.abc123.js`) are derived from
file content, so they only change when the content changes. There are
deployment scenarios where you need to force all filenames to rotate —
for example after a CDN misconfiguration has poisoned caches for a
particular hash space — without actually changing source code. A stable,
opt-in salt lets operators do this without touching application code.

Some customers prefer the config-file approach
(`turbopack.outputHashSalt`) over environment variables, so both are
supported.

### How?

**Webpack** already has `output.hashSalt` in its config. We simply
forward `NEXT_HASH_SALT` to that option.

**Turbopack** required threading the value through several layers:

1. The effective hash salt is computed once in
`assignDefaultsAndValidate` as `config.turbopackHashSalt =
(turbopack.outputHashSalt ?? '') + (NEXT_HASH_SALT ?? '')` and stored on
`NextConfigComplete`. Both `turbopackBuild` (production) and
`createHotReloaderTurbopack` (dev) read from this single field.
2. `ProjectOptions.hash_salt` receives the pre-computed salt.
3. `Project` stores the salt and passes it into the three chunking
context option structs (`ClientChunkingContextOptions`,
`ServerChunkingContextOptions`, `EdgeChunkingContextOptions`).
4. Both `BrowserChunkingContext` and `NodeJsChunkingContext` gain a
`hash_salt: RcStr` field.
5. A new `deterministic_hash_with_salt(salt, input, algorithm)` function
in `turbo-tasks-hash` writes the salt bytes first, then the content
bytes, into a single hasher — one pass, no hash-of-hash composition.
6. A matching `content_hash_with_salt` method is added to `FileContent`
and `AssetContent`.
7. `ChunkingContext::asset_path` is changed to accept `Vc<AssetContent>`
(instead of a pre-computed `Vc<RcStr>`) so the chunking context can
choose the correct hash path itself. `StaticOutputAsset::path`
simplifies accordingly.

Without `NEXT_HASH_SALT` and without `turbopack.outputHashSalt` set,
behaviour is identical to before — no hash change, no performance
impact.

**e2e test** (`test/production/app-dir/hash-salt/`) verifies:
- Two builds with the same salt produce identical chunk and static asset
filenames.
- A build with a different salt produces different filenames.
- `turbopack.outputHashSalt` (config) changes filenames vs no salt.
- Combined config + env salt differs from either alone.
- Runs for both Turbopack and Webpack.

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
Co-authored-by: 's avatarLuke Sandberg <lukesandberg@users.noreply.github.com>
parent a5c0a897
......@@ -6,7 +6,7 @@ use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::{HashAlgorithm, encode_hex};
use turbopack_core::{
asset::Asset,
asset::{Asset, no_hash_salt},
output::{OutputAsset, OutputAssets},
reference::all_assets_from_entries,
};
......@@ -39,7 +39,7 @@ async fn asset_path(
let hash = if let Some(algorithm) = should_content_hash {
asset
.content()
.content_hash(algorithm)
.content_hash(no_hash_salt(), algorithm)
.owned()
.await?
.context("asset content not found")?
......
......@@ -370,6 +370,11 @@ pub struct ProjectOptions {
/// Whether server-side HMR is enabled (disabled with --no-server-fast-refresh).
pub server_hmr: bool,
/// A salt to mix into chunk and asset content hashes, allowing users to
/// force new filenames without changing file content. Empty string means
/// no salt.
pub hash_salt: RcStr,
}
#[derive(Default)]
......@@ -420,6 +425,9 @@ pub struct PartialProjectOptions {
/// Debug build paths for selective builds.
/// When set, only routes matching these paths will be included in the build.
pub debug_build_paths: Option<DebugBuildPaths>,
/// An optional salt to mix into chunk and asset content hashes.
pub hash_salt: Option<RcStr>,
}
#[derive(
......@@ -671,6 +679,7 @@ impl ProjectContainer {
no_mangling,
write_routes_hashes_manifest,
debug_build_paths,
hash_salt,
} = options;
let mut new_options = this
......@@ -721,6 +730,9 @@ impl ProjectContainer {
if let Some(debug_build_paths) = debug_build_paths {
new_options.debug_build_paths = Some(debug_build_paths);
}
if let Some(hash_salt) = hash_salt {
new_options.hash_salt = hash_salt;
}
// TODO: Handle mode switch, should prevent mode being switched.
let watch = new_options.watch;
......@@ -801,6 +813,7 @@ impl ProjectContainer {
let deferred_entries;
let is_persistent_caching_enabled;
let server_hmr;
let hash_salt;
{
let options = self.options_state.get();
let options = options
......@@ -829,6 +842,7 @@ impl ProjectContainer {
deferred_entries = options.deferred_entries.clone().unwrap_or_default();
is_persistent_caching_enabled = options.is_persistent_caching_enabled;
server_hmr = options.server_hmr;
hash_salt = options.hash_salt.clone();
}
let dist_dir = next_config.dist_dir().owned().await?;
......@@ -859,6 +873,7 @@ impl ProjectContainer {
deferred_entries,
is_persistent_caching_enabled,
server_hmr,
hash_salt,
}
.cell())
}
......@@ -962,6 +977,10 @@ pub struct Project {
/// Whether server-side HMR is enabled (disabled with --no-server-fast-refresh).
server_hmr: bool,
/// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt.
hash_salt: RcStr,
}
#[turbo_tasks::value]
......@@ -1221,6 +1240,11 @@ impl Project {
Vc::cell(self.no_mangling)
}
#[turbo_tasks::function]
pub(crate) fn hash_salt(&self) -> Vc<RcStr> {
Vc::cell(self.hash_salt.clone())
}
#[turbo_tasks::function]
pub(super) async fn execution_context(self: Vc<Self>) -> Result<Vc<ExecutionContext>> {
let node_root = self.node_root().owned().await?;
......@@ -1567,6 +1591,7 @@ impl Project {
debug_ids: self.next_config().turbopack_debug_ids(),
should_use_absolute_url_references: self.next_config().inline_css(),
css_url_suffix,
hash_salt: self.hash_salt().to_resolved().await?,
}))
}
......@@ -1596,6 +1621,7 @@ impl Project {
client_root: self.client_relative_path().owned().await?,
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
hash_salt: self.hash_salt().to_resolved().await?,
};
Ok(if client_assets {
get_server_chunking_context_with_client_assets(options)
......@@ -1629,6 +1655,7 @@ impl Project {
client_root: self.client_relative_path().owned().await?,
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
hash_salt: self.hash_salt().to_resolved().await?,
};
Ok(if client_assets {
get_edge_chunking_context_with_client_assets(options)
......
......@@ -142,7 +142,9 @@ impl Asset for AssetHashesManifestAsset {
.map(async |(asset, path)| {
Ok((
path,
asset.content_hash(HashAlgorithm::Xxh3Hash128Base38).await?,
asset
.content_hash(self.project.hash_salt(), HashAlgorithm::Xxh3Hash128Base38)
.await?,
))
})
.try_join()
......
......@@ -189,6 +189,7 @@ fn main() {
is_persistent_caching_enabled: false,
next_version: rcstr!("0.0.0"),
server_hmr: false,
hash_salt: rcstr!(""),
};
let json = serde_json::to_string_pretty(&options).unwrap();
......
......@@ -9,7 +9,7 @@ use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::{
asset::AssetContent,
asset::{AssetContent, no_hash_salt},
context::AssetContext,
file_source::FileSource,
module::Module,
......@@ -34,7 +34,10 @@ async fn dynamic_image_metadata_with_generator_source(
let stem = stem.unwrap_or_default();
let ext = path.extension();
let hash = path.read().content_hash(HashAlgorithm::default()).await?;
let hash = path
.read()
.content_hash(no_hash_salt(), HashAlgorithm::default())
.await?;
let hash = hash.as_ref().context("metadata file not found")?;
let use_numeric_sizes = ty == "twitter" || ty == "openGraph";
......@@ -109,7 +112,10 @@ async fn dynamic_image_metadata_without_generator_source(
let stem = stem.unwrap_or_default();
let ext = path.extension();
let hash = path.read().content_hash(HashAlgorithm::default()).await?;
let hash = path
.read()
.content_hash(no_hash_salt(), HashAlgorithm::default())
.await?;
let hash = hash.as_ref().context("metadata file not found")?;
let use_numeric_sizes = ty == "twitter" || ty == "openGraph";
......
......@@ -445,6 +445,7 @@ pub struct ClientChunkingContextOptions {
pub debug_ids: Vc<bool>,
pub should_use_absolute_url_references: Vc<bool>,
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
}
#[turbo_tasks::function]
......@@ -469,6 +470,7 @@ pub async fn get_client_chunking_context(
debug_ids,
should_use_absolute_url_references,
css_url_suffix,
hash_salt,
} = options;
let next_mode = mode.await?;
......@@ -502,6 +504,7 @@ pub async fn get_client_chunking_context(
.should_use_absolute_url_references(*should_use_absolute_url_references.await?)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals())
.hash_salt(hash_salt)
.default_url_behavior(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: css_url_suffix.to_resolved().await?,
......
......@@ -202,6 +202,7 @@ pub struct EdgeChunkingContextOptions {
pub client_root: FileSystemPath,
pub asset_prefix: RcStr,
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
}
/// Like `get_edge_chunking_context` but all assets are emitted as client assets (so `/_next`)
......@@ -226,6 +227,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
client_root,
asset_prefix,
css_url_suffix,
hash_salt,
} = options;
let output_root = node_root.join("server/edge")?;
let next_mode = mode.await?;
......@@ -256,6 +258,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
.module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?)
.hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
......@@ -303,6 +306,7 @@ pub async fn get_edge_chunking_context(
client_root,
asset_prefix,
css_url_suffix,
hash_salt,
} = options;
let css_url_suffix = css_url_suffix.to_resolved().await?;
let output_root = node_root.join("server/edge")?;
......@@ -347,6 +351,7 @@ pub async fn get_edge_chunking_context(
.module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?)
.hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
......
......@@ -1004,6 +1004,7 @@ pub struct ServerChunkingContextOptions {
pub client_root: FileSystemPath,
pub asset_prefix: RcStr,
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
}
/// Like `get_server_chunking_context` but all assets are emitted as client assets (so `/_next`)
......@@ -1029,6 +1030,7 @@ pub async fn get_server_chunking_context_with_client_assets(
client_root,
asset_prefix,
css_url_suffix,
hash_salt,
} = options;
let css_url_suffix = css_url_suffix.to_resolved().await?;
......@@ -1072,6 +1074,7 @@ pub async fn get_server_chunking_context_with_client_assets(
.unused_references(unused_references.to_resolved().await?)
.file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?)
.hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
......@@ -1127,6 +1130,7 @@ pub async fn get_server_chunking_context(
client_root,
asset_prefix,
css_url_suffix,
hash_salt,
} = options;
let css_url_suffix = css_url_suffix.to_resolved().await?;
let next_mode = mode.await?;
......@@ -1170,6 +1174,7 @@ pub async fn get_server_chunking_context(
.unused_references(unused_references.to_resolved().await?)
.file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?)
.hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
......
......@@ -214,6 +214,11 @@ pub struct NapiProjectOptions {
/// Whether server-side HMR is enabled (disabled with --no-server-fast-refresh).
pub server_hmr: Option<bool>,
/// A salt to mix into chunk and asset content hashes, allowing users to
/// force new filenames without changing file content. Empty string means
/// no salt.
pub hash_salt: RcStr,
}
/// [NapiProjectOptions] with all fields optional.
......@@ -264,6 +269,9 @@ pub struct NapiPartialProjectOptions {
/// local names for variables, functions etc., which can be useful for
/// debugging/profiling purposes.
pub no_mangling: Option<bool>,
/// An optional salt to mix into chunk and asset content hashes.
pub hash_salt: Option<RcStr>,
}
#[napi(object)]
......@@ -324,6 +332,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
is_persistent_caching_enabled,
next_version,
server_hmr,
hash_salt,
} = val;
ProjectOptions {
root_path,
......@@ -348,6 +357,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
is_persistent_caching_enabled,
next_version,
server_hmr: server_hmr.unwrap_or(false),
hash_salt,
}
}
}
......@@ -368,6 +378,7 @@ impl From<NapiPartialProjectOptions> for PartialProjectOptions {
browserslist_query,
no_mangling,
write_routes_hashes_manifest,
hash_salt,
} = val;
PartialProjectOptions {
root_path,
......@@ -384,6 +395,7 @@ impl From<NapiPartialProjectOptions> for PartialProjectOptions {
no_mangling,
write_routes_hashes_manifest,
debug_build_paths: None,
hash_salt,
}
}
}
......
---
title: outputHashSalt
description: Learn how to incorporate a custom salt string into content-addressed output filenames.
version: experimental
---
`outputHashSalt` is an experimental option that incorporates a configurable salt string into every content-addressed output filename (chunks, assets). Changing this value forces all output hashes to change, which is useful for invalidating cached assets across deployments without modifying source files.
To configure the output hash salt, set `experimental.outputHashSalt` in `next.config.js`:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
outputHashSalt: 'my-deployment-salt',
},
}
module.exports = nextConfig
```
This works with both Webpack and Turbopack bundlers.
The `NEXT_HASH_SALT` environment variable can also be used for the same purpose. When both are set, the values are **concatenated** (`experimental.outputHashSalt + NEXT_HASH_SALT`) to form the effective salt. This lets you combine a per-project salt baked into the config with a per-deployment salt injected at build time via environment variable.
```bash filename="Terminal"
NEXT_HASH_SALT=my-deployment-salt next build
```
## Version History
| Version | Changes |
| -------- | ---------------------------------------- |
| `16.3.0` | `experimental.outputHashSalt` was added. |
......@@ -258,6 +258,12 @@ export interface NapiProjectOptions {
nextVersion: RcStr
/** Whether server-side HMR is enabled (disabled with --no-server-fast-refresh). */
serverHmr?: boolean
/**
* A salt to mix into chunk and asset content hashes, allowing users to
* force new filenames without changing file content. Empty string means
* no salt.
*/
hashSalt: RcStr
}
/** [NapiProjectOptions] with all fields optional. */
export interface NapiPartialProjectOptions {
......@@ -302,6 +308,8 @@ export interface NapiPartialProjectOptions {
* debugging/profiling purposes.
*/
noMangling?: boolean
/** An optional salt to mix into chunk and asset content hashes. */
hashSalt?: RcStr
}
export interface NapiDefineEnv {
client: Array<NapiOptionEnvVar>
......
......@@ -91,6 +91,7 @@ export async function turbopackAnalyze(
currentNodeJsVersion,
isPersistentCachingEnabled: persistentCaching,
nextVersion: process.env.__NEXT_VERSION as string,
hashSalt: config.hashSalt,
},
{
memoryLimit: config.experimental?.turbopackMemoryLimit,
......
......@@ -114,6 +114,7 @@ export async function turbopackBuild(): Promise<{
isPersistentCachingEnabled: persistentCaching,
deferredEntries: config.experimental.deferredEntries,
nextVersion: process.env.__NEXT_VERSION as string,
hashSalt: config.hashSalt,
}
const sharedTurboOptions = {
......
......@@ -1345,6 +1345,9 @@ export default async function getBaseWebpackConfig(
webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
hashFunction: 'xxhash64',
hashDigestLength: 16,
// Webpack requires hashSalt to be a non-empty string; omit it entirely
// when no salt is configured.
...(config.hashSalt ? { hashSalt: config.hashSalt } : {}),
},
performance: false,
resolve: resolveConfig,
......@@ -1796,6 +1799,7 @@ export default async function getBaseWebpackConfig(
compilerType,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
hashSalt: config.hashSalt,
},
},
]
......
......@@ -10,16 +10,23 @@ interface Options {
isDev: boolean
assetPrefix: string
basePath: string
hashSalt: string
}
function nextImageLoader(this: any, content: Buffer) {
const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader')
return imageLoaderSpan.traceAsyncFn(async () => {
const options: Options = this.getOptions()
const { compilerType, isDev, assetPrefix, basePath } = options
const { compilerType, isDev, assetPrefix, basePath, hashSalt } = options
const context = this.rootContext
const opts = { context, content }
// Prepend the hash salt to the content for filename hash computation, so
// that NEXT_HASH_SALT causes image filenames to change (like it does for
// chunks). The actual file content is unaffected.
const contentForHash = hashSalt
? Buffer.concat([Buffer.from(hashSalt, 'utf8'), content])
: content
const opts = { context, content: contentForHash }
const interpolatedName = loaderUtils.interpolateName(
this,
'/static/media/[name].[hash:8].[ext]',
......
......@@ -188,6 +188,7 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
})
export const experimentalSchema = {
outputHashSalt: z.string().optional(),
useSkewCookie: z.boolean().optional(),
after: z.boolean().optional(),
appNavFailHandling: z.boolean().optional(),
......
......@@ -40,6 +40,9 @@ export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {
// since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't
// traverse into the output directory.
distDirRoot: string
// Pre-computed effective hash salt: experimental.outputHashSalt (from config)
// concatenated with NEXT_HASH_SALT (from env). Used by both Webpack and Turbopack.
hashSalt: string
}
export type I18NDomains = readonly DomainLocale[]
......@@ -393,6 +396,17 @@ export interface LightningCssFeatures {
}
export interface ExperimentalConfig {
/**
* A string that is incorporated into content-addressed output filenames
* (chunks, assets) for both Webpack and Turbopack. Changing this value
* forces all output hashes to change, which is useful for invalidating
* cached assets across deployments without modifying source files.
*
* When `NEXT_HASH_SALT` environment variable is also set, the two values are
* concatenated (`outputHashSalt + NEXT_HASH_SALT`) to form the effective salt.
*/
outputHashSalt?: string
appNewScrollHandler?: boolean
useSkewCookie?: boolean
/** @deprecated use top-level `cacheHandlers` instead */
......
......@@ -1455,6 +1455,10 @@ function assignDefaultsAndValidate(
// Store the distDirRoot in the config before it is modified for development mode
;(result as NextConfigComplete).distDirRoot = result.distDir
// Pre-compute the effective hash salt (used by both Webpack and Turbopack).
;(result as NextConfigComplete).hashSalt =
(result.experimental?.outputHashSalt ?? '') +
(process.env.NEXT_HASH_SALT ?? '')
if (phase === PHASE_DEVELOPMENT_SERVER) {
result.distDir = join(result.distDir, 'dev')
}
......
......@@ -417,6 +417,7 @@ export async function createHotReloaderTurbopack(
),
nextVersion: process.env.__NEXT_VERSION as string,
serverHmr: serverFastRefresh,
hashSalt: opts.nextConfig.hashSalt,
},
{
memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,
......
......@@ -233,6 +233,7 @@ async function main() {
currentNodeJsVersion: '18.0.0',
isPersistentCachingEnabled: false,
nextVersion: '0.0.0',
hashSalt: '',
});
const entrypointsSubscription = project.entrypointsSubscribe();
......@@ -393,6 +394,7 @@ describe('next.rs api', () => {
currentNodeJsVersion: '18.0.0',
isPersistentCachingEnabled: false,
nextVersion: '0.0.0',
hashSalt: '',
})
projectUpdateSubscription = filterMapAsyncIterator(
project.updateInfoSubscribe(1000),
......
import './globals.css'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Image from 'next/image'
import testPng from './test.png'
export default function Page() {
return (
<>
<p>hello world</p>
<Image src={testPng} alt="test" />
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import { readdir } from 'fs/promises'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
async function getFilenames(dir: string, ext: string): Promise<string[]> {
const entries: string[] = []
try {
for (const entry of await readdir(dir, { withFileTypes: true })) {
if (!entry.isDirectory() && entry.name.endsWith(ext)) {
entries.push(entry.name)
}
}
} catch {
// directory may not exist
}
return entries
}
describe('NEXT_HASH_SALT', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
const chunksDir = () => join(next.testDir, '.next/static/chunks')
const mediaDir = () => join(next.testDir, '.next/static/media')
// Turbopack places CSS in .next/static/chunks/ rather than .next/static/css/,
// so search the entire static tree for .css files.
const staticDir = () => join(next.testDir, '.next/static')
async function getCssFilenames(): Promise<string[]> {
try {
const paths = await recursiveReadDir(staticDir(), {
pathnameFilter: (f) => f.endsWith('.css'),
})
return paths.map((p) => p.replace(/.*[\\/]/, ''))
} catch {
return []
}
}
/** Build with the given salt and return { chunks, images, css } filename lists. */
async function buildWithSalt(salt: string) {
await next.build({ env: { NEXT_HASH_SALT: salt } })
const chunks = await getFilenames(chunksDir(), '.js')
const images = await getFilenames(mediaDir(), '.png')
const css = await getCssFilenames()
await next.clean()
return { chunks, images, css }
}
// Three builds: salt-a (twice for reproducibility check) and salt-b.
let saltAFirst: Awaited<ReturnType<typeof buildWithSalt>>
let saltASecond: Awaited<ReturnType<typeof buildWithSalt>>
let saltB: Awaited<ReturnType<typeof buildWithSalt>>
beforeAll(
async () => {
saltAFirst = await buildWithSalt('salt-a')
saltASecond = await buildWithSalt('salt-a')
saltB = await buildWithSalt('salt-b')
},
5 * 60 * 1000
)
it('should produce chunk files', () => {
expect(saltAFirst.chunks.length).toBeGreaterThan(0)
})
it('same salt produces identical chunk filenames', () => {
expect(saltAFirst.chunks.sort()).toEqual(saltASecond.chunks.sort())
})
it('different salt produces different chunk filenames', () => {
expect(saltAFirst.chunks.sort()).not.toEqual(saltB.chunks.sort())
})
it('should produce image files', () => {
expect(saltAFirst.images.length).toBeGreaterThan(0)
})
it('different salt produces different image filenames', () => {
expect(saltAFirst.images.sort()).not.toEqual(saltB.images.sort())
})
it('same salt produces identical image filenames', () => {
expect(saltAFirst.images.sort()).toEqual(saltASecond.images.sort())
})
it('should produce css files', () => {
expect(saltAFirst.css.length).toBeGreaterThan(0)
})
it('different salt produces different css filenames', () => {
expect(saltAFirst.css.sort()).not.toEqual(saltB.css.sort())
})
it('same salt produces identical css filenames', () => {
expect(saltAFirst.css.sort()).toEqual(saltASecond.css.sort())
})
})
describe('experimental.outputHashSalt', () => {
// Uses the fixture's next.config.js which reads OUTPUT_HASH_SALT_CONFIG from env,
// allowing multiple builds with different config salts from a single next instance.
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
const chunksDir = () => join(next.testDir, '.next/static/chunks')
async function buildWithSalts(opts: {
configSalt?: string
envSalt?: string
}) {
const env: Record<string, string> = {}
if (opts.configSalt) env.OUTPUT_HASH_SALT_CONFIG = opts.configSalt
if (opts.envSalt) env.NEXT_HASH_SALT = opts.envSalt
await next.build({ env })
const chunks = await getFilenames(chunksDir(), '.js')
await next.clean()
return chunks
}
let noSaltChunks: string[]
let configOnlyChunks: string[]
let envOnlyChunks: string[]
let bothChunks: string[]
beforeAll(
async () => {
noSaltChunks = await buildWithSalts({})
configOnlyChunks = await buildWithSalts({ configSalt: 'config-salt' })
envOnlyChunks = await buildWithSalts({ envSalt: 'env-salt' })
bothChunks = await buildWithSalts({
configSalt: 'config-salt',
envSalt: 'env-salt',
})
},
5 * 60 * 1000
)
it('config salt changes filenames compared to no salt', () => {
expect(configOnlyChunks.sort()).not.toEqual(noSaltChunks.sort())
})
it('combined salt differs from env-var-only salt', () => {
expect(bothChunks.sort()).not.toEqual(envOnlyChunks.sort())
})
it('combined salt differs from config-only salt', () => {
expect(bothChunks.sort()).not.toEqual(configOnlyChunks.sort())
})
})
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
// Allow tests to inject outputHashSalt via env var without touching source.
outputHashSalt: process.env.OUTPUT_HASH_SALT_CONFIG || undefined,
},
}
......@@ -2409,13 +2409,20 @@ impl FileContent {
Ok(Vc::cell(hash_xxh3_hash64(self)))
}
/// Compared to [FileContent::hash], this hashes only the bytes of the file content and nothing
/// else. If there is no file content, it returns `None`.
/// Compared to [FileContent::hash], this hashes only the bytes of the file content and
/// nothing else, returning `None` if the file does not exist.
///
/// If `salt` is non-empty it is written into the hasher before the file bytes in a single
/// pass. An empty salt produces the same result as hashing without a prefix.
#[turbo_tasks::function]
pub async fn content_hash(&self, algorithm: HashAlgorithm) -> Result<Vc<Option<RcStr>>> {
pub async fn content_hash(
&self,
salt: Vc<RcStr>,
algorithm: HashAlgorithm,
) -> Result<Vc<Option<RcStr>>> {
match self {
FileContent::Content(file) => Ok(Vc::cell(Some(
deterministic_hash(file.content().content_hash(), algorithm).into(),
deterministic_hash(&salt.await?, file.content().content_hash(), algorithm).into(),
))),
FileContent::NotFound => Ok(Vc::cell(None)),
}
......
......@@ -38,43 +38,42 @@ pub enum HashAlgorithm {
Sha512Base64,
}
pub fn deterministic_hash<T: DeterministicHash>(input: T, algorithm: HashAlgorithm) -> String {
/// Feed `salt` (if non-empty) then `input` into `hasher` in a single pass, then return it.
/// An empty salt writes zero bytes, which produces the same result as calling with no prefix.
fn feed<H: DeterministicHasher, T: DeterministicHash>(mut h: H, salt: &str, input: T) -> H {
h.write_bytes(salt.as_bytes());
input.deterministic_hash(&mut h);
h
}
/// Hash `input` with `algorithm`. If `salt` is non-empty it is written into
/// the hasher before the content so the two are mixed in a single pass —
/// never as a hash-of-hash composition. An empty salt produces the same
/// result as hashing without a prefix.
pub fn deterministic_hash<T: DeterministicHash>(
salt: &str,
input: T,
algorithm: HashAlgorithm,
) -> String {
// Each arm feeds salt+input into the appropriate hasher and encodes the output.
// The inherent finish() methods on the hasher types are used (not the trait method,
// which panics for 128-bit and SHA hashers).
match algorithm {
HashAlgorithm::Xxh3Hash64Hex => {
let mut hasher = Xxh3Hash64Hasher::new();
input.deterministic_hash(&mut hasher);
encode_hex(hasher.finish())
encode_hex(feed(Xxh3Hash64Hasher::new(), salt, &input).finish())
}
HashAlgorithm::Xxh3Hash128Hex => {
let mut hasher = Xxh3Hash128Hasher::new();
input.deterministic_hash(&mut hasher);
encode_hex_128(hasher.finish())
encode_hex_128(feed(Xxh3Hash128Hasher::new(), salt, &input).finish())
}
HashAlgorithm::Xxh3Hash64Base38 => {
let mut hasher = Xxh3Hash64Hasher::new();
input.deterministic_hash(&mut hasher);
encode_base38(hasher.finish())
encode_base38(feed(Xxh3Hash64Hasher::new(), salt, &input).finish())
}
HashAlgorithm::Xxh3Hash128Base38 => {
let mut hasher = Xxh3Hash128Hasher::new();
input.deterministic_hash(&mut hasher);
encode_base38_128(hasher.finish())
}
HashAlgorithm::Sha256Base64 => {
let mut hasher = ShaHasher::new_sha256();
input.deterministic_hash(&mut hasher);
hasher.finish_base64()
}
HashAlgorithm::Sha384Base64 => {
let mut hasher = ShaHasher::new_sha384();
input.deterministic_hash(&mut hasher);
hasher.finish_base64()
}
HashAlgorithm::Sha512Base64 => {
let mut hasher = ShaHasher::new_sha512();
input.deterministic_hash(&mut hasher);
hasher.finish_base64()
encode_base38_128(feed(Xxh3Hash128Hasher::new(), salt, &input).finish())
}
HashAlgorithm::Sha256Base64 => feed(ShaHasher::new_sha256(), salt, &input).finish_base64(),
HashAlgorithm::Sha384Base64 => feed(ShaHasher::new_sha384(), salt, &input).finish_base64(),
HashAlgorithm::Sha512Base64 => feed(ShaHasher::new_sha512(), salt, &input).finish_base64(),
}
}
......
......@@ -5,7 +5,7 @@ use turbo_tasks::{FxIndexMap, ResolvedVc, TaskInput, TryJoinIterExt, Upcast, Val
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::{
asset::Asset,
asset::{Asset, AssetContent},
chunk::{
AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule,
ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, EntryChunkGroupResult,
......@@ -219,6 +219,11 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn hash_salt(mut self, salt: ResolvedVc<RcStr>) -> Self {
self.chunking_context.hash_salt = salt;
self
}
pub fn build(self) -> Vc<BrowserChunkingContext> {
BrowserChunkingContext::cell(self.chunking_context)
}
......@@ -315,6 +320,8 @@ pub struct BrowserChunkingContext {
/// The global variable name used for chunk loading.
/// Default: "TURBOPACK"
chunk_loading_global: Option<RcStr>,
/// Salt mixed into chunk and asset content hashes. Empty string means no salt.
hash_salt: ResolvedVc<RcStr>,
}
impl BrowserChunkingContext {
......@@ -367,6 +374,7 @@ impl BrowserChunkingContext {
should_use_absolute_url_references: false,
worker_forwarded_globals: vec![],
chunk_loading_global: Default::default(),
hash_salt: ResolvedVc::cell(RcStr::default()),
},
}
}
......@@ -425,6 +433,7 @@ impl BrowserChunkingContext {
)
}
}
#[turbo_tasks::value_impl]
impl BrowserChunkingContext {
#[turbo_tasks::function]
......@@ -432,6 +441,11 @@ impl BrowserChunkingContext {
self.current_chunk_method.cell()
}
#[turbo_tasks::function]
pub fn hash_salt(&self) -> Vc<RcStr> {
*self.hash_salt
}
/// Returns the kind of runtime to include in output chunks.
///
/// This is defined directly on `BrowserChunkingContext` so it is zero-cost
......@@ -558,14 +572,13 @@ impl ChunkingContext for BrowserChunkingContext {
};
let hash = asset
.content()
.content_hash(HashAlgorithm::Xxh3Hash128Base38)
.content_hash(self.hash_salt(), HashAlgorithm::Xxh3Hash128Base38)
.await?;
let hash = hash.as_ref().context(
"chunk_path requires an asset with file content when content hashing is \
enabled",
)?;
let length = length as usize;
let hash = &hash[0..length];
let hash = &hash[..length as usize];
if let Some(prefix) = prefix {
format!("{prefix}-{hash}{extension}").into()
} else {
......@@ -624,16 +637,22 @@ impl ChunkingContext for BrowserChunkingContext {
#[turbo_tasks::function]
async fn asset_path(
&self,
content_hash: Vc<RcStr>,
self: Vc<Self>,
content: Vc<AssetContent>,
original_asset_ident: Vc<AssetIdent>,
tag: Option<RcStr>,
) -> Result<Vc<FileSystemPath>> {
let this = self.await?;
let source_path = original_asset_ident.path().await?;
let basename = source_path.file_name();
let content_hash = content_hash.await?;
let ContentHashing::Direct { length } = self.asset_content_hashing;
let short_hash = &content_hash[..length as usize];
let ContentHashing::Direct { length } = this.asset_content_hashing;
let hash = content
.content_hash(self.hash_salt(), HashAlgorithm::Xxh3Hash128Base38)
.await?;
let hash = hash
.as_ref()
.context("Missing content when trying to generate the content hash for static asset")?;
let short_hash = &hash[..length as usize];
let asset_path = match source_path.extension_ref() {
Some(ext) => format!(
"{basename}.{short_hash}.{ext}",
......@@ -644,8 +663,8 @@ impl ChunkingContext for BrowserChunkingContext {
let asset_root_path = tag
.as_ref()
.and_then(|tag| self.asset_root_paths.get(tag))
.unwrap_or(&self.asset_root_path);
.and_then(|tag| this.asset_root_paths.get(tag))
.unwrap_or(&this.asset_root_path);
Ok(asset_root_path.join(&asset_path)?.cell())
}
......
......@@ -8,6 +8,15 @@ use turbo_tasks_hash::{HashAlgorithm, Xxh3Hash64Hasher};
use crate::version::{VersionedAssetContent, VersionedContent};
/// Returns an empty salt `Vc<RcStr>` meaning "no salt applied to this hash".
///
/// Use this instead of `Vc::cell(RcStr::default())` at call sites that don't control the
/// hash salt — e.g. internal hashes not exposed to the user as filenames.
#[turbo_tasks::function]
pub fn no_hash_salt() -> Vc<RcStr> {
Vc::cell(RcStr::default())
}
/// A file or intermediate result containing content as a [`Rope`] or a symlink.
///
/// This is a supertrait for [`Source`], [`OutputAsset`], and [`OutputChunk`].
......@@ -27,10 +36,15 @@ pub trait Asset {
Ok(Vc::upcast(VersionedAssetContent::new(self.content())))
}
/// Hash of the content of the `Asset`.
/// Hash of the content of the `Asset`. If `salt` is non-empty it is mixed
/// into the hash in a single pass before the file bytes.
#[turbo_tasks::function]
fn content_hash(self: Vc<Self>, algorithm: HashAlgorithm) -> Vc<Option<RcStr>> {
self.content().content_hash(algorithm)
fn content_hash(
self: Vc<Self>,
salt: Vc<RcStr>,
algorithm: HashAlgorithm,
) -> Vc<Option<RcStr>> {
self.content().content_hash(salt, algorithm)
}
}
......@@ -130,12 +144,19 @@ impl AssetContent {
}
}
/// Compared to [AssetContent::hash], this hashes only the bytes of the file content and nothing
/// else. If there is no file content, it returns `None`.
/// Compared to [AssetContent::hash], this hashes only the bytes of the file content and
/// nothing else, returning `None` for redirects or missing files.
///
/// If `salt` is non-empty it is written into the hasher before the file bytes in a single
/// pass. An empty salt produces the same result as hashing without a prefix.
#[turbo_tasks::function]
pub async fn content_hash(&self, algorithm: HashAlgorithm) -> Result<Vc<Option<RcStr>>> {
pub async fn content_hash(
&self,
salt: Vc<RcStr>,
algorithm: HashAlgorithm,
) -> Result<Vc<Option<RcStr>>> {
match self {
AssetContent::File(content) => Ok(content.content_hash(algorithm)),
AssetContent::File(content) => Ok(content.content_hash(salt, algorithm)),
AssetContent::Redirect { .. } => Ok(Vc::cell(None)),
}
}
......
......@@ -10,7 +10,7 @@ use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::DeterministicHash;
use crate::{
asset::Asset,
asset::{Asset, AssetContent},
chunk::{
ChunkItem, ChunkType, ChunkableModule, availability_info::AvailabilityInfo,
chunk_id_strategy::ModuleIdStrategy,
......@@ -352,7 +352,7 @@ pub trait ChunkingContext {
#[turbo_tasks::function]
fn asset_path(
self: Vc<Self>,
content_hash: Vc<RcStr>,
content: Vc<AssetContent>,
original_asset_ident: Vc<AssetIdent>,
tag: Option<RcStr>,
) -> Vc<FileSystemPath>;
......
......@@ -8,7 +8,7 @@ use turbo_tasks::{
};
use turbo_tasks_hash::HashAlgorithm;
use crate::asset::AssetContent;
use crate::asset::{AssetContent, no_hash_salt};
#[turbo_tasks::value(transparent)]
pub struct OptionVersionedContent(Option<ResolvedVc<Box<dyn VersionedContent>>>);
......@@ -231,7 +231,7 @@ impl FileHashVersion {
match asset_content {
AssetContent::File(file_vc) => {
let hash = file_vc
.content_hash(HashAlgorithm::Xxh3Hash128Base38)
.content_hash(no_hash_salt(), HashAlgorithm::Xxh3Hash128Base38)
.owned()
.await?
.context("file not found")?;
......
......@@ -3,8 +3,9 @@ use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, TryJoinIterExt, Upcast, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::{
asset::Asset,
asset::{Asset, AssetContent},
chunk::{
AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule,
ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, EntryChunkGroupResult,
......@@ -162,6 +163,11 @@ impl NodeJsChunkingContextBuilder {
self
}
pub fn hash_salt(mut self, salt: ResolvedVc<RcStr>) -> Self {
self.chunking_context.hash_salt = salt;
self
}
/// Builds the chunking context.
pub fn build(self) -> Vc<NodeJsChunkingContext> {
NodeJsChunkingContext::cell(self.chunking_context)
......@@ -234,6 +240,8 @@ pub struct NodeJsChunkingContext {
worker_forwarded_globals: Vec<RcStr>,
/// Content hashing for asset filenames.
asset_content_hashing: ContentHashing,
/// Salt mixed into chunk and asset content hashes. Empty string means no salt.
hash_salt: ResolvedVc<RcStr>,
}
impl NodeJsChunkingContext {
......@@ -279,6 +287,7 @@ impl NodeJsChunkingContext {
debug_ids: false,
worker_forwarded_globals: vec![],
asset_content_hashing: ContentHashing::Direct { length: 13 },
hash_salt: ResolvedVc::cell(RcStr::default()),
},
}
}
......@@ -301,6 +310,11 @@ impl NodeJsChunkingContext {
self.minify_type.cell()
}
#[turbo_tasks::function]
pub fn hash_salt(&self) -> Vc<RcStr> {
*self.hash_salt
}
#[turbo_tasks::function]
pub fn asset_prefix(&self) -> Vc<Option<RcStr>> {
Vc::cell(self.asset_prefix.clone())
......@@ -462,16 +476,22 @@ impl ChunkingContext for NodeJsChunkingContext {
#[turbo_tasks::function]
async fn asset_path(
&self,
content_hash: Vc<RcStr>,
self: Vc<Self>,
content: Vc<AssetContent>,
original_asset_ident: Vc<AssetIdent>,
tag: Option<RcStr>,
) -> Result<Vc<FileSystemPath>> {
let this = self.await?;
let source_path = original_asset_ident.path().await?;
let basename = source_path.file_name();
let content_hash = content_hash.await?;
let ContentHashing::Direct { length } = self.asset_content_hashing;
let short_hash = &content_hash[..length as usize];
let ContentHashing::Direct { length } = this.asset_content_hashing;
let hash = content
.content_hash(self.hash_salt(), HashAlgorithm::Xxh3Hash128Base38)
.await?;
let hash = hash
.as_ref()
.context("Missing content when trying to generate the content hash for static asset")?;
let short_hash = &hash[..length as usize];
let asset_path = match source_path.extension_ref() {
Some(ext) => format!(
"{basename}.{short_hash}.{ext}",
......@@ -482,8 +502,8 @@ impl ChunkingContext for NodeJsChunkingContext {
let asset_root_path = tag
.as_ref()
.and_then(|tag| self.asset_root_paths.get(tag))
.unwrap_or(&self.asset_root_path);
.and_then(|tag| this.asset_root_paths.get(tag))
.unwrap_or(&this.asset_root_path);
Ok(asset_root_path.join(&asset_path)?.cell())
}
......
use anyhow::{Context, Result};
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::ChunkingContext,
......@@ -38,20 +36,12 @@ impl OutputAssetsReference for StaticOutputAsset {}
#[turbo_tasks::value_impl]
impl OutputAsset for StaticOutputAsset {
#[turbo_tasks::function]
async fn path(&self) -> Result<Vc<FileSystemPath>> {
let content = self.source.content();
let content_hash = content
.content_hash(HashAlgorithm::Xxh3Hash128Base38)
.owned()
.await?
.context(
"Missing content when trying to generate the content hash for StaticOutputAsset",
)?;
Ok(self.chunking_context.asset_path(
Vc::cell(content_hash),
fn path(&self) -> Vc<FileSystemPath> {
self.chunking_context.asset_path(
self.source.content(),
self.source.ident(),
self.tag.clone(),
))
)
}
}
......
......@@ -13,7 +13,7 @@ use anyhow::{Context, Result};
use turbo_rcstr::RcStr;
use turbo_tasks::Vc;
use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::asset::Asset;
use turbopack_core::asset::{Asset, no_hash_salt};
pub(crate) mod analysis;
pub(crate) mod loader;
......@@ -26,7 +26,7 @@ pub mod source;
pub async fn wasm_edge_var_name(asset: Vc<Box<dyn Asset>>) -> Result<Vc<RcStr>> {
let hash = asset
.content()
.content_hash(HashAlgorithm::Xxh3Hash128Hex)
.content_hash(no_hash_salt(), HashAlgorithm::Xxh3Hash128Hex)
.await?;
let hash = hash
.as_ref()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment