@baukit/auth-node 0.18.3 → 0.19.1

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.
@@ -2,17 +2,36 @@
2
2
 
3
3
  import { createHash, randomBytes } from 'node:crypto';
4
4
 
5
- import { isAllowedWebScheme } from './api-origin.js';
5
+ import { isRecord } from '@baukit/type-guards';
6
+
6
7
  import { NodeTokenCache, type CachedTokenProfile, type NodeTokenCacheOptions } from './cache.js';
8
+ import {
9
+ normalizeConfig,
10
+ normalizePolicy,
11
+ normalizeWebUrl,
12
+ optionalPositiveInteger,
13
+ optionalString,
14
+ positiveInteger,
15
+ requiredPositiveInteger,
16
+ requiredString,
17
+ validateDiscoveredEndpoint,
18
+ validateWebUrl,
19
+ type NormalizedConfig,
20
+ } from './device-flow-config.js';
21
+ import {
22
+ abortableDelay,
23
+ combineSignals,
24
+ mapAbort,
25
+ postForm,
26
+ requestJson,
27
+ throwIfAborted,
28
+ timeoutSignal,
29
+ type JsonResponse,
30
+ } from './device-flow-http.js';
7
31
  import { AuthNodeError } from './errors.js';
8
32
 
9
- const DEFAULT_SCOPES = ['openid', 'profile', 'offline_access'] as const;
10
33
  const DEFAULT_DEVICE_INTERVAL_SECONDS = 5;
11
34
  const SLOW_DOWN_INCREMENT_SECONDS = 5;
12
- const DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024;
13
- const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
14
- const DEFAULT_LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
15
- const DEFAULT_REFRESH_LEEWAY_SECONDS = 60;
16
35
  const DISPLAY_CLAIMS_MAX_BYTES = 16 * 1024;
17
36
  const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
18
37
 
@@ -87,19 +106,6 @@ export interface DisplayOnlyClaims {
87
106
  readonly expiresAt?: number;
88
107
  }
89
108
 
