Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/portable-http-helmet-nonce.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@mcansh/http-helmet": patch
---

Remove the Node.js Buffer dependency from createNonce by using native Uint8Array Base64 encoding when available, with a btoa fallback for older runtimes.
47 changes: 47 additions & 0 deletions packages/http-helmet/src/nonce.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { expect, it, vi } from "vitest";

import { createNonce } from "./index.ts";

it("generates distinct base64-encoded UUID nonces", () => {
let first = createNonce();
let second = createNonce();
expect(first).not.toBe(second);
expect(atob(first)).toMatch(
/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,
);
});

it.each([true, false])(
"encodes a nonce with toBase64 available: %s",
(available) => {
let uuid = "00000000-0000-4000-8000-000000000000" as const;
let original = Object.getOwnPropertyDescriptor(
Uint8Array.prototype,
"toBase64",
);
let toBase64 = vi.fn(function (this: Uint8Array) {
return btoa(String.fromCharCode(...this));
});
Object.defineProperty(Uint8Array.prototype, "toBase64", {
configurable: true,
value: available ? toBase64 : undefined,
});
let encode = vi.spyOn(TextEncoder.prototype, "encode");
let randomUUID = vi.spyOn(crypto, "randomUUID").mockReturnValue(uuid);

try {
expect(createNonce()).toBe(btoa(uuid));
expect(encode).toHaveBeenCalledTimes(available ? 1 : 0);
if (available) expect(encode).toHaveBeenCalledWith(uuid);
expect(toBase64).toHaveBeenCalledTimes(available ? 1 : 0);
} finally {
encode.mockRestore();
randomUUID.mockRestore();
if (original) {
Object.defineProperty(Uint8Array.prototype, "toBase64", original);
} else {
Reflect.deleteProperty(Uint8Array.prototype, "toBase64");
}
}
},
);
10 changes: 9 additions & 1 deletion packages/http-helmet/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,13 @@ export function mergeHeaders(...sources: HeadersInit[]): Headers {
}

export function createNonce(): string {
return Buffer.from(crypto.randomUUID()).toString("base64");
let uuid = crypto.randomUUID();
// SAFETY: This standard method is optional on older runtimes and checked before calling.
let toBase64 = (
Uint8Array.prototype as Uint8Array & { toBase64?: () => string }
).toBase64;

return typeof toBase64 === "function"
? toBase64.call(new TextEncoder().encode(uuid))
: btoa(uuid);
}
Loading