-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathauth.ts
More file actions
29 lines (27 loc) · 1.02 KB
/
auth.ts
File metadata and controls
29 lines (27 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const _textEncoder = new TextEncoder();
/**
* Constant-time string comparison to prevent timing attacks.
* Uses UTF-8 byte comparison for proper Unicode handling.
* Always compares all bytes regardless of where differences occur.
*/
export function timingSafeEqual(a: string, b: string): boolean {
const aBuf = _textEncoder.encode(a);
const bBuf = _textEncoder.encode(b);
const aLen = aBuf.length;
const bLen = bBuf.length;
// Always compare against the longer buffer length to avoid length-based timing leaks
const len = Math.max(aLen, bLen);
let result = aLen === bLen ? 0 : 1;
for (let i = 0; i < len; i++) {
// Use bitwise XOR to compare bytes; accumulate differences with OR
result |= (aBuf[i % aLen] ?? 0) ^ (bBuf[i % bLen] ?? 0);
}
return result === 0;
}
/**
* Add random delay (0-100ms) to prevent timing-based credential inference.
*/
export function randomJitter(): Promise<void> {
const jitter = Math.floor(Math.random() * 100);
return new Promise((resolve) => setTimeout(resolve, jitter));
}