@grow-codes/oidc 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnvReader, K as KnownSecret, S as Secret, a as EnvMap, H as HealthStatus, R as RequestLike, A as AuthUser, V as Verifier } from './verifier-ERmLmytF.cjs';
2
- export { D as DEFAULT_ALGORITHMS, b as DEFAULT_CLOCK_SKEW_MS, c as DEFAULT_HTTP_TIMEOUT_MS, d as DEFAULT_JWKS_CACHE_TTL_MS, e as DEFAULT_JWKS_REFRESH_COOLDOWN_MS, f as EnvHit, g as HeadersInput, M as MIN_SECRET_LENGTH, h as REDACTED, i as SENSITIVE_FIELD_PARTS, j as SigningAlgorithm, k as VerifierOptions, l as bearerToken, m as healthStatus, n as isHealthyWord, o as isSensitiveField, p as isSensitiveHeader, q as parseBool, r as parseDuration, s as parseInteger, t as probeHealth, u as redactError, v as redactFields, w as redactHeaders, x as redactText, y as redactUrl } from './verifier-ERmLmytF.cjs';
1
+ import { E as EnvReader, K as KnownSecret, S as Secret, a as EnvMap, H as HealthStatus, R as RequestLike, A as AuthUser, V as Verifier } from './verifier-AJ2o8XWA.cjs';
2
+ export { D as DEFAULT_ALGORITHMS, b as DEFAULT_CLOCK_SKEW_MS, c as DEFAULT_HTTP_TIMEOUT_MS, d as DEFAULT_JWKS_CACHE_TTL_MS, e as DEFAULT_JWKS_REFRESH_COOLDOWN_MS, f as EnvHit, g as HeadersInput, M as MIN_SECRET_LENGTH, h as REDACTED, i as SENSITIVE_FIELD_PARTS, j as SigningAlgorithm, k as VerifierOptions, l as bearerToken, m as healthStatus, n as isHealthyWord, o as isSensitiveField, p as isSensitiveHeader, q as parseBool, r as parseDuration, s as parseInteger, t as probeHealth, u as redactError, v as redactFields, w as redactHeaders, x as redactText, y as redactUrl } from './verifier-AJ2o8XWA.cjs';
3
3
  import { Dispatcher } from 'undici';
4
4
 
5
5
  /** Throws {@link CancelledError} when the signal is already aborted. */
@@ -495,7 +495,7 @@ declare class HttpTransport {
495
495
  declare function redactSecretsInText(text: string): string;
496
496
 
497
497
  /** Package version (kept in sync by release-please). */
498
- declare const SDK_VERSION = "0.1.0";
498
+ declare const SDK_VERSION = "0.1.1";
499
499
  /** Catalog key of the service (`oidc`). */
500
500
  declare const PACKAGE_KEY = "oidc";
501
501
  /** Language tag used in the User-Agent. */
package/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnvReader, K as KnownSecret, S as Secret, a as EnvMap, H as HealthStatus, R as RequestLike, A as AuthUser, V as Verifier } from './verifier-ERmLmytF.js';
2
- export { D as DEFAULT_ALGORITHMS, b as DEFAULT_CLOCK_SKEW_MS, c as DEFAULT_HTTP_TIMEOUT_MS, d as DEFAULT_JWKS_CACHE_TTL_MS, e as DEFAULT_JWKS_REFRESH_COOLDOWN_MS, f as EnvHit, g as HeadersInput, M as MIN_SECRET_LENGTH, h as REDACTED, i as SENSITIVE_FIELD_PARTS, j as SigningAlgorithm, k as VerifierOptions, l as bearerToken, m as healthStatus, n as isHealthyWord, o as isSensitiveField, p as isSensitiveHeader, q as parseBool, r as parseDuration, s as parseInteger, t as probeHealth, u as redactError, v as redactFields, w as redactHeaders, x as redactText, y as redactUrl } from './verifier-ERmLmytF.js';
1
+ import { E as EnvReader, K as KnownSecret, S as Secret, a as EnvMap, H as HealthStatus, R as RequestLike, A as AuthUser, V as Verifier } from './verifier-AJ2o8XWA.js';
2
+ export { D as DEFAULT_ALGORITHMS, b as DEFAULT_CLOCK_SKEW_MS, c as DEFAULT_HTTP_TIMEOUT_MS, d as DEFAULT_JWKS_CACHE_TTL_MS, e as DEFAULT_JWKS_REFRESH_COOLDOWN_MS, f as EnvHit, g as HeadersInput, M as MIN_SECRET_LENGTH, h as REDACTED, i as SENSITIVE_FIELD_PARTS, j as SigningAlgorithm, k as VerifierOptions, l as bearerToken, m as healthStatus, n as isHealthyWord, o as isSensitiveField, p as isSensitiveHeader, q as parseBool, r as parseDuration, s as parseInteger, t as probeHealth, u as redactError, v as redactFields, w as redactHeaders, x as redactText, y as redactUrl } from './verifier-AJ2o8XWA.js';
3
3
  import { Dispatcher } from 'undici';
4
4
 
