@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.js ADDED
@@ -0,0 +1,1748 @@
1
+ import { ConfigError, OidcError, ErrorCode, sleep, CancelledError, TimeoutError, errorForStatus, UnavailableError, UnsupportedError, AuthenticationError } from './chunk-4JJJPKI5.js';
2
+ export { AuthenticationError, CancelledError, ConfigError, ConflictError, ErrorCode, NotFoundError, OidcError, PermissionDeniedError, RateLimitError, TimeoutError, UnavailableError, UnsupportedError, ValidationError, codeForStatus, errorForCode, errorForStatus, isOidcError, pollUntil, reasonForCode, sleep, throwIfAborted } from './chunk-4JJJPKI5.js';
3
+ import { readFileSync } from 'fs';
4
+ import { ProxyAgent, Agent, fetch } from 'undici';
5
+ import { decodeProtectedHeader, errors, jwtVerify, createLocalJWKSet } from 'jose';
6
+ import { createRequire } from 'module';
7
+ import { join } from 'path';
8
+
9
+ // src/core/redaction.ts
10
+ var REDACTED = "[REDACTED]";
11
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
12
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
13
+ "authorization",
14
+ "proxy-authorization",
15
+ "cookie",
16
+ "set-cookie"
17
+ ]);
18
+ var SENSITIVE_HEADER_PARTS = [
19
+ "token",
20
+ "secret",
21
+ "password",
22
+ "api-key",
23
+ "apikey",
24
+ "key",
25
+ "auth",
26
+ "session",
27
+ "signature",
28
+ "credential"
29
+ ];
30
+ var SENSITIVE_FIELD_PARTS = [
31
+ "password",
32
+ "passwd",
33
+ "secret",
34
+ "token",
35
+ "authorization",
36
+ "cookie",
37
+ "api_key",
38
+ "apikey",
39
+ "api-key",
40
+ "access_key",
41
+ "private_key",
42
+ "client_secret",
43
+ "credential",
44
+ "session",
45
+ "signature"
46
+ ];
47
+ var MIN_SECRET_LENGTH = 4;
48
+ function isSensitiveHeader(name) {
49
+ const n = name.toLowerCase();
50
+ return SENSITIVE_HEADERS.has(n) || SENSITIVE_HEADER_PARTS.some((p) => n.includes(p));
51
+ }
52
+ var PATH_NAME = /path$/;
53
+ function isSensitiveField(name, extraKeys = []) {
54
+ const n = name.toLowerCase();
55
+ return !PATH_NAME.test(n) && SENSITIVE_FIELD_PARTS.some((p) => n.includes(p)) || extraKeys.some((k) => k !== "" && n.includes(k.toLowerCase()));
56
+ }
57
+ function headerEntries(headers) {
58
+ if (Symbol.iterator in headers) {
59
+ return Array.from(headers, ([k, v]) => [k, v]);
60
+ }
61
+ const out = [];
62
+ for (const [k, v] of Object.entries(headers)) {
63
+ if (v === void 0) continue;
64
+ out.push([k, typeof v === "string" ? v : v.join(", ")]);
65
+ }
66
+ return out;
67
+ }
68
+ function redactHeaders(headers) {
69
+ const out = {};
70
+ for (const [k, v] of headerEntries(headers)) {
71
+ out[k] = isSensitiveHeader(k) ? REDACTED : v;
72
+ }
73
+ return out;
74
+ }
75
+ function redactUrl(url) {
76
+ let parsed;
77
+ try {
78
+ parsed = new URL(url.toString());
79
+ } catch {
80
+ return redactQueryString(url.toString());
81
+ }
82
+ if (parsed.password !== "") parsed.password = REDACTED;
83
+ if (parsed.password === "" && parsed.username !== "" && parsed.username !== REDACTED) {
84
+ parsed.username = REDACTED;
85
+ }
86
+ const params = parsed.searchParams;
87
+ let changed = false;
88
+ const next = new URLSearchParams();
89
+ for (const [k, v] of params) {
90
+ if (isSensitiveField(k)) {
91
+ next.append(k, REDACTED);
92
+ changed = true;
93
+ } else {
94
+ next.append(k, v);
95
+ }
96
+ }
97
+ if (changed) parsed.search = next.toString();
98
+ return parsed.toString().replaceAll(encodeURIComponent(REDACTED), REDACTED);
99
+ }
100
+ function redactQueryString(text) {
101
+ return text.replace(
102
+ /([?&])([^=&#?\s]+)=([^&#\s]*)/g,
103
+ (m, sep, k) => isSensitiveField(k) ? `${sep}${k}=${REDACTED}` : m
104
+ );
105
+ }
106
+ function redactFields(value, extraKeys = []) {
107
+ return redactValue(value, extraKeys, /* @__PURE__ */ new WeakMap());
108
+ }
109
+ function redactValue(value, extraKeys, seen) {
110
+ if (value === null || typeof value !== "object") return value;
111
+ if (value instanceof Date || value instanceof Uint8Array) return value;
112
+ const cached = seen.get(value);
113
+ if (cached !== void 0) return cached;
114
+ if (Array.isArray(value)) {
115
+ const arr = [];
116
+ seen.set(value, arr);
117
+ for (const item of value) arr.push(redactValue(item, extraKeys, seen));
118
+ return arr;
119
+ }
120
+ if (value instanceof Map) {
121
+ const map = /* @__PURE__ */ new Map();
122
+ seen.set(value, map);
123
+ for (const [k, v] of value) {
124
+ map.set(
125
+ k,
126
+ typeof k === "string" && isSensitiveField(k, extraKeys) ? REDACTED : redactValue(v, extraKeys, seen)
127
+ );
128
+ }
129
+ return map;
130
+ }
131
+ const out = {};
132
+ seen.set(value, out);
133
+ for (const [k, v] of Object.entries(value)) {
134
+ out[k] = isSensitiveField(k, extraKeys) ? REDACTED : redactValue(v, extraKeys, seen);
135
+ }
136
+ return out;
137
+ }
138
+ function redactText(text, knownSecrets = []) {
139
+ const values = /* @__PURE__ */ new Set();
140
+ for (const s of knownSecrets) {
141
+ const v = s instanceof Secret ? s.reveal() : s;
142
+ if (typeof v === "string" && v.length >= MIN_SECRET_LENGTH) values.add(v);
143
+ }
144
+ let out = text;
145
+ for (const v of [...values].sort((a, b) => b.length - a.length)) {
146
+ out = out.split(v).join(REDACTED);
147
+ }
148
+ return out;
149
+ }
150
+ var Secret = class _Secret {
151
+ #value;
152
+ constructor(value) {
153
+ this.#value = value;
154
+ }
155
+ /** Wraps a string (returns `undefined` for `undefined`/empty, keeps an existing Secret). */
156
+ static from(value) {
157
+ if (value === void 0 || value === null) return void 0;
158
+ if (value instanceof _Secret) return value;
159
+ return value === "" ? void 0 : new _Secret(value);
160
+ }
161
+ /** The wrapped value. */
162
+ reveal() {
163
+ return this.#value;
164
+ }
165
+ /** Constant-time-ish comparison with another value. */
166
+ equals(other) {
167
+ const a = this.#value;
168
+ const b = other instanceof _Secret ? other.reveal() : other;
169
+ if (a.length !== b.length) return false;
170
+ let diff = 0;
171
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
172
+ return diff === 0;
173
+ }
174
+ toString() {
175
+ return REDACTED;
176
+ }
177
+ toJSON() {
178
+ return REDACTED;
179
+ }
180
+ [INSPECT]() {
181
+ return REDACTED;
182
+ }
183
+ };
184
+ function redactError(err, knownSecrets = []) {
185
+ const secrets = [...knownSecrets];
186
+ if (err instanceof Error) {
187
+ const copy = new Error(redactText(redactQueryString(err.message), secrets));
188
+ copy.name = err.name;
189
+ const code = err.code;
190
+ if (typeof code === "string") copy.code = code;
191
+ if (err.cause !== void 0) copy.cause = redactError(err.cause, secrets);
192
+ return copy;
193
+ }
194
+ return new Error(redactText(String(err), secrets));
195
+ }
196
+
197
+ // src/core/env.ts
198
+ var UNIT_MS = {
199
+ ns: 1e-6,
200
+ us: 1e-3,
201
+ \u00B5s: 1e-3,
202
+ ms: 1,
203
+ s: 1e3,
204
+ m: 6e4,
205
+ h: 36e5
206
+ };
207
+ var DURATION_UNITS = ["ns", "us", "\xB5s", "ms", "s", "m", "h"];
208
+ function parseDuration(raw) {
209
+ const text = raw.trim();
210
+ if (/^\d+$/.test(text)) return Number(text);
211
+ if (text === "") return void 0;
212
+ let total = 0;
213
+ let i = 0;
214
+ const isDigit = (at) => at < text.length && text.charCodeAt(at) >= 48 && text.charCodeAt(at) <= 57;
215
+ while (i < text.length) {
216
+ const start = i;
217
+ while (isDigit(i)) i += 1;
218
+ const intDigits = i - start;
219
+ if (text[i] === ".") {
220
+ i += 1;
221
+ const fracStart = i;
222
+ while (isDigit(i)) i += 1;
223
+ if (i === fracStart) return void 0;
224
+ } else if (intDigits === 0) {
225
+ return void 0;
226
+ }
227
+ const value = Number(text.slice(start, i));
228
+ const unit = DURATION_UNITS.find((u) => text.startsWith(u, i));
229
+ if (unit === void 0) return void 0;
230
+ total += value * UNIT_MS[unit];
231
+ i += unit.length;
232
+ }
233
+ return Math.round(total);
234
+ }
235
+ var TRUE_WORDS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
236
+ var FALSE_WORDS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
237
+ function parseBool(raw) {
238
+ const text = raw.trim().toLowerCase();
239
+ if (TRUE_WORDS.has(text)) return true;
240
+ if (FALSE_WORDS.has(text)) return false;
241
+ return void 0;
242
+ }
243
+ function parseInteger(raw) {
244
+ const text = raw.trim();
245
+ if (!/^[+-]?\d+$/.test(text)) return void 0;
246
+ const n = Number(text);
247
+ return Number.isSafeInteger(n) ? n : void 0;
248
+ }
249
+ var EnvReader = class {
250
+ prefix;
251
+ #env;
252
+ /**
253
+ * @param prefix e.g. `"GROW_OIDC_"`.
254
+ * @param env environment map, defaults to `process.env`.
255
+ */
256
+ constructor(prefix, env = process.env) {
257
+ this.prefix = prefix;
258
+ this.#env = env;
259
+ }
260
+ /** Finds the first present variable: `<prefix><name>`, then each vendor name. */
261
+ lookup(name, vendorNames = []) {
262
+ for (const candidate of [this.prefix + name, ...vendorNames]) {
263
+ const value = this.#env[candidate];
264
+ if (value !== void 0 && value !== "") return { name: candidate, value };
265
+ }
266
+ return void 0;
267
+ }
268
+ /** String value. */
269
+ string(name, vendorNames = []) {
270
+ return this.lookup(name, vendorNames)?.value;
271
+ }
272
+ /** Credential value wrapped in a {@link Secret}. */
273
+ secret(name, vendorNames = []) {
274
+ return Secret.from(this.string(name, vendorNames));
275
+ }
276
+ /** Duration in milliseconds (see {@link parseDuration}). */
277
+ duration(name, vendorNames = []) {
278
+ return this.#parse(name, vendorNames, parseDuration, "a duration such as 1500, 500ms or 10s");
279
+ }
280
+ /** Boolean (see {@link parseBool}). */
281
+ bool(name, vendorNames = []) {
282
+ return this.#parse(name, vendorNames, parseBool, "a boolean (true/false/1/0/yes/no/on/off)");
283
+ }
284
+ /** Integer. */
285
+ int(name, vendorNames = []) {
286
+ return this.#parse(name, vendorNames, parseInteger, "an integer");
287
+ }
288
+ #parse(name, vendorNames, parse, expected) {
289
+ const hit = this.lookup(name, vendorNames);
290
+ if (hit === void 0) return void 0;
291
+ const value = parse(hit.value);
292
+ if (value === void 0) {
293
+ throw new ConfigError(
294
+ `invalid value in environment variable ${hit.name}: expected ${expected}`
295
+ );
296
+ }
297
+ return value;
298
+ }
299
+ };
300
+
301
+ // src/core/health.ts
302
+ var HEALTHY_WORDS = /* @__PURE__ */ new Set([
303
+ "ok",
304
+ "up",
305
+ "healthy",
306
+ "pass",
307
+ "passing",
308
+ "green",
309
+ "ready",
310
+ "available",
311
+ "running",
312
+ "serving"
313
+ ]);
314
+ function isHealthyWord(status) {
315
+ return HEALTHY_WORDS.has(status.trim().toLowerCase());
316
+ }
317
+ function healthStatus(status, details = {}, healthy = isHealthyWord(status)) {
318
+ const flat = {};
319
+ for (const [k, v] of Object.entries(details)) {
320
+ if (v === void 0 || v === null) continue;
321
+ if (typeof v === "string") flat[k] = v;
322
+ else if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint")
323
+ flat[k] = String(v);
324
+ else if (typeof v === "object") flat[k] = JSON.stringify(v);
325
+ }
326
+ return { healthy, status, details: flat };
327
+ }
328
+ async function probeHealth(probe) {
329
+ try {
330
+ return await probe();
331
+ } catch (err) {
332
+ if (err instanceof OidcError) {
333
+ if (err.code === ErrorCode.Cancelled || err.code === ErrorCode.Config) throw err;
334
+ if (err.httpStatus !== void 0) {
335
+ return healthStatus("unhealthy", { httpStatus: err.httpStatus, error: err.code }, false);
336
+ }
337
+ return healthStatus("unreachable", { error: err.code }, false);
338
+ }
339
+ return healthStatus("unreachable", { error: ErrorCode.Unavailable }, false);
340
+ }
341
+ }
342
+
343
+ // src/core/hooks.ts
344
+ var silentLogger = Object.freeze({
345
+ debug: () => void 0,
346
+ info: () => void 0,
347
+ warn: () => void 0,
348
+ error: () => void 0
349
+ });
350
+ function safeCall(fn, ...args) {
351
+ if (fn === void 0) return;
352
+ try {
353
+ const result = fn(...args);
354
+ if (result instanceof Promise) result.catch(() => void 0);
355
+ } catch {
356
+ }
357
+ }
358
+ function safeLogger(logger) {
359
+ if (logger === void 0) return silentLogger;
360
+ return {
361
+ debug: (m, f) => {
362
+ safeCall(
363
+ (a, b) => {
364
+ logger.debug(a, b);
365
+ },
366
+ m,
367
+ f
368
+ );
369
+ },
370
+ info: (m, f) => {
371
+ safeCall(
372
+ (a, b) => {
373
+ logger.info(a, b);
374
+ },
375
+ m,
376
+ f
377
+ );
378
+ },
379
+ warn: (m, f) => {
380
+ safeCall(
381
+ (a, b) => {
382
+ logger.warn(a, b);
383
+ },
384
+ m,
385
+ f
386
+ );
387
+ },
388
+ error: (m, f) => {
389
+ safeCall(
390
+ (a, b) => {
391
+ logger.error(a, b);
392
+ },
393
+ m,
394
+ f
395
+ );
396
+ }
397
+ };
398
+ }
399
+
400
+ // src/core/retry.ts
401
+ var RetryPolicy = class _RetryPolicy {
402
+ static DEFAULTS = Object.freeze({
403
+ maxRetries: 3,
404
+ initialBackoffMs: 100,
405
+ maxBackoffMs: 1e4,
406
+ multiplier: 2,
407
+ maxRetryAfterMs: 6e4
408
+ });
409
+ maxRetries;
410
+ initialBackoffMs;
411
+ maxBackoffMs;
412
+ multiplier;
413
+ maxRetryAfterMs;
414
+ random;
415
+ constructor(options = {}) {
416
+ const d = _RetryPolicy.DEFAULTS;
417
+ this.maxRetries = options.maxRetries ?? d.maxRetries;
418
+ this.initialBackoffMs = options.initialBackoffMs ?? d.initialBackoffMs;
419
+ this.maxBackoffMs = options.maxBackoffMs ?? d.maxBackoffMs;
420
+ this.multiplier = options.multiplier ?? d.multiplier;
421
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? d.maxRetryAfterMs;
422
+ this.random = options.random ?? Math.random;
423
+ Object.freeze(this);
424
+ }
425
+ /** Returns a policy from options, keeping an existing instance as is. */
426
+ static from(value) {
427
+ return value instanceof _RetryPolicy ? value : new _RetryPolicy(value);
428
+ }
429
+ /** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
430
+ backoffCapMs(retry) {
431
+ return Math.min(this.maxBackoffMs, this.initialBackoffMs * this.multiplier ** retry);
432
+ }
433
+ /** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
434
+ backoffMs(retry) {
435
+ return this.random() * this.backoffCapMs(retry);
436
+ }
437
+ /** Validation problems (empty when valid). */
438
+ problems() {
439
+ const out = [];
440
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0)
441
+ out.push("retry.maxRetries must be an integer >= 0");
442
+ if (!(this.initialBackoffMs >= 0)) out.push("retry.initialBackoffMs must be >= 0");
443
+ if (!(this.maxBackoffMs >= 0)) out.push("retry.maxBackoffMs must be >= 0");
444
+ if (!(this.multiplier >= 1)) out.push("retry.multiplier must be >= 1");
445
+ if (!(this.maxRetryAfterMs >= 0)) out.push("retry.maxRetryAfterMs must be >= 0");
446
+ return out;
447
+ }
448
+ toJSON() {
449
+ return {
450
+ maxRetries: this.maxRetries,
451
+ initialBackoffMs: this.initialBackoffMs,
452
+ maxBackoffMs: this.maxBackoffMs,
453
+ multiplier: this.multiplier,
454
+ maxRetryAfterMs: this.maxRetryAfterMs
455
+ };
456
+ }
457
+ };
458
+ function parseRetryAfter(value, now = Date.now()) {
459
+ if (value === null || value === void 0) return void 0;
460
+ const text = value.trim();
461
+ if (text === "") return void 0;
462
+ if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1e3);
463
+ if (!/[a-z]/i.test(text)) return void 0;
464
+ const at = Date.parse(text);
465
+ if (Number.isNaN(at)) return void 0;
466
+ return Math.max(0, at - now);
467
+ }
468
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
469
+ "GET",
470
+ "HEAD",
471
+ "OPTIONS",
472
+ "PUT",
473
+ "DELETE"
474
+ ]);
475
+ function isIdempotentMethod(method) {
476
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
477
+ }
478
+ function isRetryableStatus(status, idempotent) {
479
+ if (status === 429) return true;
480
+ if (!idempotent) return false;
481
+ return status === 408 || status === 500 || status === 502 || status === 503 || status === 504;
482
+ }
483
+
484
+ // src/core/options.ts
485
+ var DEFAULT_TIMEOUTS = Object.freeze({
486
+ connectTimeoutMs: 1e4,
487
+ requestTimeoutMs: 3e4,
488
+ totalTimeoutMs: 12e4
489
+ });
490
+ function resolveCommonConfig(options, defaultUrl) {
491
+ const out = {
492
+ url: options.url ?? defaultUrl,
493
+ connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_TIMEOUTS.connectTimeoutMs,
494
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_TIMEOUTS.requestTimeoutMs,
495
+ totalTimeoutMs: options.totalTimeoutMs ?? DEFAULT_TIMEOUTS.totalTimeoutMs,
496
+ retry: RetryPolicy.from(options.retry),
497
+ tls: Object.freeze({ ...options.tls }),
498
+ headers: Object.freeze({ ...options.headers })
499
+ };
500
+ if (options.proxy !== void 0) out.proxy = options.proxy;
501
+ if (options.userAgentSuffix !== void 0) out.userAgentSuffix = options.userAgentSuffix;
502
+ if (options.hooks !== void 0) out.hooks = options.hooks;
503
+ if (options.logger !== void 0) out.logger = options.logger;
504
+ return out;
505
+ }
506
+ function isHttpUrl(value) {
507
+ try {
508
+ const u = new URL(value);
509
+ return u.protocol === "http:" || u.protocol === "https:";
510
+ } catch {
511
+ return false;
512
+ }
513
+ }
514
+ function validateCommonConfig(config) {
515
+ const problems = [];
516
+ if (!isHttpUrl(config.url)) problems.push("url must be an http or https URL");
517
+ for (const key of ["connectTimeoutMs", "requestTimeoutMs", "totalTimeoutMs"]) {
518
+ const v = config[key];
519
+ if (!Number.isFinite(v) || v <= 0) problems.push(`${key} must be a positive number`);
520
+ }
521
+ problems.push(...config.retry.problems());
522
+ const tls = config.tls;
523
+ if (tls.clientCertPath === void 0 !== (tls.clientKeyPath === void 0)) {
524
+ problems.push("tls.clientCertPath and tls.clientKeyPath must be given together");
525
+ }
526
+ if (config.proxy !== void 0 && !isHttpUrl(config.proxy)) {
527
+ problems.push("proxy must be an http or https URL");
528
+ }
529
+ if (problems.length > 0) throw new ConfigError(`invalid configuration: ${problems.join("; ")}`);
530
+ }
531
+ function readCommonEnv(reader, vendor = {}) {
532
+ const out = {};
533
+ const url = reader.string("URL", vendor.url);
534
+ if (url !== void 0) out.url = url;
535
+ const connect = reader.duration("CONNECT_TIMEOUT");
536
+ if (connect !== void 0) out.connectTimeoutMs = connect;
537
+ const request = reader.duration("REQUEST_TIMEOUT");
538
+ if (request !== void 0) out.requestTimeoutMs = request;
539
+ const total = reader.duration("TOTAL_TIMEOUT");
540
+ if (total !== void 0) out.totalTimeoutMs = total;
541
+ const maxRetries = reader.int("MAX_RETRIES");
542
+ if (maxRetries !== void 0) out.retry = { maxRetries };
543
+ const tls = {};
544
+ const ca = reader.string("CA_CERT", vendor.caCert);
545
+ if (ca !== void 0) tls.caCertPath = ca;
546
+ const cert = reader.string("CLIENT_CERT", vendor.clientCert);
547
+ if (cert !== void 0) tls.clientCertPath = cert;
548
+ const key = reader.string("CLIENT_KEY", vendor.clientKey);
549
+ if (key !== void 0) tls.clientKeyPath = key;
550
+ const insecure = reader.bool("INSECURE_SKIP_VERIFY", vendor.insecureSkipVerify);
551
+ if (insecure !== void 0) tls.insecureSkipVerify = insecure;
552
+ if (Object.keys(tls).length > 0) out.tls = tls;
553
+ const proxy = reader.string("PROXY", vendor.proxy);
554
+ if (proxy !== void 0) out.proxy = proxy;
555
+ return out;
556
+ }
557
+ function definedOnly(value) {
558
+ const out = {};
559
+ for (const [k, v] of Object.entries(value)) {
560
+ if (v !== void 0) out[k] = v;
561
+ }
562
+ return out;
563
+ }
564
+ function mergeOptions(...layers) {
565
+ const out = {};
566
+ for (const layer of layers) {
567
+ if (layer === void 0) continue;
568
+ for (const [k, v] of Object.entries(definedOnly(layer))) {
569
+ const prev = out[k];
570
+ if ((k === "tls" || k === "headers" || k === "retry" && !(v instanceof RetryPolicy)) && typeof prev === "object" && prev !== null) {
571
+ const base = prev instanceof RetryPolicy ? prev.toJSON() : prev;
572
+ out[k] = { ...base, ...definedOnly(v) };
573
+ } else {
574
+ out[k] = v;
575
+ }
576
+ }
577
+ }
578
+ return out;
579
+ }
580
+ function describeCommonConfig(config) {
581
+ const headers = {};
582
+ for (const k of Object.keys(config.headers)) headers[k] = REDACTED;
583
+ const out = {
584
+ url: redactUrl(config.url),
585
+ connectTimeoutMs: config.connectTimeoutMs,
586
+ requestTimeoutMs: config.requestTimeoutMs,
587
+ totalTimeoutMs: config.totalTimeoutMs,
588
+ retry: config.retry.toJSON(),
589
+ tls: {
590
+ ...config.tls,
591
+ ...config.tls.caCertPem === void 0 ? {} : { caCertPem: REDACTED }
592
+ },
593
+ headers
594
+ };
595
+ if (config.proxy !== void 0) out.proxy = redactUrl(config.proxy);
596
+ if (config.userAgentSuffix !== void 0) out.userAgentSuffix = config.userAgentSuffix;
597
+ return out;
598
+ }
599
+ function secretValues(...values) {
600
+ return values.filter((v) => v instanceof Secret).map((s) => s.reveal());
601
+ }
602
+
603
+ // src/core/version.ts
604
+ var SDK_VERSION = "0.1.0";
605
+ var PACKAGE_KEY = "oidc";
606
+ var LANGUAGE = "typescript";
607
+ var SDK_KIT_VERSION = "0.3.0";
608
+
609
+ // src/core/transport.ts
610
+ var DEFAULT_REQUEST_ID_HEADERS = [
611
+ "x-request-id",
612
+ "x-amzn-requestid",
613
+ "x-amz-request-id",
614
+ "x-datadog-request-id",
615
+ "request-id",
616
+ "x-correlation-id"
617
+ ];
618
+ var MAX_VENDOR_TEXT = 300;
619
+ var PRE_SEND_CODES = /* @__PURE__ */ new Set([
620
+ "ECONNREFUSED",
621
+ "ENOTFOUND",
622
+ "EAI_AGAIN",
623
+ "EHOSTUNREACH",
624
+ "ENETUNREACH",
625
+ "EADDRNOTAVAIL",
626
+ "UND_ERR_CONNECT_TIMEOUT"
627
+ ]);
628
+ var TLS_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS|ERR_SSL|DEPTH_ZERO/;
629
+ var CANCEL = /* @__PURE__ */ Symbol("cancel");
630
+ var ATTEMPT_TIMEOUT = /* @__PURE__ */ Symbol("attempt-timeout");
631
+ var insecureWarned = false;
632
+ var AbortedAttempt = class extends Error {
633
+ kind;
634
+ constructor(kind) {
635
+ super("aborted");
636
+ this.kind = kind;
637
+ }
638
+ };
639
+ function errorCode(err) {
640
+ let current = err;
641
+ for (let depth = 0; depth < 5 && current !== void 0 && current !== null; depth++) {
642
+ const code = current.code;
643
+ if (typeof code === "string") return code;
644
+ current = current.cause;
645
+ }
646
+ return void 0;
647
+ }
648
+ function readPem(path) {
649
+ return path === void 0 ? void 0 : readFileSync(path, "utf8");
650
+ }
651
+ function createDispatcher(config, logger = safeLogger(config.logger)) {
652
+ const tls = config.tls;
653
+ if (tls.insecureSkipVerify === true && !insecureWarned) {
654
+ insecureWarned = true;
655
+ logger.warn("TLS certificate verification is disabled (insecureSkipVerify); use only in tests");
656
+ }
657
+ const caParts = [tls.caCertPem, readPem(tls.caCertPath)].filter(
658
+ (v) => v !== void 0
659
+ );
660
+ const tlsOptions = {
661
+ timeout: config.connectTimeoutMs,
662
+ rejectUnauthorized: tls.insecureSkipVerify !== true,
663
+ ...caParts.length > 0 ? { ca: caParts } : {},
664
+ ...tls.clientCertPath === void 0 ? {} : { cert: readPem(tls.clientCertPath) },
665
+ ...tls.clientKeyPath === void 0 ? {} : { key: readPem(tls.clientKeyPath) }
666
+ };
667
+ if (config.proxy !== void 0) {
668
+ return new ProxyAgent({
669
+ uri: config.proxy,
670
+ connect: { timeout: config.connectTimeoutMs },
671
+ requestTls: tlsOptions
672
+ });
673
+ }
674
+ return new Agent({ connect: tlsOptions });
675
+ }
676
+ var HttpTransport = class {
677
+ /** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
678
+ userAgent;
679
+ retry;
680
+ #config;
681
+ #options;
682
+ #logger;
683
+ #hooks;
684
+ #fetch;
685
+ #sleep;
686
+ #now;
687
+ #requestIdHeaders;
688
+ #dispatcher;
689
+ #closed = false;
690
+ constructor(options) {
691
+ this.#options = options;
692
+ this.#config = options.config;
693
+ this.retry = options.config.retry;
694
+ this.#logger = safeLogger(options.config.logger);
695
+ this.#hooks = options.config.hooks ?? {};
696
+ this.#fetch = fetch;
697
+ this.#sleep = options.sleep ?? sleep;
698
+ this.#now = options.now ?? Date.now;
699
+ this.#requestIdHeaders = options.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS;
700
+ this.#dispatcher = options.dispatcher;
701
+ const suffix = options.config.userAgentSuffix;
702
+ this.userAgent = `grow-codes-${PACKAGE_KEY}/${SDK_VERSION} (${LANGUAGE})` + (suffix !== void 0 && suffix !== "" ? ` ${suffix}` : "");
703
+ }
704
+ /** Whether {@link close} was called. */
705
+ get closed() {
706
+ return this.#closed;
707
+ }
708
+ /**
709
+ * Throws `CancelledError` (`"<operation>: client is closed"`, not retryable) once {@link close}
710
+ * was called (SPEC §2.4). Requests check this themselves; service methods that send no request
711
+ * (cached reads, local helpers) call it first.
712
+ */
713
+ ensureOpen(operation) {
714
+ if (this.#closed) throw new CancelledError(`${operation}: client is closed`);
715
+ }
716
+ /** Builds the absolute URL for a path and query. */
717
+ buildUrl(path, query) {
718
+ let url;
719
+ if (/^https?:\/\//i.test(path)) {
720
+ url = new URL(path);
721
+ } else {
722
+ const base = this.#config.url.endsWith("/") ? this.#config.url : this.#config.url + "/";
723
+ url = new URL(path.replace(/^\/+/, ""), base);
724
+ }
725
+ for (const [k, v] of Object.entries(query ?? {})) {
726
+ if (v === void 0 || v === null) continue;
727
+ if (Array.isArray(v)) {
728
+ for (const item of v)
729
+ url.searchParams.append(k, String(item));
730
+ } else {
731
+ url.searchParams.append(k, String(v));
732
+ }
733
+ }
734
+ return url;
735
+ }
736
+ /** Redacts known secrets from a text (error messages, vendor text). */
737
+ redact(text) {
738
+ return redactText(text, this.#knownSecrets());
739
+ }
740
+ #knownSecrets() {
741
+ return [...this.#options.knownSecrets?.() ?? []];
742
+ }
743
+ #getDispatcher() {
744
+ this.#dispatcher ??= createDispatcher(this.#config, this.#logger);
745
+ return this.#dispatcher;
746
+ }
747
+ /** `GET` shortcut. */
748
+ get(path, options = {}) {
749
+ return this.request({ ...options, method: "GET", path });
750
+ }
751
+ /** `POST` shortcut. */
752
+ post(path, options = {}) {
753
+ return this.request({ ...options, method: "POST", path });
754
+ }
755
+ /** `PUT` shortcut. */
756
+ put(path, options = {}) {
757
+ return this.request({ ...options, method: "PUT", path });
758
+ }
759
+ /** `DELETE` shortcut. */
760
+ delete(path, options = {}) {
761
+ return this.request({ ...options, method: "DELETE", path });
762
+ }
763
+ /**
764
+ * Sends a request with retries; throws an SDK error on failure. Every error message passes
765
+ * through {@link redact} with the known secrets.
766
+ */
767
+ async request(options) {
768
+ try {
769
+ return await this.#request(options);
770
+ } catch (err) {
771
+ if (err instanceof OidcError) err.message = this.redact(err.message);
772
+ throw err;
773
+ }
774
+ }
775
+ async #request(options) {
776
+ const method = (options.method ?? "GET").toUpperCase();
777
+ const operation = options.operation ?? `${method} ${options.path.split("?")[0] ?? ""}`;
778
+ this.ensureOpen(operation);
779
+ const signal = options.signal;
780
+ if (signal?.aborted === true) throw new CancelledError(`${operation}: cancelled`);
781
+ const url = this.buildUrl(options.path, options.query);
782
+ const safeUrl = redactUrl(url);
783
+ const headers = this.#buildHeaders(options);
784
+ const body = options.json !== void 0 ? JSON.stringify(options.json) : options.body;
785
+ const idempotent = options.idempotent ?? isIdempotentMethod(method);
786
+ const requestTimeout = options.requestTimeoutMs ?? this.#config.requestTimeoutMs;
787
+ const totalTimeout = options.totalTimeoutMs ?? this.#config.totalTimeoutMs;
788
+ const start = this.#now();
789
+ const deadline = start + totalTimeout;
790
+ const policy = this.retry;
791
+ for (let attempt = 1; ; attempt++) {
792
+ const remaining = deadline - this.#now();
793
+ if (remaining <= 0) {
794
+ throw new TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`);
795
+ }
796
+ const attemptTimeout = Math.min(requestTimeout, remaining);
797
+ const isTotal = attemptTimeout < requestTimeout;
798
+ safeCall(this.#hooks.onRequest, {
799
+ method,
800
+ url: safeUrl,
801
+ headers: redactHeaders(headers),
802
+ attempt
803
+ });
804
+ this.#logger.debug("http request", { method, url: safeUrl, attempt });
805
+ const attemptStart = this.#now();
806
+ let failure;
807
+ let willRetry = false;
808
+ let waitMs = 0;
809
+ try {
810
+ const res = await this.#attempt(
811
+ url,
812
+ method,
813
+ headers,
814
+ body,
815
+ attemptTimeout,
816
+ signal,
817
+ options.responseType ?? "json",
818
+ options.allowStatus ?? []
819
+ );
820
+ const durationMs = this.#now() - attemptStart;
821
+ const requestId = this.#requestId(res.headers);
822
+ safeCall(this.#hooks.onResponse, {
823
+ method,
824
+ url: safeUrl,
825
+ status: res.status,
826
+ durationMs,
827
+ attempt,
828
+ ...requestId === void 0 ? {} : { requestId }
829
+ });
830
+ this.#logger.debug("http response", {
831
+ method,
832
+ url: safeUrl,
833
+ status: res.status,
834
+ durationMs,
835
+ attempt
836
+ });
837
+ if (res.status < 400 || options.allowStatus?.includes(res.status) === true) {
838
+ return {
839
+ status: res.status,
840
+ headers: res.headers,
841
+ data: res.data,
842
+ ...requestId === void 0 ? {} : { requestId },
843
+ durationMs: this.#now() - start,
844
+ attempts: attempt,
845
+ ...res.status >= 400 ? { text: res.text } : {}
846
+ };
847
+ }
848
+ const retryAfter = res.status === 429 || res.status === 503 ? parseRetryAfter(res.headers.get("retry-after"), this.#now()) : void 0;
849
+ const reason = this.vendorText(res.text);
850
+ const defaultError = errorForStatus(operation, res.status, {
851
+ ...reason === void 0 ? {} : { reason },
852
+ ...requestId === void 0 ? {} : { requestId },
853
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
854
+ });
855
+ const classified = this.#classifyResponse(options.classifyError, {
856
+ operation,
857
+ method,
858
+ status: res.status,
859
+ headers: res.headers,
860
+ body: res.text,
861
+ ...reason === void 0 ? {} : { reason },
862
+ ...requestId === void 0 ? {} : { requestId },
863
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter },
864
+ attempt,
865
+ defaultError
866
+ });
867
+ failure = classified ?? defaultError;
868
+ if (isRetryableStatus(res.status, idempotent) && (classified === void 0 || classified.retryable) && attempt <= policy.maxRetries) {
869
+ const backoff = policy.backoffMs(attempt - 1);
870
+ if (retryAfter !== void 0) {
871
+ if (retryAfter > policy.maxRetryAfterMs || retryAfter >= deadline - this.#now()) {
872
+ willRetry = false;
873
+ } else {
874
+ willRetry = true;
875
+ waitMs = Math.max(retryAfter, backoff);
876
+ }
877
+ } else {
878
+ willRetry = true;
879
+ waitMs = backoff;
880
+ }
881
+ }
882
+ } catch (err) {
883
+ failure = this.#classify(err, operation, attemptTimeout, isTotal, totalTimeout);
884
+ const preSend = PRE_SEND_CODES.has(errorCode(err) ?? "");
885
+ willRetry = failure.retryable && !(failure.code === "TIMEOUT" && isTotal) && (idempotent || preSend) && attempt <= policy.maxRetries;
886
+ waitMs = willRetry ? policy.backoffMs(attempt - 1) : 0;
887
+ }
888
+ if (willRetry && waitMs >= deadline - this.#now()) {
889
+ safeCall(this.#hooks.onError, {
890
+ method,
891
+ url: safeUrl,
892
+ error: failure,
893
+ attempt,
894
+ willRetry: false
895
+ });
896
+ throw new TimeoutError(
897
+ `${operation}: total timeout of ${totalTimeout} ms exceeded after ${attempt} attempts`,
898
+ {
899
+ cause: failure,
900
+ ...failure.httpStatus === void 0 ? {} : { httpStatus: failure.httpStatus },
901
+ ...failure.requestId === void 0 ? {} : { requestId: failure.requestId }
902
+ }
903
+ );
904
+ }
905
+ safeCall(this.#hooks.onError, { method, url: safeUrl, error: failure, attempt, willRetry });
906
+ if (!willRetry) {
907
+ this.#logger.debug("http call failed", {
908
+ method,
909
+ url: safeUrl,
910
+ attempt,
911
+ code: failure.code
912
+ });
913
+ throw failure;
914
+ }
915
+ this.#logger.warn("http call failed, retrying", {
916
+ method,
917
+ url: safeUrl,
918
+ attempt,
919
+ code: failure.code,
920
+ waitMs: Math.round(waitMs)
921
+ });
922
+ await this.#sleep(waitMs, signal).catch((err) => {
923
+ throw err instanceof OidcError ? err : new CancelledError(`${operation}: cancelled`);
924
+ });
925
+ }
926
+ }
927
+ #buildHeaders(options) {
928
+ const headers = {
929
+ accept: "application/json",
930
+ "user-agent": this.userAgent
931
+ };
932
+ const layers = [
933
+ this.#config.headers,
934
+ this.#options.defaultHeaders?.() ?? {},
935
+ options.headers ?? {}
936
+ ];
937
+ for (const layer of layers) {
938
+ for (const [k, v] of Object.entries(layer)) headers[k.toLowerCase()] = v;
939
+ }
940
+ if (options.json !== void 0 && headers["content-type"] === void 0) {
941
+ headers["content-type"] = "application/json";
942
+ }
943
+ return headers;
944
+ }
945
+ async #attempt(url, method, headers, body, timeoutMs, signal, responseType, allowStatus) {
946
+ const controller = new AbortController();
947
+ const timer = setTimeout(() => {
948
+ controller.abort(ATTEMPT_TIMEOUT);
949
+ }, timeoutMs);
950
+ timer.unref();
951
+ const onAbort = () => {
952
+ controller.abort(CANCEL);
953
+ };
954
+ signal?.addEventListener("abort", onAbort, { once: true });
955
+ try {
956
+ const init = {
957
+ method,
958
+ headers,
959
+ signal: controller.signal,
960
+ dispatcher: this.#getDispatcher(),
961
+ redirect: "follow"
962
+ };
963
+ if (body !== void 0) init.body = body;
964
+ const res = await this.#fetch(url, init);
965
+ const bytes = new Uint8Array(await res.arrayBuffer());
966
+ const isError = res.status >= 400;
967
+ const allowed = isError && allowStatus.includes(res.status);
968
+ const text = isError || responseType === "json" || responseType === "text" ? new TextDecoder().decode(bytes) : "";
969
+ let data;
970
+ if (isError && !allowed || responseType === "none") {
971
+ data = void 0;
972
+ } else if (responseType === "bytes") {
973
+ data = bytes;
974
+ } else if (responseType === "text") {
975
+ data = text;
976
+ } else if (allowed) {
977
+ data = parseJsonOrUndefined(text);
978
+ } else {
979
+ data = this.#parseJson(text, res.status);
980
+ }
981
+ return { status: res.status, headers: res.headers, data, text };
982
+ } catch (err) {
983
+ const reason = controller.signal.reason;
984
+ if (controller.signal.aborted && (reason === CANCEL || reason === ATTEMPT_TIMEOUT)) {
985
+ throw new AbortedAttempt(reason);
986
+ }
987
+ throw err;
988
+ } finally {
989
+ clearTimeout(timer);
990
+ signal?.removeEventListener("abort", onAbort);
991
+ }
992
+ }
993
+ #parseJson(text, status) {
994
+ if (text.trim() === "") return void 0;
995
+ try {
996
+ return JSON.parse(text);
997
+ } catch {
998
+ throw new UnavailableError(`invalid JSON in response (HTTP ${status})`, {
999
+ retryable: false,
1000
+ httpStatus: status
1001
+ });
1002
+ }
1003
+ }
1004
+ #classify(err, operation, timeoutMs, isTotal, totalTimeout) {
1005
+ if (err instanceof OidcError) return err;
1006
+ if (err instanceof AbortedAttempt) {
1007
+ if (err.kind === CANCEL) return new CancelledError(`${operation}: cancelled`);
1008
+ return isTotal ? new TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`) : new TimeoutError(`${operation}: request timed out after ${timeoutMs} ms`);
1009
+ }
1010
+ const cause = redactError(err, this.#knownSecrets());
1011
+ const code = errorCode(err);
1012
+ if (code === "UND_ERR_CONNECT_TIMEOUT") {
1013
+ return new TimeoutError(
1014
+ `${operation}: connect timeout after ${this.#config.connectTimeoutMs} ms`,
1015
+ { cause }
1016
+ );
1017
+ }
1018
+ if (code !== void 0 && TLS_CODE.test(code)) {
1019
+ return new UnavailableError(`${operation}: TLS error (${code})`, { cause, retryable: false });
1020
+ }
1021
+ return new UnavailableError(
1022
+ `${operation}: network error${code === void 0 ? "" : ` (${code})`}`,
1023
+ { cause }
1024
+ );
1025
+ }
1026
+ #classifyResponse(perRequest, response) {
1027
+ for (const classify of [perRequest, this.#options.classifyError]) {
1028
+ if (classify === void 0) continue;
1029
+ let mapped;
1030
+ try {
1031
+ mapped = classify(response);
1032
+ } catch (err) {
1033
+ mapped = err instanceof OidcError ? err : void 0;
1034
+ }
1035
+ if (mapped instanceof OidcError) return mapped;
1036
+ }
1037
+ return void 0;
1038
+ }
1039
+ /**
1040
+ * Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
1041
+ * text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
1042
+ * {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
1043
+ */
1044
+ vendorText(text) {
1045
+ const trimmed = text.trim();
1046
+ if (trimmed === "") return void 0;
1047
+ let extracted;
1048
+ try {
1049
+ extracted = extractMessage(JSON.parse(trimmed));
1050
+ } catch {
1051
+ extracted = /^\s*</.test(trimmed) ? void 0 : trimmed;
1052
+ }
1053
+ const collapsed = extracted?.replace(/\s+/g, " ").trim();
1054
+ if (collapsed === void 0 || collapsed === "") return void 0;
1055
+ const redacted = redactSecretsInText(this.redact(collapsed));
1056
+ return redacted.length > MAX_VENDOR_TEXT ? redacted.slice(0, MAX_VENDOR_TEXT - 1).trimEnd() + "\u2026" : redacted;
1057
+ }
1058
+ #requestId(headers) {
1059
+ for (const name of this.#requestIdHeaders) {
1060
+ const v = headers.get(name);
1061
+ if (v !== null && v !== "") return v;
1062
+ }
1063
+ return void 0;
1064
+ }
1065
+ /** Releases connections. Idempotent. */
1066
+ async close() {
1067
+ if (this.#closed) return;
1068
+ this.#closed = true;
1069
+ const dispatcher = this.#dispatcher;
1070
+ this.#dispatcher = void 0;
1071
+ if (dispatcher !== void 0 && this.#options.dispatcher === void 0) {
1072
+ await dispatcher.close().catch(() => void 0);
1073
+ }
1074
+ }
1075
+ };
1076
+ function parseJsonOrUndefined(text) {
1077
+ if (text.trim() === "") return void 0;
1078
+ try {
1079
+ return JSON.parse(text);
1080
+ } catch {
1081
+ return void 0;
1082
+ }
1083
+ }
1084
+ function extractMessage(body) {
1085
+ if (typeof body === "string") return body;
1086
+ if (body === null || typeof body !== "object") return void 0;
1087
+ if (Array.isArray(body)) return body.length > 0 ? extractMessage(body[0]) : void 0;
1088
+ const obj = body;
1089
+ for (const key of [
1090
+ "message",
1091
+ "error_description",
1092
+ "error",
1093
+ "errors",
1094
+ "detail",
1095
+ "msg",
1096
+ "title",
1097
+ "reason"
1098
+ ]) {
1099
+ const found = extractMessage(obj[key]);
1100
+ if (found !== void 0 && found !== "") return found;
1101
+ }
1102
+ return void 0;
1103
+ }
1104
+ var SECRET_ASSIGNMENT = /((?:password|passwd|secret|token|authorization|api[_-]?key|access[_-]?key|private[_-]?key|credential|session|signature)["']?\s*[:=]\s*["']?)([^"'\s,;&}]+)/gi;
1105
+ var BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi;
1106
+ function redactSecretsInText(text) {
1107
+ return text.replace(BEARER, "$1 [REDACTED]").replace(SECRET_ASSIGNMENT, "$1[REDACTED]");
1108
+ }
1109
+
1110
+ // src/config.ts
1111
+ var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
1112
+ var CATALOG_PORT = "8000";
1113
+ var VENDOR_ENV = {
1114
+ url: [],
1115
+ token: []
1116
+ };
1117
+ var OidcConfig = class _OidcConfig {
1118
+ /** Default endpoint. */
1119
+ static DEFAULT_URL = `http://127.0.0.1:${/\d+/.exec(CATALOG_PORT)?.[0] ?? "8080"}`;
1120
+ /** Prefix of every environment variable. */
1121
+ static ENV_PREFIX = "GROW_OIDC_";
1122
+ url;
1123
+ connectTimeoutMs;
1124
+ requestTimeoutMs;
1125
+ totalTimeoutMs;
1126
+ retry;
1127
+ tls;
1128
+ proxy;
1129
+ headers;
1130
+ userAgentSuffix;
1131
+ hooks;
1132
+ logger;
1133
+ /** API token. */
1134
+ token;
1135
+ /** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
1136
+ constructor(options = {}) {
1137
+ const common = resolveCommonConfig(options, _OidcConfig.DEFAULT_URL);
1138
+ this.url = common.url;
1139
+ this.connectTimeoutMs = common.connectTimeoutMs;
1140
+ this.requestTimeoutMs = common.requestTimeoutMs;
1141
+ this.totalTimeoutMs = common.totalTimeoutMs;
1142
+ this.retry = common.retry;
1143
+ this.tls = common.tls;
1144
+ this.headers = common.headers;
1145
+ if (common.proxy !== void 0) this.proxy = common.proxy;
1146
+ if (common.userAgentSuffix !== void 0) this.userAgentSuffix = common.userAgentSuffix;
1147
+ if (common.hooks !== void 0) this.hooks = common.hooks;
1148
+ if (common.logger !== void 0) this.logger = common.logger;
1149
+ const token = Secret.from(options.token);
1150
+ if (token !== void 0) this.token = token;
1151
+ this.validate();
1152
+ Object.freeze(this);
1153
+ }
1154
+ /** Returns `options` when it already is a config, otherwise builds one. */
1155
+ static from(options = {}) {
1156
+ if (options instanceof _OidcConfig) return options;
1157
+ return new _OidcConfig(options);
1158
+ }
1159
+ /**
1160
+ * Builds a config from the environment. Precedence: explicit `overrides` >
1161
+ * `GROW_OIDC_<NAME>` > vendor variables ({@link VENDOR_ENV}) > defaults.
1162
+ */
1163
+ static fromEnv(overrides = {}, env = process.env) {
1164
+ const reader = new EnvReader(_OidcConfig.ENV_PREFIX, env);
1165
+ const fromEnv = readCommonEnv(reader, VENDOR_ENV);
1166
+ const token = reader.secret("TOKEN", VENDOR_ENV.token);
1167
+ if (token !== void 0) fromEnv.token = token;
1168
+ const merged = mergeOptions(fromEnv, overrides);
1169
+ return new _OidcConfig(merged);
1170
+ }
1171
+ /** Throws {@link ConfigError} when a setting is invalid. Service rules go here. */
1172
+ validate() {
1173
+ validateCommonConfig(this);
1174
+ if (this.token?.reveal().trim() === "")
1175
+ throw new ConfigError("invalid configuration: token must not be blank");
1176
+ }
1177
+ /** Credential values to redact from error messages and logs. */
1178
+ knownSecrets() {
1179
+ return secretValues(this.token);
1180
+ }
1181
+ /** Debug form with every credential redacted. */
1182
+ toJSON() {
1183
+ return { ...describeCommonConfig(this), token: this.token === void 0 ? null : REDACTED };
1184
+ }
1185
+ toString() {
1186
+ return `OidcConfig(${JSON.stringify(this.toJSON())})`;
1187
+ }
1188
+ [INSPECT2]() {
1189
+ return this.toString();
1190
+ }
1191
+ };
1192
+
1193
+ // src/client.ts
1194
+ var DISCOVERY_PATH = ".well-known/openid-configuration";
1195
+ function trimTrailingSlashes(value) {
1196
+ let end = value.length;
1197
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1198
+ return value.slice(0, end);
1199
+ }
1200
+ function relativeEndpoint(base, endpoint) {
1201
+ const root = trimTrailingSlashes(base);
1202
+ if (endpoint.startsWith(root + "/")) return endpoint.slice(root.length);
1203
+ try {
1204
+ const url = new URL(endpoint);
1205
+ return url.pathname + url.search;
1206
+ } catch {
1207
+ return endpoint;
1208
+ }
1209
+ }
1210
+ var OidcClient = class _OidcClient {
1211
+ /** The immutable configuration. */
1212
+ config;
1213
+ #transport;
1214
+ #closed = false;
1215
+ /** Accepts a {@link OidcConfig} or plain options. */
1216
+ constructor(config = {}, internals = {}) {
1217
+ const cfg = OidcConfig.from(config);
1218
+ this.config = cfg;
1219
+ this.#transport = new HttpTransport({
1220
+ ...internals,
1221
+ config: cfg,
1222
+ knownSecrets: () => cfg.knownSecrets()
1223
+ });
1224
+ }
1225
+ /** Builds a client from `GROW_OIDC_*` (and vendor) environment variables. */
1226
+ static fromEnv(overrides = {}) {
1227
+ return new _OidcClient(OidcConfig.fromEnv(overrides));
1228
+ }
1229
+ /** The shared HTTP transport (for service modules). @internal */
1230
+ get transport() {
1231
+ return this.#transport;
1232
+ }
1233
+ /**
1234
+ * Unauthenticated liveness: `GET <url>/.well-known/openid-configuration` (healthy when the
1235
+ * discovery document answers 2xx). Never throws for an unhealthy or unreachable provider (only
1236
+ * `CANCELLED` and `CONFIG`).
1237
+ */
1238
+ health(options = {}) {
1239
+ return probeHealth(async () => {
1240
+ const doc = await this.#discovery("health", options);
1241
+ const details = {};
1242
+ if (typeof doc.issuer === "string") details.issuer = doc.issuer;
1243
+ return healthStatus("ok", details);
1244
+ });
1245
+ }
1246
+ /**
1247
+ * Authenticated round trip with the configured access token (`token`): `GET` the provider's
1248
+ * `userinfo_endpoint` from discovery. Returns the latency in milliseconds; a rejected token
1249
+ * raises `AuthenticationError`, a provider without userinfo `UnsupportedError`.
1250
+ */
1251
+ async ping(options = {}) {
1252
+ const start = performance.now();
1253
+ const doc = await this.#discovery("ping", options);
1254
+ if (typeof doc.userinfo_endpoint !== "string" || doc.userinfo_endpoint === "") {
1255
+ throw new UnsupportedError("ping: the provider has no userinfo endpoint");
1256
+ }
1257
+ const token = this.config.token;
1258
+ await this.#transport.get(relativeEndpoint(this.config.url, doc.userinfo_endpoint), {
1259
+ operation: "ping",
1260
+ responseType: "none",
1261
+ headers: token === void 0 ? {} : { authorization: `Bearer ${token.reveal()}` },
1262
+ ...options
1263
+ });
1264
+ return performance.now() - start;
1265
+ }
1266
+ /** OpenID Connect has no version endpoint: always `UnsupportedError` (`CANCELLED` once closed). */
1267
+ serverVersion(_options = {}) {
1268
+ return new Promise((_resolve, reject) => {
1269
+ this.#transport.ensureOpen("serverVersion");
1270
+ reject(new UnsupportedError("serverVersion: OpenID Connect providers expose no version"));
1271
+ });
1272
+ }
1273
+ async #discovery(operation, options) {
1274
+ const res = await this.#transport.get(DISCOVERY_PATH, { operation, ...options });
1275
+ const data = res.data;
1276
+ return data !== null && typeof data === "object" && !Array.isArray(data) ? data : {};
1277
+ }
1278
+ /** Releases connections. Idempotent. */
1279
+ async close() {
1280
+ if (this.#closed) return;
1281
+ this.#closed = true;
1282
+ await this.#transport.close();
1283
+ }
1284
+ };
1285
+
1286
+ // src/oidc/roles.ts
1287
+ var ROLE_OBJECT_KEYS = ["name", "code", "role", "value"];
1288
+ function claimAt(claims, path) {
1289
+ if (Object.hasOwn(claims, path)) return claims[path];
1290
+ let current = claims;
1291
+ for (const part of path.split(".")) {
1292
+ if (current === null || typeof current !== "object" || Array.isArray(current)) return void 0;
1293
+ const record = current;
1294
+ if (!Object.hasOwn(record, part)) return void 0;
1295
+ current = record[part];
1296
+ }
1297
+ return current;
1298
+ }
1299
+ function roleName(entry) {
1300
+ if (typeof entry === "string") return entry.trim() === "" ? void 0 : entry.trim();
1301
+ if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
1302
+ const record = entry;
1303
+ for (const key of ROLE_OBJECT_KEYS) {
1304
+ const value = record[key];
1305
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
1306
+ }
1307
+ }
1308
+ return void 0;
1309
+ }
1310
+ function extractRoles(claims, rolesClaim = "roles") {
1311
+ const raw = claimAt(claims, rolesClaim);
1312
+ let names = [];
1313
+ if (typeof raw === "string") {
1314
+ names = raw.split(/[\s,]+/u);
1315
+ } else if (Array.isArray(raw)) {
1316
+ names = raw.map(roleName);
1317
+ }
1318
+ const out = [];
1319
+ for (const name of names) {
1320
+ if (name !== void 0 && name !== "" && !out.includes(name)) out.push(name);
1321
+ }
1322
+ return out;
1323
+ }
1324
+ function hasAnyRole(userRoles, required) {
1325
+ if (required.length === 0) return true;
1326
+ const have = new Set(userRoles.map((role) => role.toLowerCase()));
1327
+ return required.some((role) => have.has(role.toLowerCase()));
1328
+ }
1329
+ var DEFAULT_ALGORITHMS = ["RS256", "ES256", "EdDSA"];
1330
+ var DEFAULT_CLOCK_SKEW_MS = 6e4;
1331
+ var DEFAULT_JWKS_CACHE_TTL_MS = 6e5;
1332
+ var DEFAULT_JWKS_REFRESH_COOLDOWN_MS = 3e4;
1333
+ var DEFAULT_HTTP_TIMEOUT_MS = 1e4;
1334
+ function bearerToken(req) {
1335
+ if (req === null || req === void 0) return null;
1336
+ let value;
1337
+ if (req instanceof Headers) {
1338
+ value = req.get("authorization");
1339
+ } else if (req.headers instanceof Headers) {
1340
+ value = req.headers.get("authorization");
1341
+ } else {
1342
+ const headers = req.headers;
1343
+ const raw = headers.authorization ?? headers.Authorization;
1344
+ value = Array.isArray(raw) ? raw[0] : raw;
1345
+ }
1346
+ if (typeof value !== "string") return null;
1347
+ const match = /^\s*bearer\s+(\S+)\s*$/iu.exec(value);
1348
+ return match?.[1] ?? null;
1349
+ }
1350
+ var Verifier = class _Verifier {
1351
+ issuer;
1352
+ audience;
1353
+ rolesClaim;
1354
+ algorithms;
1355
+ clockSkewMs;
1356
+ #jwksUrl;
1357
+ #ttlMs;
1358
+ #cooldownMs;
1359
+ #timeoutMs;
1360
+ #fetch;
1361
+ #now;
1362
+ #resolvedJwksUrl;
1363
+ #keys;
1364
+ #inflight;
1365
+ constructor(options) {
1366
+ if (typeof options.issuer !== "string" || options.issuer.trim() === "") {
1367
+ throw new ConfigError("oidc: issuer is required");
1368
+ }
1369
+ if (typeof options.audience !== "string" || options.audience.trim() === "") {
1370
+ throw new ConfigError("oidc: audience is required");
1371
+ }
1372
+ const algorithms = options.algorithms ?? DEFAULT_ALGORITHMS;
1373
+ if (algorithms.length === 0 || algorithms.some((alg) => !DEFAULT_ALGORITHMS.includes(alg))) {
1374
+ throw new ConfigError("oidc: algorithms must be a non-empty subset of RS256, ES256, EdDSA");
1375
+ }
1376
+ for (const [name, value] of [
1377
+ ["clockSkewMs", options.clockSkewMs],
1378
+ ["jwksCacheTtlMs", options.jwksCacheTtlMs],
1379
+ ["jwksRefreshCooldownMs", options.jwksRefreshCooldownMs],
1380
+ ["httpTimeoutMs", options.httpTimeoutMs]
1381
+ ]) {
1382
+ if (value !== void 0 && (!Number.isFinite(value) || value < 0)) {
1383
+ throw new ConfigError(`oidc: ${name} must be a non-negative number`);
1384
+ }
1385
+ }
1386
+ this.issuer = options.issuer.trim();
1387
+ this.audience = options.audience.trim();
1388
+ this.rolesClaim = options.rolesClaim?.trim() || "roles";
1389
+ this.algorithms = [...algorithms];
1390
+ this.clockSkewMs = options.clockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
1391
+ this.#jwksUrl = options.jwksUrl?.trim() || void 0;
1392
+ if (this.#jwksUrl !== void 0) checkUrl("jwksUrl", this.#jwksUrl);
1393
+ checkUrl("issuer", this.issuer);
1394
+ this.#ttlMs = options.jwksCacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
1395
+ this.#cooldownMs = options.jwksRefreshCooldownMs ?? DEFAULT_JWKS_REFRESH_COOLDOWN_MS;
1396
+ this.#timeoutMs = options.httpTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS;
1397
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1398
+ this.#now = options.now ?? Date.now;
1399
+ }
1400
+ /**
1401
+ * Builds a verifier from `GROW_AUTH_ISSUER` (required), `GROW_AUTH_AUDIENCE` (default
1402
+ * `GROW_AUTH_CLIENT_ID`), `GROW_AUTH_JWKS_URL`, `GROW_AUTH_ROLES_CLAIM` (default `roles`) and
1403
+ * `GROW_AUTH_CLOCK_SKEW` (duration, default 60s). Explicit `overrides` win.
1404
+ */
1405
+ static fromEnv(overrides = {}, env = process.env) {
1406
+ const read = (name) => {
1407
+ const value = env[name]?.trim();
1408
+ return value === void 0 || value === "" ? void 0 : value;
1409
+ };
1410
+ const issuer = overrides.issuer ?? read("GROW_AUTH_ISSUER");
1411
+ if (issuer === void 0) throw new ConfigError("oidc: GROW_AUTH_ISSUER is required");
1412
+ const audience = overrides.audience ?? read("GROW_AUTH_AUDIENCE") ?? read("GROW_AUTH_CLIENT_ID");
1413
+ if (audience === void 0) {
1414
+ throw new ConfigError("oidc: GROW_AUTH_AUDIENCE (or GROW_AUTH_CLIENT_ID) is required");
1415
+ }
1416
+ let clockSkewMs = overrides.clockSkewMs;
1417
+ const skew = read("GROW_AUTH_CLOCK_SKEW");
1418
+ if (clockSkewMs === void 0 && skew !== void 0) {
1419
+ clockSkewMs = parseDuration(skew);
1420
+ if (clockSkewMs === void 0)
1421
+ throw new ConfigError("oidc: GROW_AUTH_CLOCK_SKEW is not a duration");
1422
+ }
1423
+ const options = { ...overrides, issuer, audience };
1424
+ const jwksUrl = overrides.jwksUrl ?? read("GROW_AUTH_JWKS_URL");
1425
+ if (jwksUrl !== void 0) options.jwksUrl = jwksUrl;
1426
+ const rolesClaim = overrides.rolesClaim ?? read("GROW_AUTH_ROLES_CLAIM");
1427
+ if (rolesClaim !== void 0) options.rolesClaim = rolesClaim;
1428
+ if (clockSkewMs !== void 0) options.clockSkewMs = clockSkewMs;
1429
+ return new _Verifier(options);
1430
+ }
1431
+ /** Verifies a raw JWT access token and returns its user. */
1432
+ async verify(token) {
1433
+ if (typeof token !== "string" || token.split(".").length !== 3) {
1434
+ throw new AuthenticationError("verify: malformed token");
1435
+ }
1436
+ let alg;
1437
+ let kid;
1438
+ try {
1439
+ ({ alg, kid } = decodeProtectedHeader(token));
1440
+ } catch {
1441
+ throw new AuthenticationError("verify: malformed token header");
1442
+ }
1443
+ if (alg === void 0 || !this.algorithms.includes(alg)) {
1444
+ throw new AuthenticationError(`verify: algorithm ${String(alg)} is not allowed`);
1445
+ }
1446
+ let entry = await this.#keySet(false);
1447
+ try {
1448
+ return await this.#verifyWith(token, entry);
1449
+ } catch (err) {
1450
+ if (!(err instanceof errors.JWKSNoMatchingKey) || !this.#mayRefresh(entry)) {
1451
+ throw mapJoseError(err, kid);
1452
+ }
1453
+ }
1454
+ entry = await this.#keySet(true);
1455
+ try {
1456
+ return await this.#verifyWith(token, entry);
1457
+ } catch (err) {
1458
+ throw mapJoseError(err, kid);
1459
+ }
1460
+ }
1461
+ /** Verifies the bearer token of a request (`AuthenticationError` when there is none). */
1462
+ async verifyRequest(req) {
1463
+ const token = bearerToken(req);
1464
+ if (token === null) throw new AuthenticationError("verify: missing bearer token");
1465
+ return this.verify(token);
1466
+ }
1467
+ /** Drops the cached JWKS so the next verification refetches it. */
1468
+ clearCache() {
1469
+ this.#keys = void 0;
1470
+ }
1471
+ async #verifyWith(token, entry) {
1472
+ const { payload } = await jwtVerify(token, entry.getKey, {
1473
+ issuer: this.issuer,
1474
+ audience: this.audience,
1475
+ algorithms: [...this.algorithms],
1476
+ clockTolerance: Math.floor(this.clockSkewMs / 1e3),
1477
+ requiredClaims: ["exp", "sub"],
1478
+ currentDate: new Date(this.#now())
1479
+ });
1480
+ return this.#toUser(payload);
1481
+ }
1482
+ #toUser(payload) {
1483
+ const claims = { ...payload };
1484
+ const user = {
1485
+ sub: String(payload.sub),
1486
+ roles: extractRoles(claims, this.rolesClaim),
1487
+ claims
1488
+ };
1489
+ if (typeof claims.email === "string") user.email = claims.email;
1490
+ const name = typeof claims.name === "string" ? claims.name : claims.preferred_username;
1491
+ if (typeof name === "string") user.name = name;
1492
+ return user;
1493
+ }
1494
+ #mayRefresh(entry) {
1495
+ return this.#now() - entry.fetchedAt >= this.#cooldownMs;
1496
+ }
1497
+ async #keySet(force) {
1498
+ const cached = this.#keys;
1499
+ if (!force && cached !== void 0 && this.#now() - cached.fetchedAt < this.#ttlMs)
1500
+ return cached;
1501
+ if (this.#inflight !== void 0) return this.#inflight;
1502
+ const pending = this.#loadKeySet().finally(() => {
1503
+ this.#inflight = void 0;
1504
+ });
1505
+ this.#inflight = pending;
1506
+ return pending;
1507
+ }
1508
+ async #loadKeySet() {
1509
+ const url = await this.#jwksUri();
1510
+ const body = await this.#getJson(url, "jwks");
1511
+ if (body === null || typeof body !== "object" || !Array.isArray(body.keys)) {
1512
+ throw new UnavailableError("jwks: response has no keys array");
1513
+ }
1514
+ const entry = {
1515
+ getKey: createLocalJWKSet(body),
1516
+ fetchedAt: this.#now()
1517
+ };
1518
+ this.#keys = entry;
1519
+ return entry;
1520
+ }
1521
+ async #jwksUri() {
1522
+ if (this.#jwksUrl !== void 0) return this.#jwksUrl;
1523
+ if (this.#resolvedJwksUrl !== void 0) return this.#resolvedJwksUrl;
1524
+ const url = `${trimTrailingSlashes2(this.issuer)}/.well-known/openid-configuration`;
1525
+ const doc = await this.#getJson(url, "discovery");
1526
+ const jwksUri = doc?.jwks_uri;
1527
+ if (typeof jwksUri !== "string" || jwksUri === "") {
1528
+ throw new UnavailableError("discovery: document has no jwks_uri");
1529
+ }
1530
+ this.#resolvedJwksUrl = jwksUri;
1531
+ return jwksUri;
1532
+ }
1533
+ async #getJson(url, operation) {
1534
+ let res;
1535
+ try {
1536
+ res = await this.#fetch(url, {
1537
+ headers: { accept: "application/json" },
1538
+ signal: AbortSignal.timeout(this.#timeoutMs)
1539
+ });
1540
+ } catch (err) {
1541
+ throw new UnavailableError(`${operation}: request failed`, { cause: err });
1542
+ }
1543
+ if (!res.ok) {
1544
+ throw new UnavailableError(`${operation}: unexpected response (HTTP ${res.status})`, {
1545
+ httpStatus: res.status
1546
+ });
1547
+ }
1548
+ try {
1549
+ return await res.json();
1550
+ } catch (err) {
1551
+ throw new UnavailableError(`${operation}: response is not JSON`, { cause: err });
1552
+ }
1553
+ }
1554
+ };
1555
+ function trimTrailingSlashes2(value) {
1556
+ let end = value.length;
1557
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1558
+ return value.slice(0, end);
1559
+ }
1560
+ function checkUrl(name, value) {
1561
+ let parsed;
1562
+ try {
1563
+ parsed = new URL(value);
1564
+ } catch {
1565
+ throw new ConfigError(`oidc: ${name} is not a URL`);
1566
+ }
1567
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1568
+ throw new ConfigError(`oidc: ${name} must use http or https`);
1569
+ }
1570
+ }
1571
+ function mapJoseError(err, kid) {
1572
+ if (err instanceof OidcError) return err;
1573
+ if (err instanceof errors.JWTExpired) return new AuthenticationError("verify: token expired");
1574
+ if (err instanceof errors.JWTClaimValidationFailed) {
1575
+ return new AuthenticationError(`verify: claim ${err.claim} is invalid (${err.reason})`);
1576
+ }
1577
+ if (err instanceof errors.JWKSNoMatchingKey) {
1578
+ return new AuthenticationError(`verify: no key matches kid ${kid ?? "(none)"}`);
1579
+ }
1580
+ if (err instanceof errors.JWKSMultipleMatchingKeys) {
1581
+ return new AuthenticationError("verify: several keys match and none verified the signature");
1582
+ }
1583
+ if (err instanceof errors.JWSSignatureVerificationFailed) {
1584
+ return new AuthenticationError("verify: signature is invalid");
1585
+ }
1586
+ return new AuthenticationError("verify: token is invalid", { cause: err });
1587
+ }
1588
+
1589
+ // src/oidc/express.ts
1590
+ function deny(res, status, error) {
1591
+ if (status === 401) res.setHeader("WWW-Authenticate", 'Bearer error="invalid_token"');
1592
+ res.status(status).json({ error });
1593
+ }
1594
+ function expressAuth(verifier, options = {}) {
1595
+ return async (req, res, next) => {
1596
+ const token = bearerToken(req);
1597
+ if (token === null) {
1598
+ if (options.optional === true) {
1599
+ next();
1600
+ return;
1601
+ }
1602
+ deny(res, 401, "unauthorized");
1603
+ return;
1604
+ }
1605
+ try {
1606
+ req.user = await verifier.verify(token);
1607
+ } catch (err) {
1608
+ if (err instanceof UnavailableError) {
1609
+ deny(res, 503, "auth_unavailable");
1610
+ return;
1611
+ }
1612
+ if (err instanceof OidcError) {
1613
+ deny(res, 401, "unauthorized");
1614
+ return;
1615
+ }
1616
+ next(err);
1617
+ return;
1618
+ }
1619
+ next();
1620
+ };
1621
+ }
1622
+ function requireRoles(...roles) {
1623
+ return (req, res, next) => {
1624
+ const user = req.user;
1625
+ if (user === void 0) deny(res, 401, "unauthorized");
1626
+ else if (!hasAnyRole(user.roles, roles)) deny(res, 403, "forbidden");
1627
+ else next();
1628
+ return Promise.resolve();
1629
+ };
1630
+ }
1631
+ var ROLES_KEY = "grow:oidc:roles";
1632
+ var PUBLIC_KEY = "grow:oidc:public";
1633
+ var reflect = Reflect;
1634
+ var store = /* @__PURE__ */ new WeakMap();
1635
+ function setMeta(target, key, value) {
1636
+ let entry = store.get(target);
1637
+ if (entry === void 0) {
1638
+ entry = /* @__PURE__ */ new Map();
1639
+ store.set(target, entry);
1640
+ }
1641
+ entry.set(key, value);
1642
+ reflect.defineMetadata?.(key, value, target);
1643
+ }
1644
+ function getMeta(target, key) {
1645
+ if (target === null || typeof target !== "object" && typeof target !== "function")
1646
+ return void 0;
1647
+ const local = store.get(target)?.get(key);
1648
+ return local !== void 0 ? local : reflect.getMetadata?.(key, target);
1649
+ }
1650
+ function metaDecorator(key, value) {
1651
+ return (target, _key, descriptor) => {
1652
+ const holder = descriptor?.value ?? target;
1653
+ setMeta(holder, key, value);
1654
+ };
1655
+ }
1656
+ function Roles(...roles) {
1657
+ return metaDecorator(ROLES_KEY, roles);
1658
+ }
1659
+ function Public() {
1660
+ return metaDecorator(PUBLIC_KEY, true);
1661
+ }
1662
+ var nestExceptions;
1663
+ function loadNestExceptions() {
1664
+ if (nestExceptions !== void 0) return nestExceptions;
1665
+ try {
1666
+ const appRequire = createRequire(join(process.cwd(), "package.json"));
1667
+ const common = appRequire("@nestjs/common");
1668
+ nestExceptions = {
1669
+ unauthorized: common.UnauthorizedException,
1670
+ forbidden: common.ForbiddenException,
1671
+ unavailable: common.ServiceUnavailableException
1672
+ };
1673
+ } catch {
1674
+ nestExceptions = {};
1675
+ }
1676
+ return nestExceptions;
1677
+ }
1678
+ function resetNestExceptionsForTests(value) {
1679
+ nestExceptions = value;
1680
+ }
1681
+ var HttpStatusError = class extends Error {
1682
+ statusCode;
1683
+ constructor(statusCode, message) {
1684
+ super(message);
1685
+ this.name = "HttpStatusError";
1686
+ this.statusCode = statusCode;
1687
+ }
1688
+ /** Nest `HttpException`-compatible accessor. */
1689
+ getStatus() {
1690
+ return this.statusCode;
1691
+ }
1692
+ };
1693
+ function httpError(status) {
1694
+ const ex = loadNestExceptions();
1695
+ const ctor = status === 401 ? ex.unauthorized : status === 403 ? ex.forbidden : ex.unavailable;
1696
+ const message = status === 401 ? "Unauthorized" : status === 403 ? "Forbidden" : "Service Unavailable";
1697
+ return ctor !== void 0 ? new ctor(message) : new HttpStatusError(status, message);
1698
+ }
1699
+ function isPublic(ctx) {
1700
+ return getMeta(ctx.getHandler(), PUBLIC_KEY) === true || getMeta(ctx.getClass(), PUBLIC_KEY) === true;
1701
+ }
1702
+ var NestAuthGuard = class {
1703
+ #verifier;
1704
+ #optional;
1705
+ constructor(verifier, options = {}) {
1706
+ this.#verifier = verifier;
1707
+ this.#optional = options.optional === true;
1708
+ }
1709
+ /** Nest `CanActivate`. */
1710
+ async canActivate(ctx) {
1711
+ const req = ctx.switchToHttp().getRequest();
1712
+ const token = bearerToken(req);
1713
+ if (token === null) {
1714
+ if (this.#optional || isPublic(ctx)) return true;
1715
+ throw httpError(401);
1716
+ }
1717
+ try {
1718
+ req.user = await this.#verifier.verify(token);
1719
+ return true;
1720
+ } catch (err) {
1721
+ if (isPublic(ctx)) return true;
1722
+ if (err instanceof UnavailableError) throw httpError(503);
1723
+ if (err instanceof OidcError) throw httpError(401);
1724
+ throw err;
1725
+ }
1726
+ }
1727
+ };
1728
+ var RolesGuard = class {
1729
+ #roles;
1730
+ constructor(roles) {
1731
+ this.#roles = roles;
1732
+ }
1733
+ /** Nest `CanActivate`. */
1734
+ canActivate(ctx) {
1735
+ const required = this.#roles ?? getMeta(ctx.getHandler(), ROLES_KEY) ?? getMeta(ctx.getClass(), ROLES_KEY);
1736
+ const user = ctx.switchToHttp().getRequest().user;
1737
+ if (user === void 0) {
1738
+ if (required === void 0 || isPublic(ctx)) return true;
1739
+ throw httpError(401);
1740
+ }
1741
+ if (required === void 0 || hasAnyRole(user.roles, required)) return true;
1742
+ throw httpError(403);
1743
+ }
1744
+ };
1745
+
1746
+ export { DEFAULT_ALGORITHMS, DEFAULT_CLOCK_SKEW_MS, DEFAULT_HTTP_TIMEOUT_MS, DEFAULT_JWKS_CACHE_TTL_MS, DEFAULT_JWKS_REFRESH_COOLDOWN_MS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, DISCOVERY_PATH, EnvReader, HttpStatusError, HttpTransport, LANGUAGE, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, NestAuthGuard, OidcClient, OidcConfig, PACKAGE_KEY, PUBLIC_KEY, Public, REDACTED, ROLES_KEY, RetryPolicy, Roles, RolesGuard, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, VENDOR_ENV, Verifier, bearerToken, claimAt, createDispatcher, definedOnly, describeCommonConfig, expressAuth, extractRoles, hasAnyRole, healthStatus, isHealthyWord, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, mergeOptions, parseBool, parseDuration, parseInteger, parseRetryAfter, probeHealth, readCommonEnv, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, relativeEndpoint, requireRoles, resetNestExceptionsForTests, resolveCommonConfig, safeCall, safeLogger, secretValues, silentLogger, validateCommonConfig };
1747
+ //# sourceMappingURL=index.js.map
1748
+ //# sourceMappingURL=index.js.map