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: support output.trustedTypes.onPolicyCreationFailure #8619

Merged
merged 1 commit into from
Dec 4, 2024
Merged
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
1 change: 1 addition & 0 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2019,6 +2019,7 @@ export interface RawToOptions {

export interface RawTrustedTypes {
policyName?: string
onPolicyCreationFailure?: string
}

/**
Expand Down
9 changes: 8 additions & 1 deletion crates/rspack_binding_options/src/options/raw_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,26 @@ use napi::Either;
use napi_derive::napi;
use rspack_binding_values::library::JsLibraryOptions;
use rspack_binding_values::{JsCleanOptions, JsFilename};
use rspack_core::{CleanOptions, CrossOriginLoading, Environment, PathInfo};
use rspack_core::{
CleanOptions, CrossOriginLoading, Environment, OnPolicyCreationFailure, PathInfo,
};
use rspack_core::{OutputOptions, TrustedTypes};

#[derive(Debug)]
#[napi(object)]
pub struct RawTrustedTypes {
pub policy_name: Option<String>,
pub on_policy_creation_failure: Option<String>,
}

impl From<RawTrustedTypes> for TrustedTypes {
fn from(value: RawTrustedTypes) -> Self {
Self {
policy_name: value.policy_name,
on_policy_creation_failure: match value.on_policy_creation_failure {
Some(v) => OnPolicyCreationFailure::from(v),
None => OnPolicyCreationFailure::Stop,
},
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions crates/rspack_core/src/options/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,26 @@ impl From<&OutputOptions> for RspackHash {
}
}

#[derive(Debug)]
pub enum OnPolicyCreationFailure {
Continue,
Stop,
}

impl From<String> for OnPolicyCreationFailure {
fn from(value: String) -> Self {
if value == "continue" {
Self::Continue
} else {
Self::Stop
}
}
}

#[derive(Debug)]
pub struct TrustedTypes {
pub policy_name: Option<String>,
pub on_policy_creation_failure: OnPolicyCreationFailure,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use rspack_collections::Identifier;
use rspack_core::{
impl_runtime_module,
rspack_sources::{BoxSource, RawSource, SourceExt},
ChunkUkey, Compilation, RuntimeGlobals, RuntimeModule,
ChunkUkey, Compilation, OnPolicyCreationFailure, RuntimeGlobals, RuntimeModule,
};

use crate::get_chunk_runtime_requirements;
Expand Down Expand Up @@ -40,6 +40,10 @@ impl RuntimeModule for GetTrustedTypesPolicyRuntimeModule {
get_chunk_runtime_requirements(compilation, &self.chunk.expect("should have chunk"));
let create_script = runtime_requirements.contains(RuntimeGlobals::CREATE_SCRIPT);
let create_script_url = runtime_requirements.contains(RuntimeGlobals::CREATE_SCRIPT_URL);
let wrap_policy_creation_in_try_catch = matches!(
trusted_types.on_policy_creation_failure,
OnPolicyCreationFailure::Continue
);

let result = include_str!("runtime/get_trusted_types_policy.js").cow_replace(
"$policyName$",
Expand All @@ -66,10 +70,36 @@ impl RuntimeModule for GetTrustedTypesPolicyRuntimeModule {
.to_string(),
);
}
let wrap_policy_creation_try_catch_start = if wrap_policy_creation_in_try_catch {
"try {"
} else {
""
};
let wrap_policy_creation_try_catch_end = if wrap_policy_creation_in_try_catch {
format!(
r#"
}} catch (e) {{
console.warn('Could not create trusted-types policy {}');
}}
"#,
serde_json::to_string(&trusted_types.policy_name.clone().unwrap_or_default())
.expect("invalid json to_string"),
)
} else {
"".to_string()
};
Ok(
RawSource::from(
result
.cow_replace("$policyContent$", policy_content.join(",\n").as_ref())
.cow_replace(
"$wrapPolicyCreationTryCatchStart$",
wrap_policy_creation_try_catch_start,
)
.cow_replace(
"$wrapPolicyCreationTryCatchEnd$",
&wrap_policy_creation_try_catch_end,
)
.into_owned(),
)
.boxed(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ __webpack_require__.tt = function () {
$policyContent$
};
if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {
$wrapPolicyCreationTryCatchStart$
policy = trustedTypes.createPolicy("$policyName$", policy);
$wrapPolicyCreationTryCatchEnd$
}
}
return policy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ module.exports = {
- "trustedTypes": undefined,
- "uniqueName": "@rspack/test-tools",
+ "trustedTypes": Object {
+ "onPolicyCreationFailure": "stop",
+ "policyName": "@@@Hello_World_",
+ },
+ "uniqueName": "@@@Hello World!",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** @type {import("@rspack/core").Configuration} */
module.exports = {
entry: {
bundle: {
import: "./src/index",
chunkLoading: "import-scripts"
}
},
output: {
trustedTypes: {
policyName: "my-application#webpack",
onPolicyCreationFailure: "continue"
}
},
target: "web"
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default 42;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import(/* webpackChunkName: "chunk" */ "./chunk");
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** @type {import("../../..").TDiffCaseConfig} */
module.exports = {
modules: false,
runtimeModules: ["webpack/runtime/get_trusted_types_policy"]
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** @type {import("webpack").Configuration} */
module.exports = {
entry: {
bundle: {
import: "./src/index",
chunkLoading: "import-scripts"
}
},
output: {
trustedTypes: {
policyName: "my-application#webpack",
onPolicyCreationFailure: "continue"
}
},
target: "web"
};
8 changes: 8 additions & 0 deletions packages/rspack/etc/core.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5857,10 +5857,13 @@ export const rspackOptions: z.ZodObject<{
enabledChunkLoadingTypes: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodEnum<["jsonp", "import-scripts", "require", "async-node", "import"]>, z.ZodString]>, "many">>;
trustedTypes: z.ZodOptional<z.ZodUnion<[z.ZodUnion<[z.ZodLiteral<true>, z.ZodString]>, z.ZodObject<{
policyName: z.ZodOptional<z.ZodString>;
onPolicyCreationFailure: z.ZodOptional<z.ZodEnum<["continue", "stop"]>>;
}, "strict", z.ZodTypeAny, {
policyName?: string | undefined;
onPolicyCreationFailure?: "continue" | "stop" | undefined;
}, {
policyName?: string | undefined;
onPolicyCreationFailure?: "continue" | "stop" | undefined;
}>]>>;
sourceMapFilename: z.ZodOptional<z.ZodString>;
hashDigest: z.ZodOptional<z.ZodString>;
Expand Down Expand Up @@ -6003,6 +6006,7 @@ export const rspackOptions: z.ZodObject<{
enabledChunkLoadingTypes?: string[] | undefined;
trustedTypes?: string | true | {
policyName?: string | undefined;
onPolicyCreationFailure?: "continue" | "stop" | undefined;
} | undefined;
sourceMapFilename?: string | undefined;
hashDigest?: string | undefined;
Expand Down Expand Up @@ -6101,6 +6105,7 @@ export const rspackOptions: z.ZodObject<{
enabledChunkLoadingTypes?: string[] | undefined;
trustedTypes?: string | true | {
policyName?: string | undefined;
onPolicyCreationFailure?: "continue" | "stop" | undefined;
} | undefined;
sourceMapFilename?: string | undefined;
hashDigest?: string | undefined;
Expand Down Expand Up @@ -8677,6 +8682,7 @@ export const rspackOptions: z.ZodObject<{
enabledChunkLoadingTypes?: string[] | undefined;
trustedTypes?: string | true | {
policyName?: string | undefined;
onPolicyCreationFailure?: "continue" | "stop" | undefined;
} | undefined;
sourceMapFilename?: string | undefined;
hashDigest?: string | undefined;
Expand Down Expand Up @@ -9302,6 +9308,7 @@ export const rspackOptions: z.ZodObject<{
enabledChunkLoadingTypes?: string[] | undefined;
trustedTypes?: string | true | {
policyName?: string | undefined;
onPolicyCreationFailure?: "continue" | "stop" | undefined;
} | undefined;
sourceMapFilename?: string | undefined;
hashDigest?: string | undefined;
Expand Down Expand Up @@ -10925,6 +10932,7 @@ type TransformEffect<T> = {
// @public
export type TrustedTypes = {
policyName?: string;
onPolicyCreationFailure?: "continue" | "stop";
};

// @public (undocumented)
Expand Down
1 change: 1 addition & 0 deletions packages/rspack/src/config/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@ const applyOutputDefaults = (
() =>
output.uniqueName!.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack"
);
D(trustedTypes, "onPolicyCreationFailure", "stop");
}

const forEachEntry = (fn: (desc: EntryDescriptionNormalized) => void) => {
Expand Down
7 changes: 7 additions & 0 deletions packages/rspack/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,14 @@ export type WorkerPublicPath = string;

/** Controls [Trusted Types](https://web.dev/articles/trusted-types) compatibility. */
export type TrustedTypes = {
/**
* The name of the Trusted Types policy created by webpack to serve bundle chunks.
*/
policyName?: string;
/**
* If the call to `trustedTypes.createPolicy(...)` fails -- e.g., due to the policy name missing from the CSP `trusted-types` list, or it being a duplicate name, etc. -- controls whether to continue with loading in the hope that `require-trusted-types-for 'script'` isn't enforced yet, versus fail immediately. Default behavior is 'stop'.
*/
onPolicyCreationFailure?: "continue" | "stop";
};

/** The encoding to use when generating the hash. */
Expand Down
3 changes: 2 additions & 1 deletion packages/rspack/src/config/zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ const chunkFormat = z
const workerPublicPath = z.string() satisfies z.ZodType<t.WorkerPublicPath>;

const trustedTypes = z.strictObject({
policyName: z.string().optional()
policyName: z.string().optional(),
onPolicyCreationFailure: z.enum(["continue", "stop"]).optional()
}) satisfies z.ZodType<t.TrustedTypes>;

const hashDigest = z.string() satisfies z.ZodType<t.HashDigest>;
Expand Down
22 changes: 22 additions & 0 deletions website/docs/en/config/output.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1703,6 +1703,28 @@ module.exports = {
};
```

### output.trustedTypes.onPolicyCreationFailure

<ApiMeta addedVersion={'1.1.6'} />

- **Type:** `"stop" | "continue"`
- **Default:** `"stop"`

Determine whether to proceed with loading in anticipation that [`require-trusted-types-for 'script'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) has not been enforced or to immediately fail when the call to `trustedTypes.createPolicy(...)` fails due to the policy name being absent from the CSP `trusted-types` list or being a duplicate.

```js title="rspack.config.js"
module.exports = {
//...
output: {
//...
trustedTypes: {
policyName: 'my-application#webpack',
onPolicyCreationFailure: 'continue',
},
},
};
```

## output.uniqueName

- **Type:** `string`
Expand Down
22 changes: 22 additions & 0 deletions website/docs/zh/config/output.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1695,6 +1695,28 @@ module.exports = {
};
```

### output.trustedTypes.onPolicyCreationFailure

<ApiMeta addedVersion={'1.1.6'} />

- **类型:** `"stop" | "continue"`
- **默认值:** `"stop"`

确定当 [`require-trusted-types-for 'script'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) 未能正确执行时,是继续加载还是异常终止。未能正确执行可能是由于策略名称不在 CSP 的 `trusted-types` 列表中或策略名称重复而使得 `trustedTypes.createPolicy(...)` 执行失败。

```js title="rspack.config.js"
module.exports = {
//...
output: {
//...
trustedTypes: {
policyName: 'my-application#webpack',
onPolicyCreationFailure: 'continue',
},
},
};
```

## output.uniqueName

- **类型:** `string`
Expand Down
Loading