5
5
  /** Throws {@link CancelledError} when the signal is already aborted. */
@@ -495,7 +495,7 @@ declare class HttpTransport {
495
495
  declare function redactSecretsInText(text: string): string;
496
496
 
497
497
  /** Package version (kept in sync by release-please). */
498
- declare const SDK_VERSION = "0.1.0";
498
+ declare const SDK_VERSION = "0.1.1";
499
499
  /** Catalog key of the service (`oidc`). */
500
500
  declare const PACKAGE_KEY = "oidc";
501
501
  /** Language tag used in the User-Agent. */
package/lib/index.js CHANGED
@@ -1,303 +1,10 @@
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';
1
+ import { Secret, EnvReader, ConfigError, REDACTED, redactUrl, OidcError, ErrorCode, sleep, CancelledError, redactText, TimeoutError, redactHeaders, errorForStatus, UnavailableError, redactError, UnsupportedError, bearerToken, hasAnyRole } from './chunk-HB2FEHOY.js';
2
+ export { AuthenticationError, CancelledError, ConfigError, ConflictError, DEFAULT_ALGORITHMS, DEFAULT_CLOCK_SKEW_MS, DEFAULT_HTTP_TIMEOUT_MS, DEFAULT_JWKS_CACHE_TTL_MS, DEFAULT_JWKS_REFRESH_COOLDOWN_MS, EnvReader, ErrorCode, MIN_SECRET_LENGTH, NotFoundError, OidcError, PermissionDeniedError, REDACTED, RateLimitError, SENSITIVE_FIELD_PARTS, Secret, TimeoutError, UnavailableError, UnsupportedError, ValidationError, Verifier, bearerToken, claimAt, codeForStatus, errorForCode, errorForStatus, extractRoles, hasAnyRole, isOidcError, isSensitiveField, isSensitiveHeader, parseBool, parseDuration, parseInteger, pollUntil, reasonForCode, redactError, redactFields, redactHeaders, redactText, redactUrl, sleep, throwIfAborted } from './chunk-HB2FEHOY.js';
3
3
  import { readFileSync } from 'fs';
4
4
  import { ProxyAgent, Agent, fetch } from 'undici';
5
- import { decodeProtectedHeader, errors, jwtVerify, createLocalJWKSet } from 'jose';
6
5
  import { createRequire } from 'module';
7
6
  import { join } from 'path';
8
7
 
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
8
  // src/core/health.ts
302
9
  var HEALTHY_WORDS = /* @__PURE__ */ new Set([
303
10
  "ok",
@@ -601,7 +308,7 @@ function secretValues(...values) {
601
308
  }
602
309
 
603
310
  // src/core/version.ts
604
- var SDK_VERSION = "0.1.0";
311
+ var SDK_VERSION = "0.1.1";
605
312
  var PACKAGE_KEY = "oidc";
606
313
  var LANGUAGE = "typescript";
607
314
  var SDK_KIT_VERSION = "0.3.0";
@@ -1108,7 +815,7 @@ function redactSecretsInText(text) {
1108
815
  }
1109
816
 
1110
817
  // src/config.ts
1111
- var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
818
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
1112
819
  var CATALOG_PORT = "8000";
1113
820
  var VENDOR_ENV = {
1114
821
  url: [],
@@ -1185,7 +892,7 @@ var OidcConfig = class _OidcConfig {
1185
892
  toString() {
1186
893
  return `OidcConfig(${JSON.stringify(this.toJSON())})`;
1187
894
  }
1188
- [INSPECT2]() {
895
+ [INSPECT]() {
1189
896
  return this.toString();
1190
897
  }
1191
898
  };
@@ -1283,309 +990,6 @@ var OidcClient = class _OidcClient {
1283
990
  }
1284
991
  };
1285
992
 
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
993
  // src/oidc/express.ts
1590
994
  function deny(res, status, error) {
1591
995
  if (status === 401) res.setHeader("WWW-Authenticate", 'Bearer error="invalid_token"');
@@ -1743,6 +1147,6 @@ var RolesGuard = class {
1743
1147
  }
1744
1148
  };
1745
1149
 
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 };
1150
+ export { DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, DISCOVERY_PATH, HttpStatusError, HttpTransport, LANGUAGE, MAX_VENDOR_TEXT, NestAuthGuard, OidcClient, OidcConfig, PACKAGE_KEY, PUBLIC_KEY, Public, ROLES_KEY, RetryPolicy, Roles, RolesGuard, SDK_KIT_VERSION, SDK_VERSION, VENDOR_ENV, createDispatcher, definedOnly, describeCommonConfig, expressAuth, healthStatus, isHealthyWord, isIdempotentMethod, isRetryableStatus, mergeOptions, parseRetryAfter, probeHealth, readCommonEnv, redactSecretsInText, relativeEndpoint, requireRoles, resetNestExceptionsForTests, resolveCommonConfig, safeCall, safeLogger, secretValues, silentLogger, validateCommonConfig };
1747
1151
  //# sourceMappingURL=index.js.map
1748
1152
  //# sourceMappingURL=index.js.map