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
18 changes: 13 additions & 5 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,8 @@
"typescript-eslint": "8.72.1",
"vite": "8.3.6",
"vitest": "5.1.0"
},
"overrides": {
"minimatch": "11.0.8"
}
}
3 changes: 2 additions & 1 deletion frontend/src/components/forms/AccountForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { useId, useState, type FormEvent, type JSX } from "react";

import { useCrmApi } from "../../api/useCrmApi";
import { randomToken } from "../../lib/randomToken";
import type { Account } from "../../types/domain";
import { ErrorBanner } from "./ErrorBanner";

Expand Down Expand Up @@ -79,7 +80,7 @@ export function AccountForm({ initial, onSaved, onCancel }: AccountFormProps): J
region: values.region || undefined,
website: values.website || undefined,
employee_count: employeeCount,
transaction_key: `create-account-${Date.now()}-${Math.random().toString(36).slice(2)}`,
transaction_key: `create-account-${Date.now()}-${randomToken(11)}`,
});
const accountId = extractAccountId(response);
onSaved(accountId ?? "");
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/forms/ContactForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { useId, useState, type FormEvent, type JSX } from "react";

import { useCrmApi } from "../../api/useCrmApi";
import { randomToken } from "../../lib/randomToken";
import type { Contact, ContactStatus } from "../../types/domain";
import { ErrorBanner } from "./ErrorBanner";

Expand Down Expand Up @@ -86,7 +87,7 @@ export function ContactForm({
email: values.email || undefined,
phone: values.phone || undefined,
status: values.status,
transaction_key: `create-contact-${Date.now()}-${Math.random().toString(36).slice(2)}`,
transaction_key: `create-contact-${Date.now()}-${randomToken(11)}`,
});
const contactId = extractContactId(response);
onSaved(contactId ?? "");
Expand Down
7 changes: 1 addition & 6 deletions frontend/src/components/timeline/LogActivityForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,13 @@
import { useId, useState, type FormEvent, type JSX } from "react";

import { useCrmApi } from "../../api/useCrmApi";
import { newTransactionKey } from "../../lib/randomToken";
import { ACTIVITY_KINDS, type ActivityKind } from "../../types/domain";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { cn, focusRing } from "../ui/utils";
import { ApiErrorBanner } from "../../pages/opportunities/ApiErrorBanner";

