From a8befb3b9d7a1eadfd9974d26f3102e4d6ed8879 Mon Sep 17 00:00:00 2001 From: Sohrab Chegini Date: Mon, 29 Apr 2024 18:31:33 +0330 Subject: [PATCH] `getDefaultDirectives` should do a deep copy See [#463] and [#465]. [#463]: https://github.com/helmetjs/helmet/issues/463 [#465]: https://github.com/helmetjs/helmet/pull/465 --- CHANGELOG.md | 1 + middlewares/content-security-policy/index.ts | 2 +- test/content-security-policy.test.ts | 10 ++++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c035acd..0b776e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - **Breaking:** `Strict-Transport-Security` now has a max-age of 365 days, up from 180 - **Breaking:** `Content-Security-Policy` middleware now throws an error if a directive should have quotes but does not, such as `self` instead of `'self'`. See [#454](https://github.com/helmetjs/helmet/issues/454) +- **Breaking:** `Content-Security-Policy`'s `getDefaultDirectives` now returns a deep copy. This only affects users who were mutating the result - **Breaking:** `Strict-Transport-Security` now throws an error when "includeSubDomains" option is misspelled. This was previously a warning ### Removed diff --git a/middlewares/content-security-policy/index.ts b/middlewares/content-security-policy/index.ts index d336631..38cc436 100644 --- a/middlewares/content-security-policy/index.ts +++ b/middlewares/content-security-policy/index.ts @@ -68,7 +68,7 @@ const SHOULD_BE_QUOTED: ReadonlySet = new Set([ "wasm-unsafe-eval", ]); -const getDefaultDirectives = () => ({ ...DEFAULT_DIRECTIVES }); +const getDefaultDirectives = () => structuredClone(DEFAULT_DIRECTIVES); const dashify = (str: string): string => str.replace(/[A-Z]/g, (capitalLetter) => "-" + capitalLetter.toLowerCase()); diff --git a/test/content-security-policy.test.ts b/test/content-security-policy.test.ts index 897c6af..b4fc44f 100644 --- a/test/content-security-policy.test.ts +++ b/test/content-security-policy.test.ts @@ -581,4 +581,14 @@ describe("getDefaultDirectives", () => { contentSecurityPolicy.getDefaultDirectives, ); }); + + it("returns a new copy each time", () => { + const one = getDefaultDirectives(); + one["worker-src"] = ["ignored.example"]; + (one["img-src"] as Array).push("ignored.example"); + + const two = getDefaultDirectives(); + expect(two).not.toHaveProperty("worker-src"); + expect(two["img-src"]).not.toContain("ignored.example"); + }); });