Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

web-crypto.ts

31 lines1.1 KB

1/**
2 * Web Crypto helpers for the Workers runtime, where `node:crypto` is
3 * unavailable. The sandbox layer's `timingSafeBearerEqual` is node-based; this
4 * is the equivalent for a Worker / Durable Object.
5 */
6​
7/**
8 * Constant-time check of an `Authorization: Bearer <token>` header against the
9 * expected token. A length mismatch returns false early (token length is not
10 * secret); the equal-length comparison is timing-safe.
11 */
12export function timingSafeBearerEqualWeb(
13 header: string | undefined,
14 token: string,
15): boolean {
16 if (header === undefined) return false
17 const a = new TextEncoder().encode(header)
18 const b = new TextEncoder().encode(`Bearer ${token}`)
19 if (a.length !== b.length) return false
20 let diff = 0
21 for (let i = 0; i < a.length; i += 1) {
22 const ai = a[i]
23 const bi = b[i]
24 // In-bounds by construction (i < a.length === b.length); the guard satisfies
25 // `noUncheckedIndexedAccess` without a non-null assertion and treats any
26 // impossible out-of-bounds read as "not equal".
27 if (ai === undefined || bi === undefined) return false
28 diff |= ai ^ bi
29 }
30 return diff === 0