feat(auth): harden OAuth state generation and callback validation (closes #1562)

generateOAuthState() now throws when crypto.getRandomValues is unavailable
instead of silently degrading to a non-cryptographic Math.random() fallback —
OAuth state is a CSRF token and must be unpredictable.

The web /oauth/callback handler now rejects a returned `state` param that does
not parse to the expected 64-char-hex authId shape (a forgery indicator),
surfacing a clear error toast instead of proceeding with an undefined session.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S3fTN8H3R8YV4yUGvZjYnX
This commit is contained in:
cliffhall 2026-07-01 18:23:38 -04:00
commit 2b84281346

View file

@ -1,4 +1,4 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, afterEach } from "vitest";
import {
parseHttpUrl,
parseOAuthCallbackParams,
@ -51,6 +51,17 @@ describe("parseOAuthCallbackParams", () => {
});
describe("generateOAuthState", () => {
const originalCrypto = globalThis.crypto;
afterEach(() => {
// Restore the real WebCrypto after tests that stub/remove it.
Object.defineProperty(globalThis, "crypto", {
configurable: true,
writable: true,
value: originalCrypto,
});
});
it("should generate 64-char hex state", () => {
const state = generateOAuthState();
expect(state).toMatch(/^[a-f0-9]{64}$/i);
@ -61,6 +72,31 @@ describe("generateOAuthState", () => {
const s2 = generateOAuthState();
expect(s1).not.toBe(s2);
});
it("throws when the crypto global is entirely absent (no silent Math.random fallback)", () => {
// Simulate an exotic runtime with no WebCrypto at all. Rather than minting
// a guessable CSRF token, generateOAuthState must fail loudly.
Object.defineProperty(globalThis, "crypto", {
configurable: true,
writable: true,
value: undefined,
});
expect(() => generateOAuthState()).toThrow(
/crypto\.getRandomValues is not available/,
);
});
it("throws when crypto.getRandomValues is missing", () => {
// crypto exists but lacks getRandomValues — still refuse to degrade.
Object.defineProperty(globalThis, "crypto", {
configurable: true,
writable: true,
value: {},
});
expect(() => generateOAuthState()).toThrow(
/crypto\.getRandomValues is not available/,
);
});
});
describe("parseOAuthState", () => {