90
- interface NormalizedConfig {
91
- readonly issuer: string;
92
- readonly clientId: string;
93
- readonly scopes: readonly string[];
94
- readonly audience?: string;
95
- readonly profile: string;
96
- readonly endpointPolicy: Required<EndpointPolicy>;
97
- readonly maxResponseBytes: number;
98
- readonly requestTimeoutMs: number;
99
- readonly loginTimeoutMs: number;
100
- readonly refreshLeewayMs: number;
101
- }
102
-
103
109
  interface DeviceAuthorization {
104
110
  readonly deviceCode: string;
105
111
  readonly userCode: string;
@@ -197,7 +203,7 @@ export class DeviceFlowClient {
197
203
 
198
204
  public async accessToken(options: AccessTokenOptions = {}): Promise<string> {
199
205
  const environmentToken = (await this.#environment.environmentToken?.())?.trim();
200
- if (environmentToken) return environmentToken;
206
+ if (environmentToken !== undefined && environmentToken !== '') return environmentToken;
201
207
  const signal = combineSignals(this.#environment.signal, options.signal);
202
208
  throwIfAborted(signal);
203
209
  const cached = await this.#cache.read(this.#config.profile);
@@ -249,10 +255,12 @@ export class DeviceFlowClient {
249
255
  code_challenge_method: 'S256',
250
256
  ...(this.#config.audience === undefined ? {} : { audience: this.#config.audience }),
251
257
  },
252
- this.#environment.fetch,
253
- this.#requestOptions(signal),
254
- 'invalid_device_response',
255
- 'device_authorization_failed',
258
+ {
259
+ fetchImplementation: this.#environment.fetch,
260
+ options: this.#requestOptions(signal),
261
+ invalidResponseCode: 'invalid_device_response',
262
+ requestFailureCode: 'device_authorization_failed',
263
+ },
256
264
  );
257
265
  if (!response.response.ok) {
258
266
  throw new AuthNodeError('device_authorization_failed', { status: response.response.status });
@@ -298,10 +306,12 @@ export class DeviceFlowClient {
298
306
  client_id: this.#config.clientId,
299
307
  code_verifier: device.codeVerifier,
300
308
  },
301
- this.#environment.fetch,
302
- this.#requestOptions(signal),
303
- 'invalid_token_response',
304
- 'device_authorization_failed',
309
+ {
310
+ fetchImplementation: this.#environment.fetch,
311
+ options: this.#requestOptions(signal),
312
+ invalidResponseCode: 'invalid_token_response',
313
+ requestFailureCode: 'device_authorization_failed',
314
+ },
305
315
  );
306
316
  if (result.response.ok) {
307
317
  await presentation?.showStatus?.('authorized');
@@ -347,10 +357,12 @@ export class DeviceFlowClient {
347
357
  client_id: this.#config.clientId,
348
358
  ...(this.#config.audience === undefined ? {} : { audience: this.#config.audience }),
349
359
  },
350
- this.#environment.fetch,
351
- this.#requestOptions(signal),
352
- 'invalid_token_response',
353
- 'refresh_failed',
360
+ {
361
+ fetchImplementation: this.#environment.fetch,
362
+ options: this.#requestOptions(signal),
363
+ invalidResponseCode: 'invalid_token_response',
364
+ requestFailureCode: 'refresh_failed',
365
+ },
354
366
  );
355
367
  if (!result.response.ok) {
356
368
  throw new AuthNodeError('refresh_failed', {
@@ -435,10 +447,12 @@ export async function discoverDeviceProvider(
435
447
  result = await requestJson(
436
448
  discoveryUrl,
437
449
  { headers: { Accept: 'application/json' } },
438
- fetchImplementation,
439
- requestOptions,
440
- 'invalid_discovery_document',
441
- 'discovery_failed',
450
+ {
451
+ fetchImplementation: fetchImplementation,
452
+ options: requestOptions,
453
+ invalidResponseCode: 'invalid_discovery_document',
454
+ requestFailureCode: 'discovery_failed',
455
+ },
442
456
  );
443
457
  } catch (error) {
444
458
  if (error instanceof AuthNodeError) throw error;
@@ -497,87 +511,6 @@ export function decodeDisplayOnlyClaims(token: string): DisplayOnlyClaims | unde
497
511
  }
498
512
  }
499
513
 
500
- interface JsonResponse {
501
- readonly response: Response;
502
- readonly body: Record<string, unknown>;
503
- }
504
-
505
- async function postForm(
506
- endpoint: string,
507
- fields: Record<string, string>,
508
- fetchImplementation: typeof globalThis.fetch,
509
- options: DeviceProviderRequestOptions,
510
- invalidResponseCode:
511
- 'invalid_device_response' | 'invalid_discovery_document' | 'invalid_token_response',
512
- requestFailureCode: 'device_authorization_failed' | 'discovery_failed' | 'refresh_failed',
513
- ): Promise<JsonResponse> {
514
- return requestJson(
515
- endpoint,
516
- {
517
- method: 'POST',
518
- headers: {
519
- Accept: 'application/json',
520
- 'Content-Type': 'application/x-www-form-urlencoded',
521
- },
522
- body: new URLSearchParams(fields),
523
- },
524
- fetchImplementation,
525
- options,
526
- invalidResponseCode,
527
- requestFailureCode,
528
- );
529
- }
530
-
531
- async function requestJson(
532
- input: string,
533
- init: RequestInit,
534
- fetchImplementation: typeof globalThis.fetch,
535
- options: DeviceProviderRequestOptions,
536
- invalidResponseCode:
537
- 'invalid_device_response' | 'invalid_discovery_document' | 'invalid_token_response',
538
- requestFailureCode: 'device_authorization_failed' | 'discovery_failed' | 'refresh_failed',
539
- ): Promise<JsonResponse> {
540
- const requestTimeout = timeoutSignal(options.signal, options.requestTimeoutMs);
541
- try {
542
- const response = await fetchImplementation(input, { ...init, signal: requestTimeout.signal });
543
- const declaredLength = Number(response.headers.get('content-length'));
544
- if (Number.isFinite(declaredLength) && declaredLength > options.maxResponseBytes) {
545
- throw new AuthNodeError(invalidResponseCode);
546
- }
547
- let text = '';
548
- if (response.body !== null) {
549
- const reader = response.body.getReader();
550
- const decoder = new TextDecoder();
551
- let bytes = 0;
552
- for (;;) {
553
- const chunk = await reader.read();
554
- if (chunk.done) break;
555
- bytes += chunk.value.byteLength;
556
- if (bytes > options.maxResponseBytes) {
557
- await reader.cancel().catch(() => undefined);
558
- throw new AuthNodeError(invalidResponseCode);
559
- }
560
- text += decoder.decode(chunk.value, { stream: true });
561
- }
562
- text += decoder.decode();
563
- }
564
- let value: unknown;
565
- try {
566
- value = JSON.parse(text) as unknown;
567
- } catch {
568
- throw new AuthNodeError(invalidResponseCode);
569
- }
570
- if (!isRecord(value)) throw new AuthNodeError(invalidResponseCode);
571
- return { response, body: value };
572
- } catch (error) {
573
- const mapped = mapAbort(error, options.signal, requestTimeout.didTimeout());
574
- if (mapped instanceof AuthNodeError) throw mapped;
575
- throw new AuthNodeError(requestFailureCode, { retryable: true });
576
- } finally {
577
- requestTimeout.dispose();
578
- }
579
- }
580
-
581
514
  function parseTokenResponse(body: Record<string, unknown>): TokenResponse {
582
515
  const refreshToken = optionalString(body, 'refresh_token');
583
516
  const idToken = optionalString(body, 'id_token');
@@ -589,241 +522,3 @@ function parseTokenResponse(body: Record<string, unknown>): TokenResponse {
589
522
  expiresIn: requiredPositiveInteger(body, 'expires_in', 'invalid_token_response'),
590
523
  };
591
524
  }
592
-
593
- function normalizeConfig(config: DeviceFlowClientConfig): NormalizedConfig {
594
- const policy = normalizePolicy(config.endpointPolicy ?? {});
595
- const issuer = normalizeWebUrl(config.issuer, policy.allowLoopbackHttp, 'issuer');
596
- const clientId = requiredText(config.clientId, 'OIDC client ID');
597
- const scopes = normalizeScopes(config.scopes);
598
- return {
599
- issuer,
600
- clientId,
601
- scopes,
602
- ...(config.audience === undefined
603
- ? {}
604
- : { audience: requiredText(config.audience, 'audience') }),
605
- profile: config.profile ?? 'default',
606
- endpointPolicy: policy,
607
- maxResponseBytes: positiveInteger(
608
- config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
609
- 'maximum response size',
610
- ),
611
- requestTimeoutMs: positiveInteger(
612
- config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
613
- 'request timeout',
614
- ),
615
- loginTimeoutMs: positiveInteger(
616
- config.loginTimeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS,
617
- 'login timeout',
618
- ),
619
- refreshLeewayMs:
620
- nonNegativeInteger(
621
- config.refreshLeewaySeconds ?? DEFAULT_REFRESH_LEEWAY_SECONDS,
622
- 'refresh leeway',
623
- ) * 1000,
624
- };
625
- }
626
-
627
- function normalizePolicy(policy: EndpointPolicy): Required<EndpointPolicy> {
628
- const allowLoopbackHttp = policy.allowLoopbackHttp ?? false;
629
- return {
630
- allowLoopbackHttp,
631
- issuerAllowlist: (policy.issuerAllowlist ?? []).map((issuer) =>
632
- normalizeWebUrl(issuer, allowLoopbackHttp, 'issuer'),
633
- ),
634
- endpointOriginAllowlist: (policy.endpointOriginAllowlist ?? []).map((origin) => {
635
- const url = parseUrl(origin, 'config');
636
- if (url.origin !== url.toString().replace(/\/$/u, '') || url.username || url.password) {
637
- throw new TypeError('endpoint origin allowlist entries must contain only an origin.');
638
- }
639
- validateWebUrl(url.toString(), allowLoopbackHttp);
640
- return url.origin;
641
- }),
642
- };
643
- }
644
-
645
- function validateDiscoveredEndpoint(
646
- value: string,
647
- issuer: string,
648
- policy: Required<EndpointPolicy>,
649
- ): string {
650
- const endpoint = parseUrl(value, 'provider');
651
- validateWebUrl(endpoint.toString(), policy.allowLoopbackHttp);
652
- if (endpoint.username || endpoint.password || endpoint.hash) {
653
- throw new AuthNodeError('endpoint_policy_violation');
654
- }
655
- const issuerUrl = parseUrl(issuer, 'provider');
656
- const originAllowed =
657
- endpoint.origin === issuerUrl.origin ||
658
- policy.endpointOriginAllowlist.includes(endpoint.origin);
659
- if (!originAllowed) throw new AuthNodeError('endpoint_policy_violation');
660
- if (endpoint.origin === issuerUrl.origin) {
661
- const issuerPath = issuerUrl.pathname.replace(/\/$/u, '');
662
- const relatedPath =
663
- issuerPath.length === 0 ||
664
- endpoint.pathname === issuerPath ||
665
- endpoint.pathname.startsWith(`${issuerPath}/`);
666
- if (!relatedPath) throw new AuthNodeError('endpoint_policy_violation');
667
- }
668
- return endpoint.toString();
669
- }
670
-
671
- function normalizeWebUrl(value: string, allowLoopbackHttp: boolean, label: string): string {
672
- const url = parseUrl(requiredText(value, `OIDC ${label}`), 'config');
673
- if (url.search || url.hash || url.username || url.password) {
674
- throw new TypeError(`OIDC ${label} must not contain credentials, a query, or a fragment.`);
675
- }
676
- validateWebUrl(url.toString(), allowLoopbackHttp);
677
- return url.toString().replace(/\/+$/u, '');
678
- }
679
-
680
- function validateWebUrl(value: string, allowLoopbackHttp: boolean): void {
681
- if (!isAllowedWebScheme(parseUrl(value, 'provider'), allowLoopbackHttp)) {
682
- throw new AuthNodeError('endpoint_policy_violation');
683
- }
684
- }
685
-
686
- function parseUrl(value: string, source: 'config' | 'provider'): URL {
687
- try {
688
- return new URL(value);
689
- } catch {
690
- if (source === 'config') throw new TypeError('OIDC URL is invalid.');
691
- throw new AuthNodeError('endpoint_policy_violation');
692
- }
693
- }
694
-
695
- function normalizeScopes(scopes: readonly string[] | undefined): readonly string[] {
696
- const values = scopes ?? DEFAULT_SCOPES;
697
- const normalized = values.map((scope) => requiredText(scope, 'OIDC scope'));
698
- if (!normalized.includes('openid')) normalized.unshift('openid');
699
- return [...new Set(normalized)];
700
- }
701
-
702
- function requiredString(
703
- value: Record<string, unknown>,
704
- key: string,
705
- code: 'invalid_device_response' | 'invalid_discovery_document' | 'invalid_token_response',
706
- ): string {
707
- const result = optionalString(value, key);
708
- if (result === undefined) throw new AuthNodeError(code);
709
- return result;
710
- }
711
-
712
- function optionalString(value: Record<string, unknown>, key: string): string | undefined {
713
- const result = value[key];
714
- return typeof result === 'string' && result.length > 0 ? result : undefined;
715
- }
716
-
717
- function requiredPositiveInteger(
718
- value: Record<string, unknown>,
719
- key: string,
720
- code: 'invalid_device_response' | 'invalid_token_response',
721
- ): number {
722
- const result = optionalPositiveInteger(value, key, code);
723
- if (result === undefined) throw new AuthNodeError(code);
724
- return result;
725
- }
726
-
727
- function optionalPositiveInteger(
728
- value: Record<string, unknown>,
729
- key: string,
730
- code: 'invalid_device_response' | 'invalid_token_response',
731
- ): number | undefined {
732
- const result = value[key];
733
- if (result === undefined) return undefined;
734
- if (!Number.isSafeInteger(result) || (result as number) <= 0) throw new AuthNodeError(code);
735
- return result as number;
736
- }
737
-
738
- function requiredText(value: string, label: string): string {
739
- const trimmed = value.trim();
740
- if (trimmed.length === 0) throw new TypeError(`${label} must not be empty.`);
741
- return trimmed;
742
- }
743
-
744
- function positiveInteger(value: number, label: string): number {
745
- if (!Number.isSafeInteger(value) || value <= 0)
746
- throw new RangeError(`${label} must be positive.`);
747
- return value;
748
- }
749
-
750
- function nonNegativeInteger(value: number, label: string): number {
751
- if (!Number.isSafeInteger(value) || value < 0) {
752
- throw new RangeError(`${label} must be a non-negative integer.`);
753
- }
754
- return value;
755
- }
756
-
757
- function isRecord(value: unknown): value is Record<string, unknown> {
758
- return typeof value === 'object' && value !== null && !Array.isArray(value);
759
- }
760
-
761
- function throwIfAborted(signal?: AbortSignal): void {
762
- if (signal?.aborted === true) throw new AuthNodeError('aborted');
763
- }
764
-
765
- function mapAbort(
766
- error: unknown,
767
- parentSignal: AbortSignal | undefined,
768
- timedOut: boolean,
769
- ): unknown {
770
- if (parentSignal?.aborted === true) return new AuthNodeError('aborted');
771
- if (timedOut) return new AuthNodeError('login_timeout', { retryable: true });
772
- return error;
773
- }
774
-
775
- function combineSignals(
776
- first: AbortSignal | undefined,
777
- second: AbortSignal | undefined,
778
- ): AbortSignal | undefined {
779
- if (first === undefined) return second;
780
- if (second === undefined) return first;
781
- return AbortSignal.any([first, second]);
782
- }
783
-
784
- function timeoutSignal(
785
- parent: AbortSignal | undefined,
786
- milliseconds: number,
787
- ): {
788
- readonly signal: AbortSignal;
789
- readonly didTimeout: () => boolean;
790
- readonly dispose: () => void;
791
- } {
792
- const controller = new AbortController();
793
- let timedOut = false;
794
- const timeout = setTimeout(() => {
795
- timedOut = true;
796
- controller.abort();
797
- }, milliseconds);
798
- const abortFromParent = (): void => {
799
- controller.abort();
800
- };
801
- parent?.addEventListener('abort', abortFromParent, { once: true });
802
- if (parent?.aborted === true) controller.abort();
803
- return {
804
- signal: controller.signal,
805
- didTimeout: () => timedOut,
806
- dispose: () => {
807
- clearTimeout(timeout);
808
- parent?.removeEventListener('abort', abortFromParent);
809
- },
810
- };
811
- }
812
-
813
- function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise<void> {
814
- return new Promise((resolveDelay, reject) => {
815
- if (signal?.aborted === true) {
816
- reject(new AuthNodeError('aborted'));
817
- return;
818
- }
819
- const onAbort = (): void => {
820
- clearTimeout(timeout);
821
- reject(new AuthNodeError('aborted'));
822
- };
823
- const timeout = setTimeout(() => {
824
- signal?.removeEventListener('abort', onAbort);
825
- resolveDelay();
826
- }, milliseconds);
827
- signal?.addEventListener('abort', onAbort, { once: true });
828
- });
829
- }
@@ -162,8 +162,8 @@ export async function allowKeycloakWebOrigin(
162
162
  postLogoutRedirectUris.includes(SAME_AS_REDIRECT_URIS) ||
163
163
  postLogoutRedirectUris.includes(redirectUri);
164
164
  if (
165
- client.redirectUris?.includes(redirectUri) &&
166
- client.webOrigins?.includes(origin) &&
165
+ client.redirectUris?.includes(redirectUri) === true &&
166
+ client.webOrigins?.includes(origin) === true &&
167
167
  logoutAllowed
168
168
  ) {
169
169
  return;