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