@grow-codes/oidc 0.0.0-stage → 0.1.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/lib/index.d.ts ADDED
@@ -0,0 +1,717 @@
1
+ import { E as EnvReader, K as KnownSecret, S as Secret, a as EnvMap, H as HealthStatus, R as RequestLike, A as AuthUser, V as Verifier } from './verifier-ERmLmytF.js';
2
+ export { D as DEFAULT_ALGORITHMS, b as DEFAULT_CLOCK_SKEW_MS, c as DEFAULT_HTTP_TIMEOUT_MS, d as DEFAULT_JWKS_CACHE_TTL_MS, e as DEFAULT_JWKS_REFRESH_COOLDOWN_MS, f as EnvHit, g as HeadersInput, M as MIN_SECRET_LENGTH, h as REDACTED, i as SENSITIVE_FIELD_PARTS, j as SigningAlgorithm, k as VerifierOptions, l as bearerToken, m as healthStatus, n as isHealthyWord, o as isSensitiveField, p as isSensitiveHeader, q as parseBool, r as parseDuration, s as parseInteger, t as probeHealth, u as redactError, v as redactFields, w as redactHeaders, x as redactText, y as redactUrl } from './verifier-ERmLmytF.js';
3
+ import { Dispatcher } from 'undici';
4
+
5
+ /** Throws {@link CancelledError} when the signal is already aborted. */
6
+ declare function throwIfAborted(signal: AbortSignal | undefined, operation: string): void;
7
+ /**
8
+ * Resolves after `ms` milliseconds; rejects with {@link CancelledError} when `signal` aborts
9
+ * first. The timer does not keep the process alive.
10
+ */
11
+ declare function sleep(ms: number, signal?: AbortSignal, operation?: string): Promise<void>;
12
+
13
+ /** Canonical error codes shared by every Grow Codes SDK (SPEC §2.1). Values are the wire form. */
14
+ declare const ErrorCode: {
15
+ readonly Config: "CONFIG";
16
+ readonly Authentication: "AUTHENTICATION";
17
+ readonly PermissionDenied: "PERMISSION_DENIED";
18
+ readonly NotFound: "NOT_FOUND";
19
+ readonly Conflict: "CONFLICT";
20
+ readonly RateLimited: "RATE_LIMITED";
21
+ readonly Validation: "VALIDATION";
22
+ readonly Unavailable: "UNAVAILABLE";
23
+ readonly Timeout: "TIMEOUT";
24
+ readonly Unsupported: "UNSUPPORTED";
25
+ readonly Cancelled: "CANCELLED";
26
+ };
27
+ /** One of the {@link ErrorCode} wire values, e.g. `"NOT_FOUND"`. */
28
+ type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
29
+ /** Optional details attached to an SDK error. */
30
+ interface ErrorDetails {
31
+ /** HTTP status when the error came from a response. */
32
+ httpStatus?: number;
33
+ /** Vendor request id header when present. */
34
+ requestId?: string;
35
+ /** Overrides the default retryability of the code. */
36
+ retryable?: boolean;
37
+ /** Server-requested wait (from `Retry-After`) in milliseconds. */
38
+ retryAfterMs?: number;
39
+ /** Underlying error (already redacted). */
40
+ cause?: unknown;
41
+ }
42
+ /**
43
+ * Base class of every error thrown by the OIDC SDK.
44
+ *
45
+ * The message never contains credentials, request bodies or unfiltered response bodies.
46
+ */
47
+ declare class OidcError extends Error {
48
+ /** Canonical error code. */
49
+ readonly code: ErrorCode;
50
+ /** HTTP status when the error came from a response. */
51
+ readonly httpStatus?: number;
52
+ /** Vendor request id when the response carried one. */
53
+ readonly requestId?: string;
54
+ /** Whether retrying the same call may succeed. */
55
+ readonly retryable: boolean;
56
+ /** Server-requested wait in milliseconds (rate limits, `Retry-After`). */
57
+ readonly retryAfterMs?: number;
58
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails);
59
+ /** JSON form (no stack, no cause). */
60
+ toJSON(): Record<string, unknown>;
61
+ }
62
+ /** Invalid or missing configuration. */
63
+ declare class ConfigError extends OidcError {
64
+ constructor(message: string, details?: ErrorDetails);
65
+ }
66
+ /** HTTP 401: missing or invalid credentials. */
67
+ declare class AuthenticationError extends OidcError {
68
+ constructor(message: string, details?: ErrorDetails);
69
+ }
70
+ /** HTTP 403: the credentials do not allow the operation. */
71
+ declare class PermissionDeniedError extends OidcError {
72
+ constructor(message: string, details?: ErrorDetails);
73
+ }
74
+ /** HTTP 404 or a missing record. */
75
+ declare class NotFoundError extends OidcError {
76
+ constructor(message: string, details?: ErrorDetails);
77
+ }
78
+ /** HTTP 409/412 or a compare-and-set mismatch. */
79
+ declare class ConflictError extends OidcError {
80
+ constructor(message: string, details?: ErrorDetails);
81
+ }
82
+ /** HTTP 429. `retryAfterMs` is set when the server sent `Retry-After`. */
83
+ declare class RateLimitError extends OidcError {
84
+ constructor(message: string, details?: ErrorDetails);
85
+ }
86
+ /** HTTP 400/413/422/other 4xx, or bad input caught client side. */
87
+ declare class ValidationError extends OidcError {
88
+ constructor(message: string, details?: ErrorDetails);
89
+ }
90
+ /** Network error or HTTP 500/502/503. */
91
+ declare class UnavailableError extends OidcError {
92
+ constructor(message: string, details?: ErrorDetails);
93
+ }
94
+ /** A connect, request or total deadline was exceeded, or HTTP 408/504. */
95
+ declare class TimeoutError extends OidcError {
96
+ constructor(message: string, details?: ErrorDetails);
97
+ }
98
+ /** The service or deployment does not offer the capability (HTTP 501, missing API). */
99
+ declare class UnsupportedError extends OidcError {
100
+ constructor(message: string, details?: ErrorDetails);
101
+ }
102
+ /** The caller cancelled the operation (AbortSignal). */
103
+ declare class CancelledError extends OidcError {
104
+ constructor(message: string, details?: ErrorDetails);
105
+ }
106
+ /** Creates the subclass that matches `code`. */
107
+ declare function errorForCode(code: ErrorCode, message: string, details?: ErrorDetails): OidcError;
108
+ /** Default short reason for a code, used in messages such as `"op: not found (HTTP 404)"`. */
109
+ declare function reasonForCode(code: ErrorCode): string;
110
+ /** Maps an HTTP status (>= 400) to its canonical {@link ErrorCode} (SPEC §2.1). */
111
+ declare function codeForStatus(status: number): ErrorCode;
112
+ /** Builds the error for an HTTP error response: `"<operation>: <reason> (HTTP <status>)"`. */
113
+ declare function errorForStatus(operation: string, status: number, details?: Omit<ErrorDetails, "httpStatus"> & {
114
+ reason?: string;
115
+ }): OidcError;
116
+ /** True when `err` is an SDK error (optionally with the given code). */
117
+ declare function isOidcError(err: unknown, code?: ErrorCode): err is OidcError;
118
+
119
+ /** Structured fields attached to a log line. */
120
+ type LogFields = Record<string, unknown>;
121
+ /**
122
+ * Minimal logger the client writes diagnostics to (SPEC §2.5). Compatible with `console`,
123
+ * pino and winston loggers. The default is silent.
124
+ */
125
+ interface ClientLogger {
126
+ debug(message: string, fields?: LogFields): void;
127
+ info(message: string, fields?: LogFields): void;
128
+ warn(message: string, fields?: LogFields): void;
129
+ error(message: string, fields?: LogFields): void;
130
+ }
131
+ /** A logger that discards everything (the default). */
132
+ declare const silentLogger: ClientLogger;
133
+ /** Data passed to {@link Hooks.onRequest}. URL query values and headers are redacted. */
134
+ interface RequestInfo {
135
+ method: string;
136
+ url: string;
137
+ headers: Record<string, string>;
138
+ /** Attempt number, starting at 1. */
139
+ attempt: number;
140
+ }
141
+ /** Data passed to {@link Hooks.onResponse}. */
142
+ interface ResponseInfo {
143
+ method: string;
144
+ url: string;
145
+ status: number;
146
+ durationMs: number;
147
+ attempt: number;
148
+ requestId?: string;
149
+ }
150
+ /** Data passed to {@link Hooks.onError}. */
151
+ interface ErrorInfo {
152
+ method: string;
153
+ url: string;
154
+ error: Error;
155
+ attempt: number;
156
+ /** Whether the transport will retry after this error. */
157
+ willRetry: boolean;
158
+ }
159
+ /** Observability hooks called on every HTTP attempt. Exceptions thrown by hooks are ignored. */
160
+ interface Hooks {
161
+ onRequest?: (info: RequestInfo) => void;
162
+ onResponse?: (info: ResponseInfo) => void;
163
+ onError?: (info: ErrorInfo) => void;
164
+ }
165
+ /** Calls `fn` and swallows anything it throws (hooks and loggers must never break a call). */
166
+ declare function safeCall<A extends unknown[]>(fn: ((...args: A) => unknown) | undefined, ...args: A): void;
167
+ /** Wraps a logger so that no method ever throws. */
168
+ declare function safeLogger(logger: ClientLogger | undefined): ClientLogger;
169
+
170
+ /** Options of {@link RetryPolicy} (SPEC §2.3). */
171
+ interface RetryPolicyOptions {
172
+ /** Retries after the first attempt (default 3, so up to 4 attempts). */
173
+ maxRetries?: number;
174
+ /** Backoff cap for the first retry, in ms (default 100). */
175
+ initialBackoffMs?: number;
176
+ /** Upper bound of any backoff, in ms (default 10 000). */
177
+ maxBackoffMs?: number;
178
+ /** Exponential growth factor (default 2). */
179
+ multiplier?: number;
180
+ /** Longest `Retry-After` the client is willing to wait, in ms (default 60 000). */
181
+ maxRetryAfterMs?: number;
182
+ /** Random source in [0, 1) used for full jitter; injectable for tests. */
183
+ random?: () => number;
184
+ }
185
+ /** Retry policy with full-jitter exponential backoff. Immutable. */
186
+ declare class RetryPolicy {
187
+ static readonly DEFAULTS: Readonly<{
188
+ maxRetries: 3;
189
+ initialBackoffMs: 100;
190
+ maxBackoffMs: 10000;
191
+ multiplier: 2;
192
+ maxRetryAfterMs: 60000;
193
+ }>;
194
+ readonly maxRetries: number;
195
+ readonly initialBackoffMs: number;
196
+ readonly maxBackoffMs: number;
197
+ readonly multiplier: number;
198
+ readonly maxRetryAfterMs: number;
199
+ readonly random: () => number;
200
+ constructor(options?: RetryPolicyOptions);
201
+ /** Returns a policy from options, keeping an existing instance as is. */
202
+ static from(value: RetryPolicy | RetryPolicyOptions | undefined): RetryPolicy;
203
+ /** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
204
+ backoffCapMs(retry: number): number;
205
+ /** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
206
+ backoffMs(retry: number): number;
207
+ /** Validation problems (empty when valid). */
208
+ problems(): string[];
209
+ toJSON(): Record<string, number>;
210
+ }
211
+ /**
212
+ * Parses a `Retry-After` header (delta seconds or HTTP-date) into milliseconds from `now`.
213
+ * Returns `undefined` when absent or invalid; past dates give 0.
214
+ */
215
+ declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
216
+ /** `GET HEAD OPTIONS PUT DELETE` are idempotent. */
217
+ declare function isIdempotentMethod(method: string): boolean;
218
+ /**
219
+ * Whether a response with this status should be retried (SPEC §2.3): 429 always; 408, 502, 503,
220
+ * 504 for idempotent requests; 500 only for idempotent requests. Non-idempotent requests are
221
+ * retried only on 429.
222
+ */
223
+ declare function isRetryableStatus(status: number, idempotent: boolean): boolean;
224
+
225
+ /** TLS settings (SPEC §2.2). */
226
+ interface TlsOptions {
227
+ /** Path to a PEM CA bundle. */
228
+ caCertPath?: string;
229
+ /** PEM CA bundle contents. */
230
+ caCertPem?: string;
231
+ /** Path to a PEM client certificate (requires {@link clientKeyPath}). */
232
+ clientCertPath?: string;
233
+ /** Path to the PEM client key (requires {@link clientCertPath}). */
234
+ clientKeyPath?: string;
235
+ /** Disables certificate verification. Tests only; logs a warning once. */
236
+ insecureSkipVerify?: boolean;
237
+ }
238
+ /** Common configuration input shared by every client config (all optional). */
239
+ interface CommonConfigOptions {
240
+ /** Endpoint base URL. */
241
+ url?: string;
242
+ /** Connection setup timeout in ms (default 10 000). */
243
+ connectTimeoutMs?: number;
244
+ /** Per-attempt timeout in ms, headers + body (default 30 000). */
245
+ requestTimeoutMs?: number;
246
+ /** Whole-call timeout in ms including retries and backoff (default 120 000). */
247
+ totalTimeoutMs?: number;
248
+ /** Retry policy or its options. */
249
+ retry?: RetryPolicy | RetryPolicyOptions;
250
+ /** TLS settings. */
251
+ tls?: TlsOptions;
252
+ /** Proxy URL. Environment proxies (`HTTPS_PROXY`, …) are ignored unless set here. */
253
+ proxy?: string;
254
+ /** Extra request headers. */
255
+ headers?: Record<string, string>;
256
+ /** Appended after the standard User-Agent. */
257
+ userAgentSuffix?: string;
258
+ /** Request/response hooks. */
259
+ hooks?: Hooks;
260
+ /** Diagnostic logger (silent by default). */
261
+ logger?: ClientLogger;
262
+ }
263
+ /** Resolved common configuration (defaults applied). */
264
+ interface CommonConfig {
265
+ readonly url: string;
266
+ readonly connectTimeoutMs: number;
267
+ readonly requestTimeoutMs: number;
268
+ readonly totalTimeoutMs: number;
269
+ readonly retry: RetryPolicy;
270
+ readonly tls: Readonly<TlsOptions>;
271
+ readonly proxy?: string;
272
+ readonly headers: Readonly<Record<string, string>>;
273
+ readonly userAgentSuffix?: string;
274
+ readonly hooks?: Hooks;
275
+ readonly logger?: ClientLogger;
276
+ }
277
+ /** Default timeouts (SPEC §2.2). */
278
+ declare const DEFAULT_TIMEOUTS: Readonly<{
279
+ connectTimeoutMs: 10000;
280
+ requestTimeoutMs: 30000;
281
+ totalTimeoutMs: 120000;
282
+ }>;
283
+ /** Applies defaults to common options. Does not validate (see {@link validateCommonConfig}). */
284
+ declare function resolveCommonConfig(options: CommonConfigOptions, defaultUrl: string): CommonConfig;
285
+ /** Throws {@link ConfigError} when the common settings are invalid (SPEC §2.2). */
286
+ declare function validateCommonConfig(config: CommonConfig): void;
287
+ /** Vendor variable names consulted after `GROW_<KEY_UPPER>_<NAME>` for the common settings. */
288
+ interface CommonVendorEnv {
289
+ url?: readonly string[];
290
+ caCert?: readonly string[];
291
+ clientCert?: readonly string[];
292
+ clientKey?: readonly string[];
293
+ insecureSkipVerify?: readonly string[];
294
+ proxy?: readonly string[];
295
+ }
296
+ /** Reads the common settings from the environment (only values that are present). */
297
+ declare function readCommonEnv(reader: EnvReader, vendor?: CommonVendorEnv): CommonConfigOptions;
298
+ /** Drops keys whose value is `undefined` so they do not shadow lower-precedence values. */
299
+ declare function definedOnly<T extends object>(value: T): Partial<T>;
300
+ /**
301
+ * Merges option layers, later layers winning; `retry`, `tls` and `headers` are merged
302
+ * key by key. `undefined` values never override.
303
+ */
304
+ declare function mergeOptions<T extends CommonConfigOptions>(...layers: (Partial<T> | undefined)[]): T;
305
+ /** Debug description of the common settings with credentials redacted. */
306
+ declare function describeCommonConfig(config: CommonConfig): Record<string, unknown>;
307
+ /** Collects the revealed values of every {@link Secret} found in `values`. */
308
+ declare function secretValues(...values: unknown[]): string[];
309
+
310
+ /** Options of {@link pollUntil}. */
311
+ interface PollOptions {
312
+ /** Give up after this many ms (default 30 000). */
313
+ timeoutMs?: number;
314
+ /** Wait between attempts in ms (default 1 000). */
315
+ intervalMs?: number;
316
+ /** Caller cancellation. */
317
+ signal?: AbortSignal;
318
+ /** Name used in the timeout message (default `"poll"`). */
319
+ operation?: string;
320
+ /** Errors for which polling continues instead of failing (default: none). */
321
+ ignoreError?: (error: unknown) => boolean;
322
+ /** Test seam. */
323
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
324
+ /** Test seam: clock in ms. */
325
+ now?: () => number;
326
+ }
327
+ /**
328
+ * Calls `fn` until `predicate(value)` is true and returns that value. Throws
329
+ * {@link TimeoutError} when the time budget runs out (the message includes the last value's
330
+ * failure reason when the predicate never matched) and `CancelledError` on abort.
331
+ */
332
+ declare function pollUntil<T>(fn: (attempt: number) => Promise<T>, predicate: (value: T) => boolean, options?: PollOptions): Promise<T>;
333
+
334
+ /** Response headers that carry a vendor request id, checked in order. */
335
+ declare const DEFAULT_REQUEST_ID_HEADERS: readonly string[];
336
+ /** Longest vendor error text kept in an error message (SPEC §2.1). */
337
+ declare const MAX_VENDOR_TEXT = 300;
338
+ /** Query parameter values accepted by {@link RequestOptions.query}. */
339
+ type QueryValue = string | number | boolean | null | undefined | readonly (string | number | boolean)[];
340
+ /** How the response body is decoded. */
341
+ type ResponseType = "json" | "text" | "bytes" | "none";
342
+ /** One HTTP call made through {@link HttpTransport.request}. */
343
+ interface RequestOptions {
344
+ /** HTTP method (default `GET`). */
345
+ method?: string;
346
+ /** Path joined to the base URL (`/v1/x`), or an absolute URL. */
347
+ path: string;
348
+ /** Query parameters (`undefined`/`null` are skipped, arrays repeat the key). */
349
+ query?: Readonly<Record<string, QueryValue>>;
350
+ /** Extra headers for this call. */
351
+ headers?: Readonly<Record<string, string>>;
352
+ /** JSON body (sets `content-type: application/json`). */
353
+ json?: unknown;
354
+ /** Raw body. */
355
+ body?: string | Uint8Array;
356
+ /** Marks a non-idempotent method (e.g. `POST`) as safe to retry. */
357
+ idempotent?: boolean;
358
+ /** Caller cancellation. */
359
+ signal?: AbortSignal;
360
+ /** Operation name used in error messages (default `"<METHOD> <path>"`). */
361
+ operation?: string;
362
+ /** Per-attempt timeout override in ms. */
363
+ requestTimeoutMs?: number;
364
+ /** Whole-call timeout override in ms. */
365
+ totalTimeoutMs?: number;
366
+ /** Body decoding (default `json`; empty bodies decode to `undefined`). */
367
+ responseType?: ResponseType;
368
+ /**
369
+ * Error statuses returned to the caller instead of thrown (e.g. `[404]`). Their body is decoded
370
+ * like a success body (`data`; JSON that does not parse decodes to `undefined` instead of
371
+ * throwing) and the raw text is in {@link TransportResponse.text}.
372
+ */
373
+ allowStatus?: readonly number[];
374
+ /**
375
+ * Maps an HTTP error response of this call to an SDK error; runs before
376
+ * {@link TransportOptions.classifyError}. Return `undefined` to keep the next mapping.
377
+ */
378
+ classifyError?: ErrorClassifier;
379
+ }
380
+ /**
381
+ * An HTTP error response (status >= 400, not in `allowStatus`), passed to an
382
+ * {@link ErrorClassifier} before the transport decides about retries and calls `onError`.
383
+ */
384
+ interface ErrorResponse {
385
+ /** Operation name used in error messages (e.g. `"GET /v1/x"`). */
386
+ readonly operation: string;
387
+ readonly method: string;
388
+ readonly status: number;
389
+ readonly headers: Headers;
390
+ /**
391
+ * Raw response body text. It is NOT redacted: parse it (vendor error codes, request ids), but do
392
+ * not copy it into an error message unfiltered — use {@link reason} or
393
+ * {@link HttpTransport.redact} instead.
394
+ */
395
+ readonly body: string;
396
+ /** Vendor message extracted from the body: whitespace collapsed, redacted, truncated. */
397
+ readonly reason?: string;
398
+ readonly requestId?: string;
399
+ readonly retryAfterMs?: number;
400
+ /** 1-based attempt number. */
401
+ readonly attempt: number;
402
+ /** The error the transport throws when no classifier returns one (SPEC §2.1 mapping). */
403
+ readonly defaultError: OidcError;
404
+ }
405
+ /**
406
+ * Service-specific error mapping: returns the error to raise for an HTTP error response, or
407
+ * `undefined` to keep the default. Retries still follow the HTTP status (SPEC §2.3); a returned
408
+ * error with `retryable: false` stops them. A classifier that throws an SDK error is treated as
409
+ * if it had returned it; any other exception is ignored.
410
+ */
411
+ type ErrorClassifier = (response: ErrorResponse) => OidcError | undefined;
412
+ /** Result of {@link HttpTransport.request}. */
413
+ interface TransportResponse<T = unknown> {
414
+ status: number;
415
+ headers: Headers;
416
+ data: T;
417
+ requestId?: string;
418
+ durationMs: number;
419
+ /** Attempts made, starting at 1. */
420
+ attempts: number;
421
+ /** Raw body text of an allowed error response (status >= 400 listed in `allowStatus`). */
422
+ text?: string;
423
+ }
424
+ /** Options of {@link HttpTransport}. */
425
+ interface TransportOptions {
426
+ /** Resolved common configuration (URL, timeouts, retry, TLS, proxy, headers, hooks, logger). */
427
+ config: CommonConfig;
428
+ /** Default headers added to every request (e.g. authorization), after `config.headers`. */
429
+ defaultHeaders?: () => Readonly<Record<string, string>>;
430
+ /** Known secret values redacted from every error message, hook payload and log line. */
431
+ knownSecrets?: () => Iterable<KnownSecret>;
432
+ /** Header names that carry a vendor request id. */
433
+ requestIdHeaders?: readonly string[];
434
+ /**
435
+ * Service-specific mapping of HTTP error responses to SDK errors (e.g. a vendor error code in
436
+ * the body that means `CONFLICT`). Runs after {@link RequestOptions.classifyError} and before
437
+ * retries and the `onError` hook, so hooks see the mapped error.
438
+ */
439
+ classifyError?: ErrorClassifier;
440
+ /** Test seam: replaces the dispatcher built from TLS/proxy settings (e.g. undici `MockAgent`). */
441
+ dispatcher?: Dispatcher;
442
+ /** Test seam: replaces the backoff sleep. */
443
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
444
+ /** Test seam: clock in ms. */
445
+ now?: () => number;
446
+ }
447
+ /** Builds the undici dispatcher for the TLS, proxy and connect-timeout settings. */
448
+ declare function createDispatcher(config: CommonConfig, logger?: ClientLogger): Dispatcher;
449
+ /**
450
+ * The HTTP transport shared by every client: base URL join, query and JSON encoding, default
451
+ * headers and User-Agent, retries with full-jitter backoff and `Retry-After`, per-attempt and
452
+ * total timeouts, cancellation, hooks, logging and status → error mapping (SPEC §2.3).
453
+ */
454
+ declare class HttpTransport {
455
+ #private;
456
+ /** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
457
+ readonly userAgent: string;
458
+ readonly retry: RetryPolicy;
459
+ constructor(options: TransportOptions);
460
+ /** Whether {@link close} was called. */
461
+ get closed(): boolean;
462
+ /**
463
+ * Throws `CancelledError` (`"<operation>: client is closed"`, not retryable) once {@link close}
464
+ * was called (SPEC §2.4). Requests check this themselves; service methods that send no request
465
+ * (cached reads, local helpers) call it first.
466
+ */
467
+ ensureOpen(operation: string): void;
468
+ /** Builds the absolute URL for a path and query. */
469
+ buildUrl(path: string, query?: Readonly<Record<string, QueryValue>>): URL;
470
+ /** Redacts known secrets from a text (error messages, vendor text). */
471
+ redact(text: string): string;
472
+ /** `GET` shortcut. */
473
+ get<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
474
+ /** `POST` shortcut. */
475
+ post<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
476
+ /** `PUT` shortcut. */
477
+ put<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
478
+ /** `DELETE` shortcut. */
479
+ delete<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
480
+ /**
481
+ * Sends a request with retries; throws an SDK error on failure. Every error message passes
482
+ * through {@link redact} with the known secrets.
483
+ */
484
+ request<T = unknown>(options: RequestOptions): Promise<TransportResponse<T>>;
485
+ /**
486
+ * Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
487
+ * text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
488
+ * {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
489
+ */
490
+ vendorText(text: string): string | undefined;
491
+ /** Releases connections. Idempotent. */
492
+ close(): Promise<void>;
493
+ }
494
+ /** Redacts `key=value`/`"key": "value"` pairs with sensitive keys and bearer tokens. */
495
+ declare function redactSecretsInText(text: string): string;
496
+
497
+ /** Package version (kept in sync by release-please). */
498
+ declare const SDK_VERSION = "0.1.0";
499
+ /** Catalog key of the service (`oidc`). */
500
+ declare const PACKAGE_KEY = "oidc";
501
+ /** Language tag used in the User-Agent. */
502
+ declare const LANGUAGE = "typescript";
503
+ /** sdk-kit version this package was generated from. */
504
+ declare const SDK_KIT_VERSION = "0.3.0";
505
+
506
+ declare const INSPECT: unique symbol;
507
+ /** Options accepted by {@link OidcConfig} (all optional). */
508
+ interface OidcConfigOptions extends CommonConfigOptions {
509
+ /** API token sent as `Authorization: Bearer <token>` (env `GROW_OIDC_TOKEN`). */
510
+ token?: string | Secret;
511
+ }
512
+ /**
513
+ * Vendor environment variables read after `GROW_OIDC_*`, in order
514
+ * (e.g. `BAO_ADDR` then `VAULT_ADDR`). Filled in by the service.
515
+ */
516
+ declare const VENDOR_ENV: CommonVendorEnv & {
517
+ token: readonly string[];
518
+ };
519
+ /** Immutable configuration of {@link OidcClient}. */
520
+ declare class OidcConfig implements CommonConfig {
521
+ /** Default endpoint. */
522
+ static readonly DEFAULT_URL: string;
523
+ /** Prefix of every environment variable. */
524
+ static readonly ENV_PREFIX = "GROW_OIDC_";
525
+ readonly url: string;
526
+ readonly connectTimeoutMs: number;
527
+ readonly requestTimeoutMs: number;
528
+ readonly totalTimeoutMs: number;
529
+ readonly retry: RetryPolicy;
530
+ readonly tls: Readonly<TlsOptions>;
531
+ readonly proxy?: string;
532
+ readonly headers: Readonly<Record<string, string>>;
533
+ readonly userAgentSuffix?: string;
534
+ readonly hooks?: Hooks;
535
+ readonly logger?: ClientLogger;
536
+ /** API token. */
537
+ readonly token?: Secret;
538
+ /** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
539
+ constructor(options?: OidcConfigOptions);
540
+ /** Returns `options` when it already is a config, otherwise builds one. */
541
+ static from(options?: OidcConfigOptions): OidcConfig;
542
+ /**
543
+ * Builds a config from the environment. Precedence: explicit `overrides` >
544
+ * `GROW_OIDC_<NAME>` > vendor variables ({@link VENDOR_ENV}) > defaults.
545
+ */
546
+ static fromEnv(overrides?: OidcConfigOptions, env?: EnvMap): OidcConfig;
547
+ /** Throws {@link ConfigError} when a setting is invalid. Service rules go here. */
548
+ validate(): void;
549
+ /** Credential values to redact from error messages and logs. */
550
+ knownSecrets(): string[];
551
+ /** Debug form with every credential redacted. */
552
+ toJSON(): Record<string, unknown>;
553
+ toString(): string;
554
+ [INSPECT](): string;
555
+ }
556
+
557
+ /** Discovery document path, relative to the provider URL (keeps realm prefixes such as Keycloak's). */
558
+ declare const DISCOVERY_PATH = ".well-known/openid-configuration";
559
+ /**
560
+ * Path of an endpoint relative to the provider URL: the part after the provider URL when the
561
+ * endpoint starts with it (keeps realm prefixes out), else the endpoint's own path and query.
562
+ */
563
+ declare function relativeEndpoint(base: string, endpoint: string): string;
564
+ /** Per-call options. */
565
+ interface CallOptions {
566
+ /** Cancels the call (`CancelledError`). */
567
+ signal?: AbortSignal;
568
+ }
569
+ /** Test seams (undici `MockAgent`, fake sleep). Not part of the stable API. */
570
+ type ClientInternals = Pick<TransportOptions, "dispatcher" | "sleep" | "now">;
571
+ /** Client for OIDC. */
572
+ declare class OidcClient {
573
+ #private;
574
+ /** The immutable configuration. */
575
+ readonly config: OidcConfig;
576
+ /** Accepts a {@link OidcConfig} or plain options. */
577
+ constructor(config?: OidcConfigOptions, internals?: ClientInternals);
578
+ /** Builds a client from `GROW_OIDC_*` (and vendor) environment variables. */
579
+ static fromEnv(overrides?: OidcConfigOptions): OidcClient;
580
+ /** The shared HTTP transport (for service modules). @internal */
581
+ get transport(): HttpTransport;
582
+ /**
583
+ * Unauthenticated liveness: `GET <url>/.well-known/openid-configuration` (healthy when the
584
+ * discovery document answers 2xx). Never throws for an unhealthy or unreachable provider (only
585
+ * `CANCELLED` and `CONFIG`).
586
+ */
587
+ health(options?: CallOptions): Promise<HealthStatus>;
588
+ /**
589
+ * Authenticated round trip with the configured access token (`token`): `GET` the provider's
590
+ * `userinfo_endpoint` from discovery. Returns the latency in milliseconds; a rejected token
591
+ * raises `AuthenticationError`, a provider without userinfo `UnsupportedError`.
592
+ */
593
+ ping(options?: CallOptions): Promise<number>;
594
+ /** OpenID Connect has no version endpoint: always `UnsupportedError` (`CANCELLED` once closed). */
595
+ serverVersion(_options?: CallOptions): Promise<string>;
596
+ /** Releases connections. Idempotent. */
597
+ close(): Promise<void>;
598
+ }
599
+
600
+ /** The request shape the middleware needs; `user` is set after a successful verification. */
601
+ type AuthRequest = Exclude<RequestLike, Headers | null | undefined> & {
602
+ user?: AuthUser;
603
+ };
604
+ /** The response shape the middleware needs (Express `res`). */
605
+ interface AuthResponse {
606
+ status(code: number): AuthResponse;
607
+ setHeader(name: string, value: string): unknown;
608
+ json(body: unknown): unknown;
609
+ }
610
+ /** Express `next`. */
611
+ type NextFunction = (err?: unknown) => void;
612
+ /** An Express-style middleware. */
613
+ type AuthMiddleware = (req: AuthRequest, res: AuthResponse, next: NextFunction) => Promise<void>;
614
+ /** Options of {@link expressAuth}. */
615
+ interface ExpressAuthOptions {
616
+ /** Let requests without a token through anonymously (an invalid token is still 401). */
617
+ optional?: boolean;
618
+ }
619
+ /**
620
+ * Express middleware: verifies the bearer token and sets `req.user` ({@link AuthUser}).
621
+ * Missing token → 401 (or anonymous with `optional`), invalid token → 401, JWKS/discovery
622
+ * unreachable → 503. The response never says why a token was rejected.
623
+ */
624
+ declare function expressAuth(verifier: Verifier, options?: ExpressAuthOptions): AuthMiddleware;
625
+ /**
626
+ * Express middleware placed after {@link expressAuth}: 401 without `req.user`, 403 unless the user
627
+ * has at least one of `roles` (case-insensitive). No roles = any authenticated user.
628
+ */
629
+ declare function requireRoles(...roles: string[]): AuthMiddleware;
630
+
631
+ /** Metadata key of {@link Roles}. */
632
+ declare const ROLES_KEY = "grow:oidc:roles";
633
+ /** Metadata key of {@link Public}. */
634
+ declare const PUBLIC_KEY = "grow:oidc:public";
635
+ /** The parts of Nest's `ExecutionContext` the guards use. */
636
+ interface ExecutionContextLike {
637
+ switchToHttp(): {
638
+ getRequest(): unknown;
639
+ };
640
+ getHandler(): unknown;
641
+ getClass(): unknown;
642
+ }
643
+ /** Options of {@link NestAuthGuard}. */
644
+ interface NestAuthGuardOptions {
645
+ /** Let requests without a token through anonymously (an invalid token is still 401). */
646
+ optional?: boolean;
647
+ }
648
+ /** A decorator usable on classes and methods (legacy `experimentalDecorators`, as Nest uses). */
649
+ type ClassOrMethodDecorator = (target: object, key?: string | symbol, descriptor?: PropertyDescriptor) => void;
650
+ /** Requires at least one of `roles` on a controller or route (checked by {@link RolesGuard}). */
651
+ declare function Roles(...roles: string[]): ClassOrMethodDecorator;
652
+ /** Marks a controller or route as public: {@link NestAuthGuard} lets it through without a token. */
653
+ declare function Public(): ClassOrMethodDecorator;
654
+ type HttpExceptionCtor = new (message?: string) => Error;
655
+ declare let nestExceptions: {
656
+ unauthorized?: HttpExceptionCtor;
657
+ forbidden?: HttpExceptionCtor;
658
+ unavailable?: HttpExceptionCtor;
659
+ } | undefined;
660
+ /** Resets the cached Nest exception classes (tests). @internal */
661
+ declare function resetNestExceptionsForTests(value?: typeof nestExceptions): void;
662
+ /** An error Nest's exception filter turns into the given status (fallback without @nestjs/common). */
663
+ declare class HttpStatusError extends Error {
664
+ readonly statusCode: number;
665
+ constructor(statusCode: number, message: string);
666
+ /** Nest `HttpException`-compatible accessor. */
667
+ getStatus(): number;
668
+ }
669
+ /**
670
+ * Nest guard: verifies the bearer token and sets `request.user`. Routes marked {@link Public} pass
671
+ * without a token. Register it globally (`app.useGlobalGuards(new NestAuthGuard(verifier))` or an
672
+ * `APP_GUARD` provider with `useFactory`). 401 for a missing/invalid token, 503 when the JWKS is
673
+ * unreachable.
674
+ */
675
+ declare class NestAuthGuard {
676
+ #private;
677
+ constructor(verifier: Verifier, options?: NestAuthGuardOptions);
678
+ /** Nest `CanActivate`. */
679
+ canActivate(ctx: ExecutionContextLike): Promise<boolean>;
680
+ }
681
+ /**
682
+ * Nest guard: 403 unless `request.user` has at least one required role. The roles come from the
683
+ * constructor (`new RolesGuard(["admin"])`) or else from {@link Roles} on the route/controller;
684
+ * without either, any authenticated user passes. Runs after {@link NestAuthGuard}.
685
+ */
686
+ declare class RolesGuard {
687
+ #private;
688
+ constructor(roles?: readonly string[]);
689
+ /** Nest `CanActivate`. */
690
+ canActivate(ctx: ExecutionContextLike): boolean;
691
+ }
692
+
693
+ /**
694
+ * Reads the value at a claim path. A path is a claim name (`roles`) or a dotted path into nested
695
+ * objects (`realm_access.roles`). An exact top-level match wins over the dotted interpretation, so
696
+ * claims whose names contain dots (`https://example.com/roles`) keep working.
697
+ */
698
+ declare function claimAt(claims: Readonly<Record<string, unknown>>, path: string): unknown;
699
+ /**
700
+ * Extracts role names from the claim at `rolesClaim` (default `roles`).
701
+ *
702
+ * - a string → split on commas and whitespace (`"admin editor"`, `"admin,editor"`);
703
+ * - an array of strings and/or objects → each string, or the object's `name` (Casdoor), `code`,
704
+ * `role` or `value`;
705
+ * - anything else (missing, number, object) → `[]`.
706
+ *
707
+ * Duplicates are removed; order is kept.
708
+ */
709
+ declare function extractRoles(claims: Readonly<Record<string, unknown>>, rolesClaim?: string): string[];
710
+ /**
711
+ * True when `userRoles` contains at least one of `required` (case-insensitive). An empty
712
+ * `required` list means "any authenticated user".
713
+ */
714
+ declare function hasAnyRole(userRoles: readonly string[], required: readonly string[]): boolean;
715
+
716
+ export { AuthUser, AuthenticationError, CancelledError, ConfigError, ConflictError, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, DISCOVERY_PATH, EnvMap, EnvReader, ErrorCode, HealthStatus, HttpStatusError, HttpTransport, KnownSecret, LANGUAGE, MAX_VENDOR_TEXT, NestAuthGuard, NotFoundError, OidcClient, OidcConfig, OidcError, PACKAGE_KEY, PUBLIC_KEY, PermissionDeniedError, Public, ROLES_KEY, RateLimitError, RequestLike, RetryPolicy, Roles, RolesGuard, SDK_KIT_VERSION, SDK_VERSION, Secret, TimeoutError, UnavailableError, UnsupportedError, VENDOR_ENV, ValidationError, Verifier, claimAt, codeForStatus, createDispatcher, definedOnly, describeCommonConfig, errorForCode, errorForStatus, expressAuth, extractRoles, hasAnyRole, isIdempotentMethod, isOidcError, isRetryableStatus, mergeOptions, parseRetryAfter, pollUntil, readCommonEnv, reasonForCode, redactSecretsInText, relativeEndpoint, requireRoles, resetNestExceptionsForTests, resolveCommonConfig, safeCall, safeLogger, secretValues, silentLogger, sleep, throwIfAborted, validateCommonConfig };
717
+ export type { AuthMiddleware, AuthRequest, AuthResponse, CallOptions, ClassOrMethodDecorator, ClientInternals, ClientLogger, CommonConfig, CommonConfigOptions, CommonVendorEnv, ErrorClassifier, ErrorDetails, ErrorInfo, ErrorResponse, ExecutionContextLike, ExpressAuthOptions, Hooks, LogFields, NestAuthGuardOptions, NextFunction, OidcConfigOptions, PollOptions, QueryValue, RequestInfo, RequestOptions, ResponseInfo, ResponseType, RetryPolicyOptions, TlsOptions, TransportOptions, TransportResponse };