@grow-codes/oidc 0.0.0-stage → 0.1.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/lib/index.js ADDED
@@ -0,0 +1,1152 @@
1
+ import { Secret, EnvReader, ConfigError, REDACTED, redactUrl, OidcError, ErrorCode, sleep, CancelledError, redactText, TimeoutError, redactHeaders, errorForStatus, UnavailableError, redactError, UnsupportedError, bearerToken, hasAnyRole } from './chunk-HB2FEHOY.js';
2
+ export { AuthenticationError, CancelledError, ConfigError, ConflictError, DEFAULT_ALGORITHMS, DEFAULT_CLOCK_SKEW_MS, DEFAULT_HTTP_TIMEOUT_MS, DEFAULT_JWKS_CACHE_TTL_MS, DEFAULT_JWKS_REFRESH_COOLDOWN_MS, EnvReader, ErrorCode, MIN_SECRET_LENGTH, NotFoundError, OidcError, PermissionDeniedError, REDACTED, RateLimitError, SENSITIVE_FIELD_PARTS, Secret, TimeoutError, UnavailableError, UnsupportedError, ValidationError, Verifier, bearerToken, claimAt, codeForStatus, errorForCode, errorForStatus, extractRoles, hasAnyRole, isOidcError, isSensitiveField, isSensitiveHeader, parseBool, parseDuration, parseInteger, pollUntil, reasonForCode, redactError, redactFields, redactHeaders, redactText, redactUrl, sleep, throwIfAborted } from './chunk-HB2FEHOY.js';
3
+ import { readFileSync } from 'fs';
4
+ import { ProxyAgent, Agent, fetch } from 'undici';
5
+ import { createRequire } from 'module';
6
+ import { join } from 'path';
7
+
8
+ // src/core/health.ts
9
+ var HEALTHY_WORDS = /* @__PURE__ */ new Set([
10
+ "ok",
11
+ "up",
12
+ "healthy",
13
+ "pass",
14
+ "passing",
15
+ "green",
16
+ "ready",
17
+ "available",
18
+ "running",
19
+ "serving"
20
+ ]);
21
+ function isHealthyWord(status) {
22
+ return HEALTHY_WORDS.has(status.trim().toLowerCase());
23
+ }
24
+ function healthStatus(status, details = {}, healthy = isHealthyWord(status)) {
25
+ const flat = {};
26
+ for (const [k, v] of Object.entries(details)) {
27
+ if (v === void 0 || v === null) continue;
28
+ if (typeof v === "string") flat[k] = v;
29
+ else if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint")
30
+ flat[k] = String(v);
31
+ else if (typeof v === "object") flat[k] = JSON.stringify(v);
32
+ }
33
+ return { healthy, status, details: flat };
34
+ }
35
+ async function probeHealth(probe) {
36
+ try {
37
+ return await probe();
38
+ } catch (err) {
39
+ if (err instanceof OidcError) {
40
+ if (err.code === ErrorCode.Cancelled || err.code === ErrorCode.Config) throw err;
41
+ if (err.httpStatus !== void 0) {
42
+ return healthStatus("unhealthy", { httpStatus: err.httpStatus, error: err.code }, false);
43
+ }
44
+ return healthStatus("unreachable", { error: err.code }, false);
45
+ }
46
+ return healthStatus("unreachable", { error: ErrorCode.Unavailable }, false);
47
+ }
48
+ }
49
+
50
+ // src/core/hooks.ts
51
+ var silentLogger = Object.freeze({
52
+ debug: () => void 0,
53
+ info: () => void 0,
54
+ warn: () => void 0,
55
+ error: () => void 0
56
+ });
57
+ function safeCall(fn, ...args) {
58
+ if (fn === void 0) return;
59
+ try {
60
+ const result = fn(...args);
61
+ if (result instanceof Promise) result.catch(() => void 0);
62
+ } catch {
63
+ }
64
+ }
65
+ function safeLogger(logger) {
66
+ if (logger === void 0) return silentLogger;
67
+ return {
68
+ debug: (m, f) => {
69
+ safeCall(
70
+ (a, b) => {
71
+ logger.debug(a, b);
72
+ },
73
+ m,
74
+ f
75
+ );
76
+ },
77
+ info: (m, f) => {
78
+ safeCall(
79
+ (a, b) => {
80
+ logger.info(a, b);
81
+ },
82
+ m,
83
+ f
84
+ );
85
+ },
86
+ warn: (m, f) => {
87
+ safeCall(
88
+ (a, b) => {
89
+ logger.warn(a, b);
90
+ },
91
+ m,
92
+ f
93
+ );
94
+ },
95
+ error: (m, f) => {
96
+ safeCall(
97
+ (a, b) => {
98
+ logger.error(a, b);
99
+ },
100
+ m,
101
+ f
102
+ );
103
+ }
104
+ };
105
+ }
106
+
107
+ // src/core/retry.ts
108
+ var RetryPolicy = class _RetryPolicy {
109
+ static DEFAULTS = Object.freeze({
110
+ maxRetries: 3,
111
+ initialBackoffMs: 100,
112
+ maxBackoffMs: 1e4,
113
+ multiplier: 2,
114
+ maxRetryAfterMs: 6e4
115
+ });
116
+ maxRetries;
117
+ initialBackoffMs;
118
+ maxBackoffMs;
119
+ multiplier;
120
+ maxRetryAfterMs;
121
+ random;
122
+ constructor(options = {}) {
123
+ const d = _RetryPolicy.DEFAULTS;
124
+ this.maxRetries = options.maxRetries ?? d.maxRetries;
125
+ this.initialBackoffMs = options.initialBackoffMs ?? d.initialBackoffMs;
126
+ this.maxBackoffMs = options.maxBackoffMs ?? d.maxBackoffMs;
127
+ this.multiplier = options.multiplier ?? d.multiplier;
128
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? d.maxRetryAfterMs;
129
+ this.random = options.random ?? Math.random;
130
+ Object.freeze(this);
131
+ }
132
+ /** Returns a policy from options, keeping an existing instance as is. */
133
+ static from(value) {
134
+ return value instanceof _RetryPolicy ? value : new _RetryPolicy(value);
135
+ }
136
+ /** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
137
+ backoffCapMs(retry) {
138
+ return Math.min(this.maxBackoffMs, this.initialBackoffMs * this.multiplier ** retry);
139
+ }
140
+ /** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
141
+ backoffMs(retry) {
142
+ return this.random() * this.backoffCapMs(retry);
143
+ }
144
+ /** Validation problems (empty when valid). */
145
+ problems() {
146
+ const out = [];
147
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0)
148
+ out.push("retry.maxRetries must be an integer >= 0");
149
+ if (!(this.initialBackoffMs >= 0)) out.push("retry.initialBackoffMs must be >= 0");
150
+ if (!(this.maxBackoffMs >= 0)) out.push("retry.maxBackoffMs must be >= 0");
151
+ if (!(this.multiplier >= 1)) out.push("retry.multiplier must be >= 1");
152
+ if (!(this.maxRetryAfterMs >= 0)) out.push("retry.maxRetryAfterMs must be >= 0");
153
+ return out;
154
+ }
155
+ toJSON() {
156
+ return {
157
+ maxRetries: this.maxRetries,
158
+ initialBackoffMs: this.initialBackoffMs,
159
+ maxBackoffMs: this.maxBackoffMs,
160
+ multiplier: this.multiplier,
161
+ maxRetryAfterMs: this.maxRetryAfterMs
162
+ };
163
+ }
164
+ };
165
+ function parseRetryAfter(value, now = Date.now()) {
166
+ if (value === null || value === void 0) return void 0;
167
+ const text = value.trim();
168
+ if (text === "") return void 0;
169
+ if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1e3);
170
+ if (!/[a-z]/i.test(text)) return void 0;
171
+ const at = Date.parse(text);
172
+ if (Number.isNaN(at)) return void 0;
173
+ return Math.max(0, at - now);
174
+ }
175
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
176
+ "GET",
177
+ "HEAD",
178
+ "OPTIONS",
179
+ "PUT",
180
+ "DELETE"
181
+ ]);
182
+ function isIdempotentMethod(method) {
183
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
184
+ }
185
+ function isRetryableStatus(status, idempotent) {
186
+ if (status === 429) return true;
187
+ if (!idempotent) return false;
188
+ return status === 408 || status === 500 || status === 502 || status === 503 || status === 504;
189
+ }
190
+
191
+ // src/core/options.ts
192
+ var DEFAULT_TIMEOUTS = Object.freeze({
193
+ connectTimeoutMs: 1e4,
194
+ requestTimeoutMs: 3e4,
195
+ totalTimeoutMs: 12e4
196
+ });
197
+ function resolveCommonConfig(options, defaultUrl) {
198
+ const out = {
199
+ url: options.url ?? defaultUrl,
200
+ connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_TIMEOUTS.connectTimeoutMs,
201
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_TIMEOUTS.requestTimeoutMs,
202
+ totalTimeoutMs: options.totalTimeoutMs ?? DEFAULT_TIMEOUTS.totalTimeoutMs,
203
+ retry: RetryPolicy.from(options.retry),
204
+ tls: Object.freeze({ ...options.tls }),
205
+ headers: Object.freeze({ ...options.headers })
206
+ };
207
+ if (options.proxy !== void 0) out.proxy = options.proxy;
208
+ if (options.userAgentSuffix !== void 0) out.userAgentSuffix = options.userAgentSuffix;
209
+ if (options.hooks !== void 0) out.hooks = options.hooks;
210
+ if (options.logger !== void 0) out.logger = options.logger;
211
+ return out;
212
+ }
213
+ function isHttpUrl(value) {
214
+ try {
215
+ const u = new URL(value);
216
+ return u.protocol === "http:" || u.protocol === "https:";
217
+ } catch {
218
+ return false;
219
+ }
220
+ }
221
+ function validateCommonConfig(config) {
222
+ const problems = [];
223
+ if (!isHttpUrl(config.url)) problems.push("url must be an http or https URL");
224
+ for (const key of ["connectTimeoutMs", "requestTimeoutMs", "totalTimeoutMs"]) {
225
+ const v = config[key];
226
+ if (!Number.isFinite(v) || v <= 0) problems.push(`${key} must be a positive number`);
227
+ }
228
+ problems.push(...config.retry.problems());
229
+ const tls = config.tls;
230
+ if (tls.clientCertPath === void 0 !== (tls.clientKeyPath === void 0)) {
231
+ problems.push("tls.clientCertPath and tls.clientKeyPath must be given together");
232
+ }
233
+ if (config.proxy !== void 0 && !isHttpUrl(config.proxy)) {
234
+ problems.push("proxy must be an http or https URL");
235
+ }
236
+ if (problems.length > 0) throw new ConfigError(`invalid configuration: ${problems.join("; ")}`);
237
+ }
238
+ function readCommonEnv(reader, vendor = {}) {
239
+ const out = {};
240
+ const url = reader.string("URL", vendor.url);
241
+ if (url !== void 0) out.url = url;
242
+ const connect = reader.duration("CONNECT_TIMEOUT");
243
+ if (connect !== void 0) out.connectTimeoutMs = connect;
244
+ const request = reader.duration("REQUEST_TIMEOUT");
245
+ if (request !== void 0) out.requestTimeoutMs = request;
246
+ const total = reader.duration("TOTAL_TIMEOUT");
247
+ if (total !== void 0) out.totalTimeoutMs = total;
248
+ const maxRetries = reader.int("MAX_RETRIES");
249
+ if (maxRetries !== void 0) out.retry = { maxRetries };
250
+ const tls = {};
251
+ const ca = reader.string("CA_CERT", vendor.caCert);
252
+ if (ca !== void 0) tls.caCertPath = ca;
253
+ const cert = reader.string("CLIENT_CERT", vendor.clientCert);
254
+ if (cert !== void 0) tls.clientCertPath = cert;
255
+ const key = reader.string("CLIENT_KEY", vendor.clientKey);
256
+ if (key !== void 0) tls.clientKeyPath = key;
257
+ const insecure = reader.bool("INSECURE_SKIP_VERIFY", vendor.insecureSkipVerify);
258
+ if (insecure !== void 0) tls.insecureSkipVerify = insecure;
259
+ if (Object.keys(tls).length > 0) out.tls = tls;
260
+ const proxy = reader.string("PROXY", vendor.proxy);
261
+ if (proxy !== void 0) out.proxy = proxy;
262
+ return out;
263
+ }
264
+ function definedOnly(value) {
265
+ const out = {};
266
+ for (const [k, v] of Object.entries(value)) {
267
+ if (v !== void 0) out[k] = v;
268
+ }
269
+ return out;
270
+ }
271
+ function mergeOptions(...layers) {
272
+ const out = {};
273
+ for (const layer of layers) {
274
+ if (layer === void 0) continue;
275
+ for (const [k, v] of Object.entries(definedOnly(layer))) {
276
+ const prev = out[k];
277
+ if ((k === "tls" || k === "headers" || k === "retry" && !(v instanceof RetryPolicy)) && typeof prev === "object" && prev !== null) {
278
+ const base = prev instanceof RetryPolicy ? prev.toJSON() : prev;
279
+ out[k] = { ...base, ...definedOnly(v) };
280
+ } else {
281
+ out[k] = v;
282
+ }
283
+ }
284
+ }
285
+ return out;
286
+ }
287
+ function describeCommonConfig(config) {
288
+ const headers = {};
289
+ for (const k of Object.keys(config.headers)) headers[k] = REDACTED;
290
+ const out = {
291
+ url: redactUrl(config.url),
292
+ connectTimeoutMs: config.connectTimeoutMs,
293
+ requestTimeoutMs: config.requestTimeoutMs,
294
+ totalTimeoutMs: config.totalTimeoutMs,
295
+ retry: config.retry.toJSON(),
296
+ tls: {
297
+ ...config.tls,
298
+ ...config.tls.caCertPem === void 0 ? {} : { caCertPem: REDACTED }
299
+ },
300
+ headers
301
+ };
302
+ if (config.proxy !== void 0) out.proxy = redactUrl(config.proxy);
303
+ if (config.userAgentSuffix !== void 0) out.userAgentSuffix = config.userAgentSuffix;
304
+ return out;
305
+ }
306
+ function secretValues(...values) {
307
+ return values.filter((v) => v instanceof Secret).map((s) => s.reveal());
308
+ }
309
+
310
+ // src/core/version.ts
311
+ var SDK_VERSION = "0.1.1";
312
+ var PACKAGE_KEY = "oidc";
313
+ var LANGUAGE = "typescript";
314
+ var SDK_KIT_VERSION = "0.3.0";
315
+
316
+ // src/core/transport.ts
317
+ var DEFAULT_REQUEST_ID_HEADERS = [
318
+ "x-request-id",
319
+ "x-amzn-requestid",
320
+ "x-amz-request-id",
321
+ "x-datadog-request-id",
322
+ "request-id",
323
+ "x-correlation-id"
324
+ ];
325
+ var MAX_VENDOR_TEXT = 300;
326
+ var PRE_SEND_CODES = /* @__PURE__ */ new Set([
327
+ "ECONNREFUSED",
328
+ "ENOTFOUND",
329
+ "EAI_AGAIN",
330
+ "EHOSTUNREACH",
331
+ "ENETUNREACH",
332
+ "EADDRNOTAVAIL",
333
+ "UND_ERR_CONNECT_TIMEOUT"
334
+ ]);
335
+ var TLS_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS|ERR_SSL|DEPTH_ZERO/;
336
+ var CANCEL = /* @__PURE__ */ Symbol("cancel");
337
+ var ATTEMPT_TIMEOUT = /* @__PURE__ */ Symbol("attempt-timeout");
338
+ var insecureWarned = false;
339
+ var AbortedAttempt = class extends Error {
340
+ kind;
341
+ constructor(kind) {
342
+ super("aborted");
343
+ this.kind = kind;
344
+ }
345
+ };
346
+ function errorCode(err) {
347
+ let current = err;
348
+ for (let depth = 0; depth < 5 && current !== void 0 && current !== null; depth++) {
349
+ const code = current.code;
350
+ if (typeof code === "string") return code;
351
+ current = current.cause;
352
+ }
353
+ return void 0;
354
+ }
355
+ function readPem(path) {
356
+ return path === void 0 ? void 0 : readFileSync(path, "utf8");
357
+ }
358
+ function createDispatcher(config, logger = safeLogger(config.logger)) {
359
+ const tls = config.tls;
360
+ if (tls.insecureSkipVerify === true && !insecureWarned) {
361
+ insecureWarned = true;
362
+ logger.warn("TLS certificate verification is disabled (insecureSkipVerify); use only in tests");
363
+ }
364
+ const caParts = [tls.caCertPem, readPem(tls.caCertPath)].filter(
365
+ (v) => v !== void 0
366
+ );
367
+ const tlsOptions = {
368
+ timeout: config.connectTimeoutMs,
369
+ rejectUnauthorized: tls.insecureSkipVerify !== true,
370
+ ...caParts.length > 0 ? { ca: caParts } : {},
371
+ ...tls.clientCertPath === void 0 ? {} : { cert: readPem(tls.clientCertPath) },
372
+ ...tls.clientKeyPath === void 0 ? {} : { key: readPem(tls.clientKeyPath) }
373
+ };
374
+ if (config.proxy !== void 0) {
375
+ return new ProxyAgent({
376
+ uri: config.proxy,
377
+ connect: { timeout: config.connectTimeoutMs },
378
+ requestTls: tlsOptions
379
+ });
380
+ }
381
+ return new Agent({ connect: tlsOptions });
382
+ }
383
+ var HttpTransport = class {
384
+ /** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
385
+ userAgent;
386
+ retry;
387
+ #config;
388
+ #options;
389
+ #logger;
390
+ #hooks;
391
+ #fetch;
392
+ #sleep;
393
+ #now;
394
+ #requestIdHeaders;
395
+ #dispatcher;
396
+ #closed = false;
397
+ constructor(options) {
398
+ this.#options = options;
399
+ this.#config = options.config;
400
+ this.retry = options.config.retry;
401
+ this.#logger = safeLogger(options.config.logger);
402
+ this.#hooks = options.config.hooks ?? {};
403
+ this.#fetch = fetch;
404
+ this.#sleep = options.sleep ?? sleep;
405
+ this.#now = options.now ?? Date.now;
406
+ this.#requestIdHeaders = options.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS;
407
+ this.#dispatcher = options.dispatcher;
408
+ const suffix = options.config.userAgentSuffix;
409
+ this.userAgent = `grow-codes-${PACKAGE_KEY}/${SDK_VERSION} (${LANGUAGE})` + (suffix !== void 0 && suffix !== "" ? ` ${suffix}` : "");
410
+ }
411
+ /** Whether {@link close} was called. */
412
+ get closed() {
413
+ return this.#closed;
414
+ }
415
+ /**
416
+ * Throws `CancelledError` (`"<operation>: client is closed"`, not retryable) once {@link close}
417
+ * was called (SPEC §2.4). Requests check this themselves; service methods that send no request
418
+ * (cached reads, local helpers) call it first.
419
+ */
420
+ ensureOpen(operation) {
421
+ if (this.#closed) throw new CancelledError(`${operation}: client is closed`);
422
+ }
423
+ /** Builds the absolute URL for a path and query. */
424
+ buildUrl(path, query) {
425
+ let url;
426
+ if (/^https?:\/\//i.test(path)) {
427
+ url = new URL(path);
428
+ } else {
429
+ const base = this.#config.url.endsWith("/") ? this.#config.url : this.#config.url + "/";
430
+ url = new URL(path.replace(/^\/+/, ""), base);
431
+ }
432
+ for (const [k, v] of Object.entries(query ?? {})) {
433
+ if (v === void 0 || v === null) continue;
434
+ if (Array.isArray(v)) {
435
+ for (const item of v)
436
+ url.searchParams.append(k, String(item));
437
+ } else {
438
+ url.searchParams.append(k, String(v));
439
+ }
440
+ }
441
+ return url;
442
+ }
443
+ /** Redacts known secrets from a text (error messages, vendor text). */
444
+ redact(text) {
445
+ return redactText(text, this.#knownSecrets());
446
+ }
447
+ #knownSecrets() {
448
+ return [...this.#options.knownSecrets?.() ?? []];
449
+ }
450
+ #getDispatcher() {
451
+ this.#dispatcher ??= createDispatcher(this.#config, this.#logger);
452
+ return this.#dispatcher;
453
+ }
454
+ /** `GET` shortcut. */
455
+ get(path, options = {}) {
456
+ return this.request({ ...options, method: "GET", path });
457
+ }
458
+ /** `POST` shortcut. */
459
+ post(path, options = {}) {
460
+ return this.request({ ...options, method: "POST", path });
461
+ }
462
+ /** `PUT` shortcut. */
463
+ put(path, options = {}) {
464
+ return this.request({ ...options, method: "PUT", path });
465
+ }
466
+ /** `DELETE` shortcut. */
467
+ delete(path, options = {}) {
468
+ return this.request({ ...options, method: "DELETE", path });
469
+ }
470
+ /**
471
+ * Sends a request with retries; throws an SDK error on failure. Every error message passes
472
+ * through {@link redact} with the known secrets.
473
+ */
474
+ async request(options) {
475
+ try {
476
+ return await this.#request(options);
477
+ } catch (err) {
478
+ if (err instanceof OidcError) err.message = this.redact(err.message);
479
+ throw err;
480
+ }
481
+ }
482
+ async #request(options) {
483
+ const method = (options.method ?? "GET").toUpperCase();
484
+ const operation = options.operation ?? `${method} ${options.path.split("?")[0] ?? ""}`;
485
+ this.ensureOpen(operation);
486
+ const signal = options.signal;
487
+ if (signal?.aborted === true) throw new CancelledError(`${operation}: cancelled`);
488
+ const url = this.buildUrl(options.path, options.query);
489
+ const safeUrl = redactUrl(url);
490
+ const headers = this.#buildHeaders(options);
491
+ const body = options.json !== void 0 ? JSON.stringify(options.json) : options.body;
492
+ const idempotent = options.idempotent ?? isIdempotentMethod(method);
493
+ const requestTimeout = options.requestTimeoutMs ?? this.#config.requestTimeoutMs;
494
+ const totalTimeout = options.totalTimeoutMs ?? this.#config.totalTimeoutMs;
495
+ const start = this.#now();
496
+ const deadline = start + totalTimeout;
497
+ const policy = this.retry;
498
+ for (let attempt = 1; ; attempt++) {
499
+ const remaining = deadline - this.#now();
500
+ if (remaining <= 0) {
501
+ throw new TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`);
502
+ }
503
+ const attemptTimeout = Math.min(requestTimeout, remaining);
504
+ const isTotal = attemptTimeout < requestTimeout;
505
+ safeCall(this.#hooks.onRequest, {
506
+ method,
507
+ url: safeUrl,
508
+ headers: redactHeaders(headers),
509
+ attempt
510
+ });
511
+ this.#logger.debug("http request", { method, url: safeUrl, attempt });
512
+ const attemptStart = this.#now();
513
+ let failure;
514
+ let willRetry = false;
515
+ let waitMs = 0;
516
+ try {
517
+ const res = await this.#attempt(
518
+ url,
519
+ method,
520
+ headers,
521
+ body,
522
+ attemptTimeout,
523
+ signal,
524
+ options.responseType ?? "json",
525
+ options.allowStatus ?? []
526
+ );
527
+ const durationMs = this.#now() - attemptStart;
528
+ const requestId = this.#requestId(res.headers);
529
+ safeCall(this.#hooks.onResponse, {
530
+ method,
531
+ url: safeUrl,
532
+ status: res.status,
533
+ durationMs,
534
+ attempt,
535
+ ...requestId === void 0 ? {} : { requestId }
536
+ });
537
+ this.#logger.debug("http response", {
538
+ method,
539
+ url: safeUrl,
540
+ status: res.status,
541
+ durationMs,
542
+ attempt
543
+ });
544
+ if (res.status < 400 || options.allowStatus?.includes(res.status) === true) {
545
+ return {
546
+ status: res.status,
547
+ headers: res.headers,
548
+ data: res.data,
549
+ ...requestId === void 0 ? {} : { requestId },
550
+ durationMs: this.#now() - start,
551
+ attempts: attempt,
552
+ ...res.status >= 400 ? { text: res.text } : {}
553
+ };
554
+ }
555
+ const retryAfter = res.status === 429 || res.status === 503 ? parseRetryAfter(res.headers.get("retry-after"), this.#now()) : void 0;
556
+ const reason = this.vendorText(res.text);
557
+ const defaultError = errorForStatus(operation, res.status, {
558
+ ...reason === void 0 ? {} : { reason },
559
+ ...requestId === void 0 ? {} : { requestId },
560
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
561
+ });
562
+ const classified = this.#classifyResponse(options.classifyError, {
563
+ operation,
564
+ method,
565
+ status: res.status,
566
+ headers: res.headers,
567
+ body: res.text,
568
+ ...reason === void 0 ? {} : { reason },
569
+ ...requestId === void 0 ? {} : { requestId },
570
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter },
571
+ attempt,
572
+ defaultError
573
+ });
574
+ failure = classified ?? defaultError;
575
+ if (isRetryableStatus(res.status, idempotent) && (classified === void 0 || classified.retryable) && attempt <= policy.maxRetries) {
576
+ const backoff = policy.backoffMs(attempt - 1);
577
+ if (retryAfter !== void 0) {
578
+ if (retryAfter > policy.maxRetryAfterMs || retryAfter >= deadline - this.#now()) {
579
+ willRetry = false;
580
+ } else {
581
+ willRetry = true;
582
+ waitMs = Math.max(retryAfter, backoff);
583
+ }
584
+ } else {
585
+ willRetry = true;
586
+ waitMs = backoff;
587
+ }
588
+ }
589
+ } catch (err) {
590
+ failure = this.#classify(err, operation, attemptTimeout, isTotal, totalTimeout);
591
+ const preSend = PRE_SEND_CODES.has(errorCode(err) ?? "");
592
+ willRetry = failure.retryable && !(failure.code === "TIMEOUT" && isTotal) && (idempotent || preSend) && attempt <= policy.maxRetries;
593
+ waitMs = willRetry ? policy.backoffMs(attempt - 1) : 0;
594
+ }
595
+ if (willRetry && waitMs >= deadline - this.#now()) {
596
+ safeCall(this.#hooks.onError, {
597
+ method,
598
+ url: safeUrl,
599
+ error: failure,
600
+ attempt,
601
+ willRetry: false
602
+ });
603
+ throw new TimeoutError(
604
+ `${operation}: total timeout of ${totalTimeout} ms exceeded after ${attempt} attempts`,
605
+ {
606
+ cause: failure,
607
+ ...failure.httpStatus === void 0 ? {} : { httpStatus: failure.httpStatus },
608
+ ...failure.requestId === void 0 ? {} : { requestId: failure.requestId }
609
+ }
610
+ );
611
+ }
612
+ safeCall(this.#hooks.onError, { method, url: safeUrl, error: failure, attempt, willRetry });
613
+ if (!willRetry) {
614
+ this.#logger.debug("http call failed", {
615
+ method,
616
+ url: safeUrl,
617
+ attempt,
618
+ code: failure.code
619
+ });
620
+ throw failure;
621
+ }
622
+ this.#logger.warn("http call failed, retrying", {
623
+ method,
624
+ url: safeUrl,
625
+ attempt,
626
+ code: failure.code,
627
+ waitMs: Math.round(waitMs)
628
+ });
629
+ await this.#sleep(waitMs, signal).catch((err) => {
630
+ throw err instanceof OidcError ? err : new CancelledError(`${operation}: cancelled`);
631
+ });
632
+ }
633
+ }
634
+ #buildHeaders(options) {
635
+ const headers = {
636
+ accept: "application/json",
637
+ "user-agent": this.userAgent
638
+ };
639
+ const layers = [
640
+ this.#config.headers,
641
+ this.#options.defaultHeaders?.() ?? {},
642
+ options.headers ?? {}
643
+ ];
644
+ for (const layer of layers) {
645
+ for (const [k, v] of Object.entries(layer)) headers[k.toLowerCase()] = v;
646
+ }
647
+ if (options.json !== void 0 && headers["content-type"] === void 0) {
648
+ headers["content-type"] = "application/json";
649
+ }
650
+ return headers;
651
+ }
652
+ async #attempt(url, method, headers, body, timeoutMs, signal, responseType, allowStatus) {
653
+ const controller = new AbortController();
654
+ const timer = setTimeout(() => {
655
+ controller.abort(ATTEMPT_TIMEOUT);
656
+ }, timeoutMs);
657
+ timer.unref();
658
+ const onAbort = () => {
659
+ controller.abort(CANCEL);
660
+ };
661
+ signal?.addEventListener("abort", onAbort, { once: true });
662
+ try {
663
+ const init = {
664
+ method,
665
+ headers,
666
+ signal: controller.signal,
667
+ dispatcher: this.#getDispatcher(),
668
+ redirect: "follow"
669
+ };
670
+ if (body !== void 0) init.body = body;
671
+ const res = await this.#fetch(url, init);
672
+ const bytes = new Uint8Array(await res.arrayBuffer());
673
+ const isError = res.status >= 400;
674
+ const allowed = isError && allowStatus.includes(res.status);
675
+ const text = isError || responseType === "json" || responseType === "text" ? new TextDecoder().decode(bytes) : "";
676
+ let data;
677
+ if (isError && !allowed || responseType === "none") {
678
+ data = void 0;
679
+ } else if (responseType === "bytes") {
680
+ data = bytes;
681
+ } else if (responseType === "text") {
682
+ data = text;
683
+ } else if (allowed) {
684
+ data = parseJsonOrUndefined(text);
685
+ } else {
686
+ data = this.#parseJson(text, res.status);
687
+ }
688
+ return { status: res.status, headers: res.headers, data, text };
689
+ } catch (err) {
690
+ const reason = controller.signal.reason;
691
+ if (controller.signal.aborted && (reason === CANCEL || reason === ATTEMPT_TIMEOUT)) {
692
+ throw new AbortedAttempt(reason);
693
+ }
694
+ throw err;
695
+ } finally {
696
+ clearTimeout(timer);
697
+ signal?.removeEventListener("abort", onAbort);
698
+ }
699
+ }
700
+ #parseJson(text, status) {
701
+ if (text.trim() === "") return void 0;
702
+ try {
703
+ return JSON.parse(text);
704
+ } catch {
705
+ throw new UnavailableError(`invalid JSON in response (HTTP ${status})`, {
706
+ retryable: false,
707
+ httpStatus: status
708
+ });
709
+ }
710
+ }
711
+ #classify(err, operation, timeoutMs, isTotal, totalTimeout) {
712
+ if (err instanceof OidcError) return err;
713
+ if (err instanceof AbortedAttempt) {
714
+ if (err.kind === CANCEL) return new CancelledError(`${operation}: cancelled`);
715
+ return isTotal ? new TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`) : new TimeoutError(`${operation}: request timed out after ${timeoutMs} ms`);
716
+ }
717
+ const cause = redactError(err, this.#knownSecrets());
718
+ const code = errorCode(err);
719
+ if (code === "UND_ERR_CONNECT_TIMEOUT") {
720
+ return new TimeoutError(
721
+ `${operation}: connect timeout after ${this.#config.connectTimeoutMs} ms`,
722
+ { cause }
723
+ );
724
+ }
725
+ if (code !== void 0 && TLS_CODE.test(code)) {
726
+ return new UnavailableError(`${operation}: TLS error (${code})`, { cause, retryable: false });
727
+ }
728
+ return new UnavailableError(
729
+ `${operation}: network error${code === void 0 ? "" : ` (${code})`}`,
730
+ { cause }
731
+ );
732
+ }
733
+ #classifyResponse(perRequest, response) {
734
+ for (const classify of [perRequest, this.#options.classifyError]) {
735
+ if (classify === void 0) continue;
736
+ let mapped;
737
+ try {
738
+ mapped = classify(response);
739
+ } catch (err) {
740
+ mapped = err instanceof OidcError ? err : void 0;
741
+ }
742
+ if (mapped instanceof OidcError) return mapped;
743
+ }
744
+ return void 0;
745
+ }
746
+ /**
747
+ * Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
748
+ * text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
749
+ * {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
750
+ */
751
+ vendorText(text) {
752
+ const trimmed = text.trim();
753
+ if (trimmed === "") return void 0;
754
+ let extracted;
755
+ try {
756
+ extracted = extractMessage(JSON.parse(trimmed));
757
+ } catch {
758
+ extracted = /^\s*</.test(trimmed) ? void 0 : trimmed;
759
+ }
760
+ const collapsed = extracted?.replace(/\s+/g, " ").trim();
761
+ if (collapsed === void 0 || collapsed === "") return void 0;
762
+ const redacted = redactSecretsInText(this.redact(collapsed));
763
+ return redacted.length > MAX_VENDOR_TEXT ? redacted.slice(0, MAX_VENDOR_TEXT - 1).trimEnd() + "\u2026" : redacted;
764
+ }
765
+ #requestId(headers) {
766
+ for (const name of this.#requestIdHeaders) {
767
+ const v = headers.get(name);
768
+ if (v !== null && v !== "") return v;
769
+ }
770
+ return void 0;
771
+ }
772
+ /** Releases connections. Idempotent. */
773
+ async close() {
774
+ if (this.#closed) return;
775
+ this.#closed = true;
776
+ const dispatcher = this.#dispatcher;
777
+ this.#dispatcher = void 0;
778
+ if (dispatcher !== void 0 && this.#options.dispatcher === void 0) {
779
+ await dispatcher.close().catch(() => void 0);
780
+ }
781
+ }
782
+ };
783
+ function parseJsonOrUndefined(text) {
784
+ if (text.trim() === "") return void 0;
785
+ try {
786
+ return JSON.parse(text);
787
+ } catch {
788
+ return void 0;
789
+ }
790
+ }
791
+ function extractMessage(body) {
792
+ if (typeof body === "string") return body;
793
+ if (body === null || typeof body !== "object") return void 0;
794
+ if (Array.isArray(body)) return body.length > 0 ? extractMessage(body[0]) : void 0;
795
+ const obj = body;
796
+ for (const key of [
797
+ "message",
798
+ "error_description",
799
+ "error",
800
+ "errors",
801
+ "detail",
802
+ "msg",
803
+ "title",
804
+ "reason"
805
+ ]) {
806
+ const found = extractMessage(obj[key]);
807
+ if (found !== void 0 && found !== "") return found;
808
+ }
809
+ return void 0;
810
+ }
811
+ var SECRET_ASSIGNMENT = /((?:password|passwd|secret|token|authorization|api[_-]?key|access[_-]?key|private[_-]?key|credential|session|signature)["']?\s*[:=]\s*["']?)([^"'\s,;&}]+)/gi;
812
+ var BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi;
813
+ function redactSecretsInText(text) {
814
+ return text.replace(BEARER, "$1 [REDACTED]").replace(SECRET_ASSIGNMENT, "$1[REDACTED]");
815
+ }
816
+
817
+ // src/config.ts
818
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
819
+ var CATALOG_PORT = "8000";
820
+ var VENDOR_ENV = {
821
+ url: [],
822
+ token: []
823
+ };
824
+ var OidcConfig = class _OidcConfig {
825
+ /** Default endpoint. */
826
+ static DEFAULT_URL = `http://127.0.0.1:${/\d+/.exec(CATALOG_PORT)?.[0] ?? "8080"}`;
827
+ /** Prefix of every environment variable. */
828
+ static ENV_PREFIX = "GROW_OIDC_";
829
+ url;
830
+ connectTimeoutMs;
831
+ requestTimeoutMs;
832
+ totalTimeoutMs;
833
+ retry;
834
+ tls;
835
+ proxy;
836
+ headers;
837
+ userAgentSuffix;
838
+ hooks;
839
+ logger;
840
+ /** API token. */
841
+ token;
842
+ /** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
843
+ constructor(options = {}) {
844
+ const common = resolveCommonConfig(options, _OidcConfig.DEFAULT_URL);
845
+ this.url = common.url;
846
+ this.connectTimeoutMs = common.connectTimeoutMs;
847
+ this.requestTimeoutMs = common.requestTimeoutMs;
848
+ this.totalTimeoutMs = common.totalTimeoutMs;
849
+ this.retry = common.retry;
850
+ this.tls = common.tls;
851
+ this.headers = common.headers;
852
+ if (common.proxy !== void 0) this.proxy = common.proxy;
853
+ if (common.userAgentSuffix !== void 0) this.userAgentSuffix = common.userAgentSuffix;
854
+ if (common.hooks !== void 0) this.hooks = common.hooks;
855
+ if (common.logger !== void 0) this.logger = common.logger;
856
+ const token = Secret.from(options.token);
857
+ if (token !== void 0) this.token = token;
858
+ this.validate();
859
+ Object.freeze(this);
860
+ }
861
+ /** Returns `options` when it already is a config, otherwise builds one. */
862
+ static from(options = {}) {
863
+ if (options instanceof _OidcConfig) return options;
864
+ return new _OidcConfig(options);
865
+ }
866
+ /**
867
+ * Builds a config from the environment. Precedence: explicit `overrides` >
868
+ * `GROW_OIDC_<NAME>` > vendor variables ({@link VENDOR_ENV}) > defaults.
869
+ */
870
+ static fromEnv(overrides = {}, env = process.env) {
871
+ const reader = new EnvReader(_OidcConfig.ENV_PREFIX, env);
872
+ const fromEnv = readCommonEnv(reader, VENDOR_ENV);
873
+ const token = reader.secret("TOKEN", VENDOR_ENV.token);
874
+ if (token !== void 0) fromEnv.token = token;
875
+ const merged = mergeOptions(fromEnv, overrides);
876
+ return new _OidcConfig(merged);
877
+ }
878
+ /** Throws {@link ConfigError} when a setting is invalid. Service rules go here. */
879
+ validate() {
880
+ validateCommonConfig(this);
881
+ if (this.token?.reveal().trim() === "")
882
+ throw new ConfigError("invalid configuration: token must not be blank");
883
+ }
884
+ /** Credential values to redact from error messages and logs. */
885
+ knownSecrets() {
886
+ return secretValues(this.token);
887
+ }
888
+ /** Debug form with every credential redacted. */
889
+ toJSON() {
890
+ return { ...describeCommonConfig(this), token: this.token === void 0 ? null : REDACTED };
891
+ }
892
+ toString() {
893
+ return `OidcConfig(${JSON.stringify(this.toJSON())})`;
894
+ }
895
+ [INSPECT]() {
896
+ return this.toString();
897
+ }
898
+ };
899
+
900
+ // src/client.ts
901
+ var DISCOVERY_PATH = ".well-known/openid-configuration";
902
+ function trimTrailingSlashes(value) {
903
+ let end = value.length;
904
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
905
+ return value.slice(0, end);
906
+ }
907
+ function relativeEndpoint(base, endpoint) {
908
+ const root = trimTrailingSlashes(base);
909
+ if (endpoint.startsWith(root + "/")) return endpoint.slice(root.length);
910
+ try {
911
+ const url = new URL(endpoint);
912
+ return url.pathname + url.search;
913
+ } catch {
914
+ return endpoint;
915
+ }
916
+ }
917
+ var OidcClient = class _OidcClient {
918
+ /** The immutable configuration. */
919
+ config;
920
+ #transport;
921
+ #closed = false;
922
+ /** Accepts a {@link OidcConfig} or plain options. */
923
+ constructor(config = {}, internals = {}) {
924
+ const cfg = OidcConfig.from(config);
925
+ this.config = cfg;
926
+ this.#transport = new HttpTransport({
927
+ ...internals,
928
+ config: cfg,
929
+ knownSecrets: () => cfg.knownSecrets()
930
+ });
931
+ }
932
+ /** Builds a client from `GROW_OIDC_*` (and vendor) environment variables. */
933
+ static fromEnv(overrides = {}) {
934
+ return new _OidcClient(OidcConfig.fromEnv(overrides));
935
+ }
936
+ /** The shared HTTP transport (for service modules). @internal */
937
+ get transport() {
938
+ return this.#transport;
939
+ }
940
+ /**
941
+ * Unauthenticated liveness: `GET <url>/.well-known/openid-configuration` (healthy when the
942
+ * discovery document answers 2xx). Never throws for an unhealthy or unreachable provider (only
943
+ * `CANCELLED` and `CONFIG`).
944
+ */
945
+ health(options = {}) {
946
+ return probeHealth(async () => {
947
+ const doc = await this.#discovery("health", options);
948
+ const details = {};
949
+ if (typeof doc.issuer === "string") details.issuer = doc.issuer;
950
+ return healthStatus("ok", details);
951
+ });
952
+ }
953
+ /**
954
+ * Authenticated round trip with the configured access token (`token`): `GET` the provider's
955
+ * `userinfo_endpoint` from discovery. Returns the latency in milliseconds; a rejected token
956
+ * raises `AuthenticationError`, a provider without userinfo `UnsupportedError`.
957
+ */
958
+ async ping(options = {}) {
959
+ const start = performance.now();
960
+ const doc = await this.#discovery("ping", options);
961
+ if (typeof doc.userinfo_endpoint !== "string" || doc.userinfo_endpoint === "") {
962
+ throw new UnsupportedError("ping: the provider has no userinfo endpoint");
963
+ }
964
+ const token = this.config.token;
965
+ await this.#transport.get(relativeEndpoint(this.config.url, doc.userinfo_endpoint), {
966
+ operation: "ping",
967
+ responseType: "none",
968
+ headers: token === void 0 ? {} : { authorization: `Bearer ${token.reveal()}` },
969
+ ...options
970
+ });
971
+ return performance.now() - start;
972
+ }
973
+ /** OpenID Connect has no version endpoint: always `UnsupportedError` (`CANCELLED` once closed). */
974
+ serverVersion(_options = {}) {
975
+ return new Promise((_resolve, reject) => {
976
+ this.#transport.ensureOpen("serverVersion");
977
+ reject(new UnsupportedError("serverVersion: OpenID Connect providers expose no version"));
978
+ });
979
+ }
980
+ async #discovery(operation, options) {
981
+ const res = await this.#transport.get(DISCOVERY_PATH, { operation, ...options });
982
+ const data = res.data;
983
+ return data !== null && typeof data === "object" && !Array.isArray(data) ? data : {};
984
+ }
985
+ /** Releases connections. Idempotent. */
986
+ async close() {
987
+ if (this.#closed) return;
988
+ this.#closed = true;
989
+ await this.#transport.close();
990
+ }
991
+ };
992
+
993
+ // src/oidc/express.ts
994
+ function deny(res, status, error) {
995
+ if (status === 401) res.setHeader("WWW-Authenticate", 'Bearer error="invalid_token"');
996
+ res.status(status).json({ error });
997
+ }
998
+ function expressAuth(verifier, options = {}) {
999
+ return async (req, res, next) => {
1000
+ const token = bearerToken(req);
1001
+ if (token === null) {
1002
+ if (options.optional === true) {
1003
+ next();
1004
+ return;
1005
+ }
1006
+ deny(res, 401, "unauthorized");
1007
+ return;
1008
+ }
1009
+ try {
1010
+ req.user = await verifier.verify(token);
1011
+ } catch (err) {
1012
+ if (err instanceof UnavailableError) {
1013
+ deny(res, 503, "auth_unavailable");
1014
+ return;
1015
+ }
1016
+ if (err instanceof OidcError) {
1017
+ deny(res, 401, "unauthorized");
1018
+ return;
1019
+ }
1020
+ next(err);
1021
+ return;
1022
+ }
1023
+ next();
1024
+ };
1025
+ }
1026
+ function requireRoles(...roles) {
1027
+ return (req, res, next) => {
1028
+ const user = req.user;
1029
+ if (user === void 0) deny(res, 401, "unauthorized");
1030
+ else if (!hasAnyRole(user.roles, roles)) deny(res, 403, "forbidden");
1031
+ else next();
1032
+ return Promise.resolve();
1033
+ };
1034
+ }
1035
+ var ROLES_KEY = "grow:oidc:roles";
1036
+ var PUBLIC_KEY = "grow:oidc:public";
1037
+ var reflect = Reflect;
1038
+ var store = /* @__PURE__ */ new WeakMap();
1039
+ function setMeta(target, key, value) {
1040
+ let entry = store.get(target);
1041
+ if (entry === void 0) {
1042
+ entry = /* @__PURE__ */ new Map();
1043
+ store.set(target, entry);
1044
+ }
1045
+ entry.set(key, value);
1046
+ reflect.defineMetadata?.(key, value, target);
1047
+ }
1048
+ function getMeta(target, key) {
1049
+ if (target === null || typeof target !== "object" && typeof target !== "function")
1050
+ return void 0;
1051
+ const local = store.get(target)?.get(key);
1052
+ return local !== void 0 ? local : reflect.getMetadata?.(key, target);
1053
+ }
1054
+ function metaDecorator(key, value) {
1055
+ return (target, _key, descriptor) => {
1056
+ const holder = descriptor?.value ?? target;
1057
+ setMeta(holder, key, value);
1058
+ };
1059
+ }
1060
+ function Roles(...roles) {
1061
+ return metaDecorator(ROLES_KEY, roles);
1062
+ }
1063
+ function Public() {
1064
+ return metaDecorator(PUBLIC_KEY, true);
1065
+ }
1066
+ var nestExceptions;
1067
+ function loadNestExceptions() {
1068
+ if (nestExceptions !== void 0) return nestExceptions;
1069
+ try {
1070
+ const appRequire = createRequire(join(process.cwd(), "package.json"));
1071
+ const common = appRequire("@nestjs/common");
1072
+ nestExceptions = {
1073
+ unauthorized: common.UnauthorizedException,
1074
+ forbidden: common.ForbiddenException,
1075
+ unavailable: common.ServiceUnavailableException
1076
+ };
1077
+ } catch {
1078
+ nestExceptions = {};
1079
+ }
1080
+ return nestExceptions;
1081
+ }
1082
+ function resetNestExceptionsForTests(value) {
1083
+ nestExceptions = value;
1084
+ }
1085
+ var HttpStatusError = class extends Error {
1086
+ statusCode;
1087
+ constructor(statusCode, message) {
1088
+ super(message);
1089
+ this.name = "HttpStatusError";
1090
+ this.statusCode = statusCode;
1091
+ }
1092
+ /** Nest `HttpException`-compatible accessor. */
1093
+ getStatus() {
1094
+ return this.statusCode;
1095
+ }
1096
+ };
1097
+ function httpError(status) {
1098
+ const ex = loadNestExceptions();
1099
+ const ctor = status === 401 ? ex.unauthorized : status === 403 ? ex.forbidden : ex.unavailable;
1100
+ const message = status === 401 ? "Unauthorized" : status === 403 ? "Forbidden" : "Service Unavailable";
1101
+ return ctor !== void 0 ? new ctor(message) : new HttpStatusError(status, message);
1102
+ }
1103
+ function isPublic(ctx) {
1104
+ return getMeta(ctx.getHandler(), PUBLIC_KEY) === true || getMeta(ctx.getClass(), PUBLIC_KEY) === true;
1105
+ }
1106
+ var NestAuthGuard = class {
1107
+ #verifier;
1108
+ #optional;
1109
+ constructor(verifier, options = {}) {
1110
+ this.#verifier = verifier;
1111
+ this.#optional = options.optional === true;
1112
+ }
1113
+ /** Nest `CanActivate`. */
1114
+ async canActivate(ctx) {
1115
+ const req = ctx.switchToHttp().getRequest();
1116
+ const token = bearerToken(req);
1117
+ if (token === null) {
1118
+ if (this.#optional || isPublic(ctx)) return true;
1119
+ throw httpError(401);
1120
+ }
1121
+ try {
1122
+ req.user = await this.#verifier.verify(token);
1123
+ return true;
1124
+ } catch (err) {
1125
+ if (isPublic(ctx)) return true;
1126
+ if (err instanceof UnavailableError) throw httpError(503);
1127
+ if (err instanceof OidcError) throw httpError(401);
1128
+ throw err;
1129
+ }
1130
+ }
1131
+ };
1132
+ var RolesGuard = class {
1133
+ #roles;
1134
+ constructor(roles) {
1135
+ this.#roles = roles;
1136
+ }
1137
+ /** Nest `CanActivate`. */
1138
+ canActivate(ctx) {
1139
+ const required = this.#roles ?? getMeta(ctx.getHandler(), ROLES_KEY) ?? getMeta(ctx.getClass(), ROLES_KEY);
1140
+ const user = ctx.switchToHttp().getRequest().user;
1141
+ if (user === void 0) {
1142
+ if (required === void 0 || isPublic(ctx)) return true;
1143
+ throw httpError(401);
1144
+ }
1145
+ if (required === void 0 || hasAnyRole(user.roles, required)) return true;
1146
+ throw httpError(403);
1147
+ }
1148
+ };
1149
+
1150
+ export { DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, DISCOVERY_PATH, HttpStatusError, HttpTransport, LANGUAGE, MAX_VENDOR_TEXT, NestAuthGuard, OidcClient, OidcConfig, PACKAGE_KEY, PUBLIC_KEY, Public, ROLES_KEY, RetryPolicy, Roles, RolesGuard, SDK_KIT_VERSION, SDK_VERSION, VENDOR_ENV, createDispatcher, definedOnly, describeCommonConfig, expressAuth, healthStatus, isHealthyWord, isIdempotentMethod, isRetryableStatus, mergeOptions, parseRetryAfter, probeHealth, readCommonEnv, redactSecretsInText, relativeEndpoint, requireRoles, resetNestExceptionsForTests, resolveCommonConfig, safeCall, safeLogger, secretValues, silentLogger, validateCommonConfig };
1151
+ //# sourceMappingURL=index.js.map
1152
+ //# sourceMappingURL=index.js.map