@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.
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +29 -20
- package/dist/cache.js.map +1 -1
- package/dist/device-flow-config.d.ts +32 -0
- package/dist/device-flow-config.d.ts.map +1 -0
- package/dist/device-flow-config.js +136 -0
- package/dist/device-flow-config.js.map +1 -0
- package/dist/device-flow-http.d.ts +23 -0
- package/dist/device-flow-http.d.ts.map +1 -0
- package/dist/device-flow-http.js +121 -0
- package/dist/device-flow-http.js.map +1 -0
- package/dist/device-flow.d.ts.map +1 -1
- package/dist/device-flow.js +28 -255
- package/dist/device-flow.js.map +1 -1
- package/dist/keycloak-testing.js +2 -2
- package/dist/keycloak-testing.js.map +1 -1
- package/package.json +5 -2
- package/src/cache.ts +40 -22
- package/src/device-flow-config.ts +188 -0
- package/src/device-flow-http.ts +161 -0
- package/src/device-flow.ts +50 -355
- package/src/keycloak-testing.ts +2 -2
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { isSafeInteger } from '@baukit/type-guards';
|
|
2
|
+
|
|
3
|
+
import type { DeviceFlowClientConfig, EndpointPolicy } from './device-flow.js';
|
|
4
|
+
import { isAllowedWebScheme } from './api-origin.js';
|
|
5
|
+
import { AuthNodeError } from './errors.js';
|
|
6
|
+
|
|
7
|
+
const DEFAULT_SCOPES = ['openid', 'profile', 'offline_access'] as const;
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024;
|
|
10
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
|
|
11
|
+
export const DEFAULT_LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
12
|
+
export const DEFAULT_REFRESH_LEEWAY_SECONDS = 60;
|
|
13
|
+
export interface NormalizedConfig {
|
|
14
|
+
readonly issuer: string;
|
|
15
|
+
readonly clientId: string;
|
|
16
|
+
readonly scopes: readonly string[];
|
|
17
|
+
readonly audience?: string;
|
|
18
|
+
readonly profile: string;
|
|
19
|
+
readonly endpointPolicy: Required<EndpointPolicy>;
|
|
20
|
+
readonly maxResponseBytes: number;
|
|
21
|
+
readonly requestTimeoutMs: number;
|
|
22
|
+
readonly loginTimeoutMs: number;
|
|
23
|
+
readonly refreshLeewayMs: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function normalizeConfig(config: DeviceFlowClientConfig): NormalizedConfig {
|
|
27
|
+
const policy = normalizePolicy(config.endpointPolicy ?? {});
|
|
28
|
+
const issuer = normalizeWebUrl(config.issuer, policy.allowLoopbackHttp, 'issuer');
|
|
29
|
+
const clientId = requiredText(config.clientId, 'OIDC client ID');
|
|
30
|
+
const scopes = normalizeScopes(config.scopes);
|
|
31
|
+
return {
|
|
32
|
+
issuer,
|
|
33
|
+
clientId,
|
|
34
|
+
scopes,
|
|
35
|
+
...(config.audience === undefined
|
|
36
|
+
? {}
|
|
37
|
+
: { audience: requiredText(config.audience, 'audience') }),
|
|
38
|
+
profile: config.profile ?? 'default',
|
|
39
|
+
endpointPolicy: policy,
|
|
40
|
+
maxResponseBytes: positiveInteger(
|
|
41
|
+
config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
|
|
42
|
+
'maximum response size',
|
|
43
|
+
),
|
|
44
|
+
requestTimeoutMs: positiveInteger(
|
|
45
|
+
config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
46
|
+
'request timeout',
|
|
47
|
+
),
|
|
48
|
+
loginTimeoutMs: positiveInteger(
|
|
49
|
+
config.loginTimeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS,
|
|
50
|
+
'login timeout',
|
|
51
|
+
),
|
|
52
|
+
refreshLeewayMs:
|
|
53
|
+
nonNegativeInteger(
|
|
54
|
+
config.refreshLeewaySeconds ?? DEFAULT_REFRESH_LEEWAY_SECONDS,
|
|
55
|
+
'refresh leeway',
|
|
56
|
+
) * 1000,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function normalizePolicy(policy: EndpointPolicy): Required<EndpointPolicy> {
|
|
61
|
+
const allowLoopbackHttp = policy.allowLoopbackHttp ?? false;
|
|
62
|
+
return {
|
|
63
|
+
allowLoopbackHttp,
|
|
64
|
+
issuerAllowlist: (policy.issuerAllowlist ?? []).map((issuer) =>
|
|
65
|
+
normalizeWebUrl(issuer, allowLoopbackHttp, 'issuer'),
|
|
66
|
+
),
|
|
67
|
+
endpointOriginAllowlist: (policy.endpointOriginAllowlist ?? []).map((origin) => {
|
|
68
|
+
const url = parseUrl(origin, 'config');
|
|
69
|
+
if (url.origin !== url.toString().replace(/\/$/u, '') || url.username || url.password) {
|
|
70
|
+
throw new TypeError('endpoint origin allowlist entries must contain only an origin.');
|
|
71
|
+
}
|
|
72
|
+
validateWebUrl(url.toString(), allowLoopbackHttp);
|
|
73
|
+
return url.origin;
|
|
74
|
+
}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function validateDiscoveredEndpoint(
|
|
79
|
+
value: string,
|
|
80
|
+
issuer: string,
|
|
81
|
+
policy: Required<EndpointPolicy>,
|
|
82
|
+
): string {
|
|
83
|
+
const endpoint = parseUrl(value, 'provider');
|
|
84
|
+
validateWebUrl(endpoint.toString(), policy.allowLoopbackHttp);
|
|
85
|
+
if (endpoint.username || endpoint.password || endpoint.hash) {
|
|
86
|
+
throw new AuthNodeError('endpoint_policy_violation');
|
|
87
|
+
}
|
|
88
|
+
const issuerUrl = parseUrl(issuer, 'provider');
|
|
89
|
+
const originAllowed =
|
|
90
|
+
endpoint.origin === issuerUrl.origin ||
|
|
91
|
+
policy.endpointOriginAllowlist.includes(endpoint.origin);
|
|
92
|
+
if (!originAllowed) throw new AuthNodeError('endpoint_policy_violation');
|
|
93
|
+
if (endpoint.origin === issuerUrl.origin) {
|
|
94
|
+
const issuerPath = issuerUrl.pathname.replace(/\/$/u, '');
|
|
95
|
+
const relatedPath =
|
|
96
|
+
issuerPath.length === 0 ||
|
|
97
|
+
endpoint.pathname === issuerPath ||
|
|
98
|
+
endpoint.pathname.startsWith(`${issuerPath}/`);
|
|
99
|
+
if (!relatedPath) throw new AuthNodeError('endpoint_policy_violation');
|
|
100
|
+
}
|
|
101
|
+
return endpoint.toString();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function normalizeWebUrl(value: string, allowLoopbackHttp: boolean, label: string): string {
|
|
105
|
+
const url = parseUrl(requiredText(value, `OIDC ${label}`), 'config');
|
|
106
|
+
if (url.search || url.hash || url.username || url.password) {
|
|
107
|
+
throw new TypeError(`OIDC ${label} must not contain credentials, a query, or a fragment.`);
|
|
108
|
+
}
|
|
109
|
+
validateWebUrl(url.toString(), allowLoopbackHttp);
|
|
110
|
+
return url.toString().replace(/\/+$/u, '');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function validateWebUrl(value: string, allowLoopbackHttp: boolean): void {
|
|
114
|
+
if (!isAllowedWebScheme(parseUrl(value, 'provider'), allowLoopbackHttp)) {
|
|
115
|
+
throw new AuthNodeError('endpoint_policy_violation');
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function parseUrl(value: string, source: 'config' | 'provider'): URL {
|
|
120
|
+
try {
|
|
121
|
+
return new URL(value);
|
|
122
|
+
} catch {
|
|
123
|
+
if (source === 'config') throw new TypeError('OIDC URL is invalid.');
|
|
124
|
+
throw new AuthNodeError('endpoint_policy_violation');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function normalizeScopes(scopes: readonly string[] | undefined): readonly string[] {
|
|
129
|
+
const values = scopes ?? DEFAULT_SCOPES;
|
|
130
|
+
const normalized = values.map((scope) => requiredText(scope, 'OIDC scope'));
|
|
131
|
+
if (!normalized.includes('openid')) normalized.unshift('openid');
|
|
132
|
+
return [...new Set(normalized)];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function requiredString(
|
|
136
|
+
value: Record<string, unknown>,
|
|
137
|
+
key: string,
|
|
138
|
+
code: 'invalid_device_response' | 'invalid_discovery_document' | 'invalid_token_response',
|
|
139
|
+
): string {
|
|
140
|
+
const result = optionalString(value, key);
|
|
141
|
+
if (result === undefined) throw new AuthNodeError(code);
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function optionalString(value: Record<string, unknown>, key: string): string | undefined {
|
|
146
|
+
const result = value[key];
|
|
147
|
+
return typeof result === 'string' && result.length > 0 ? result : undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function requiredPositiveInteger(
|
|
151
|
+
value: Record<string, unknown>,
|
|
152
|
+
key: string,
|
|
153
|
+
code: 'invalid_device_response' | 'invalid_token_response',
|
|
154
|
+
): number {
|
|
155
|
+
const result = optionalPositiveInteger(value, key, code);
|
|
156
|
+
if (result === undefined) throw new AuthNodeError(code);
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function optionalPositiveInteger(
|
|
161
|
+
value: Record<string, unknown>,
|
|
162
|
+
key: string,
|
|
163
|
+
code: 'invalid_device_response' | 'invalid_token_response',
|
|
164
|
+
): number | undefined {
|
|
165
|
+
const result = value[key];
|
|
166
|
+
if (result === undefined) return undefined;
|
|
167
|
+
if (!isSafeInteger(result) || result <= 0) throw new AuthNodeError(code);
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function requiredText(value: string, label: string): string {
|
|
172
|
+
const trimmed = value.trim();
|
|
173
|
+
if (trimmed.length === 0) throw new TypeError(`${label} must not be empty.`);
|
|
174
|
+
return trimmed;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function positiveInteger(value: number, label: string): number {
|
|
178
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
179
|
+
throw new RangeError(`${label} must be positive.`);
|
|
180
|
+
return value;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function nonNegativeInteger(value: number, label: string): number {
|
|
184
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
185
|
+
throw new RangeError(`${label} must be a non-negative integer.`);
|
|
186
|
+
}
|
|
187
|
+
return value;
|
|
188
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { isRecord } from '@baukit/type-guards';
|
|
2
|
+
|
|
3
|
+
import type { DeviceProviderRequestOptions } from './device-flow.js';
|
|
4
|
+
import { AuthNodeError } from './errors.js';
|
|
5
|
+
|
|
6
|
+
export interface JsonResponse {
|
|
7
|
+
readonly response: Response;
|
|
8
|
+
readonly body: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface JsonRequest {
|
|
12
|
+
readonly fetchImplementation: typeof globalThis.fetch;
|
|
13
|
+
readonly options: DeviceProviderRequestOptions;
|
|
14
|
+
readonly invalidResponseCode:
|
|
15
|
+
'invalid_device_response' | 'invalid_discovery_document' | 'invalid_token_response';
|
|
16
|
+
readonly requestFailureCode:
|
|
17
|
+
'device_authorization_failed' | 'discovery_failed' | 'refresh_failed';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function postForm(
|
|
21
|
+
endpoint: string,
|
|
22
|
+
fields: Record<string, string>,
|
|
23
|
+
request: JsonRequest,
|
|
24
|
+
): Promise<JsonResponse> {
|
|
25
|
+
return requestJson(
|
|
26
|
+
endpoint,
|
|
27
|
+
{
|
|
28
|
+
method: 'POST',
|
|
29
|
+
headers: {
|
|
30
|
+
Accept: 'application/json',
|
|
31
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
32
|
+
},
|
|
33
|
+
body: new URLSearchParams(fields),
|
|
34
|
+
},
|
|
35
|
+
request,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function requestJson(
|
|
40
|
+
input: string,
|
|
41
|
+
init: RequestInit,
|
|
42
|
+
request: JsonRequest,
|
|
43
|
+
): Promise<JsonResponse> {
|
|
44
|
+
const { fetchImplementation, options, invalidResponseCode, requestFailureCode } = request;
|
|
45
|
+
const requestTimeout = timeoutSignal(options.signal, options.requestTimeoutMs);
|
|
46
|
+
try {
|
|
47
|
+
const response = await fetchImplementation(input, { ...init, signal: requestTimeout.signal });
|
|
48
|
+
const declaredLength = Number(response.headers.get('content-length'));
|
|
49
|
+
if (Number.isFinite(declaredLength) && declaredLength > options.maxResponseBytes) {
|
|
50
|
+
throw new AuthNodeError(invalidResponseCode);
|
|
51
|
+
}
|
|
52
|
+
const text = await readLimitedText(response, options.maxResponseBytes, invalidResponseCode);
|
|
53
|
+
let value: unknown;
|
|
54
|
+
try {
|
|
55
|
+
value = JSON.parse(text) as unknown;
|
|
56
|
+
} catch {
|
|
57
|
+
throw new AuthNodeError(invalidResponseCode);
|
|
58
|
+
}
|
|
59
|
+
if (!isRecord(value)) throw new AuthNodeError(invalidResponseCode);
|
|
60
|
+
return { response, body: value };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
const mapped = mapAbort(error, options.signal, requestTimeout.didTimeout());
|
|
63
|
+
if (mapped instanceof AuthNodeError) throw mapped;
|
|
64
|
+
throw new AuthNodeError(requestFailureCode, { retryable: true });
|
|
65
|
+
} finally {
|
|
66
|
+
requestTimeout.dispose();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function readLimitedText(
|
|
71
|
+
response: Response,
|
|
72
|
+
maxBytes: number,
|
|
73
|
+
invalidResponseCode: JsonRequest['invalidResponseCode'],
|
|
74
|
+
): Promise<string> {
|
|
75
|
+
if (response.body === null) return '';
|
|
76
|
+
const reader = response.body.getReader();
|
|
77
|
+
const decoder = new TextDecoder();
|
|
78
|
+
let text = '';
|
|
79
|
+
let bytes = 0;
|
|
80
|
+
for (;;) {
|
|
81
|
+
const chunk = await reader.read();
|
|
82
|
+
if (chunk.done) break;
|
|
83
|
+
bytes += chunk.value.byteLength;
|
|
84
|
+
if (bytes > maxBytes) {
|
|
85
|
+
await reader.cancel().catch(() => undefined);
|
|
86
|
+
throw new AuthNodeError(invalidResponseCode);
|
|
87
|
+
}
|
|
88
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
89
|
+
}
|
|
90
|
+
return text + decoder.decode();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function throwIfAborted(signal?: AbortSignal): void {
|
|
94
|
+
if (signal?.aborted === true) throw new AuthNodeError('aborted');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function mapAbort(
|
|
98
|
+
error: unknown,
|
|
99
|
+
parentSignal: AbortSignal | undefined,
|
|
100
|
+
timedOut: boolean,
|
|
101
|
+
): unknown {
|
|
102
|
+
if (parentSignal?.aborted === true) return new AuthNodeError('aborted');
|
|
103
|
+
if (timedOut) return new AuthNodeError('login_timeout', { retryable: true });
|
|
104
|
+
return error;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function combineSignals(
|
|
108
|
+
first: AbortSignal | undefined,
|
|
109
|
+
second: AbortSignal | undefined,
|
|
110
|
+
): AbortSignal | undefined {
|
|
111
|
+
if (first === undefined) return second;
|
|
112
|
+
if (second === undefined) return first;
|
|
113
|
+
return AbortSignal.any([first, second]);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function timeoutSignal(
|
|
117
|
+
parent: AbortSignal | undefined,
|
|
118
|
+
milliseconds: number,
|
|
119
|
+
): {
|
|
120
|
+
readonly signal: AbortSignal;
|
|
121
|
+
readonly didTimeout: () => boolean;
|
|
122
|
+
readonly dispose: () => void;
|
|
123
|
+
} {
|
|
124
|
+
const controller = new AbortController();
|
|
125
|
+
let timedOut = false;
|
|
126
|
+
const timeout = setTimeout(() => {
|
|
127
|
+
timedOut = true;
|
|
128
|
+
controller.abort();
|
|
129
|
+
}, milliseconds);
|
|
130
|
+
const abortFromParent = (): void => {
|
|
131
|
+
controller.abort();
|
|
132
|
+
};
|
|
133
|
+
parent?.addEventListener('abort', abortFromParent, { once: true });
|
|
134
|
+
if (parent?.aborted === true) controller.abort();
|
|
135
|
+
return {
|
|
136
|
+
signal: controller.signal,
|
|
137
|
+
didTimeout: () => timedOut,
|
|
138
|
+
dispose: () => {
|
|
139
|
+
clearTimeout(timeout);
|
|
140
|
+
parent?.removeEventListener('abort', abortFromParent);
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise<void> {
|
|
146
|
+
return new Promise((resolveDelay, reject) => {
|
|
147
|
+
if (signal?.aborted === true) {
|
|
148
|
+
reject(new AuthNodeError('aborted'));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const onAbort = (): void => {
|
|
152
|
+
clearTimeout(timeout);
|
|
153
|
+
reject(new AuthNodeError('aborted'));
|
|
154
|
+
};
|
|
155
|
+
const timeout = setTimeout(() => {
|
|
156
|
+
signal?.removeEventListener('abort', onAbort);
|
|
157
|
+
resolveDelay();
|
|
158
|
+
}, milliseconds);
|
|
159
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
160
|
+
});
|
|
161
|
+
}
|