@workos/authkit-session 0.3.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -27
- package/dist/core/AuthKitCore.d.ts +20 -0
- package/dist/core/AuthKitCore.d.ts.map +1 -1
- package/dist/core/AuthKitCore.js +36 -4
- package/dist/core/AuthKitCore.js.map +1 -1
- package/dist/core/client/types.d.ts.map +1 -1
- package/dist/core/encryption/ironWebcryptoEncryption.d.ts +2 -1
- package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
- package/dist/core/encryption/ironWebcryptoEncryption.js +2 -2
- package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
- package/dist/core/errors.d.ts +9 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +18 -0
- package/dist/core/errors.js.map +1 -1
- package/dist/core/pkce/cookieOptions.d.ts +36 -0
- package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
- package/dist/core/pkce/cookieOptions.js +55 -0
- package/dist/core/pkce/cookieOptions.js.map +1 -0
- package/dist/core/pkce/generateAuthorizationUrl.d.ts +45 -0
- package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
- package/dist/core/pkce/generateAuthorizationUrl.js +82 -0
- package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
- package/dist/core/pkce/state.d.ts +53 -0
- package/dist/core/pkce/state.d.ts.map +1 -0
- package/dist/core/pkce/state.js +91 -0
- package/dist/core/pkce/state.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts +25 -15
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
- package/dist/core/session/CookieSessionStorage.js +20 -27
- package/dist/core/session/CookieSessionStorage.js.map +1 -1
- package/dist/core/session/TokenManager.js +2 -2
- package/dist/core/session/TokenManager.js.map +1 -1
- package/dist/core/session/serializeCookie.d.ts +13 -0
- package/dist/core/session/serializeCookie.d.ts.map +1 -0
- package/dist/core/session/serializeCookie.js +32 -0
- package/dist/core/session/serializeCookie.js.map +1 -0
- package/dist/core/session/types.d.ts +71 -2
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/operations/AuthOperations.d.ts +15 -13
- package/dist/operations/AuthOperations.d.ts.map +1 -1
- package/dist/operations/AuthOperations.js +22 -34
- package/dist/operations/AuthOperations.js.map +1 -1
- package/dist/service/AuthService.d.ts +58 -15
- package/dist/service/AuthService.d.ts.map +1 -1
- package/dist/service/AuthService.js +157 -71
- package/dist/service/AuthService.js.map +1 -1
- package/dist/service/factory.d.ts.map +1 -1
- package/dist/service/factory.js +4 -3
- package/dist/service/factory.js.map +1 -1
- package/dist/utils.d.ts +16 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +23 -0
- package/dist/utils.js.map +1 -1
- package/package.json +35 -29
- package/src/core/AuthKitCore.spec.ts +109 -0
- package/src/core/AuthKitCore.ts +55 -4
- package/src/core/client/types.ts +3 -6
- package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
- package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
- package/src/core/errors.spec.ts +33 -142
- package/src/core/errors.ts +21 -0
- package/src/core/pkce/cookieOptions.spec.ts +144 -0
- package/src/core/pkce/cookieOptions.ts +64 -0
- package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
- package/src/core/pkce/pkce.spec.ts +166 -0
- package/src/core/pkce/state.spec.ts +216 -0
- package/src/core/pkce/state.ts +120 -0
- package/src/core/session/CookieSessionStorage.spec.ts +79 -3
- package/src/core/session/CookieSessionStorage.ts +60 -39
- package/src/core/session/TokenManager.ts +2 -2
- package/src/core/session/serializeCookie.ts +33 -0
- package/src/core/session/types.ts +79 -2
- package/src/index.ts +3 -0
- package/src/operations/AuthOperations.spec.ts +107 -62
- package/src/operations/AuthOperations.ts +34 -40
- package/src/service/AuthService.spec.ts +615 -98
- package/src/service/AuthService.ts +198 -73
- package/src/service/factory.spec.ts +4 -3
- package/src/service/factory.ts +6 -3
- package/src/utils.ts +22 -0
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import type { WorkOS } from '@workos-inc/node';
|
|
2
2
|
import { AuthKitCore } from '../core/AuthKitCore.js';
|
|
3
3
|
import type { AuthKitConfig } from '../core/config/types.js';
|
|
4
|
+
import {
|
|
5
|
+
getPKCECookieOptions,
|
|
6
|
+
PKCE_COOKIE_NAME,
|
|
7
|
+
} from '../core/pkce/cookieOptions.js';
|
|
4
8
|
import { AuthOperations } from '../operations/AuthOperations.js';
|
|
5
9
|
import type {
|
|
6
10
|
AuthResult,
|
|
11
|
+
CreateAuthorizationResult,
|
|
7
12
|
CustomClaims,
|
|
8
13
|
GetAuthorizationUrlOptions,
|
|
9
14
|
HeadersBag,
|
|
@@ -12,6 +17,39 @@ import type {
|
|
|
12
17
|
SessionStorage,
|
|
13
18
|
} from '../core/session/types.js';
|
|
14
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Merge two `HeadersBag` values. `Set-Cookie` matching is case-insensitive;
|
|
22
|
+
* existing key casing is preserved. Multiple `Set-Cookie` values are
|
|
23
|
+
* concatenated into a `string[]`. Other keys are shallow-merged (second wins).
|
|
24
|
+
*/
|
|
25
|
+
function mergeHeaderBags(
|
|
26
|
+
a: HeadersBag | undefined,
|
|
27
|
+
b: HeadersBag | undefined,
|
|
28
|
+
): HeadersBag | undefined {
|
|
29
|
+
if (!a) return b;
|
|
30
|
+
if (!b) return a;
|
|
31
|
+
const merged: HeadersBag = { ...a };
|
|
32
|
+
let setCookieKey = Object.keys(merged).find(
|
|
33
|
+
k => k.toLowerCase() === 'set-cookie',
|
|
34
|
+
);
|
|
35
|
+
for (const [key, value] of Object.entries(b)) {
|
|
36
|
+
if (key.toLowerCase() !== 'set-cookie') {
|
|
37
|
+
merged[key] = value;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (!setCookieKey) {
|
|
41
|
+
merged[key] = value;
|
|
42
|
+
setCookieKey = key;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const left = merged[setCookieKey]!;
|
|
46
|
+
const leftArr = Array.isArray(left) ? left : [left];
|
|
47
|
+
const rightArr = Array.isArray(value) ? value : [value];
|
|
48
|
+
merged[setCookieKey] = [...leftArr, ...rightArr];
|
|
49
|
+
}
|
|
50
|
+
return merged;
|
|
51
|
+
}
|
|
52
|
+
|
|
15
53
|
/**
|
|
16
54
|
* Framework-agnostic authentication service.
|
|
17
55
|
*
|
|
@@ -23,7 +61,7 @@ import type {
|
|
|
23
61
|
* Provides common patterns:
|
|
24
62
|
* - `withAuth()` - Validate session with auto-refresh
|
|
25
63
|
* - `handleCallback()` - Process OAuth callback
|
|
26
|
-
* - `signOut()`, `
|
|
64
|
+
* - `signOut()`, `createSignIn()`, etc. - Delegate to AuthOperations
|
|
27
65
|
*
|
|
28
66
|
* **Used by:** @workos/authkit-tanstack-react-start
|
|
29
67
|
*/
|
|
@@ -44,7 +82,7 @@ export class AuthService<TRequest, TResponse> {
|
|
|
44
82
|
this.storage = storage;
|
|
45
83
|
this.client = client;
|
|
46
84
|
this.core = new AuthKitCore(config, client, encryption);
|
|
47
|
-
this.operations = new AuthOperations(this.core, client, config);
|
|
85
|
+
this.operations = new AuthOperations(this.core, client, config, encryption);
|
|
48
86
|
}
|
|
49
87
|
|
|
50
88
|
/**
|
|
@@ -179,28 +217,75 @@ export class AuthService<TRequest, TResponse> {
|
|
|
179
217
|
}
|
|
180
218
|
|
|
181
219
|
/**
|
|
182
|
-
*
|
|
220
|
+
* Create an authorization URL and write the PKCE verifier cookie.
|
|
221
|
+
*
|
|
222
|
+
* @param response - Framework-specific response object (may be undefined —
|
|
223
|
+
* adapters that mutate responses in-place will get back a mutated copy).
|
|
224
|
+
* @param options - screenHint, returnPathname, custom state, redirectUri, etc.
|
|
225
|
+
* @returns The URL to redirect the browser to, plus storage's
|
|
226
|
+
* `{ response?, headers? }` carrying the verifier `Set-Cookie`.
|
|
183
227
|
*/
|
|
184
|
-
async
|
|
185
|
-
|
|
228
|
+
async createAuthorization(
|
|
229
|
+
response: TResponse | undefined,
|
|
230
|
+
options: GetAuthorizationUrlOptions = {},
|
|
231
|
+
): Promise<CreateAuthorizationResult<TResponse>> {
|
|
232
|
+
const { url, sealedState, cookieOptions } =
|
|
233
|
+
await this.operations.createAuthorization(options);
|
|
234
|
+
const write = await this.storage.setCookie(
|
|
235
|
+
response,
|
|
236
|
+
PKCE_COOKIE_NAME,
|
|
237
|
+
sealedState,
|
|
238
|
+
cookieOptions,
|
|
239
|
+
);
|
|
240
|
+
return { url, ...write };
|
|
186
241
|
}
|
|
187
242
|
|
|
188
243
|
/**
|
|
189
|
-
* Convenience:
|
|
244
|
+
* Convenience: Create sign-in URL and write the PKCE verifier cookie.
|
|
190
245
|
*/
|
|
191
|
-
async
|
|
246
|
+
async createSignIn(
|
|
247
|
+
response: TResponse | undefined,
|
|
192
248
|
options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
|
|
193
|
-
) {
|
|
194
|
-
return this.
|
|
249
|
+
): Promise<CreateAuthorizationResult<TResponse>> {
|
|
250
|
+
return this.createAuthorization(response, {
|
|
251
|
+
...options,
|
|
252
|
+
screenHint: 'sign-in',
|
|
253
|
+
});
|
|
195
254
|
}
|
|
196
255
|
|
|
197
256
|
/**
|
|
198
|
-
* Convenience:
|
|
257
|
+
* Convenience: Create sign-up URL and write the PKCE verifier cookie.
|
|
199
258
|
*/
|
|
200
|
-
async
|
|
259
|
+
async createSignUp(
|
|
260
|
+
response: TResponse | undefined,
|
|
201
261
|
options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
|
|
202
|
-
) {
|
|
203
|
-
return this.
|
|
262
|
+
): Promise<CreateAuthorizationResult<TResponse>> {
|
|
263
|
+
return this.createAuthorization(response, {
|
|
264
|
+
...options,
|
|
265
|
+
screenHint: 'sign-up',
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Emit a `Set-Cookie` header that clears the PKCE verifier cookie.
|
|
271
|
+
*
|
|
272
|
+
* Use on any exit path where a sign-in was started (verifier cookie
|
|
273
|
+
* written) but `handleCallback` will not run to clear it — OAuth error
|
|
274
|
+
* responses, missing `code`, early bail-outs.
|
|
275
|
+
*
|
|
276
|
+
* Pass `options.redirectUri` on requests that used a per-request
|
|
277
|
+
* `redirectUri` override at sign-in time, so the delete cookie's computed
|
|
278
|
+
* attributes (notably `secure`) match what was originally set.
|
|
279
|
+
*/
|
|
280
|
+
async clearPendingVerifier(
|
|
281
|
+
response: TResponse | undefined,
|
|
282
|
+
options?: Pick<GetAuthorizationUrlOptions, 'redirectUri'>,
|
|
283
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
284
|
+
return this.storage.clearCookie(
|
|
285
|
+
response,
|
|
286
|
+
PKCE_COOKIE_NAME,
|
|
287
|
+
getPKCECookieOptions(this.config, options?.redirectUri),
|
|
288
|
+
);
|
|
204
289
|
}
|
|
205
290
|
|
|
206
291
|
/**
|
|
@@ -213,76 +298,116 @@ export class AuthService<TRequest, TResponse> {
|
|
|
213
298
|
|
|
214
299
|
/**
|
|
215
300
|
* Handle OAuth callback.
|
|
216
|
-
* This creates a new session after successful authentication.
|
|
217
301
|
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
*
|
|
302
|
+
* Reads the verifier cookie via storage, verifies it against the URL
|
|
303
|
+
* `state`, exchanges the code, saves the session, and — on success —
|
|
304
|
+
* also emits a verifier-delete `Set-Cookie` so `HeadersBag['Set-Cookie']`
|
|
305
|
+
* carries both entries as a `string[]`. Adapters MUST append each
|
|
306
|
+
* `Set-Cookie` as its own header (never comma-join).
|
|
307
|
+
*
|
|
308
|
+
* Error-path cleanup: if any step after the cookie read throws
|
|
309
|
+
* (state mismatch, tampered seal, code-exchange failure, session-save
|
|
310
|
+
* failure), `handleCallback` attempts a best-effort `clearCookie` on the
|
|
311
|
+
* response before rethrowing so the verifier does not linger for its full
|
|
312
|
+
* 600s TTL. Response-mutating adapters get the delete `Set-Cookie`
|
|
313
|
+
* applied in place; headers-only adapters should still call
|
|
314
|
+
* `clearPendingVerifier` in their catch block to capture the headers bag.
|
|
222
315
|
*/
|
|
223
316
|
async handleCallback(
|
|
224
|
-
|
|
317
|
+
request: TRequest,
|
|
225
318
|
response: TResponse,
|
|
226
|
-
options: {
|
|
319
|
+
options: {
|
|
320
|
+
code: string;
|
|
321
|
+
state: string | undefined;
|
|
322
|
+
},
|
|
227
323
|
) {
|
|
228
|
-
|
|
229
|
-
const authResponse = await this.client.userManagement.authenticateWithCode({
|
|
230
|
-
code: options.code,
|
|
231
|
-
clientId: this.config.clientId,
|
|
232
|
-
});
|
|
324
|
+
const cookieValue = await this.storage.getCookie(request, PKCE_COOKIE_NAME);
|
|
233
325
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}
|
|
326
|
+
let unsealed;
|
|
327
|
+
try {
|
|
328
|
+
unsealed = await this.core.verifyCallbackState({
|
|
329
|
+
stateFromUrl: options.state,
|
|
330
|
+
cookieValue: cookieValue ?? undefined,
|
|
331
|
+
});
|
|
332
|
+
} catch (err) {
|
|
333
|
+
// Pre-unseal failure — we don't know the per-request redirectUri
|
|
334
|
+
// override, so emit a scheme-agnostic delete: same (name, domain,
|
|
335
|
+
// path) tuple as the original set (what the browser uses to match
|
|
336
|
+
// for replacement), with `Secure` dropped in the `sameSite: 'lax'`
|
|
337
|
+
// case so the Set-Cookie is accepted over http:// callbacks too.
|
|
338
|
+
// The `sameSite: 'none'` case already forces Secure on both set and
|
|
339
|
+
// clear, so there's no scheme-mismatch risk there.
|
|
340
|
+
await this.bestEffortClearVerifier(response, undefined, {
|
|
341
|
+
schemeAgnostic: true,
|
|
342
|
+
});
|
|
343
|
+
throw err;
|
|
344
|
+
}
|
|
241
345
|
|
|
242
|
-
const
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
346
|
+
const { codeVerifier, returnPathname, customState, redirectUri } = unsealed;
|
|
347
|
+
const clearOptions = getPKCECookieOptions(this.config, redirectUri);
|
|
348
|
+
|
|
349
|
+
try {
|
|
350
|
+
const authResponse =
|
|
351
|
+
await this.client.userManagement.authenticateWithCode({
|
|
352
|
+
code: options.code,
|
|
353
|
+
clientId: this.config.clientId,
|
|
354
|
+
codeVerifier,
|
|
355
|
+
});
|
|
247
356
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
357
|
+
const session: Session = {
|
|
358
|
+
accessToken: authResponse.accessToken,
|
|
359
|
+
refreshToken: authResponse.refreshToken,
|
|
360
|
+
user: authResponse.user,
|
|
361
|
+
impersonator: authResponse.impersonator,
|
|
362
|
+
};
|
|
251
363
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
returnPathname = parsed.returnPathname;
|
|
271
|
-
} else {
|
|
272
|
-
customState = options.state;
|
|
273
|
-
}
|
|
274
|
-
} catch {
|
|
275
|
-
customState = options.state;
|
|
276
|
-
}
|
|
277
|
-
}
|
|
364
|
+
const encryptedSession = await this.core.encryptSession(session);
|
|
365
|
+
const save = await this.storage.saveSession(response, encryptedSession);
|
|
366
|
+
const clear = await this.storage.clearCookie(
|
|
367
|
+
save.response ?? response,
|
|
368
|
+
PKCE_COOKIE_NAME,
|
|
369
|
+
clearOptions,
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
return {
|
|
373
|
+
response: clear.response ?? save.response,
|
|
374
|
+
headers: mergeHeaderBags(save.headers, clear.headers),
|
|
375
|
+
returnPathname: returnPathname ?? '/',
|
|
376
|
+
state: customState,
|
|
377
|
+
authResponse,
|
|
378
|
+
};
|
|
379
|
+
} catch (err) {
|
|
380
|
+
await this.bestEffortClearVerifier(response, redirectUri);
|
|
381
|
+
throw err;
|
|
278
382
|
}
|
|
383
|
+
}
|
|
279
384
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
385
|
+
/**
|
|
386
|
+
* Best-effort verifier cleanup on a `handleCallback` error path.
|
|
387
|
+
*
|
|
388
|
+
* Mutates the response in place for response-mutating adapters.
|
|
389
|
+
* Swallows storage errors — cleanup must never mask the original failure.
|
|
390
|
+
* The original error is always rethrown by the caller.
|
|
391
|
+
*
|
|
392
|
+
* `schemeAgnostic` (pre-unseal failures only): drops the `Secure` attribute
|
|
393
|
+
* on the delete when `sameSite === 'lax'` so the browser accepts the
|
|
394
|
+
* `Set-Cookie` over http:// dev callbacks. Cookie replacement matches on
|
|
395
|
+
* (name, domain, path), not `Secure`, so the tuple-matched original cookie
|
|
396
|
+
* is still cleared regardless of its original `Secure` flag.
|
|
397
|
+
*/
|
|
398
|
+
private async bestEffortClearVerifier(
|
|
399
|
+
response: TResponse | undefined,
|
|
400
|
+
redirectUri: string | undefined,
|
|
401
|
+
{ schemeAgnostic = false }: { schemeAgnostic?: boolean } = {},
|
|
402
|
+
): Promise<void> {
|
|
403
|
+
const options = getPKCECookieOptions(this.config, redirectUri);
|
|
404
|
+
if (schemeAgnostic && options.sameSite === 'lax') {
|
|
405
|
+
options.secure = false;
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
await this.storage.clearCookie(response, PKCE_COOKIE_NAME, options);
|
|
409
|
+
} catch {
|
|
410
|
+
// Swallow: cleanup is opportunistic; callers get the original error.
|
|
411
|
+
}
|
|
287
412
|
}
|
|
288
413
|
}
|
|
@@ -40,9 +40,10 @@ describe('createAuthService', () => {
|
|
|
40
40
|
expect(typeof service.saveSession).toBe('function');
|
|
41
41
|
expect(typeof service.clearSession).toBe('function');
|
|
42
42
|
expect(typeof service.signOut).toBe('function');
|
|
43
|
-
expect(typeof service.
|
|
44
|
-
expect(typeof service.
|
|
45
|
-
expect(typeof service.
|
|
43
|
+
expect(typeof service.createAuthorization).toBe('function');
|
|
44
|
+
expect(typeof service.createSignIn).toBe('function');
|
|
45
|
+
expect(typeof service.createSignUp).toBe('function');
|
|
46
|
+
expect(typeof service.clearPendingVerifier).toBe('function');
|
|
46
47
|
expect(typeof service.getWorkOS).toBe('function');
|
|
47
48
|
expect(typeof service.handleCallback).toBe('function');
|
|
48
49
|
});
|
package/src/service/factory.ts
CHANGED
|
@@ -72,9 +72,12 @@ export function createAuthService<TRequest, TResponse>(options: {
|
|
|
72
72
|
getService().switchOrganization(session, organizationId),
|
|
73
73
|
refreshSession: (session, organizationId) =>
|
|
74
74
|
getService().refreshSession(session, organizationId),
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
createAuthorization: (response, opts) =>
|
|
76
|
+
getService().createAuthorization(response, opts),
|
|
77
|
+
createSignIn: (response, opts) => getService().createSignIn(response, opts),
|
|
78
|
+
createSignUp: (response, opts) => getService().createSignUp(response, opts),
|
|
79
|
+
clearPendingVerifier: (response, opts) =>
|
|
80
|
+
getService().clearPendingVerifier(response, opts),
|
|
78
81
|
getWorkOS: () => getService().getWorkOS(),
|
|
79
82
|
handleCallback: (request, response, opts) =>
|
|
80
83
|
getService().handleCallback(request, response, opts),
|
package/src/utils.ts
CHANGED
|
@@ -19,3 +19,25 @@ export function once<TArgs extends unknown[], TReturn>(
|
|
|
19
19
|
return result;
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Constant-time byte-array equality.
|
|
25
|
+
*
|
|
26
|
+
* Used for comparing security-sensitive values (OAuth state, tokens, MACs)
|
|
27
|
+
* where early-return on mismatch would leak timing information about how
|
|
28
|
+
* many leading bytes matched.
|
|
29
|
+
*
|
|
30
|
+
* Runtime-portable: no `node:crypto`, no `Buffer` — works in Node, browsers,
|
|
31
|
+
* and edge runtimes. Callers produce `Uint8Array`s via `TextEncoder`.
|
|
32
|
+
*
|
|
33
|
+
* Contract:
|
|
34
|
+
* - Returns false immediately if lengths differ (length is not secret).
|
|
35
|
+
* - Once past the length gate, inspects EVERY byte regardless of mismatches.
|
|
36
|
+
* - No branches whose count depends on byte values.
|
|
37
|
+
*/
|
|
38
|
+
export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
|
|
39
|
+
if (a.length !== b.length) return false;
|
|
40
|
+
let diff = 0;
|
|
41
|
+
for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
|
|
42
|
+
return diff === 0;
|
|
43
|
+
}
|