function newTransactionKey(): string {
return typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `txn-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}

/** Field label styling, shared by every control on this form. */
const fieldLabel = "text-xs font-medium tracking-wide text-text-secondary";

Expand Down
14 changes: 14 additions & 0 deletions frontend/src/hooks/useAgentStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,20 @@ describe("newSessionId satisfies the runtimeSessionId bound", () => {
expect(id).not.toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-/);
});

it("pads the fallback from crypto.getRandomValues, never Math.random", () => {
const randomSpy = vi.spyOn(Math, "random");
try {
withoutRandomUUID(() => {
const cryptoSpy = vi.spyOn(globalThis.crypto, "getRandomValues");
newSessionId();
expect(cryptoSpy).toHaveBeenCalled();
});
expect(randomSpy).not.toHaveBeenCalled();
} finally {
randomSpy.mockRestore();
}
});

it("complies on the fallback path across many draws, not just one", () => {
// The fallback's random suffix varies in length, so the bound is checked over many draws.
const lengths = new Set<number>();
Expand Down
14 changes: 3 additions & 11 deletions frontend/src/hooks/useAgentStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { useCallback, useEffect, useRef, useState } from "react";

import type { AuthContextValue } from "../auth/AuthProvider";
import { buildRelayRequest, type RelayRequest } from "../lib/agentClient";
import { randomToken } from "../lib/randomToken";
import type { AgentEventFrame } from "../types/generated/agentEvents";

/** The closed set of event kinds this hook understands natively. */
Expand Down Expand Up @@ -178,15 +179,6 @@ const RECONNECT_BACKOFF_MS = 1000;
export const SESSION_ID_MIN_LENGTH = 33;
export const SESSION_ID_MAX_LENGTH = 256;

/** Base-36 randomness of exactly `length` characters, drawing again as needed. */
function randomBase36(length: number): string {
let out = "";
while (out.length < length) {
out += Math.random().toString(36).slice(2);
}
return out.slice(0, length);
}

/**
* A session id within {@link SESSION_ID_MIN_LENGTH} and {@link SESSION_ID_MAX_LENGTH}.
*
Expand All @@ -199,7 +191,7 @@ export function newSessionId(): string {
}
const prefix = `session-${Date.now()}-`;
const shortfall = Math.max(0, SESSION_ID_MIN_LENGTH - prefix.length);
return `${prefix}${randomBase36(Math.max(shortfall, 11))}`.slice(0, SESSION_ID_MAX_LENGTH);
return `${prefix}${randomToken(Math.max(shortfall, 11))}`.slice(0, SESSION_ID_MAX_LENGTH);
}

/**
Expand Down Expand Up @@ -325,7 +317,7 @@ export function useAgentStream(options: UseAgentStreamOptions): UseAgentStreamRe
];
const unrecognised = !knownKinds.includes(event.kind as KnownEventKind);
eventCountRef.current += 1;
const key = `evt-${eventCountRef.current}-${Math.random().toString(36).slice(2, 8)}`;
const key = `evt-${eventCountRef.current}-${randomToken(6)}`;
setTranscript((prev) => [...prev, { key, event, unrecognised }]);
if (event.kind === "completed" || event.kind === "error") {
setTurnEnded(true);
Expand Down
102 changes: 102 additions & 0 deletions frontend/src/lib/randomToken.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// SPDX-License-Identifier: MIT
// Tests for `lib/randomToken.ts`: exact length, base-36 alphabet, crypto-only randomness with
// rejection of biased bytes, input validation, and both `newTransactionKey` branches.
import { afterEach, describe, expect, it, vi } from "vitest";

import { newTransactionKey, randomToken } from "./randomToken";

const realCrypto = globalThis.crypto;

/** Replace the global `crypto` with one lacking `randomUUID`, keeping `getRandomValues`. */
function hideRandomUUID(): { getRandomValues: ReturnType<typeof vi.fn> } {
const getRandomValues = vi.fn(<T extends ArrayBufferView<ArrayBuffer>>(array: T): T =>
realCrypto.getRandomValues(array),
);
vi.stubGlobal("crypto", { getRandomValues });
return { getRandomValues };
}

afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});

describe("randomToken", () => {
it.each([1, 6, 11, 32, 200])("returns exactly %i characters", (length) => {
expect(randomToken(length)).toHaveLength(length);
});

it("uses only lowercase base-36 characters", () => {
expect(randomToken(2000)).toMatch(/^[0-9a-z]+$/);
});

it("produces distinct tokens across many draws", () => {
const tokens = new Set(Array.from({ length: 1000 }, () => randomToken(11)));
expect(tokens.size).toBe(1000);
});

it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])(
"throws RangeError for length %s",
(length) => {
expect(() => randomToken(length)).toThrow(RangeError);
},
);

it("uses crypto.getRandomValues, not Math.random", () => {
const randomSpy = vi.spyOn(Math, "random");
const cryptoSpy = vi.spyOn(globalThis.crypto, "getRandomValues");
randomToken(64);
expect(cryptoSpy).toHaveBeenCalled();
expect(randomSpy).not.toHaveBeenCalled();
});

it("rejects bytes >= 252 instead of mapping them", () => {
const batches = [
[252, 255, 253, 254, 0],
[1, 35, 251],
];
const getRandomValues = vi.fn(<T extends ArrayBufferView>(array: T): T => {
const view = array as unknown as Uint8Array;
view.fill(252);
view.set((batches.shift() ?? []).slice(0, view.length));
return array;
});
vi.stubGlobal("crypto", { getRandomValues });
expect(randomToken(4)).toBe("01zz");
});

it("resolves globalThis.crypto at call time", () => {
const { getRandomValues } = hideRandomUUID();
randomToken(8);
expect(getRandomValues).toHaveBeenCalled();
});

it("throws rather than degrading when Web Crypto is absent", () => {
vi.stubGlobal("crypto", undefined);
const randomSpy = vi.spyOn(Math, "random");
expect(() => randomToken(8)).toThrow();
expect(randomSpy).not.toHaveBeenCalled();
});
});

describe("newTransactionKey", () => {
it("returns crypto.randomUUID() when it is available", () => {
const uuidSpy = vi.spyOn(globalThis.crypto, "randomUUID");
const key = newTransactionKey();
expect(uuidSpy).toHaveBeenCalledOnce();
expect(key).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
});

it("falls back to txn-<ms>-<11 base-36> by default without randomUUID", () => {
const { getRandomValues } = hideRandomUUID();
const randomSpy = vi.spyOn(Math, "random");
expect(newTransactionKey()).toMatch(/^txn-\d+-[0-9a-z]{11}$/);
expect(getRandomValues).toHaveBeenCalled();
expect(randomSpy).not.toHaveBeenCalled();
});

it("uses an overriding prefix in the fallback", () => {
hideRandomUUID();
expect(newTransactionKey("tk")).toMatch(/^tk-\d+-[0-9a-z]{11}$/);
});
});
40 changes: 40 additions & 0 deletions frontend/src/lib/randomToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: MIT
/**
* Cryptographically random tokens and idempotency keys for the SPA.
*
* `randomToken(length)` draws from `globalThis.crypto.getRandomValues`, resolved on every call, and
* throws when no Web Crypto is present. `newTransactionKey(prefix)` prefers `crypto.randomUUID()`.
*/

const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
const UNBIASED_LIMIT = ALPHABET.length * Math.floor(256 / ALPHABET.length);

/** Lowercase base-36 token of exactly `length` characters from `crypto.getRandomValues`. */
export function randomToken(length: number): string {
if (!Number.isInteger(length) || length < 1) {
throw new RangeError(`randomToken length must be a positive integer, got ${length}`);
}
const crypto = globalThis.crypto;
let out = "";
while (out.length < length) {
const bytes = crypto.getRandomValues(new Uint8Array(length - out.length + 8));
for (const byte of bytes) {
if (byte >= UNBIASED_LIMIT) continue;
out += ALPHABET[byte % ALPHABET.length];
if (out.length === length) break;
}
}
return out;
}

/**
* An idempotency `transaction_key`: `crypto.randomUUID()` when available, otherwise
* `${prefix}-${Date.now()}-${randomToken(11)}`.
*/
export function newTransactionKey(prefix: string = "txn"): string {
const crypto = globalThis.crypto;
if (typeof crypto?.randomUUID === "function") {
return crypto.randomUUID();
}
return `${prefix}-${Date.now()}-${randomToken(11)}`;
}
49 changes: 49 additions & 0 deletions frontend/src/pages/activities/useActivities.transactionKey.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: MIT
/**
* Tests for the `transaction_key` that `useActivities` stamps on its mutating calls.
*/
import { afterEach, describe, expect, it, vi } from "vitest";

import { newTransactionKey } from "./useActivities";

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;

/** Hide `randomUUID`, the way an insecure context or an older browser does. */
function withoutRandomUUID<T>(body: () => T): T {
const original = globalThis.crypto;
vi.stubGlobal("crypto", { getRandomValues: original.getRandomValues.bind(original) });
try {
return body();
} finally {
vi.stubGlobal("crypto", original);
}
}

afterEach(() => {
vi.restoreAllMocks();
});

describe("useActivities newTransactionKey", () => {
it("is a UUID when crypto.randomUUID is available", () => {
expect(newTransactionKey()).toMatch(UUID);
});

it("falls back to a tk-prefixed crypto token when randomUUID is hidden", () => {
const key = withoutRandomUUID(() => newTransactionKey());

expect(key).toMatch(/^tk-\d+-[0-9a-z]{11}$/);
});

it("draws the fallback from crypto.getRandomValues, never Math.random", () => {
const randomSpy = vi.spyOn(Math, "random");
const keys = withoutRandomUUID(() => {
const cryptoSpy = vi.spyOn(globalThis.crypto, "getRandomValues");
const drawn = Array.from({ length: 50 }, () => newTransactionKey());
expect(cryptoSpy).toHaveBeenCalled();
return drawn;
});

expect(randomSpy).not.toHaveBeenCalled();
expect(new Set(keys).size).toBe(keys.length);
});
});
5 changes: 2 additions & 3 deletions frontend/src/pages/activities/useActivities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ import { useCallback, useEffect, useState } from "react";
import { useCrmApi } from "../../api/useCrmApi";
import { CrmApiError } from "../../api/CrmApiClient";
import { useReportView } from "../../components/AssistantPanel/useReportView";
import { newTransactionKey as transactionKeyWithPrefix } from "../../lib/randomToken";
import type { Activity, ActivityKind, Opportunity } from "../../types/domain";
import type { ListActivitiesResponse, LogActivityResponse } from "./types";

function newTransactionKey(): string {
return typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `tk-${Date.now()}-${Math.random().toString(36).slice(2)}`;
return transactionKeyWithPrefix("tk");
}

export interface UseActivitiesState {
Expand Down
10 changes: 2 additions & 8 deletions frontend/src/pages/approvals/transactionKey.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
// SPDX-License-Identifier: MIT
/**
* Generates a caller-supplied idempotency key (`transaction_key`) for a mutating call such as
* approve, reject or revert.
* approve, reject or revert: `crypto.randomUUID()`, else `txn-<ms>-<11 base-36>`.
*/
export function newTransactionKey(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
return crypto.randomUUID();
}
// Fallback for a test/JSDOM environment lacking `crypto.randomUUID`.
return `txn-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
export { newTransactionKey } from "../../lib/randomToken";
Loading
Loading