From f43935a7980878bba6623008115a05251cd2bd7c 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 --- middlewares/content-security-policy/index.ts | 2 +- test/content-security-policy.test.ts | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) 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"); + }); });