@sjawhar/pi-envoy 16.5.0 → 16.6.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/dist/dispatch.js CHANGED
@@ -15630,7 +15630,7 @@ var dispatchToolSpecs = [
15630
15630
  {
15631
15631
  name: "dispatch_whoami",
15632
15632
  example: {},
15633
- description: "Who Dispatch takes this session for: {session, owner, service, project}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token. With a null owner, a create with no assignee falls back to the parent's assignee and then to the project's default assignee. service is the subject of the verified service-account token that authenticated you, or null. project is the one project key your credential may write, or null when it names none.",
15633
+ description: "Who Dispatch takes this session for: {session, owner, service, project}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee and then to the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the fleet a broker token naming no person belongs to, or null. A broker token that names a service may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the one project key your credential may write, or null when it names none.",
15634
15634
  arguments: () => ({}),
15635
15635
  strict: true
15636
15636
  },
@@ -17033,21 +17033,24 @@ function excerpt(text, token) {
17033
17033
  }
17034
17034
 
17035
17035
  class DispatchClient {
17036
- token;
17037
17036
  fetchImpl;
17038
17037
  writeRetry;
17039
17038
  #baseUrl;
17040
17039
  #resolvedIssues = new Map;
17041
17040
  #signal;
17041
+ #credential;
17042
17042
  #madeAt;
17043
- constructor(baseUrl, token, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
17044
- this.token = token;
17043
+ constructor(baseUrl, credential, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
17045
17044
  this.fetchImpl = fetchImpl;
17046
17045
  this.writeRetry = writeRetry;
17046
+ this.#credential = credential;
17047
17047
  this.#baseUrl = baseUrl.replace(/\/+$/, "");
17048
17048
  this.#signal = requestSignal(signal);
17049
17049
  this.#madeAt = this.#now();
17050
17050
  }
17051
+ get token() {
17052
+ return this.#credential.secret();
17053
+ }
17051
17054
  async issue(input) {
17052
17055
  const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
17053
17056
  return { ...answer.payload, created: answer.status === 201 };
@@ -17458,16 +17461,14 @@ class DispatchClient {
17458
17461
  return this.#response(method, url, response);
17459
17462
  }
17460
17463
  async#send(method, url, body, accept = "application/json", signal, callerKey) {
17461
- const headers = {
17462
- Accept: accept,
17463
- Authorization: `Bearer ${this.token}`
17464
- };
17464
+ const headers = { Accept: accept };
17465
+ let presented = await this.#credential.headers(method, url);
17465
17466
  if (body !== undefined)
17466
17467
  headers["Content-Type"] = body.type;
17467
17468
  if (method !== "POST" && method !== "PATCH") {
17468
17469
  return this.fetchImpl(url, {
17469
17470
  method,
17470
- headers,
17471
+ headers: { ...headers, ...presented },
17471
17472
  signal: signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]),
17472
17473
  ...body === undefined ? {} : { body: body.content }
17473
17474
  });
@@ -17488,7 +17489,10 @@ class DispatchClient {
17488
17489
  let answer;
17489
17490
  let thrown;
17490
17491
  try {
17491
- answer = await writeAnswer(await this.#attempt(url, method, headers, body, silenceMs), key);
17492
+ if (attempt > 1)
17493
+ presented = await this.#credential.headers(method, url);
17494
+ const sent = { ...headers, ...presented };
17495
+ answer = await writeAnswer(await this.#attempt(url, method, sent, body, silenceMs), key);
17492
17496
  if (answer.echoed)
17493
17497
  KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
17494
17498
  if (!answer.again)
@@ -17588,9 +17592,10 @@ class DispatchClient {
17588
17592
  }
17589
17593
  async#probeKeyedLayer() {
17590
17594
  try {
17591
- const response = await this.fetchImpl(`${this.#baseUrl}/healthz`, {
17595
+ const probe = `${this.#baseUrl}/healthz`;
17596
+ const response = await this.fetchImpl(probe, {
17592
17597
  method: "GET",
17593
- headers: { Accept: "application/json", Authorization: `Bearer ${this.token}` },
17598
+ headers: { Accept: "application/json", ...await this.#credential.headers("GET", probe) },
17594
17599
  signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
17595
17600
  });
17596
17601
  if (!isJson(response))
@@ -20480,7 +20485,7 @@ async function checkDispatchCall(input) {
20480
20485
  };
20481
20486
  }
20482
20487
  async function executeDispatchTool(input) {
20483
- const { url: configUrl, token: configToken } = input.config;
20488
+ const { url: configUrl, credential } = input.config;
20484
20489
  const linkBase = input.config.publicUrl ?? configUrl;
20485
20490
  const baseFetch = input.fetchImpl ?? fetch;
20486
20491
  const fetchImpl = Object.assign(async (...args) => {
@@ -20503,7 +20508,7 @@ async function executeDispatchTool(input) {
20503
20508
  throw new ToolInputError(input.tool, checked.problems);
20504
20509
  const ownerArguments = checked.owner;
20505
20510
  const pictures = checked.pictures;
20506
- const dispatchClient = () => new DispatchClient(configUrl, configToken, fetchImpl, input.signal, input.writeRetry);
20511
+ const dispatchClient = () => new DispatchClient(configUrl, credential, fetchImpl, input.signal, input.writeRetry);
20507
20512
  if (input.tool === "dispatch_open_asks") {
20508
20513
  const client = dispatchClient();
20509
20514
  const project = optionalString(ownerArguments.args, "project");
@@ -20547,7 +20552,8 @@ async function executeDispatchTool(input) {
20547
20552
  const project = identity.kind === "agent" ? identity.project ?? null : null;
20548
20553
  const session = proved ?? sessionId;
20549
20554
  const unowned = "no owner, so an issue you create without an assignee takes its parent's assignee, else the project's default assignee, else nobody.";
20550
- const acting = owner !== null ? `Session ${session} acts for ${owner}: issues you create without an assignee are assigned to ${owner}.` : service !== null ? `Session ${session} runs as service ${serviceSubjectLabel(service)}: ${unowned}` : `Session ${session} runs under the shared token: ${unowned}`;
20555
+ const signInNeeded = owner === null && service !== null && proved !== null;
20556
+ const acting = owner !== null ? `Session ${session} acts for ${owner}: issues you create without an assignee are assigned to ${owner}.` : service !== null ? signInNeeded ? `Session ${session} runs as service ${serviceSubjectLabel(service)} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.` : `Session ${session} runs as service ${serviceSubjectLabel(service)}: ${unowned}` : `Session ${session} runs under the shared token: ${unowned}`;
20551
20557
  const elsewhere = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId}): Dispatch records every write you make as ${proved}.` : "";
20552
20558
  const writable = project !== null ? ` It may write project ${project} and no other.` : "";
20553
20559
  return {
@@ -22356,6 +22362,13 @@ function readEnvoyConfig(filePath, env, options) {
22356
22362
  }
22357
22363
 
22358
22364
  // ../envoy-client/src/bearer.ts
22365
+ function bearerCredential(token) {
22366
+ return {
22367
+ scheme: "Bearer",
22368
+ headers: () => ({ Authorization: `Bearer ${token}` }),
22369
+ secret: () => token
22370
+ };
22371
+ }
22359
22372
  function bearerSource(env, section, written) {
22360
22373
  const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
22361
22374
  if (pointer !== undefined) {
@@ -22386,258 +22399,2723 @@ function fileBearer(bearer, url, section, env, commands = "run") {
22386
22399
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
22387
22400
  }
22388
22401
 
22389
- // ../envoy-client/src/dispatch-config.ts
22390
- var DEFAULT_SERVER_URL = "http://localhost:8766";
22391
- function checkoutPair(checkout, serverUrl) {
22392
- const { token } = checkout.dispatch;
22393
- if (token === undefined) {
22394
- throw new Error(`${checkout.path}: dispatch.serverUrl requires dispatch.token in the same file`);
22402
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
22403
+ var encoder2 = new TextEncoder;
22404
+ var decoder = new TextDecoder;
22405
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
22406
+ var MAX_INT32 = 2 ** 32;
22407
+ function concat(...buffers) {
22408
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
22409
+ const buf = new Uint8Array(size);
22410
+ let i = 0;
22411
+ for (const buffer of buffers) {
22412
+ buf.set(buffer, i);
22413
+ i += buffer.length;
22414
+ }
22415
+ return buf;
22416
+ }
22417
+ function encode3(string) {
22418
+ const bytes = new Uint8Array(string.length);
22419
+ for (let i = 0;i < string.length; i++) {
22420
+ const code = string.charCodeAt(i);
22421
+ if (code > 127) {
22422
+ throw new TypeError("non-ASCII string encountered in encode()");
22423
+ }
22424
+ bytes[i] = code;
22395
22425
  }
22396
- return {
22397
- kind: "file",
22398
- token,
22399
- field: "dispatch.token",
22400
- path: checkout.path,
22401
- server: serverUrl,
22402
- checkout: true
22403
- };
22426
+ return bytes;
22404
22427
  }
22405
- function writtenToken(config, checkout) {
22406
- if (checkout?.dispatch.token !== undefined) {
22407
- throw new Error(`${checkout.path}: dispatch.token requires dispatch.serverUrl in the same file`);
22428
+
22429
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
22430
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
22431
+ function checkUsage(key, usage) {
22432
+ if (usage && !key.usages.includes(usage)) {
22433
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
22408
22434
  }
22409
- const own = config.dispatch;
22410
- if (own.token === undefined)
22411
- return;
22412
- const server = own.serverUrl ?? DEFAULT_SERVER_URL;
22413
- return {
22414
- token: own.token,
22415
- field: "dispatch.token",
22416
- path: config.path,
22417
- server,
22418
- checkout: false
22419
- };
22420
- }
22421
- function lostDispatchUrlNotice(env, config) {
22422
- if (nonEmpty(env.DISPATCH_TOKEN_FILE) === undefined)
22423
- return;
22424
- const link = config.missing?.link ?? null;
22425
- const old = config.missing?.oldUserFileNotice;
22426
- return [
22427
- "DISPATCH_TOKEN_FILE is set and DISPATCH_URL is not, so Dispatch is off: this shell lost the DISPATCH_URL it started with. Export DISPATCH_URL again, set to the Dispatch server that token is for",
22428
- ...link === null ? [] : [`${config.path} is a link to ${link}, which does not exist`],
22429
- ...old === undefined ? [] : [old]
22430
- ].join("; ");
22431
22435
  }
22432
- function dispatchSettings(env, config, options = {}) {
22433
- const target = dispatchTarget(env, config);
22434
- if (!target.enabled)
22435
- return target;
22436
- const { url, source } = target;
22437
- let token;
22438
- try {
22439
- token = source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands);
22440
- } catch (error) {
22441
- return offWithError(messageFor(error));
22442
- }
22443
- const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
22444
- const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
22445
- if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
22446
- return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
22436
+ function checkModulusLength(alg, key) {
22437
+ const { modulusLength } = key.algorithm;
22438
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
22439
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
22447
22440
  }
22448
- return {
22449
- enabled: true,
22450
- url,
22451
- token,
22452
- ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
22453
- };
22454
22441
  }
22455
- function dispatchTarget(env, config) {
22456
- if (config.kind === "failed")
22457
- return offWithError(config.error);
22458
- const explicitUrl = nonEmpty(env.DISPATCH_URL);
22459
- const checkoutFile = explicitUrl === undefined ? config.checkout : null;
22460
- if (checkoutFile?.kind === "invalid")
22461
- return offWithError(checkoutFile.error);
22462
- const checkout = checkoutFile?.kind === "valid" ? checkoutFile : null;
22463
- const own = config.dispatch;
22464
- if (own.enabled === false) {
22465
- return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
22442
+ function checkCryptoKey(key, expected, usage) {
22443
+ const algorithm = key.algorithm;
22444
+ if (algorithm.name !== expected.name) {
22445
+ throw unusable(expected.name);
22466
22446
  }
22467
- if (checkout?.dispatch.enabled === false) {
22468
- return offWithNotice(`${checkout.path} sets dispatch.enabled to false: Dispatch is off`);
22447
+ if (expected.hash && algorithm.hash?.name !== expected.hash) {
22448
+ throw unusable(expected.hash, "algorithm.hash");
22469
22449
  }
22470
- const checkoutServer = checkout?.dispatch.serverUrl;
22471
- const addressed = explicitUrl !== undefined || checkoutServer !== undefined || own.serverUrl !== undefined || own.enabled === true;
22472
- if (!addressed) {
22473
- const lost = lostDispatchUrlNotice(env, config);
22474
- if (lost !== undefined)
22475
- return offWithNotice(lost);
22476
- return offWithNotice(config.missing === null ? `${config.path} names no Dispatch server, and DISPATCH_URL is not set: Dispatch is off` : missingConfigNotice(config.path, config.missing, "Dispatch is off"));
22450
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
22451
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
22477
22452
  }
22478
- if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
22479
- return offWithError("DISPATCH_URL must be an http or https URL");
22453
+ if (expected.length !== undefined && algorithm.length !== expected.length) {
22454
+ throw unusable(expected.length, "algorithm.length");
22480
22455
  }
22481
- let source;
22482
- try {
22483
- source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
22484
- } catch (error) {
22485
- return offWithError(messageFor(error));
22456
+ checkUsage(key, usage);
22457
+ }
22458
+
22459
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
22460
+ function message(msg, actual, ...types) {
22461
+ if (types.length > 2) {
22462
+ const last = types.pop();
22463
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
22464
+ } else if (types.length === 2) {
22465
+ msg += `one of type ${types[0]} or ${types[1]}.`;
22466
+ } else {
22467
+ msg += `of type ${types[0]}.`;
22486
22468
  }
22487
- if (source.kind === "none") {
22488
- return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
22469
+ if (actual == null) {
22470
+ msg += ` Received ${actual}`;
22471
+ } else if (typeof actual === "function" && actual.name) {
22472
+ msg += ` Received function ${actual.name}`;
22473
+ } else if (typeof actual === "object" && actual != null) {
22474
+ if (actual.constructor?.name) {
22475
+ msg += ` Received an instance of ${actual.constructor.name}`;
22476
+ }
22489
22477
  }
22490
- const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
22491
- return { enabled: true, url, source };
22478
+ return msg;
22492
22479
  }
22480
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
22481
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
22493
22482
 
22494
- // ../envoy-client/src/envoy-settings.ts
22495
- var DEFAULT_ENVOY_URL = "http://127.0.0.1:9020";
22496
- var DEFAULT_HEARTBEAT_MS = 90000;
22497
- var MIN_PASS_DEADLINE_MS = 30000;
22498
- var MIN_INTERVAL_MS = 25;
22499
- var MAX_INTERVAL_MS = 2147483647;
22500
- function namedInterval(raw) {
22501
- const parsed = Number(raw);
22502
- return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
22503
- }
22504
- function natsSeedFromEnvironment(env) {
22505
- const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
22506
- if (file !== undefined) {
22507
- if (file === "")
22508
- throw new Error("NATS_NKEY_SEED_FILE is set but empty");
22509
- return {
22510
- value: readSecretFile("NATS_NKEY_SEED_FILE", file),
22511
- source: `NATS_NKEY_SEED_FILE (${file})`
22512
- };
22483
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
22484
+ class JOSEError extends Error {
22485
+ static code = "ERR_JOSE_GENERIC";
22486
+ code = "ERR_JOSE_GENERIC";
22487
+ constructor(message, options) {
22488
+ super(message, options);
22489
+ this.name = this.constructor.name;
22490
+ Error.captureStackTrace?.(this, this.constructor);
22513
22491
  }
22514
- if (plain === undefined)
22515
- return;
22516
- const value = plain.trim();
22517
- if (value.length === 0)
22518
- throw new Error("NATS_NKEY_SEED is set but empty");
22519
- return { value, source: "NATS_NKEY_SEED" };
22520
22492
  }
22521
- var NO_NATS_SERVER = "Envoy has no NATS server (envoy.natsUrls, ENVOY_NATS_URL)";
22522
- var NO_NATS_CONNECTION = "this session opens no NATS connection";
22523
- function natsServerKey(url) {
22524
- const match = /^([a-z][a-z0-9+.-]*):\/\/([^@/]*@)?(\[[^\]]*\]|[^:/]*)(?::(\d+))?(\/.*)?$/i.exec(url);
22525
- if (match === null)
22526
- return url;
22527
- const [, scheme = "", userinfo = "", host = "", port = "4222", rest = ""] = match;
22528
- return `${scheme.toLowerCase()}://${userinfo}${host.toLowerCase()}:${port}${rest.replace(/\/+$/, "")}`;
22493
+ class JOSENotSupported extends JOSEError {
22494
+ static code = "ERR_JOSE_NOT_SUPPORTED";
22495
+ code = "ERR_JOSE_NOT_SUPPORTED";
22529
22496
  }
22530
- function natsCredential(env, section, namedNatsUrls, filePath) {
22531
- const fromEnvironment = natsSeedFromEnvironment(env);
22532
- if (fromEnvironment !== undefined || section.natsSeed === undefined)
22533
- return fromEnvironment;
22534
- if (namedNatsUrls.length > 0) {
22535
- const servers = new Set((section.natsUrls ?? []).map(natsServerKey));
22536
- const named = new Set(namedNatsUrls.map(natsServerKey));
22537
- if (named.size !== servers.size || ![...named].every((server) => servers.has(server))) {
22538
- throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set NATS_NKEY_SEED_FILE for them`);
22539
- }
22540
- }
22541
- return {
22542
- value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
22543
- source: `envoy.natsSeed in ${filePath}`
22544
- };
22497
+ class JWSInvalid extends JOSEError {
22498
+ static code = "ERR_JWS_INVALID";
22499
+ code = "ERR_JWS_INVALID";
22545
22500
  }
22546
- function envoySettings(env, config, options = {}) {
22547
- if (config.kind === "failed")
22548
- return offWithError(config.error);
22549
- const section = config.envoy;
22550
- if (section.enabled === false) {
22551
- return offWithNotice(`${config.path} sets envoy.enabled to false: Envoy is off`);
22501
+
22502
+ class JWTInvalid extends JOSEError {
22503
+ static code = "ERR_JWT_INVALID";
22504
+ code = "ERR_JWT_INVALID";
22505
+ }
22506
+
22507
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
22508
+ var isCryptoKey = (key) => {
22509
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
22510
+ return true;
22511
+ try {
22512
+ return key instanceof CryptoKey;
22513
+ } catch {
22514
+ return false;
22552
22515
  }
22553
- const namedUrl = nonEmpty(env.ENVOY_URL);
22554
- const namedNatsUrls = (env.ENVOY_NATS_URL ?? "").split(",").map((url) => url.trim()).filter((url) => url.length > 0);
22555
- const addressed = namedUrl !== undefined || namedNatsUrls.length > 0 || section.url !== undefined || (section.natsUrls ?? []).length > 0 || section.enabled === true;
22556
- if (!addressed) {
22557
- return offWithNotice(config.missing === null ? `${config.path} names no Envoy listener or NATS server, and neither ENVOY_URL nor ENVOY_NATS_URL is set: Envoy is off` : missingConfigNotice(config.path, config.missing, "Envoy is off"));
22516
+ };
22517
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
22518
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
22519
+
22520
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
22521
+ function encodeBase64(input) {
22522
+ if (Uint8Array.prototype.toBase64) {
22523
+ return input.toBase64();
22558
22524
  }
22559
- if (namedUrl !== undefined && httpUrl2(namedUrl) === undefined) {
22560
- return offWithError("ENVOY_URL must be an http or https URL");
22525
+ const CHUNK_SIZE = 32768;
22526
+ const arr = [];
22527
+ for (let i = 0;i < input.length; i += CHUNK_SIZE) {
22528
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
22561
22529
  }
22562
- const listener = section.url ?? DEFAULT_ENVOY_URL;
22563
- const url = namedUrl ?? listener;
22564
- let token;
22565
- try {
22566
- const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
22567
- token: section.token,
22568
- field: "envoy.token",
22569
- path: config.path,
22570
- server: listener,
22571
- checkout: false
22572
- });
22573
- token = source.kind === "none" ? undefined : source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env);
22574
- } catch (error) {
22575
- return offWithError(messageFor(error));
22530
+ return btoa(arr.join(""));
22531
+ }
22532
+ function decodeBase64(encoded) {
22533
+ if (Uint8Array.fromBase64) {
22534
+ return Uint8Array.fromBase64(encoded);
22576
22535
  }
22577
- const natsUrls = namedNatsUrls.length > 0 ? namedNatsUrls : section.natsUrls ?? [];
22578
- let inbound;
22579
- if (options.nats === false)
22580
- inbound = { off: NO_NATS_CONNECTION };
22581
- else if (natsUrls.length === 0)
22582
- inbound = { off: NO_NATS_SERVER };
22583
- else {
22536
+ const binary = atob(encoded);
22537
+ const bytes = new Uint8Array(binary.length);
22538
+ for (let i = 0;i < binary.length; i++) {
22539
+ bytes[i] = binary.charCodeAt(i);
22540
+ }
22541
+ return bytes;
22542
+ }
22543
+
22544
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
22545
+ var invalid = "The input to be decoded is not correctly encoded.";
22546
+ function decode3(input) {
22547
+ if (Uint8Array.fromBase64) {
22584
22548
  try {
22585
- inbound = { natsUrls, natsSeed: natsCredential(env, section, namedNatsUrls, config.path) };
22586
- } catch (error) {
22587
- inbound = { off: messageFor(error) };
22549
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
22550
+ alphabet: "base64url"
22551
+ });
22552
+ } catch (cause) {
22553
+ throw new TypeError(invalid, { cause });
22588
22554
  }
22589
22555
  }
22590
- const namedHeartbeatMs = namedInterval(env.ENVOY_HEARTBEAT_MS);
22591
- const heartbeatMs = namedHeartbeatMs === undefined ? DEFAULT_HEARTBEAT_MS : Math.min(Math.max(namedHeartbeatMs, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
22592
- const namedPassDeadlineMs = namedInterval(env.ENVOY_PASS_DEADLINE_MS);
22593
- return {
22594
- enabled: true,
22595
- url: normalizeEnvoyUrl(url),
22596
- token,
22597
- inbound,
22598
- heartbeatMs,
22599
- passDeadlineMs: Math.min(Math.max(namedPassDeadlineMs ?? MIN_PASS_DEADLINE_MS, heartbeatMs), MAX_INTERVAL_MS),
22600
- passDeadlineRaisedFrom: namedPassDeadlineMs !== undefined && namedPassDeadlineMs < heartbeatMs ? namedPassDeadlineMs : undefined
22601
- };
22556
+ let encoded = input;
22557
+ if (encoded instanceof Uint8Array) {
22558
+ encoded = decoder.decode(encoded);
22559
+ }
22560
+ if (encoded.includes("+") || encoded.includes("/")) {
22561
+ throw new TypeError(invalid);
22562
+ }
22563
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
22564
+ try {
22565
+ return decodeBase64(encoded);
22566
+ } catch {
22567
+ throw new TypeError(invalid);
22568
+ }
22602
22569
  }
22603
- function normalizeEnvoyUrl(value) {
22604
- return value.replace(/\/+$/, "");
22570
+ function encode4(input) {
22571
+ let unencoded = input;
22572
+ if (typeof unencoded === "string") {
22573
+ unencoded = encoder2.encode(unencoded);
22574
+ }
22575
+ if (Uint8Array.prototype.toBase64) {
22576
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
22577
+ }
22578
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
22605
22579
  }
22606
22580
 
22607
- // ../envoy-client/src/session-settings.ts
22608
- function sessionConfigFile(harness, env) {
22609
- try {
22610
- return { path: envoyConfigPath(harness, env), error: null };
22611
- } catch (error) {
22612
- return { path: null, error: messageFor(error) };
22581
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
22582
+ function isObject2(input) {
22583
+ if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
22584
+ return false;
22613
22585
  }
22614
- }
22615
- function handedConfigFile(env) {
22616
- try {
22617
- const handed = handedConfigPath(env);
22618
- return handed === undefined ? null : { path: handed, error: null };
22619
- } catch (error) {
22620
- return { path: null, error: messageFor(error) };
22586
+ const prototype = Object.getPrototypeOf(input);
22587
+ if (prototype === null) {
22588
+ return true;
22589
+ }
22590
+ let proto = prototype;
22591
+ while (Object.getPrototypeOf(proto) !== null) {
22592
+ proto = Object.getPrototypeOf(proto);
22621
22593
  }
22594
+ return prototype === proto;
22622
22595
  }
22623
- function sessionDispatchSettings(file, env, options) {
22624
- if (file.path === null)
22625
- return { dispatch: offWithError(file.error), warnings: [], missing: null };
22626
- const config = readEnvoyConfig(file.path, env, options);
22627
- return {
22628
- dispatch: dispatchSettings(env, config, { commands: options.commands }),
22629
- warnings: config.kind === "read" ? config.warnings : [],
22630
- missing: config.kind === "read" ? config.missing : null
22631
- };
22596
+ function isDisjoint(...headers) {
22597
+ const parameters = new Set;
22598
+ for (const header of headers) {
22599
+ if (!header)
22600
+ continue;
22601
+ for (const parameter of Object.keys(header)) {
22602
+ if (parameters.has(parameter)) {
22603
+ return false;
22604
+ }
22605
+ parameters.add(parameter);
22606
+ }
22607
+ }
22608
+ return true;
22632
22609
  }
22633
- function sessionEnvoySettings(file, env, options) {
22634
- if (file.path === null)
22635
- return offWithError(file.error);
22636
- return envoySettings(env, readEnvoyConfig(file.path, env, options), { nats: options.nats });
22610
+ var isJWK = (key) => isObject2(key) && typeof key.kty === "string";
22611
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
22612
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
22613
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
22614
+
22615
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/helpers.js
22616
+ var unprotected = Symbol();
22617
+ function assertNotSet(value, name) {
22618
+ if (value) {
22619
+ throw new TypeError(`${name} can only be called once`);
22620
+ }
22637
22621
  }
22638
22622
 
22639
- // ../envoy-client/src/transport.ts
22640
- var DEFAULT_TIMEOUT_MS = 5000;
22623
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwk_to_key.js
22624
+ async function jwkToKey(entry, jwk) {
22625
+ if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== undefined) {
22626
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
22627
+ }
22628
+ if (!entry.kty.includes(jwk.kty)) {
22629
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
22630
+ }
22631
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle;
22632
+ const isPrivate = !!(jwk.d || jwk.priv);
22633
+ const keyData = { ...jwk };
22634
+ if (keyData.kty !== "AKP") {
22635
+ delete keyData.alg;
22636
+ }
22637
+ delete keyData.use;
22638
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
22639
+ }
22640
+
22641
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key.js
22642
+ var tag = (key) => key[Symbol.toStringTag];
22643
+ var jwkMatchesOp = (entry, key, usage) => {
22644
+ const { alg } = entry;
22645
+ if (key.use !== undefined) {
22646
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
22647
+ if (key.use !== expected) {
22648
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
22649
+ }
22650
+ }
22651
+ if (key.alg !== undefined && key.alg !== alg) {
22652
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
22653
+ }
22654
+ if (Array.isArray(key.key_ops)) {
22655
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
22656
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
22657
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
22658
+ }
22659
+ }
22660
+ };
22661
+ function checkKeyType(entry, key, usage) {
22662
+ const { alg, secret } = entry;
22663
+ const privateKey = usage === "decrypt" || usage === "sign";
22664
+ if (secret && key instanceof Uint8Array)
22665
+ return [BYTES, key];
22666
+ if (isJWK(key)) {
22667
+ if (secret ? !isSecretJWK(key) : !(privateKey ? isPrivateJWK(key) : isPublicJWK(key))) {
22668
+ throw new TypeError(secret ? `JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present` : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`);
22669
+ }
22670
+ jwkMatchesOp(entry, key, usage);
22671
+ return [JWK, key];
22672
+ }
22673
+ if (!isKeyLike(key)) {
22674
+ throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
22675
+ }
22676
+ if (secret) {
22677
+ if (key.type !== "secret") {
22678
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
22679
+ }
22680
+ } else {
22681
+ if (key.type === "secret") {
22682
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
22683
+ }
22684
+ const expectedType = privateKey ? "private" : "public";
22685
+ if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
22686
+ const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
22687
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
22688
+ }
22689
+ }
22690
+ return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
22691
+ }
22692
+ var BYTES = 0;
22693
+ var CRYPTO = 1;
22694
+ var KEYOBJECT = 2;
22695
+ var JWK = 3;
22696
+ var cache;
22697
+ var nist = {
22698
+ __proto__: null,
22699
+ prime256v1: "P-256",
22700
+ secp384r1: "P-384",
22701
+ secp521r1: "P-521"
22702
+ };
22703
+ function cached2(key, alg, value) {
22704
+ cache ||= new WeakMap;
22705
+ const entry = cache.get(key);
22706
+ if (value) {
22707
+ if (entry) {
22708
+ entry[alg] = value;
22709
+ } else {
22710
+ cache.set(key, { __proto__: null, [alg]: value });
22711
+ }
22712
+ }
22713
+ return value ?? entry?.[alg];
22714
+ }
22715
+ var handleJWK = async (key, jwk, entry) => cached2(key, entry.alg) ?? cached2(key, entry.alg, await jwkToKey(entry, { ...jwk, alg: entry.alg }));
22716
+ var handleKeyObject = (keyObject, entry) => {
22717
+ const hit = cached2(keyObject, entry.alg);
22718
+ if (hit)
22719
+ return hit;
22720
+ const isPublic = keyObject.type === "public";
22721
+ const usages = entry.usages[isPublic ? 0 : 1];
22722
+ const { asymmetricKeyType } = keyObject;
22723
+ const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
22724
+ const params = entry.resolve?.({ crv, asymmetricKeyType }) ?? entry.subtle;
22725
+ return cached2(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
22726
+ };
22727
+ async function prepareKey(entry, key, usage) {
22728
+ const tagged = checkKeyType(entry, key, usage);
22729
+ switch (tagged[0]) {
22730
+ case BYTES:
22731
+ case CRYPTO:
22732
+ return tagged[1];
22733
+ case JWK: {
22734
+ const key = tagged[1];
22735
+ if (key.k) {
22736
+ return decode3(key.k);
22737
+ }
22738
+ if (!Object.isFrozen(key)) {
22739
+ const { key_ops } = key;
22740
+ if (Array.isArray(key_ops))
22741
+ Object.freeze(key_ops);
22742
+ Object.freeze(key);
22743
+ }
22744
+ return handleJWK(key, key, entry);
22745
+ }
22746
+ case KEYOBJECT: {
22747
+ const keyObject = tagged[1];
22748
+ if (keyObject.type === "secret") {
22749
+ return keyObject.export();
22750
+ }
22751
+ if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
22752
+ return handleKeyObject(keyObject, entry);
22753
+ }
22754
+ return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
22755
+ }
22756
+ }
22757
+ }
22758
+
22759
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_descriptor.js
22760
+ function table(entries) {
22761
+ const out = { __proto__: null };
22762
+ for (const alg in entries) {
22763
+ out[alg] = { ...entries[alg], alg };
22764
+ }
22765
+ return out;
22766
+ }
22767
+
22768
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwe_algorithms.js
22769
+ var wrap = [
22770
+ ["encrypt", "wrapKey"],
22771
+ ["decrypt", "unwrapKey"]
22772
+ ];
22773
+ var derive = [[], ["deriveBits"]];
22774
+ var none = [[], []];
22775
+ function rsaes(bits) {
22776
+ return {
22777
+ kty: ["RSA"],
22778
+ subtle: { name: "RSA-OAEP", hash: `SHA-${bits}` },
22779
+ usages: wrap,
22780
+ ops: ["wrapKey", "unwrapKey"]
22781
+ };
22782
+ }
22783
+ function ecdh() {
22784
+ return {
22785
+ kty: ["EC", "OKP"],
22786
+ subtle: { name: "ECDH" },
22787
+ resolve: ({ kty, crv, asymmetricKeyType }) => {
22788
+ if (crv === "X25519" || asymmetricKeyType === "x25519") {
22789
+ return { name: "X25519" };
22790
+ }
22791
+ if (kty === "OKP") {
22792
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
22793
+ }
22794
+ return { name: "ECDH", namedCurve: crv };
22795
+ },
22796
+ usages: derive,
22797
+ ops: [undefined, "deriveBits"]
22798
+ };
22799
+ }
22800
+ function aeskw(bits, gcm = false) {
22801
+ return {
22802
+ kty: ["oct"],
22803
+ secret: true,
22804
+ subtle: { name: gcm ? "AES-GCM" : "AES-KW", length: bits },
22805
+ usages: none,
22806
+ ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
22807
+ };
22808
+ }
22809
+ function pbes2() {
22810
+ return {
22811
+ kty: ["oct"],
22812
+ secret: true,
22813
+ subtle: { name: "PBKDF2" },
22814
+ usages: none,
22815
+ ops: ["deriveBits", "deriveBits"]
22816
+ };
22817
+ }
22818
+ var JWE = table({
22819
+ dir: {
22820
+ kty: ["oct"],
22821
+ secret: true,
22822
+ subtle: { name: "AES-GCM" },
22823
+ usages: none,
22824
+ ops: ["encrypt", "decrypt"]
22825
+ },
22826
+ "RSA-OAEP": rsaes(1),
22827
+ "RSA-OAEP-256": rsaes(256),
22828
+ "RSA-OAEP-384": rsaes(384),
22829
+ "RSA-OAEP-512": rsaes(512),
22830
+ "ECDH-ES": ecdh(),
22831
+ "ECDH-ES+A128KW": ecdh(),
22832
+ "ECDH-ES+A192KW": ecdh(),
22833
+ "ECDH-ES+A256KW": ecdh(),
22834
+ A128KW: aeskw(128),
22835
+ A192KW: aeskw(192),
22836
+ A256KW: aeskw(256),
22837
+ A128GCMKW: aeskw(128, true),
22838
+ A192GCMKW: aeskw(192, true),
22839
+ A256GCMKW: aeskw(256, true),
22840
+ "PBES2-HS256+A128KW": pbes2(),
22841
+ "PBES2-HS384+A192KW": pbes2(),
22842
+ "PBES2-HS512+A256KW": pbes2()
22843
+ });
22844
+ var contentOps = ["encrypt", "decrypt"];
22845
+ function contentEncryption(bits, cbc = false) {
22846
+ return {
22847
+ kty: ["oct"],
22848
+ secret: true,
22849
+ subtle: { name: cbc ? "AES-CBC" : "AES-GCM", length: bits },
22850
+ usages: none,
22851
+ ops: contentOps,
22852
+ cekBits: bits,
22853
+ ivBits: cbc ? 128 : 96,
22854
+ cbc
22855
+ };
22856
+ }
22857
+ var ENC = table({
22858
+ A128GCM: contentEncryption(128),
22859
+ A192GCM: contentEncryption(192),
22860
+ A256GCM: contentEncryption(256),
22861
+ "A128CBC-HS256": contentEncryption(256, true),
22862
+ "A192CBC-HS384": contentEncryption(384, true),
22863
+ "A256CBC-HS512": contentEncryption(512, true)
22864
+ });
22865
+
22866
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/options.js
22867
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
22868
+ function validateCritDuplicates(Err, protectedHeader) {
22869
+ const { crit } = protectedHeader ?? {};
22870
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length) {
22871
+ throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
22872
+ }
22873
+ }
22874
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
22875
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
22876
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
22877
+ }
22878
+ if (!protectedHeader || protectedHeader.crit === undefined) {
22879
+ return [];
22880
+ }
22881
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
22882
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
22883
+ }
22884
+ const recognized = recognizedOption === undefined ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
22885
+ for (const parameter of protectedHeader.crit) {
22886
+ if (!(parameter in recognized)) {
22887
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
22888
+ }
22889
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === undefined) {
22890
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
22891
+ }
22892
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === undefined)) {
22893
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
22894
+ }
22895
+ }
22896
+ return protectedHeader.crit;
22897
+ }
22898
+
22899
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/signing.js
22900
+ async function getSigKey(entry, key, usage) {
22901
+ if (key instanceof Uint8Array) {
22902
+ return crypto.subtle.importKey("raw", key, entry.subtle, false, [
22903
+ usage
22904
+ ]);
22905
+ }
22906
+ checkCryptoKey(key, entry.subtle, usage);
22907
+ if (entry.minRsaBits)
22908
+ checkModulusLength(entry.alg, key);
22909
+ return key;
22910
+ }
22911
+ async function sign(entry, key, data) {
22912
+ const cryptoKey = await getSigKey(entry, key, "sign");
22913
+ const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
22914
+ return new Uint8Array(signature);
22915
+ }
22916
+
22917
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_algorithms.js
22918
+ var sig = [["verify"], ["sign"]];
22919
+ function hmac(bits) {
22920
+ const subtle = { name: "HMAC", hash: `SHA-${bits}` };
22921
+ return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
22922
+ }
22923
+ function rsa(bits, saltLength) {
22924
+ const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
22925
+ const subtle = { name, hash: `SHA-${bits}` };
22926
+ return {
22927
+ kty: ["RSA"],
22928
+ subtle,
22929
+ signing: saltLength ? { ...subtle, saltLength } : subtle,
22930
+ usages: sig,
22931
+ minRsaBits: 2048
22932
+ };
22933
+ }
22934
+ function ecdsa(crv, bits) {
22935
+ return {
22936
+ kty: ["EC"],
22937
+ crv,
22938
+ subtle: { name: "ECDSA", namedCurve: crv },
22939
+ signing: { name: "ECDSA", hash: `SHA-${bits}` },
22940
+ usages: sig
22941
+ };
22942
+ }
22943
+ function eddsa() {
22944
+ const subtle = { name: "Ed25519" };
22945
+ return {
22946
+ kty: ["OKP"],
22947
+ crv: "Ed25519",
22948
+ subtle,
22949
+ signing: subtle,
22950
+ usages: sig
22951
+ };
22952
+ }
22953
+ function mldsa(bits) {
22954
+ const name = `ML-DSA-${bits}`;
22955
+ const subtle = { name };
22956
+ return {
22957
+ kty: ["AKP"],
22958
+ subtle,
22959
+ signing: subtle,
22960
+ usages: sig
22961
+ };
22962
+ }
22963
+ var JWS = table({
22964
+ HS256: hmac(256),
22965
+ HS384: hmac(384),
22966
+ HS512: hmac(512),
22967
+ RS256: rsa(256),
22968
+ RS384: rsa(384),
22969
+ RS512: rsa(512),
22970
+ PS256: rsa(256, 32),
22971
+ PS384: rsa(384, 48),
22972
+ PS512: rsa(512, 64),
22973
+ ES256: ecdsa("P-256", 256),
22974
+ ES384: ecdsa("P-384", 384),
22975
+ ES512: ecdsa("P-521", 512),
22976
+ EdDSA: eddsa(),
22977
+ Ed25519: eddsa(),
22978
+ "ML-DSA-44": mldsa(44),
22979
+ "ML-DSA-65": mldsa(65),
22980
+ "ML-DSA-87": mldsa(87)
22981
+ });
22982
+ function jwsAlgorithm(alg) {
22983
+ const entry = typeof alg === "string" ? JWS[alg] : undefined;
22984
+ if (!entry) {
22985
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
22986
+ }
22987
+ return entry;
22988
+ }
22989
+
22990
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
22991
+ var epoch = (date) => Math.floor(date.getTime() / 1000);
22992
+ var multipliers = {
22993
+ s: 1,
22994
+ m: 60,
22995
+ h: 3600,
22996
+ d: 86400,
22997
+ w: 604800,
22998
+ y: 31557600
22999
+ };
23000
+ var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
23001
+ function secs(str) {
23002
+ const matched = REGEX.exec(str);
23003
+ if (!matched || matched[4] && matched[1]) {
23004
+ throw new TypeError("Invalid time period format");
23005
+ }
23006
+ const value = parseFloat(matched[2]);
23007
+ const numericDate = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
23008
+ if (matched[1] === "-" || matched[4] === "ago") {
23009
+ return -numericDate;
23010
+ }
23011
+ return numericDate;
23012
+ }
23013
+ function validateInput(label, input) {
23014
+ if (!Number.isFinite(input)) {
23015
+ throw new TypeError(`Invalid ${label} input`);
23016
+ }
23017
+ return input;
23018
+ }
23019
+ function numericDate(value, label) {
23020
+ if (typeof value === "number")
23021
+ return validateInput(label, value);
23022
+ if (value instanceof Date)
23023
+ return validateInput(label, epoch(value));
23024
+ return epoch(new Date) + secs(value);
23025
+ }
23026
+ class JWTClaimsBuilder {
23027
+ #payload;
23028
+ constructor(payload) {
23029
+ if (!isObject2(payload)) {
23030
+ throw new TypeError("JWT Claims Set MUST be an object");
23031
+ }
23032
+ this.#payload = structuredClone(payload);
23033
+ }
23034
+ data() {
23035
+ return encoder2.encode(JSON.stringify(this.#payload));
23036
+ }
23037
+ get iss() {
23038
+ return this.#payload.iss;
23039
+ }
23040
+ set iss(value) {
23041
+ this.#payload.iss = value;
23042
+ }
23043
+ get sub() {
23044
+ return this.#payload.sub;
23045
+ }
23046
+ set sub(value) {
23047
+ this.#payload.sub = value;
23048
+ }
23049
+ get aud() {
23050
+ return this.#payload.aud;
23051
+ }
23052
+ set aud(value) {
23053
+ this.#payload.aud = value;
23054
+ }
23055
+ set jti(value) {
23056
+ this.#payload.jti = value;
23057
+ }
23058
+ set nbf(value) {
23059
+ this.#payload.nbf = numericDate(value, "setNotBefore");
23060
+ }
23061
+ set exp(value) {
23062
+ this.#payload.exp = numericDate(value, "setExpirationTime");
23063
+ }
23064
+ set iat(value) {
23065
+ if (value === undefined) {
23066
+ this.#payload.iat = epoch(new Date);
23067
+ } else if (typeof value === "string") {
23068
+ this.#payload.iat = validateInput("setIssuedAt", epoch(new Date) + secs(value));
23069
+ } else {
23070
+ this.#payload.iat = numericDate(value, "setIssuedAt");
23071
+ }
23072
+ }
23073
+ }
23074
+
23075
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_sign.js
23076
+ function unencodedPayload(protectedHeader) {
23077
+ return protectedHeader?.b64 === false && Array.isArray(protectedHeader.crit) && protectedHeader.crit.includes("b64");
23078
+ }
23079
+ async function createSignature(input, key) {
23080
+ const { protectedHeader, unprotectedHeader } = input;
23081
+ if (!protectedHeader && !unprotectedHeader) {
23082
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
23083
+ }
23084
+ if (!isDisjoint(protectedHeader, unprotectedHeader)) {
23085
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
23086
+ }
23087
+ const joseHeader = { ...protectedHeader, ...unprotectedHeader };
23088
+ validateCritDuplicates(JWSInvalid, protectedHeader);
23089
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, input.crit, protectedHeader, joseHeader);
23090
+ let b64 = true;
23091
+ if (extensions.includes("b64")) {
23092
+ b64 = protectedHeader.b64;
23093
+ if (typeof b64 !== "boolean") {
23094
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
23095
+ }
23096
+ }
23097
+ const { alg } = joseHeader;
23098
+ if (typeof alg !== "string" || !alg) {
23099
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
23100
+ }
23101
+ const entry = jwsAlgorithm(alg);
23102
+ let payloadS;
23103
+ let payloadB;
23104
+ if (b64) {
23105
+ const encoded = input.encoded ??= [];
23106
+ encoded[0] ??= encode4(input.payload);
23107
+ encoded[1] ??= encode3(encoded[0]);
23108
+ payloadS = encoded[0];
23109
+ payloadB = encoded[1];
23110
+ } else {
23111
+ payloadB = input.payload;
23112
+ payloadS = "";
23113
+ }
23114
+ let protectedHeaderString;
23115
+ let protectedHeaderBytes;
23116
+ if (protectedHeader) {
23117
+ protectedHeaderString = encode4(JSON.stringify(protectedHeader));
23118
+ protectedHeaderBytes = encode3(protectedHeaderString);
23119
+ } else {
23120
+ protectedHeaderString = "";
23121
+ protectedHeaderBytes = new Uint8Array;
23122
+ }
23123
+ const data = concat(protectedHeaderBytes, encode3("."), payloadB);
23124
+ const k = await prepareKey(entry, key, "sign");
23125
+ const signature = await sign(entry, k, data);
23126
+ const jws = {
23127
+ signature: encode4(signature),
23128
+ payload: payloadS
23129
+ };
23130
+ if (protectedHeader) {
23131
+ jws.protected = protectedHeaderString;
23132
+ }
23133
+ if (unprotectedHeader) {
23134
+ jws.header = unprotectedHeader;
23135
+ }
23136
+ return jws;
23137
+ }
23138
+
23139
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/flattened/sign.js
23140
+ class FlattenedSign {
23141
+ #payload;
23142
+ #protectedHeader;
23143
+ #unprotectedHeader;
23144
+ constructor(payload) {
23145
+ if (!(payload instanceof Uint8Array)) {
23146
+ throw new TypeError("payload must be an instance of Uint8Array");
23147
+ }
23148
+ this.#payload = payload;
23149
+ }
23150
+ setProtectedHeader(protectedHeader) {
23151
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
23152
+ this.#protectedHeader = protectedHeader;
23153
+ return this;
23154
+ }
23155
+ setUnprotectedHeader(unprotectedHeader) {
23156
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
23157
+ this.#unprotectedHeader = unprotectedHeader;
23158
+ return this;
23159
+ }
23160
+ async sign(key, options) {
23161
+ return createSignature({
23162
+ payload: this.#payload,
23163
+ protectedHeader: this.#protectedHeader,
23164
+ unprotectedHeader: this.#unprotectedHeader,
23165
+ crit: options?.crit
23166
+ }, key);
23167
+ }
23168
+ }
23169
+
23170
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/compact/sign.js
23171
+ class CompactSign {
23172
+ #flattened;
23173
+ #protectedHeader;
23174
+ constructor(payload) {
23175
+ this.#flattened = new FlattenedSign(payload);
23176
+ }
23177
+ setProtectedHeader(protectedHeader) {
23178
+ this.#flattened.setProtectedHeader(protectedHeader);
23179
+ this.#protectedHeader = protectedHeader;
23180
+ return this;
23181
+ }
23182
+ async sign(key, options) {
23183
+ if (unencodedPayload(this.#protectedHeader)) {
23184
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
23185
+ }
23186
+ const jws = await this.#flattened.sign(key, options);
23187
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
23188
+ }
23189
+ }
23190
+
23191
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jwt/sign.js
23192
+ class SignJWT {
23193
+ #protectedHeader;
23194
+ #jwt;
23195
+ constructor(payload = {}) {
23196
+ this.#jwt = new JWTClaimsBuilder(payload);
23197
+ }
23198
+ setIssuer(issuer) {
23199
+ this.#jwt.iss = issuer;
23200
+ return this;
23201
+ }
23202
+ setSubject(subject) {
23203
+ this.#jwt.sub = subject;
23204
+ return this;
23205
+ }
23206
+ setAudience(audience) {
23207
+ this.#jwt.aud = audience;
23208
+ return this;
23209
+ }
23210
+ setJti(jwtId) {
23211
+ this.#jwt.jti = jwtId;
23212
+ return this;
23213
+ }
23214
+ setNotBefore(input) {
23215
+ this.#jwt.nbf = input;
23216
+ return this;
23217
+ }
23218
+ setExpirationTime(input) {
23219
+ this.#jwt.exp = input;
23220
+ return this;
23221
+ }
23222
+ setIssuedAt(input) {
23223
+ this.#jwt.iat = input;
23224
+ return this;
23225
+ }
23226
+ setProtectedHeader(protectedHeader) {
23227
+ this.#protectedHeader = protectedHeader;
23228
+ return this;
23229
+ }
23230
+ async sign(key, options) {
23231
+ const sig = new CompactSign(this.#jwt.data());
23232
+ sig.setProtectedHeader(this.#protectedHeader);
23233
+ if (unencodedPayload(this.#protectedHeader)) {
23234
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
23235
+ }
23236
+ return sig.sign(key, options);
23237
+ }
23238
+ }
23239
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_algorithm.js
23240
+ var algArgument = '"alg" (Algorithm)';
23241
+ function unsupportedAlg(source = 'JWK "alg" (Algorithm) Parameter') {
23242
+ throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
23243
+ }
23244
+ function keyAlgorithm(alg, source) {
23245
+ return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : undefined) ?? unsupportedAlg(source);
23246
+ }
23247
+
23248
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
23249
+ function omitUndefinedProperties(jwk) {
23250
+ return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
23251
+ }
23252
+ async function keyToJWK(key) {
23253
+ if (isKeyObject(key)) {
23254
+ if (key.type === "secret") {
23255
+ key = key.export();
23256
+ } else {
23257
+ return key.export({ format: "jwk" });
23258
+ }
23259
+ }
23260
+ if (key instanceof Uint8Array) {
23261
+ return {
23262
+ kty: "oct",
23263
+ k: encode4(key)
23264
+ };
23265
+ }
23266
+ if (!isCryptoKey(key)) {
23267
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
23268
+ }
23269
+ if (!key.extractable) {
23270
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
23271
+ }
23272
+ const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
23273
+ if (jwk.kty === "AKP") {
23274
+ jwk.alg = alg;
23275
+ }
23276
+ return jwk;
23277
+ }
23278
+ function exportJWK(key) {
23279
+ return keyToJWK(key);
23280
+ }
23281
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/generate_key_pair.js
23282
+ function getModulusLengthOption(options) {
23283
+ const modulusLength = options?.modulusLength ?? 2048;
23284
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
23285
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
23286
+ }
23287
+ return modulusLength;
23288
+ }
23289
+ async function generateKeyPair(alg, options) {
23290
+ const entry = keyAlgorithm(alg, algArgument);
23291
+ if (entry.secret) {
23292
+ unsupportedAlg(algArgument);
23293
+ }
23294
+ let algorithm;
23295
+ if (entry.resolve) {
23296
+ const crv = options?.crv ?? "P-256";
23297
+ switch (crv) {
23298
+ case "P-256":
23299
+ case "P-384":
23300
+ case "P-521":
23301
+ algorithm = { name: "ECDH", namedCurve: crv };
23302
+ break;
23303
+ case "X25519":
23304
+ algorithm = { name: "X25519" };
23305
+ break;
23306
+ default:
23307
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
23308
+ }
23309
+ } else {
23310
+ if (entry.crv !== undefined && options?.crv !== undefined && options.crv !== entry.crv) {
23311
+ throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);
23312
+ }
23313
+ algorithm = entry.kty[0] === "RSA" ? {
23314
+ ...entry.subtle,
23315
+ publicExponent: Uint8Array.of(1, 0, 1),
23316
+ modulusLength: getModulusLengthOption(options)
23317
+ } : entry.subtle;
23318
+ }
23319
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [
23320
+ ...entry.usages[1],
23321
+ ...entry.usages[0]
23322
+ ]);
23323
+ }
23324
+ // ../broker-client/src/dpop.ts
23325
+ var ALGORITHM = "ES256";
23326
+ function targetUri(url) {
23327
+ const parsed = new URL(url);
23328
+ parsed.search = "";
23329
+ parsed.hash = "";
23330
+ return parsed.toString();
23331
+ }
23332
+ async function accessTokenHash(accessToken) {
23333
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
23334
+ return Buffer.from(digest).toString("base64url");
23335
+ }
23336
+ async function newDpopKey() {
23337
+ const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
23338
+ const publicJwk = await exportJWK(publicKey);
23339
+ return {
23340
+ publicJwk,
23341
+ async proof(request) {
23342
+ const claims = {
23343
+ jti: crypto.randomUUID(),
23344
+ htm: request.method.toUpperCase(),
23345
+ htu: targetUri(request.url),
23346
+ iat: Math.floor(Date.now() / 1000)
23347
+ };
23348
+ if (request.nonce !== undefined && request.nonce !== "")
23349
+ claims["nonce"] = request.nonce;
23350
+ if (request.accessToken !== undefined && request.accessToken !== "") {
23351
+ claims["ath"] = await accessTokenHash(request.accessToken);
23352
+ }
23353
+ return await new SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk }).sign(privateKey);
23354
+ }
23355
+ };
23356
+ }
23357
+
23358
+ // ../broker-client/src/metadata-identity.ts
23359
+ import { Agent, request } from "http";
23360
+
23361
+ // ../broker-client/src/wire.ts
23362
+ var TOKEN_PATH = "/v1/oauth/token";
23363
+ var GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
23364
+ var EXCHANGE_CLIENT_ID = "dispatch-token-exchange";
23365
+ var FORM_SESSION = "session";
23366
+ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
23367
+ var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
23368
+ var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
23369
+ var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
23370
+ var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
23371
+ var TOKEN_TYPE_DPOP = "DPoP";
23372
+
23373
+ // ../broker-client/src/metadata-identity.ts
23374
+ var METADATA_HOST_VAR = "GCE_METADATA_HOST";
23375
+ var DEFAULT_METADATA_HOST = "metadata.google.internal";
23376
+ var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
23377
+ var TIMEOUT_MS = 1e4;
23378
+ var MAX_ANSWER_BYTES = 1 << 20;
23379
+ var agent = new Agent({ keepAlive: false });
23380
+ function tokenUrl(audience, env) {
23381
+ const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
23382
+ return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
23383
+ }
23384
+ function get(url, signal) {
23385
+ const { promise, resolve, reject } = Promise.withResolvers();
23386
+ const call = request(url, {
23387
+ agent,
23388
+ method: "GET",
23389
+ headers: { "Metadata-Flavor": "Google" },
23390
+ timeout: TIMEOUT_MS,
23391
+ ...signal === undefined ? {} : { signal }
23392
+ }, (answer) => {
23393
+ const chunks = [];
23394
+ let read = 0;
23395
+ answer.on("data", (chunk) => {
23396
+ read += chunk.length;
23397
+ if (read <= MAX_ANSWER_BYTES)
23398
+ chunks.push(chunk);
23399
+ });
23400
+ answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
23401
+ answer.on("error", reject);
23402
+ });
23403
+ call.on("timeout", () => call.destroy(new Error(`no answer within ${TIMEOUT_MS} ms`)));
23404
+ call.on("error", reject);
23405
+ call.end();
23406
+ return promise;
23407
+ }
23408
+ function metadataIdentity(audience, env = process.env) {
23409
+ return {
23410
+ async read(signal) {
23411
+ const url = tokenUrl(audience, env);
23412
+ let answer;
23413
+ try {
23414
+ answer = await get(url, signal);
23415
+ } catch (error) {
23416
+ throw new Error(`the metadata server at ${url} could not be reached (${METADATA_HOST_VAR} names its host): ${error.message}`);
23417
+ }
23418
+ if (answer.status < 200 || answer.status > 299) {
23419
+ throw new Error(`the metadata server at ${url} answered HTTP ${answer.status}`);
23420
+ }
23421
+ const token = answer.body.trim();
23422
+ if (token === "") {
23423
+ throw new Error(`the metadata server at ${url} answered an empty identity token`);
23424
+ }
23425
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
23426
+ },
23427
+ describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
23428
+ };
23429
+ }
23430
+
23431
+ // ../broker-client/src/projected-token.ts
23432
+ import { readFile } from "fs/promises";
23433
+ function projectedToken(path) {
23434
+ return {
23435
+ async read(signal) {
23436
+ let contents;
23437
+ try {
23438
+ contents = await readFile(path, {
23439
+ encoding: "utf8",
23440
+ ...signal === undefined ? {} : { signal }
23441
+ });
23442
+ } catch (error) {
23443
+ throw new Error(`read the projected service-account token ${path}: ${error.message}`);
23444
+ }
23445
+ const token = contents.trim();
23446
+ if (token === "")
23447
+ throw new Error(`the projected service-account token ${path} is empty`);
23448
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
23449
+ },
23450
+ describe: () => `the projected service-account token ${path}`
23451
+ };
23452
+ }
23453
+
23454
+ // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
23455
+ var USER_AGENT;
23456
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
23457
+ const NAME = "oauth4webapi";
23458
+ const VERSION = "v3.8.8";
23459
+ USER_AGENT = `${NAME}/${VERSION}`;
23460
+ }
23461
+ function looseInstanceOf(input, expected) {
23462
+ if (input == null) {
23463
+ return false;
23464
+ }
23465
+ try {
23466
+ return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
23467
+ } catch {
23468
+ return false;
23469
+ }
23470
+ }
23471
+ var ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
23472
+ var ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
23473
+ function CodedTypeError(message, code, cause) {
23474
+ const err = new TypeError(message, { cause });
23475
+ Object.assign(err, { code });
23476
+ return err;
23477
+ }
23478
+ var allowInsecureRequests = Symbol();
23479
+ var clockSkew = Symbol();
23480
+ var clockTolerance = Symbol();
23481
+ var customFetch = Symbol();
23482
+ var modifyAssertion = Symbol();
23483
+ var jweDecrypt = Symbol();
23484
+ var jwksCache = Symbol();
23485
+ var encoder3 = new TextEncoder;
23486
+ var decoder2 = new TextDecoder;
23487
+ function buf(input) {
23488
+ if (typeof input === "string") {
23489
+ return encoder3.encode(input);
23490
+ }
23491
+ return decoder2.decode(input);
23492
+ }
23493
+ var encodeBase64Url;
23494
+ if (Uint8Array.prototype.toBase64) {
23495
+ encodeBase64Url = (input) => {
23496
+ if (input instanceof ArrayBuffer) {
23497
+ input = new Uint8Array(input);
23498
+ }
23499
+ return input.toBase64({ alphabet: "base64url", omitPadding: true });
23500
+ };
23501
+ } else {
23502
+ const CHUNK_SIZE = 32768;
23503
+ encodeBase64Url = (input) => {
23504
+ if (input instanceof ArrayBuffer) {
23505
+ input = new Uint8Array(input);
23506
+ }
23507
+ const arr = [];
23508
+ for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
23509
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
23510
+ }
23511
+ return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
23512
+ };
23513
+ }
23514
+ var decodeBase64Url;
23515
+ if (Uint8Array.fromBase64) {
23516
+ decodeBase64Url = (input) => {
23517
+ try {
23518
+ return Uint8Array.fromBase64(input, { alphabet: "base64url" });
23519
+ } catch (cause) {
23520
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
23521
+ }
23522
+ };
23523
+ } else {
23524
+ decodeBase64Url = (input) => {
23525
+ try {
23526
+ const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
23527
+ const bytes = new Uint8Array(binary.length);
23528
+ for (let i = 0;i < binary.length; i++) {
23529
+ bytes[i] = binary.charCodeAt(i);
23530
+ }
23531
+ return bytes;
23532
+ } catch (cause) {
23533
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
23534
+ }
23535
+ };
23536
+ }
23537
+ function b64u(input) {
23538
+ if (typeof input === "string") {
23539
+ return decodeBase64Url(input);
23540
+ }
23541
+ return encodeBase64Url(input);
23542
+ }
23543
+
23544
+ class UnsupportedOperationError extends Error {
23545
+ code;
23546
+ constructor(message, options) {
23547
+ super(message, options);
23548
+ this.name = this.constructor.name;
23549
+ this.code = UNSUPPORTED_OPERATION;
23550
+ Error.captureStackTrace?.(this, this.constructor);
23551
+ }
23552
+ }
23553
+
23554
+ class OperationProcessingError extends Error {
23555
+ code;
23556
+ constructor(message, options) {
23557
+ super(message, options);
23558
+ this.name = this.constructor.name;
23559
+ if (options?.code) {
23560
+ this.code = options?.code;
23561
+ }
23562
+ Error.captureStackTrace?.(this, this.constructor);
23563
+ }
23564
+ }
23565
+ function OPE(message, code, cause) {
23566
+ return new OperationProcessingError(message, { code, cause });
23567
+ }
23568
+ function isJsonObject(input) {
23569
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
23570
+ return false;
23571
+ }
23572
+ return true;
23573
+ }
23574
+ function prepareHeaders(input) {
23575
+ if (looseInstanceOf(input, Headers)) {
23576
+ input = Object.fromEntries(input.entries());
23577
+ }
23578
+ const headers = new Headers(input ?? {});
23579
+ if (USER_AGENT && !headers.has("user-agent")) {
23580
+ headers.set("user-agent", USER_AGENT);
23581
+ }
23582
+ if (headers.has("authorization")) {
23583
+ throw CodedTypeError('"options.headers" must not include the "authorization" header name', ERR_INVALID_ARG_VALUE);
23584
+ }
23585
+ return headers;
23586
+ }
23587
+ function signal(url, value) {
23588
+ if (value !== undefined) {
23589
+ if (typeof value === "function") {
23590
+ value = value(url.href);
23591
+ }
23592
+ if (!(value instanceof AbortSignal)) {
23593
+ throw CodedTypeError('"options.signal" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);
23594
+ }
23595
+ return value;
23596
+ }
23597
+ return;
23598
+ }
23599
+ function assertNumber(input, allow0, it, code, cause) {
23600
+ try {
23601
+ if (typeof input !== "number" || !Number.isFinite(input)) {
23602
+ throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);
23603
+ }
23604
+ if (input > 0)
23605
+ return;
23606
+ if (allow0) {
23607
+ if (input !== 0) {
23608
+ throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);
23609
+ }
23610
+ return;
23611
+ }
23612
+ throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);
23613
+ } catch (err) {
23614
+ if (code) {
23615
+ throw OPE(err.message, code, cause);
23616
+ }
23617
+ throw err;
23618
+ }
23619
+ }
23620
+ function assertString(input, it, code, cause) {
23621
+ try {
23622
+ if (typeof input !== "string") {
23623
+ throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);
23624
+ }
23625
+ if (input.length === 0) {
23626
+ throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);
23627
+ }
23628
+ } catch (err) {
23629
+ if (code) {
23630
+ throw OPE(err.message, code, cause);
23631
+ }
23632
+ throw err;
23633
+ }
23634
+ }
23635
+ function assertApplicationJson(response) {
23636
+ assertContentType(response, "application/json");
23637
+ }
23638
+ function notJson(response, ...types) {
23639
+ let msg = '"response" content-type must be ';
23640
+ if (types.length > 2) {
23641
+ const last = types.pop();
23642
+ msg += `${types.join(", ")}, or ${last}`;
23643
+ } else if (types.length === 2) {
23644
+ msg += `${types[0]} or ${types[1]}`;
23645
+ } else {
23646
+ msg += types[0];
23647
+ }
23648
+ return OPE(msg, RESPONSE_IS_NOT_JSON, response);
23649
+ }
23650
+ function assertContentType(response, contentType) {
23651
+ if (getContentType(response) !== contentType) {
23652
+ throw notJson(response, contentType);
23653
+ }
23654
+ }
23655
+ function getClockSkew(client) {
23656
+ const skew = client?.[clockSkew];
23657
+ return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
23658
+ }
23659
+ function getClockTolerance(client) {
23660
+ const tolerance = client?.[clockTolerance];
23661
+ return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
23662
+ }
23663
+ function epochTime() {
23664
+ return Math.floor(Date.now() / 1000);
23665
+ }
23666
+ function assertAs(as) {
23667
+ if (typeof as !== "object" || as === null) {
23668
+ throw CodedTypeError('"as" must be an object', ERR_INVALID_ARG_TYPE);
23669
+ }
23670
+ assertString(as.issuer, '"as.issuer"');
23671
+ }
23672
+ function assertClient(client) {
23673
+ if (typeof client !== "object" || client === null) {
23674
+ throw CodedTypeError('"client" must be an object', ERR_INVALID_ARG_TYPE);
23675
+ }
23676
+ assertString(client.client_id, '"client.client_id"');
23677
+ }
23678
+ function ClientSecretPost(clientSecret) {
23679
+ assertString(clientSecret, '"clientSecret"');
23680
+ return (_as, client, body, _headers) => {
23681
+ body.set("client_id", client.client_id);
23682
+ body.set("client_secret", clientSecret);
23683
+ };
23684
+ }
23685
+ function None() {
23686
+ return (_as, client, body, _headers) => {
23687
+ body.set("client_id", client.client_id);
23688
+ };
23689
+ }
23690
+ var URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
23691
+ try {
23692
+ return new URL(url, base);
23693
+ } catch {
23694
+ return null;
23695
+ }
23696
+ };
23697
+ function checkProtocol(url, enforceHttps) {
23698
+ if (enforceHttps && url.protocol !== "https:") {
23699
+ throw OPE("only requests to HTTPS are allowed", HTTP_REQUEST_FORBIDDEN, url);
23700
+ }
23701
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
23702
+ throw OPE("only HTTP and HTTPS requests are allowed", REQUEST_PROTOCOL_FORBIDDEN, url);
23703
+ }
23704
+ }
23705
+ function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
23706
+ let url;
23707
+ if (typeof value !== "string" || !(url = URLParse(value))) {
23708
+ throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `"as.mtls_endpoint_aliases.${endpoint}"` : `"as.${endpoint}"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });
23709
+ }
23710
+ checkProtocol(url, enforceHttps);
23711
+ return url;
23712
+ }
23713
+ function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
23714
+ if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {
23715
+ return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
23716
+ }
23717
+ return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
23718
+ }
23719
+ function isDPoPNonceError(err) {
23720
+ if (err instanceof WWWAuthenticateChallengeError) {
23721
+ return err.cause.some((challenge) => challenge.scheme === "dpop" && challenge.parameters.error === "use_dpop_nonce");
23722
+ }
23723
+ if (err instanceof ResponseBodyError) {
23724
+ return err.error === "use_dpop_nonce";
23725
+ }
23726
+ return false;
23727
+ }
23728
+ class ResponseBodyError extends Error {
23729
+ cause;
23730
+ code;
23731
+ error;
23732
+ status;
23733
+ error_description;
23734
+ response;
23735
+ constructor(message, options) {
23736
+ super(message, options);
23737
+ this.name = this.constructor.name;
23738
+ this.code = RESPONSE_BODY_ERROR;
23739
+ this.cause = options.cause;
23740
+ this.error = options.cause.error;
23741
+ this.status = options.response.status;
23742
+ this.error_description = options.cause.error_description;
23743
+ Object.defineProperty(this, "response", { enumerable: false, value: options.response });
23744
+ Error.captureStackTrace?.(this, this.constructor);
23745
+ }
23746
+ }
23747
+
23748
+ class AuthorizationResponseError extends Error {
23749
+ cause;
23750
+ code;
23751
+ error;
23752
+ error_description;
23753
+ constructor(message, options) {
23754
+ super(message, options);
23755
+ this.name = this.constructor.name;
23756
+ this.code = AUTHORIZATION_RESPONSE_ERROR;
23757
+ this.cause = options.cause;
23758
+ this.error = options.cause.get("error");
23759
+ this.error_description = options.cause.get("error_description") ?? undefined;
23760
+ Error.captureStackTrace?.(this, this.constructor);
23761
+ }
23762
+ }
23763
+
23764
+ class WWWAuthenticateChallengeError extends Error {
23765
+ cause;
23766
+ code;
23767
+ response;
23768
+ status;
23769
+ constructor(message, options) {
23770
+ super(message, options);
23771
+ this.name = this.constructor.name;
23772
+ this.code = WWW_AUTHENTICATE_CHALLENGE;
23773
+ this.cause = options.cause;
23774
+ this.status = options.response.status;
23775
+ this.response = options.response;
23776
+ Object.defineProperty(this, "response", { enumerable: false });
23777
+ Error.captureStackTrace?.(this, this.constructor);
23778
+ }
23779
+ }
23780
+ var tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
23781
+ var token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}";
23782
+ var quotedMatch = '"((?:[^"\\\\]|\\\\[\\s\\S])*)"';
23783
+ var quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*" + quotedMatch;
23784
+ var paramMatcher = "(" + tokenMatch + ")\\s*=\\s*(" + tokenMatch + ")";
23785
+ var schemeRE = new RegExp("^[,\\s]*(" + tokenMatch + ")");
23786
+ var quotedParamRE = new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");
23787
+ var unquotedParamRE = new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");
23788
+ var token68ParamRE = new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");
23789
+ function parseWwwAuthenticateChallenges(response) {
23790
+ if (!looseInstanceOf(response, Response)) {
23791
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
23792
+ }
23793
+ const header = response.headers.get("www-authenticate");
23794
+ if (header === null) {
23795
+ return;
23796
+ }
23797
+ const challenges = [];
23798
+ let rest = header;
23799
+ while (rest) {
23800
+ let match = rest.match(schemeRE);
23801
+ const scheme = match?.["1"].toLowerCase();
23802
+ if (!scheme) {
23803
+ return;
23804
+ }
23805
+ const afterScheme = rest.substring(match[0].length);
23806
+ if (afterScheme && !afterScheme.match(/^[\s,]/)) {
23807
+ return;
23808
+ }
23809
+ const spaceMatch = afterScheme.match(/^\s+(.*)$/);
23810
+ const hasParameters = !!spaceMatch;
23811
+ rest = spaceMatch ? spaceMatch[1] : undefined;
23812
+ const parameters = {};
23813
+ let token68;
23814
+ if (hasParameters) {
23815
+ while (rest) {
23816
+ let key;
23817
+ let value;
23818
+ if (match = rest.match(quotedParamRE)) {
23819
+ [, key, value, rest] = match;
23820
+ if (value.includes("\\")) {
23821
+ value = value.replace(/\\([\s\S])/g, "$1");
23822
+ }
23823
+ parameters[key.toLowerCase()] = value;
23824
+ continue;
23825
+ }
23826
+ if (match = rest.match(unquotedParamRE)) {
23827
+ [, key, value, rest] = match;
23828
+ parameters[key.toLowerCase()] = value;
23829
+ continue;
23830
+ }
23831
+ if (match = rest.match(token68ParamRE)) {
23832
+ if (Object.keys(parameters).length) {
23833
+ break;
23834
+ }
23835
+ [, token68, rest] = match;
23836
+ break;
23837
+ }
23838
+ return;
23839
+ }
23840
+ } else {
23841
+ rest = afterScheme || undefined;
23842
+ }
23843
+ const challenge = { scheme, parameters };
23844
+ if (token68) {
23845
+ challenge.token68 = token68;
23846
+ }
23847
+ challenges.push(challenge);
23848
+ }
23849
+ if (!challenges.length) {
23850
+ return;
23851
+ }
23852
+ return challenges;
23853
+ }
23854
+ async function parseOAuthResponseErrorBody(response) {
23855
+ if (response.status > 399 && response.status < 500) {
23856
+ assertReadableResponse(response);
23857
+ assertApplicationJson(response);
23858
+ try {
23859
+ const json = await response.clone().json();
23860
+ if (isJsonObject(json) && typeof json.error === "string" && json.error.length) {
23861
+ return json;
23862
+ }
23863
+ } catch {}
23864
+ }
23865
+ return;
23866
+ }
23867
+ async function checkOAuthBodyError(response, expected, label) {
23868
+ if (response.status !== expected) {
23869
+ checkAuthenticationChallenges(response);
23870
+ let err;
23871
+ if (err = await parseOAuthResponseErrorBody(response)) {
23872
+ await response.body?.cancel();
23873
+ throw new ResponseBodyError("server responded with an error in the response body", {
23874
+ cause: err,
23875
+ response
23876
+ });
23877
+ }
23878
+ throw OPE(`"response" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);
23879
+ }
23880
+ }
23881
+ function assertDPoP(option) {
23882
+ if (!branded.has(option)) {
23883
+ throw CodedTypeError('"options.DPoP" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);
23884
+ }
23885
+ }
23886
+ var skipSubjectCheck = Symbol();
23887
+ function getContentType(input) {
23888
+ return input.headers.get("content-type")?.split(";")[0];
23889
+ }
23890
+ async function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {
23891
+ await clientAuthentication(as, client, body, headers);
23892
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
23893
+ return (options?.[customFetch] || fetch)(url.href, {
23894
+ body,
23895
+ headers: Object.fromEntries(headers.entries()),
23896
+ method: "POST",
23897
+ redirect: "manual",
23898
+ signal: signal(url, options?.signal)
23899
+ });
23900
+ }
23901
+ async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
23902
+ const url = resolveEndpoint(as, "token_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
23903
+ parameters.set("grant_type", grantType);
23904
+ const headers = prepareHeaders(options?.headers);
23905
+ headers.set("accept", "application/json");
23906
+ if (options?.DPoP !== undefined) {
23907
+ assertDPoP(options.DPoP);
23908
+ await options.DPoP.addProof(url, headers, "POST");
23909
+ }
23910
+ const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);
23911
+ options?.DPoP?.cacheNonce(response, url);
23912
+ return response;
23913
+ }
23914
+ var idTokenClaims = new WeakMap;
23915
+ var jwtRefs = new WeakMap;
23916
+ function getValidatedIdTokenClaims(ref) {
23917
+ if (!ref.id_token) {
23918
+ return;
23919
+ }
23920
+ const claims = idTokenClaims.get(ref);
23921
+ if (!claims) {
23922
+ throw CodedTypeError('"ref" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);
23923
+ }
23924
+ return claims;
23925
+ }
23926
+ async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
23927
+ assertAs(as);
23928
+ assertClient(client);
23929
+ if (!looseInstanceOf(response, Response)) {
23930
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
23931
+ }
23932
+ await checkOAuthBodyError(response, 200, "Token Endpoint");
23933
+ assertReadableResponse(response);
23934
+ const json = await getResponseJsonBody(response);
23935
+ assertString(json.access_token, '"response" body "access_token" property', INVALID_RESPONSE, {
23936
+ body: json
23937
+ });
23938
+ assertString(json.token_type, '"response" body "token_type" property', INVALID_RESPONSE, {
23939
+ body: json
23940
+ });
23941
+ json.token_type = json.token_type.toLowerCase();
23942
+ if (json.expires_in !== undefined) {
23943
+ let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
23944
+ assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
23945
+ body: json
23946
+ });
23947
+ json.expires_in = expiresIn;
23948
+ }
23949
+ if (json.refresh_token !== undefined) {
23950
+ assertString(json.refresh_token, '"response" body "refresh_token" property', INVALID_RESPONSE, {
23951
+ body: json
23952
+ });
23953
+ }
23954
+ if (json.scope !== undefined && typeof json.scope !== "string") {
23955
+ throw OPE('"response" body "scope" property must be a string', INVALID_RESPONSE, { body: json });
23956
+ }
23957
+ if (json.id_token !== undefined) {
23958
+ assertString(json.id_token, '"response" body "id_token" property', INVALID_RESPONSE, {
23959
+ body: json
23960
+ });
23961
+ const requiredClaims = [];
23962
+ if (client.require_auth_time === true) {
23963
+ requiredClaims.push("auth_time");
23964
+ }
23965
+ if (client.default_max_age !== undefined) {
23966
+ assertNumber(client.default_max_age, true, '"client.default_max_age"');
23967
+ requiredClaims.push("auth_time");
23968
+ }
23969
+ if (additionalRequiredIdTokenClaims?.length) {
23970
+ requiredClaims.push(...additionalRequiredIdTokenClaims);
23971
+ }
23972
+ const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);
23973
+ validateIdTokenAuthorizedParty(client, claims);
23974
+ validateIdTokenAuthTimeClaim(claims);
23975
+ jwtRefs.set(response, jwt);
23976
+ idTokenClaims.set(json, claims);
23977
+ }
23978
+ if (recognizedTokenTypes?.[json.token_type] !== undefined) {
23979
+ recognizedTokenTypes[json.token_type](response, json);
23980
+ } else if (json.token_type !== "dpop" && json.token_type !== "bearer") {
23981
+ throw new UnsupportedOperationError("unsupported `token_type` value", { cause: { body: json } });
23982
+ }
23983
+ return json;
23984
+ }
23985
+ function checkAuthenticationChallenges(response) {
23986
+ let challenges;
23987
+ if (challenges = parseWwwAuthenticateChallenges(response)) {
23988
+ throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", { cause: challenges, response });
23989
+ }
23990
+ }
23991
+ function validateAudience(expected, result) {
23992
+ if (Array.isArray(result.claims.aud)) {
23993
+ if (!result.claims.aud.includes(expected)) {
23994
+ throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
23995
+ expected,
23996
+ claims: result.claims,
23997
+ claim: "aud"
23998
+ });
23999
+ }
24000
+ } else if (result.claims.aud !== expected) {
24001
+ throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
24002
+ expected,
24003
+ claims: result.claims,
24004
+ claim: "aud"
24005
+ });
24006
+ }
24007
+ return result;
24008
+ }
24009
+ function validateIssuer(as, result) {
24010
+ const expected = as[_expectedIssuer]?.(result) ?? as.issuer;
24011
+ if (result.claims.iss !== expected) {
24012
+ throw OPE('unexpected JWT "iss" (issuer) claim value', JWT_CLAIM_COMPARISON, {
24013
+ expected,
24014
+ claims: result.claims,
24015
+ claim: "iss"
24016
+ });
24017
+ }
24018
+ return result;
24019
+ }
24020
+ var branded = new WeakSet;
24021
+ var nopkce = Symbol();
24022
+ var jwtClaimNames = {
24023
+ aud: "audience",
24024
+ c_hash: "code hash",
24025
+ client_id: "client id",
24026
+ exp: "expiration time",
24027
+ iat: "issued at",
24028
+ iss: "issuer",
24029
+ jti: "jwt id",
24030
+ nonce: "nonce",
24031
+ s_hash: "state hash",
24032
+ sub: "subject",
24033
+ ath: "access token hash",
24034
+ htm: "http method",
24035
+ htu: "http uri",
24036
+ cnf: "confirmation",
24037
+ auth_time: "authentication time"
24038
+ };
24039
+ function validatePresence(required, result) {
24040
+ for (const claim of required) {
24041
+ if (result.claims[claim] === undefined) {
24042
+ throw OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {
24043
+ claims: result.claims
24044
+ });
24045
+ }
24046
+ }
24047
+ return result;
24048
+ }
24049
+ function validateStringClaim(claim, result) {
24050
+ if (typeof result.claims[claim] !== "string") {
24051
+ throw OPE(`unexpected JWT "${claim}" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, {
24052
+ claims: result.claims
24053
+ });
24054
+ }
24055
+ return result;
24056
+ }
24057
+ function validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {
24058
+ return validateJwt(idToken, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, "RS256"), getClockSkew(client), getClockTolerance(client), decryptFn).then(validatePresence.bind(undefined, ["aud", "exp", "iat", "iss", "sub", ...requiredClaims])).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, client.client_id)).then(validateStringClaim.bind(undefined, "sub"));
24059
+ }
24060
+ function validateIdTokenAuthTimeClaim(claims) {
24061
+ if (claims.auth_time !== undefined) {
24062
+ assertNumber(claims.auth_time, true, 'ID Token "auth_time" (authentication time)', INVALID_RESPONSE, { claims });
24063
+ }
24064
+ }
24065
+ function validateIdTokenAuthorizedParty(client, claims) {
24066
+ if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
24067
+ if (claims.azp === undefined) {
24068
+ throw OPE('ID Token "aud" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: "aud" });
24069
+ }
24070
+ if (claims.azp !== client.client_id) {
24071
+ throw OPE('unexpected ID Token "azp" (authorized party) claim value', JWT_CLAIM_COMPARISON, {
24072
+ expected: client.client_id,
24073
+ claims,
24074
+ claim: "azp"
24075
+ });
24076
+ }
24077
+ }
24078
+ }
24079
+ var expectNoNonce = Symbol();
24080
+ var skipAuthTimeCheck = Symbol();
24081
+ var WWW_AUTHENTICATE_CHALLENGE = "OAUTH_WWW_AUTHENTICATE_CHALLENGE";
24082
+ var RESPONSE_BODY_ERROR = "OAUTH_RESPONSE_BODY_ERROR";
24083
+ var UNSUPPORTED_OPERATION = "OAUTH_UNSUPPORTED_OPERATION";
24084
+ var AUTHORIZATION_RESPONSE_ERROR = "OAUTH_AUTHORIZATION_RESPONSE_ERROR";
24085
+ var PARSE_ERROR = "OAUTH_PARSE_ERROR";
24086
+ var INVALID_RESPONSE = "OAUTH_INVALID_RESPONSE";
24087
+ var RESPONSE_IS_NOT_JSON = "OAUTH_RESPONSE_IS_NOT_JSON";
24088
+ var RESPONSE_IS_NOT_CONFORM = "OAUTH_RESPONSE_IS_NOT_CONFORM";
24089
+ var HTTP_REQUEST_FORBIDDEN = "OAUTH_HTTP_REQUEST_FORBIDDEN";
24090
+ var REQUEST_PROTOCOL_FORBIDDEN = "OAUTH_REQUEST_PROTOCOL_FORBIDDEN";
24091
+ var JWT_TIMESTAMP_CHECK = "OAUTH_JWT_TIMESTAMP_CHECK_FAILED";
24092
+ var JWT_CLAIM_COMPARISON = "OAUTH_JWT_CLAIM_COMPARISON_FAILED";
24093
+ var JSON_ATTRIBUTE_COMPARISON = "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";
24094
+ var MISSING_SERVER_METADATA = "OAUTH_MISSING_SERVER_METADATA";
24095
+ var INVALID_SERVER_METADATA = "OAUTH_INVALID_SERVER_METADATA";
24096
+ async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
24097
+ assertAs(as);
24098
+ assertClient(client);
24099
+ assertString(grantType, '"grantType"');
24100
+ return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);
24101
+ }
24102
+ async function processGenericTokenEndpointResponse(as, client, response, options) {
24103
+ return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
24104
+ }
24105
+ function assertReadableResponse(response) {
24106
+ if (response.bodyUsed) {
24107
+ throw CodedTypeError('"response" body has been used already', ERR_INVALID_ARG_VALUE);
24108
+ }
24109
+ }
24110
+ async function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {
24111
+ let { 0: protectedHeader, 1: payload, length } = jws.split(".");
24112
+ if (length === 5) {
24113
+ if (decryptJwt !== undefined) {
24114
+ jws = await decryptJwt(jws);
24115
+ ({ 0: protectedHeader, 1: payload, length } = jws.split("."));
24116
+ } else {
24117
+ throw new UnsupportedOperationError("JWE decryption is not configured", { cause: jws });
24118
+ }
24119
+ }
24120
+ if (length !== 3) {
24121
+ throw OPE("Invalid JWT", INVALID_RESPONSE, jws);
24122
+ }
24123
+ let header;
24124
+ try {
24125
+ header = JSON.parse(buf(b64u(protectedHeader)));
24126
+ } catch (cause) {
24127
+ throw OPE("failed to parse JWT Header body as base64url encoded JSON", PARSE_ERROR, cause);
24128
+ }
24129
+ if (!isJsonObject(header)) {
24130
+ throw OPE("JWT Header must be a top level object", INVALID_RESPONSE, jws);
24131
+ }
24132
+ checkAlg(header);
24133
+ if (header.crit !== undefined) {
24134
+ throw new UnsupportedOperationError('no JWT "crit" header parameter extensions are supported', {
24135
+ cause: { header }
24136
+ });
24137
+ }
24138
+ let claims;
24139
+ try {
24140
+ claims = JSON.parse(buf(b64u(payload)));
24141
+ } catch (cause) {
24142
+ throw OPE("failed to parse JWT Payload body as base64url encoded JSON", PARSE_ERROR, cause);
24143
+ }
24144
+ if (!isJsonObject(claims)) {
24145
+ throw OPE("JWT Payload must be a top level object", INVALID_RESPONSE, jws);
24146
+ }
24147
+ const now = epochTime() + clockSkew;
24148
+ if (claims.exp !== undefined) {
24149
+ if (typeof claims.exp !== "number") {
24150
+ throw OPE('unexpected JWT "exp" (expiration time) claim type', INVALID_RESPONSE, { claims });
24151
+ }
24152
+ if (claims.exp <= now - clockTolerance) {
24153
+ throw OPE('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: "exp" });
24154
+ }
24155
+ }
24156
+ if (claims.iat !== undefined) {
24157
+ if (typeof claims.iat !== "number") {
24158
+ throw OPE('unexpected JWT "iat" (issued at) claim type', INVALID_RESPONSE, { claims });
24159
+ }
24160
+ }
24161
+ if (claims.iss !== undefined) {
24162
+ if (typeof claims.iss !== "string") {
24163
+ throw OPE('unexpected JWT "iss" (issuer) claim type', INVALID_RESPONSE, { claims });
24164
+ }
24165
+ }
24166
+ if (claims.nbf !== undefined) {
24167
+ if (typeof claims.nbf !== "number") {
24168
+ throw OPE('unexpected JWT "nbf" (not before) claim type', INVALID_RESPONSE, { claims });
24169
+ }
24170
+ if (claims.nbf > now + clockTolerance) {
24171
+ throw OPE('unexpected JWT "nbf" (not before) claim value', JWT_TIMESTAMP_CHECK, {
24172
+ claims,
24173
+ now,
24174
+ tolerance: clockTolerance,
24175
+ claim: "nbf"
24176
+ });
24177
+ }
24178
+ }
24179
+ if (claims.aud !== undefined) {
24180
+ if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) {
24181
+ throw OPE('unexpected JWT "aud" (audience) claim type', INVALID_RESPONSE, { claims });
24182
+ }
24183
+ }
24184
+ return { header, claims, jwt: jws };
24185
+ }
24186
+ function checkSigningAlgorithm(client, issuer, fallback, header) {
24187
+ if (client !== undefined) {
24188
+ if (typeof client === "string" ? header.alg !== client : !client.includes(header.alg)) {
24189
+ throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
24190
+ header,
24191
+ expected: client,
24192
+ reason: "client configuration"
24193
+ });
24194
+ }
24195
+ return;
24196
+ }
24197
+ if (Array.isArray(issuer)) {
24198
+ if (!issuer.includes(header.alg)) {
24199
+ throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
24200
+ header,
24201
+ expected: issuer,
24202
+ reason: "authorization server metadata"
24203
+ });
24204
+ }
24205
+ return;
24206
+ }
24207
+ if (fallback !== undefined) {
24208
+ if (typeof fallback === "string" ? header.alg !== fallback : typeof fallback === "function" ? !fallback(header.alg) : !fallback.includes(header.alg)) {
24209
+ throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
24210
+ header,
24211
+ expected: fallback,
24212
+ reason: "default value"
24213
+ });
24214
+ }
24215
+ return;
24216
+ }
24217
+ throw OPE('missing client or server configuration to verify used JWT "alg" header parameter', undefined, { client, issuer, fallback });
24218
+ }
24219
+ var skipStateCheck = Symbol();
24220
+ var expectNoState = Symbol();
24221
+ async function getResponseJsonBody(response, check = assertApplicationJson) {
24222
+ let json;
24223
+ try {
24224
+ json = await response.json();
24225
+ } catch (cause) {
24226
+ check(response);
24227
+ throw OPE('failed to parse "response" body as JSON', PARSE_ERROR, cause);
24228
+ }
24229
+ if (!isJsonObject(json)) {
24230
+ throw OPE('"response" body must be a top level object', INVALID_RESPONSE, { body: json });
24231
+ }
24232
+ return json;
24233
+ }
24234
+ var _nodiscoverycheck = Symbol();
24235
+ var _expectedIssuer = Symbol();
24236
+
24237
+ // ../../node_modules/.bun/openid-client@6.8.7/node_modules/openid-client/build/index.js
24238
+ var headers;
24239
+ var USER_AGENT2;
24240
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
24241
+ const NAME = "openid-client";
24242
+ const VERSION = "v6.8.7";
24243
+ USER_AGENT2 = `${NAME}/${VERSION}`;
24244
+ headers = { "user-agent": USER_AGENT2 };
24245
+ }
24246
+ var int2 = (config) => {
24247
+ return props.get(config);
24248
+ };
24249
+ var props;
24250
+ var tbi;
24251
+ function ClientSecretPost2(clientSecret) {
24252
+ if (clientSecret !== undefined) {
24253
+ return ClientSecretPost(clientSecret);
24254
+ }
24255
+ tbi ||= new WeakMap;
24256
+ return (as, client, body, headers) => {
24257
+ let auth;
24258
+ if (!(auth = tbi.get(client))) {
24259
+ assertString2(client.client_secret, '"metadata.client_secret"');
24260
+ auth = ClientSecretPost(client.client_secret);
24261
+ tbi.set(client, auth);
24262
+ }
24263
+ return auth(as, client, body, headers);
24264
+ };
24265
+ }
24266
+ function assertString2(input, it) {
24267
+ if (typeof input !== "string") {
24268
+ throw CodedTypeError2(`${it} must be a string`, ERR_INVALID_ARG_TYPE2);
24269
+ }
24270
+ if (input.length === 0) {
24271
+ throw CodedTypeError2(`${it} must not be empty`, ERR_INVALID_ARG_VALUE2);
24272
+ }
24273
+ }
24274
+ function None2() {
24275
+ return None();
24276
+ }
24277
+ var customFetch2 = customFetch;
24278
+ var ERR_INVALID_ARG_VALUE2 = "ERR_INVALID_ARG_VALUE";
24279
+ var ERR_INVALID_ARG_TYPE2 = "ERR_INVALID_ARG_TYPE";
24280
+ function CodedTypeError2(message, code, cause) {
24281
+ const err = new TypeError(message, { cause });
24282
+ Object.assign(err, { code });
24283
+ return err;
24284
+ }
24285
+ class ClientError extends Error {
24286
+ code;
24287
+ constructor(message, options) {
24288
+ super(message, options);
24289
+ this.name = this.constructor.name;
24290
+ this.code = options?.code;
24291
+ Error.captureStackTrace?.(this, this.constructor);
24292
+ }
24293
+ }
24294
+ var decoder3 = new TextDecoder;
24295
+ function e(msg, cause, code) {
24296
+ return new ClientError(msg, { cause, code });
24297
+ }
24298
+ function errorHandler(err) {
24299
+ if (err instanceof TypeError || err instanceof ClientError || err instanceof ResponseBodyError || err instanceof AuthorizationResponseError || err instanceof WWWAuthenticateChallengeError) {
24300
+ throw err;
24301
+ }
24302
+ if (err instanceof OperationProcessingError) {
24303
+ switch (err.code) {
24304
+ case HTTP_REQUEST_FORBIDDEN:
24305
+ throw e("only requests to HTTPS are allowed", err, err.code);
24306
+ case REQUEST_PROTOCOL_FORBIDDEN:
24307
+ throw e("only requests to HTTP or HTTPS are allowed", err, err.code);
24308
+ case RESPONSE_IS_NOT_CONFORM:
24309
+ throw e("unexpected HTTP response status code", err.cause, err.code);
24310
+ case RESPONSE_IS_NOT_JSON:
24311
+ throw e("unexpected response content-type", err.cause, err.code);
24312
+ case PARSE_ERROR:
24313
+ throw e("parsing error occured", err, err.code);
24314
+ case INVALID_RESPONSE:
24315
+ throw e("invalid response encountered", err, err.code);
24316
+ case JWT_CLAIM_COMPARISON:
24317
+ throw e("unexpected JWT claim value encountered", err, err.code);
24318
+ case JSON_ATTRIBUTE_COMPARISON:
24319
+ throw e("unexpected JSON attribute value encountered", err, err.code);
24320
+ case JWT_TIMESTAMP_CHECK:
24321
+ throw e("JWT timestamp claim value failed validation", err, err.code);
24322
+ default:
24323
+ throw e(err.message, err, err.code);
24324
+ }
24325
+ }
24326
+ if (err instanceof UnsupportedOperationError) {
24327
+ throw e("unsupported operation", err, err.code);
24328
+ }
24329
+ if (err instanceof DOMException) {
24330
+ switch (err.name) {
24331
+ case "OperationError":
24332
+ throw e("runtime operation error", err, UNSUPPORTED_OPERATION);
24333
+ case "NotSupportedError":
24334
+ throw e("runtime unsupported operation", err, UNSUPPORTED_OPERATION);
24335
+ case "TimeoutError":
24336
+ throw e("operation timed out", err, "OAUTH_TIMEOUT");
24337
+ case "AbortError":
24338
+ throw e("operation aborted", err, "OAUTH_ABORT");
24339
+ }
24340
+ }
24341
+ throw new ClientError("something went wrong", { cause: err });
24342
+ }
24343
+ function getServerHelpers(metadata) {
24344
+ return {
24345
+ supportsPKCE: {
24346
+ __proto__: null,
24347
+ value(method = "S256") {
24348
+ return metadata.code_challenge_methods_supported?.includes(method) === true;
24349
+ }
24350
+ }
24351
+ };
24352
+ }
24353
+ function addServerHelpers(metadata) {
24354
+ Object.defineProperties(metadata, getServerHelpers(metadata));
24355
+ }
24356
+ var kEntraId = Symbol();
24357
+
24358
+ class Configuration {
24359
+ constructor(server, clientId, metadata, clientAuthentication) {
24360
+ if (typeof clientId !== "string" || !clientId.length) {
24361
+ throw CodedTypeError2('"clientId" must be a non-empty string', ERR_INVALID_ARG_TYPE2);
24362
+ }
24363
+ if (typeof metadata === "string") {
24364
+ metadata = { client_secret: metadata };
24365
+ }
24366
+ if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {
24367
+ throw CodedTypeError2('"clientId" and "metadata.client_id" must be the same', ERR_INVALID_ARG_VALUE2);
24368
+ }
24369
+ const client = {
24370
+ ...structuredClone(metadata),
24371
+ client_id: clientId
24372
+ };
24373
+ client[clockSkew] = metadata?.[clockSkew] ?? 0;
24374
+ client[clockTolerance] = metadata?.[clockTolerance] ?? 30;
24375
+ let auth;
24376
+ if (clientAuthentication) {
24377
+ auth = clientAuthentication;
24378
+ } else {
24379
+ if (typeof client.client_secret === "string" && client.client_secret.length) {
24380
+ auth = ClientSecretPost2(client.client_secret);
24381
+ } else {
24382
+ auth = None2();
24383
+ }
24384
+ }
24385
+ let c = Object.freeze(client);
24386
+ const clone = structuredClone(server);
24387
+ if (kEntraId in server) {
24388
+ clone[_expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace("{tenantid}", tid);
24389
+ }
24390
+ let as = Object.freeze(clone);
24391
+ props ||= new WeakMap;
24392
+ props.set(this, {
24393
+ __proto__: null,
24394
+ as,
24395
+ c,
24396
+ auth,
24397
+ tlsOnly: true,
24398
+ jwksCache: {}
24399
+ });
24400
+ }
24401
+ serverMetadata() {
24402
+ const metadata = structuredClone(int2(this).as);
24403
+ addServerHelpers(metadata);
24404
+ return metadata;
24405
+ }
24406
+ clientMetadata() {
24407
+ const metadata = structuredClone(int2(this).c);
24408
+ return metadata;
24409
+ }
24410
+ get timeout() {
24411
+ return int2(this).timeout;
24412
+ }
24413
+ set timeout(value) {
24414
+ int2(this).timeout = value;
24415
+ }
24416
+ get [customFetch2]() {
24417
+ return int2(this).fetch;
24418
+ }
24419
+ set [customFetch2](value) {
24420
+ int2(this).fetch = value;
24421
+ }
24422
+ }
24423
+ Object.freeze(Configuration.prototype);
24424
+ function getHelpers(response) {
24425
+ let exp = undefined;
24426
+ if (response.expires_in !== undefined) {
24427
+ const now = new Date;
24428
+ now.setSeconds(now.getSeconds() + response.expires_in);
24429
+ exp = now.getTime();
24430
+ }
24431
+ return {
24432
+ expiresIn: {
24433
+ __proto__: null,
24434
+ value() {
24435
+ if (exp) {
24436
+ const now = Date.now();
24437
+ if (exp > now) {
24438
+ return Math.floor((exp - now) / 1000);
24439
+ }
24440
+ return 0;
24441
+ }
24442
+ return;
24443
+ }
24444
+ },
24445
+ claims: {
24446
+ __proto__: null,
24447
+ value() {
24448
+ return getValidatedIdTokenClaims(response);
24449
+ }
24450
+ }
24451
+ };
24452
+ }
24453
+ function addHelpers(response) {
24454
+ Object.defineProperties(response, getHelpers(response));
24455
+ }
24456
+ function allowInsecureRequests2(config) {
24457
+ int2(config).tlsOnly = false;
24458
+ }
24459
+ function checkConfig(input) {
24460
+ if (!(input instanceof Configuration)) {
24461
+ throw CodedTypeError2('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE2);
24462
+ }
24463
+ if (Object.getPrototypeOf(input) !== Configuration.prototype) {
24464
+ throw CodedTypeError2("subclassing Configuration is not allowed", ERR_INVALID_ARG_VALUE2);
24465
+ }
24466
+ }
24467
+ function signal2(timeout) {
24468
+ return timeout ? AbortSignal.timeout(timeout * 1000) : undefined;
24469
+ }
24470
+ function retryable(err, options) {
24471
+ if (options?.DPoP && options.flag !== retry) {
24472
+ return isDPoPNonceError(err);
24473
+ }
24474
+ return false;
24475
+ }
24476
+ var retry = Symbol();
24477
+ async function genericGrantRequest(config, grantType, parameters, options) {
24478
+ checkConfig(config);
24479
+ const { as, c, auth, fetch: fetch2, tlsOnly, timeout, decrypt, nonRepudiation } = int2(config);
24480
+ const response = await genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {
24481
+ [customFetch]: fetch2,
24482
+ [allowInsecureRequests]: !tlsOnly,
24483
+ DPoP: options?.DPoP,
24484
+ headers: new Headers(headers),
24485
+ signal: signal2(timeout)
24486
+ }).catch(errorHandler);
24487
+ let recognizedTokenTypes;
24488
+ if (grantType === "urn:ietf:params:oauth:grant-type:token-exchange") {
24489
+ recognizedTokenTypes = { n_a: () => {} };
24490
+ }
24491
+ const p = processGenericTokenEndpointResponse(as, c, response, {
24492
+ [jweDecrypt]: decrypt,
24493
+ recognizedTokenTypes
24494
+ });
24495
+ let result;
24496
+ try {
24497
+ result = await p;
24498
+ } catch (err) {
24499
+ if (retryable(err, options)) {
24500
+ return genericGrantRequest(config, grantType, parameters, {
24501
+ ...options,
24502
+ flag: retry
24503
+ });
24504
+ }
24505
+ errorHandler(err);
24506
+ }
24507
+ result.id_token && await nonRepudiation?.(response);
24508
+ addHelpers(result);
24509
+ return result;
24510
+ }
24511
+
24512
+ // ../broker-client/src/token-client.ts
24513
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
24514
+ var TOO_MANY_REQUESTS = 429;
24515
+ var INVALID_DPOP_PROOF = "invalid_dpop_proof";
24516
+ var USE_DPOP_NONCE = "use_dpop_nonce";
24517
+
24518
+ class BrokerRefusedError extends Error {
24519
+ status;
24520
+ code;
24521
+ description;
24522
+ constructor(status, code, description) {
24523
+ super(description === "" ? `the secrets broker refused this machine's identity: HTTP ${status} ${code}` : `the secrets broker refused this machine's identity: HTTP ${status} ${code}: ${description}`);
24524
+ this.status = status;
24525
+ this.code = code;
24526
+ this.description = description;
24527
+ this.name = "BrokerRefusedError";
24528
+ }
24529
+ get permanent() {
24530
+ return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE;
24531
+ }
24532
+ }
24533
+ function statusOf(error) {
24534
+ let cause = error;
24535
+ for (let depth = 0;depth < 4; depth += 1) {
24536
+ if (cause instanceof Response)
24537
+ return cause.status;
24538
+ if (typeof cause !== "object" || cause === null || !("cause" in cause))
24539
+ return 0;
24540
+ cause = cause.cause;
24541
+ }
24542
+ return 0;
24543
+ }
24544
+ function withoutTrailingSlashes(url) {
24545
+ let end = url.length;
24546
+ while (end > 0 && url[end - 1] === "/")
24547
+ end -= 1;
24548
+ return url.slice(0, end);
24549
+ }
24550
+
24551
+ class BrokerTokenClient {
24552
+ #brokerUrl;
24553
+ #key;
24554
+ #subject;
24555
+ #actor;
24556
+ #session;
24557
+ #launcherCredential;
24558
+ #renewBeforeMs;
24559
+ #now;
24560
+ #fetch;
24561
+ #nonce = "";
24562
+ #held = null;
24563
+ #trading = null;
24564
+ constructor(options) {
24565
+ const brokerUrl = withoutTrailingSlashes(options.brokerUrl.trim());
24566
+ if (brokerUrl === "")
24567
+ throw new Error("broker client: no broker URL");
24568
+ this.#brokerUrl = brokerUrl;
24569
+ this.#key = options.key;
24570
+ this.#subject = options.subject;
24571
+ this.#actor = options.actor;
24572
+ this.#session = options.session ?? "";
24573
+ this.#launcherCredential = options.launcherCredential ?? true;
24574
+ this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
24575
+ this.#now = options.now ?? Date.now;
24576
+ this.#fetch = options.fetch ?? fetch;
24577
+ }
24578
+ get key() {
24579
+ return this.#key;
24580
+ }
24581
+ describe() {
24582
+ return this.#subject.describe();
24583
+ }
24584
+ async token(signal) {
24585
+ const held = this.#held;
24586
+ if (held !== null && this.#now() < held.expiresAt.getTime() - this.#renewBeforeMs)
24587
+ return held;
24588
+ if (this.#trading !== null)
24589
+ return await this.#trading;
24590
+ const trading = this.#renew(signal);
24591
+ this.#trading = trading;
24592
+ try {
24593
+ return await trading;
24594
+ } finally {
24595
+ this.#trading = null;
24596
+ }
24597
+ }
24598
+ async#renew(signal) {
24599
+ try {
24600
+ const token = await this.#trade(signal);
24601
+ this.#held = token;
24602
+ return token;
24603
+ } catch (error) {
24604
+ const held = this.#held;
24605
+ if (!(error instanceof BrokerRefusedError && error.permanent) && held !== null && this.#now() < held.expiresAt.getTime()) {
24606
+ return held;
24607
+ }
24608
+ this.#held = null;
24609
+ throw error;
24610
+ }
24611
+ }
24612
+ async#trade(signal) {
24613
+ const subject = await this.#subject.read(signal);
24614
+ const form = {
24615
+ subject_token: subject.token,
24616
+ subject_token_type: subject.tokenType
24617
+ };
24618
+ if (this.#session !== "")
24619
+ form[FORM_SESSION] = this.#session;
24620
+ if (!this.#launcherCredential) {
24621
+ form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
24622
+ }
24623
+ if (this.#actor !== undefined) {
24624
+ let actor;
24625
+ try {
24626
+ actor = await this.#actor.read(signal);
24627
+ } catch (error) {
24628
+ const said = error instanceof Error ? error.message : String(error);
24629
+ throw new Error(`read the machine this person signed in on: ${said}`, { cause: error });
24630
+ }
24631
+ form["actor_token"] = actor.token;
24632
+ form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
24633
+ }
24634
+ const endpoint = this.#brokerUrl + TOKEN_PATH;
24635
+ const raw = { body: undefined };
24636
+ const config = new Configuration({ issuer: this.#brokerUrl, token_endpoint: endpoint }, EXCHANGE_CLIENT_ID, {}, None2());
24637
+ allowInsecureRequests2(config);
24638
+ config[customFetch2] = (url, options) => this.#send(url, options, signal, raw);
24639
+ let answered;
24640
+ try {
24641
+ answered = await genericGrantRequest(config, GRANT_TYPE_TOKEN_EXCHANGE, form);
24642
+ } catch (error) {
24643
+ throw this.#refusal(endpoint, error);
24644
+ }
24645
+ return this.#read(endpoint, answered, raw.body);
24646
+ }
24647
+ #refusal(endpoint, error) {
24648
+ if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
24649
+ return new BrokerRefusedError(error.status, error.error, error.error_description ?? "");
24650
+ }
24651
+ const status = statusOf(error);
24652
+ const message = error instanceof Error ? error.message : String(error);
24653
+ const said = status === 0 ? message : `HTTP ${status}: ${message}`;
24654
+ return new Error(`trade ${this.#subject.describe()} at ${endpoint}: ${said}`, {
24655
+ cause: error
24656
+ });
24657
+ }
24658
+ async#send(url, options, signal, raw) {
24659
+ const send = async () => {
24660
+ const headers = new Headers(options.headers);
24661
+ headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
24662
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
24663
+ const body = options.body;
24664
+ return await this.#fetch(url, {
24665
+ method: options.method,
24666
+ headers,
24667
+ body,
24668
+ redirect: options.redirect,
24669
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
24670
+ });
24671
+ };
24672
+ let answer = await send();
24673
+ const given = answer.headers.get("DPoP-Nonce") ?? "";
24674
+ if (given !== "")
24675
+ this.#nonce = given;
24676
+ if (answer.status === 400 && given !== "") {
24677
+ const body = await answer.clone().json().catch(() => null);
24678
+ const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
24679
+ if (asked)
24680
+ answer = await send();
24681
+ }
24682
+ raw.body = await answer.clone().json().catch(() => {
24683
+ return;
24684
+ });
24685
+ return answer;
24686
+ }
24687
+ #read(endpoint, answered, raw) {
24688
+ const written = typeof raw === "object" && raw !== null && "token_type" in raw ? raw.token_type : undefined;
24689
+ const tokenType = typeof written === "string" ? written : "";
24690
+ if (tokenType.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
24691
+ throw new Error(`the broker at ${endpoint} answered token_type ${JSON.stringify(tokenType)}, and this grant mints DPoP-bound tokens alone`);
24692
+ }
24693
+ if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
24694
+ throw new Error(`the broker at ${endpoint} answered a refresh token, which this grant never issues; a renewal trades a fresh identity token instead`);
24695
+ }
24696
+ const seconds = answered.expires_in ?? 0;
24697
+ if (!(seconds > 0)) {
24698
+ throw new Error(`the broker at ${endpoint} answered no usable expires_in (${JSON.stringify(answered.expires_in)})`);
24699
+ }
24700
+ const expiresAtText = typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "";
24701
+ let credentialExpiresAt = null;
24702
+ if (expiresAtText !== "") {
24703
+ credentialExpiresAt = new Date(expiresAtText);
24704
+ if (Number.isNaN(credentialExpiresAt.getTime())) {
24705
+ throw new Error(`the broker at ${endpoint} answered a credential_expires_at that is no RFC 3339 time (${JSON.stringify(expiresAtText)})`);
24706
+ }
24707
+ }
24708
+ return {
24709
+ accessToken: answered.access_token,
24710
+ tokenType,
24711
+ expiresAt: new Date(this.#now() + seconds * 1000),
24712
+ credentialId: typeof answered["credential_id"] === "string" ? answered["credential_id"] : "",
24713
+ credentialExpiresAt
24714
+ };
24715
+ }
24716
+ }
24717
+
24718
+ // ../broker-client/src/environment.ts
24719
+ var BROKER_URL_VAR = "AGENT_SECRETS_URL";
24720
+ var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
24721
+ var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
24722
+ var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
24723
+ var SESSION_VAR = "AGENT_SECRETS_SESSION";
24724
+ var IDENTITY_KUBERNETES = "kubernetes";
24725
+ var IDENTITY_METADATA = "metadata";
24726
+ var IDENTITY_POOL = "pool";
24727
+ function value(env, name) {
24728
+ return (env[name] ?? "").trim();
24729
+ }
24730
+ function required2(env, name, kind) {
24731
+ const named = value(env, name);
24732
+ if (named === "")
24733
+ throw new Error(`${name} is required by ${IDENTITY_VAR}=${kind}`);
24734
+ return named;
24735
+ }
24736
+ function machineIdentity(env) {
24737
+ const kind = value(env, IDENTITY_VAR);
24738
+ switch (kind) {
24739
+ case "":
24740
+ return;
24741
+ case IDENTITY_KUBERNETES:
24742
+ return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind));
24743
+ case IDENTITY_METADATA:
24744
+ return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
24745
+ case IDENTITY_POOL:
24746
+ throw new Error(`${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), which federates at the workload identity pool; this process can prove ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
24747
+ default:
24748
+ throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
24749
+ }
24750
+ }
24751
+ function tradeSession(env, own = "") {
24752
+ const acting = own.trim();
24753
+ return acting !== "" ? acting : value(env, SESSION_VAR);
24754
+ }
24755
+ async function brokerTokenClient(env, own = "") {
24756
+ const brokerUrl = value(env, BROKER_URL_VAR);
24757
+ const subject = machineIdentity(env);
24758
+ if (brokerUrl === "" || subject === undefined)
24759
+ return;
24760
+ return new BrokerTokenClient({
24761
+ brokerUrl,
24762
+ key: await newDpopKey(),
24763
+ subject,
24764
+ session: tradeSession(env, own),
24765
+ launcherCredential: false
24766
+ });
24767
+ }
24768
+
24769
+ // ../envoy-client/src/broker-credential.ts
24770
+ function sessionName(naming) {
24771
+ if (naming === undefined)
24772
+ return "";
24773
+ return (typeof naming === "string" ? naming : naming()).trim();
24774
+ }
24775
+ function brokerRouteConfigured(env) {
24776
+ if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
24777
+ return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
24778
+ }
24779
+ if ((env[IDENTITY_VAR] ?? "").trim() === IDENTITY_POOL) {
24780
+ return {
24781
+ traded: false,
24782
+ gap: `${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), never by this process`
24783
+ };
24784
+ }
24785
+ if (machineIdentity(env) === undefined) {
24786
+ return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
24787
+ }
24788
+ return { traded: true };
24789
+ }
24790
+ var CLIENTS = new Map;
24791
+ function clientFor(env, own) {
24792
+ const session = tradeSession(env, own);
24793
+ const key = JSON.stringify([
24794
+ env.AGENT_SECRETS_URL,
24795
+ env.AGENT_SECRETS_MACHINE_IDENTITY,
24796
+ env.AGENT_SECRETS_MACHINE_TOKEN_FILE,
24797
+ env.AGENT_SECRETS_MACHINE_AUDIENCE
24798
+ ]);
24799
+ const held = CLIENTS.get(session) ?? new Map;
24800
+ CLIENTS.set(session, held);
24801
+ const made = held.get(key) ?? brokerTokenClient(env, session);
24802
+ held.set(key, made);
24803
+ return made;
24804
+ }
24805
+ function brokerCredential(env, session) {
24806
+ let held = "";
24807
+ return {
24808
+ scheme: "DPoP",
24809
+ async headers(method, url, acting) {
24810
+ const client = await clientFor(env, (acting ?? "").trim() || sessionName(session));
24811
+ if (client === undefined) {
24812
+ throw new Error("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
24813
+ }
24814
+ const token = await client.token();
24815
+ held = token.accessToken;
24816
+ return {
24817
+ Authorization: `DPoP ${token.accessToken}`,
24818
+ DPoP: await client.key.proof({ method, url, accessToken: token.accessToken })
24819
+ };
24820
+ },
24821
+ secret: () => held
24822
+ };
24823
+ }
24824
+
24825
+ // ../envoy-client/src/dispatch-config.ts
24826
+ var DEFAULT_SERVER_URL = "http://localhost:8766";
24827
+ function withoutTrailingSlashes2(url) {
24828
+ let end = url.length;
24829
+ while (end > 0 && url[end - 1] === "/")
24830
+ end -= 1;
24831
+ return url.slice(0, end);
24832
+ }
24833
+ function checkoutPair(checkout, serverUrl) {
24834
+ const { token } = checkout.dispatch;
24835
+ if (token === undefined) {
24836
+ throw new Error(`${checkout.path}: dispatch.serverUrl requires dispatch.token in the same file`);
24837
+ }
24838
+ return {
24839
+ kind: "file",
24840
+ token,
24841
+ field: "dispatch.token",
24842
+ path: checkout.path,
24843
+ server: serverUrl,
24844
+ checkout: true
24845
+ };
24846
+ }
24847
+ function writtenToken(config, checkout) {
24848
+ if (checkout?.dispatch.token !== undefined) {
24849
+ throw new Error(`${checkout.path}: dispatch.token requires dispatch.serverUrl in the same file`);
24850
+ }
24851
+ const own = config.dispatch;
24852
+ if (own.token === undefined)
24853
+ return;
24854
+ const server = own.serverUrl ?? DEFAULT_SERVER_URL;
24855
+ return {
24856
+ token: own.token,
24857
+ field: "dispatch.token",
24858
+ path: config.path,
24859
+ server,
24860
+ checkout: false
24861
+ };
24862
+ }
24863
+ function lostDispatchUrlNotice(env, config) {
24864
+ if (nonEmpty(env.DISPATCH_TOKEN_FILE) === undefined)
24865
+ return;
24866
+ const link = config.missing?.link ?? null;
24867
+ const old = config.missing?.oldUserFileNotice;
24868
+ return [
24869
+ "DISPATCH_TOKEN_FILE is set and DISPATCH_URL is not, so Dispatch is off: this shell lost the DISPATCH_URL it started with. Export DISPATCH_URL again, set to the Dispatch server that token is for",
24870
+ ...link === null ? [] : [`${config.path} is a link to ${link}, which does not exist`],
24871
+ ...old === undefined ? [] : [old]
24872
+ ].join("; ");
24873
+ }
24874
+ function dispatchSettings(env, config, options = {}) {
24875
+ const target = dispatchTarget(env, config);
24876
+ if (!target.enabled)
24877
+ return target;
24878
+ const { url, source } = target;
24879
+ let credential;
24880
+ try {
24881
+ credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
24882
+ } catch (error) {
24883
+ return offWithError(messageFor(error));
24884
+ }
24885
+ const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
24886
+ const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
24887
+ if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
24888
+ return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
24889
+ }
24890
+ return {
24891
+ enabled: true,
24892
+ url,
24893
+ credential,
24894
+ ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
24895
+ };
24896
+ }
24897
+ function brokerRouteForced(env) {
24898
+ const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
24899
+ if (written === "")
24900
+ return false;
24901
+ if (written === "1")
24902
+ return true;
24903
+ return offWithError(`DISPATCH_TOKEN_BROKER is "${written}" and takes 1: set it to 1 where this session's Dispatch credential is this machine's own identity traded at the secrets broker, and leave it unset where a bearer is read as usual`);
24904
+ }
24905
+ function dispatchTarget(env, config) {
24906
+ if (config.kind === "failed")
24907
+ return offWithError(config.error);
24908
+ const forced = brokerRouteForced(env);
24909
+ if (typeof forced !== "boolean")
24910
+ return forced;
24911
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
24912
+ const checkoutFile = explicitUrl === undefined ? config.checkout : null;
24913
+ if (checkoutFile?.kind === "invalid")
24914
+ return offWithError(checkoutFile.error);
24915
+ const checkout = checkoutFile?.kind === "valid" ? checkoutFile : null;
24916
+ const own = config.dispatch;
24917
+ if (own.enabled === false) {
24918
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
24919
+ }
24920
+ if (checkout?.dispatch.enabled === false) {
24921
+ return offWithNotice(`${checkout.path} sets dispatch.enabled to false: Dispatch is off`);
24922
+ }
24923
+ const checkoutServer = checkout?.dispatch.serverUrl;
24924
+ const addressed = explicitUrl !== undefined || checkoutServer !== undefined || own.serverUrl !== undefined || own.enabled === true;
24925
+ if (!addressed) {
24926
+ const lost = lostDispatchUrlNotice(env, config);
24927
+ if (lost !== undefined)
24928
+ return offWithNotice(lost);
24929
+ return offWithNotice(config.missing === null ? `${config.path} names no Dispatch server, and DISPATCH_URL is not set: Dispatch is off` : missingConfigNotice(config.path, config.missing, "Dispatch is off"));
24930
+ }
24931
+ if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
24932
+ return offWithError("DISPATCH_URL must be an http or https URL");
24933
+ }
24934
+ let source = { kind: "none" };
24935
+ if (!forced) {
24936
+ try {
24937
+ source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
24938
+ } catch (error) {
24939
+ return offWithError(messageFor(error));
24940
+ }
24941
+ }
24942
+ if (source.kind === "none") {
24943
+ let route;
24944
+ try {
24945
+ route = brokerRouteConfigured(env);
24946
+ } catch (error) {
24947
+ return offWithError(messageFor(error));
24948
+ }
24949
+ if (route.traded) {
24950
+ const brokered = withoutTrailingSlashes2(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
24951
+ return { enabled: true, url: brokered, source: { kind: "broker" } };
24952
+ }
24953
+ if (forced) {
24954
+ return offWithError(`DISPATCH_TOKEN_BROKER is set, so this session's Dispatch credential is this machine's own identity traded at the secrets broker, and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
24955
+ }
24956
+ return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
24957
+ }
24958
+ const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
24959
+ return { enabled: true, url, source };
24960
+ }
24961
+
24962
+ // ../envoy-client/src/envoy-settings.ts
24963
+ var DEFAULT_ENVOY_URL = "http://127.0.0.1:9020";
24964
+ var DEFAULT_HEARTBEAT_MS = 90000;
24965
+ var MIN_PASS_DEADLINE_MS = 30000;
24966
+ var MIN_INTERVAL_MS = 25;
24967
+ var MAX_INTERVAL_MS = 2147483647;
24968
+ function namedInterval(raw) {
24969
+ const parsed = Number(raw);
24970
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
24971
+ }
24972
+ function natsSeedFromEnvironment(env) {
24973
+ const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
24974
+ if (file !== undefined) {
24975
+ if (file === "")
24976
+ throw new Error("NATS_NKEY_SEED_FILE is set but empty");
24977
+ return {
24978
+ value: readSecretFile("NATS_NKEY_SEED_FILE", file),
24979
+ source: `NATS_NKEY_SEED_FILE (${file})`
24980
+ };
24981
+ }
24982
+ if (plain === undefined)
24983
+ return;
24984
+ const value = plain.trim();
24985
+ if (value.length === 0)
24986
+ throw new Error("NATS_NKEY_SEED is set but empty");
24987
+ return { value, source: "NATS_NKEY_SEED" };
24988
+ }
24989
+ var NO_NATS_SERVER = "Envoy has no NATS server (envoy.natsUrls, ENVOY_NATS_URL)";
24990
+ var NO_NATS_CONNECTION = "this session opens no NATS connection";
24991
+ function natsServerKey(url) {
24992
+ const match = /^([a-z][a-z0-9+.-]*):\/\/([^@/]*@)?(\[[^\]]*\]|[^:/]*)(?::(\d+))?(\/.*)?$/i.exec(url);
24993
+ if (match === null)
24994
+ return url;
24995
+ const [, scheme = "", userinfo = "", host = "", port = "4222", rest = ""] = match;
24996
+ return `${scheme.toLowerCase()}://${userinfo}${host.toLowerCase()}:${port}${rest.replace(/\/+$/, "")}`;
24997
+ }
24998
+ function natsCredential(env, section, namedNatsUrls, filePath) {
24999
+ const fromEnvironment = natsSeedFromEnvironment(env);
25000
+ if (fromEnvironment !== undefined || section.natsSeed === undefined)
25001
+ return fromEnvironment;
25002
+ if (namedNatsUrls.length > 0) {
25003
+ const servers = new Set((section.natsUrls ?? []).map(natsServerKey));
25004
+ const named = new Set(namedNatsUrls.map(natsServerKey));
25005
+ if (named.size !== servers.size || ![...named].every((server) => servers.has(server))) {
25006
+ throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set NATS_NKEY_SEED_FILE for them`);
25007
+ }
25008
+ }
25009
+ return {
25010
+ value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
25011
+ source: `envoy.natsSeed in ${filePath}`
25012
+ };
25013
+ }
25014
+ function envoySettings(env, config, options = {}) {
25015
+ if (config.kind === "failed")
25016
+ return offWithError(config.error);
25017
+ const section = config.envoy;
25018
+ if (section.enabled === false) {
25019
+ return offWithNotice(`${config.path} sets envoy.enabled to false: Envoy is off`);
25020
+ }
25021
+ const namedUrl = nonEmpty(env.ENVOY_URL);
25022
+ const namedNatsUrls = (env.ENVOY_NATS_URL ?? "").split(",").map((url) => url.trim()).filter((url) => url.length > 0);
25023
+ const addressed = namedUrl !== undefined || namedNatsUrls.length > 0 || section.url !== undefined || (section.natsUrls ?? []).length > 0 || section.enabled === true;
25024
+ if (!addressed) {
25025
+ return offWithNotice(config.missing === null ? `${config.path} names no Envoy listener or NATS server, and neither ENVOY_URL nor ENVOY_NATS_URL is set: Envoy is off` : missingConfigNotice(config.path, config.missing, "Envoy is off"));
25026
+ }
25027
+ if (namedUrl !== undefined && httpUrl2(namedUrl) === undefined) {
25028
+ return offWithError("ENVOY_URL must be an http or https URL");
25029
+ }
25030
+ const listener = section.url ?? DEFAULT_ENVOY_URL;
25031
+ const url = namedUrl ?? listener;
25032
+ let credential;
25033
+ try {
25034
+ const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
25035
+ token: section.token,
25036
+ field: "envoy.token",
25037
+ path: config.path,
25038
+ server: listener,
25039
+ checkout: false
25040
+ });
25041
+ if (source.kind === "none") {
25042
+ credential = brokerRouteConfigured(env).traded ? brokerCredential(env, options.session) : undefined;
25043
+ } else {
25044
+ credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
25045
+ }
25046
+ } catch (error) {
25047
+ return offWithError(messageFor(error));
25048
+ }
25049
+ const natsUrls = namedNatsUrls.length > 0 ? namedNatsUrls : section.natsUrls ?? [];
25050
+ let inbound;
25051
+ if (options.nats === false)
25052
+ inbound = { off: NO_NATS_CONNECTION };
25053
+ else if (natsUrls.length === 0)
25054
+ inbound = { off: NO_NATS_SERVER };
25055
+ else {
25056
+ try {
25057
+ inbound = { natsUrls, natsSeed: natsCredential(env, section, namedNatsUrls, config.path) };
25058
+ } catch (error) {
25059
+ inbound = { off: messageFor(error) };
25060
+ }
25061
+ }
25062
+ const namedHeartbeatMs = namedInterval(env.ENVOY_HEARTBEAT_MS);
25063
+ const heartbeatMs = namedHeartbeatMs === undefined ? DEFAULT_HEARTBEAT_MS : Math.min(Math.max(namedHeartbeatMs, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
25064
+ const namedPassDeadlineMs = namedInterval(env.ENVOY_PASS_DEADLINE_MS);
25065
+ return {
25066
+ enabled: true,
25067
+ url: normalizeEnvoyUrl(url),
25068
+ credential,
25069
+ inbound,
25070
+ heartbeatMs,
25071
+ passDeadlineMs: Math.min(Math.max(namedPassDeadlineMs ?? MIN_PASS_DEADLINE_MS, heartbeatMs), MAX_INTERVAL_MS),
25072
+ passDeadlineRaisedFrom: namedPassDeadlineMs !== undefined && namedPassDeadlineMs < heartbeatMs ? namedPassDeadlineMs : undefined
25073
+ };
25074
+ }
25075
+ function normalizeEnvoyUrl(value) {
25076
+ return value.replace(/\/+$/, "");
25077
+ }
25078
+
25079
+ // ../envoy-client/src/session-settings.ts
25080
+ function sessionConfigFile(harness, env) {
25081
+ try {
25082
+ return { path: envoyConfigPath(harness, env), error: null };
25083
+ } catch (error) {
25084
+ return { path: null, error: messageFor(error) };
25085
+ }
25086
+ }
25087
+ function handedConfigFile(env) {
25088
+ try {
25089
+ const handed = handedConfigPath(env);
25090
+ return handed === undefined ? null : { path: handed, error: null };
25091
+ } catch (error) {
25092
+ return { path: null, error: messageFor(error) };
25093
+ }
25094
+ }
25095
+ function sessionDispatchSettings(file, env, options) {
25096
+ if (file.path === null)
25097
+ return { dispatch: offWithError(file.error), warnings: [], missing: null };
25098
+ const config = readEnvoyConfig(file.path, env, options);
25099
+ return {
25100
+ dispatch: dispatchSettings(env, config, {
25101
+ commands: options.commands,
25102
+ session: options.session
25103
+ }),
25104
+ warnings: config.kind === "read" ? config.warnings : [],
25105
+ missing: config.kind === "read" ? config.missing : null
25106
+ };
25107
+ }
25108
+ function sessionEnvoySettings(file, env, options) {
25109
+ if (file.path === null)
25110
+ return offWithError(file.error);
25111
+ return envoySettings(env, readEnvoyConfig(file.path, env, options), {
25112
+ nats: options.nats,
25113
+ session: options.session
25114
+ });
25115
+ }
25116
+
25117
+ // ../envoy-client/src/transport.ts
25118
+ var DEFAULT_TIMEOUT_MS = 5000;
22641
25119
  var RETRY_DELAY_MS = 250;
22642
25120
  var REPLAY_TIMEOUT_MS = 1e4;
22643
25121
  var InterestWireSchema = object({
@@ -22792,14 +25270,22 @@ class EnvoySendUnconfirmedError extends Error {
22792
25270
  function createEnvoyClient(config) {
22793
25271
  const baseUrl = normalizeEnvoyUrl(config.baseUrl);
22794
25272
  const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
22795
- const apiToken = config.token;
22796
25273
  const attempts = config.retry === false ? 1 : 2;
22797
- const attemptOnce = async (url, init, deadlineMs) => {
22798
- const headers = new Headers(init.headers);
22799
- if (apiToken)
22800
- headers.set("Authorization", `Bearer ${apiToken}`);
25274
+ const credential = config.credential;
25275
+ const attemptOnce = async (url, init, deadlineMs, actingSession) => {
22801
25276
  let response;
25277
+ let unminted;
22802
25278
  try {
25279
+ const headers = new Headers(init.headers);
25280
+ let presented;
25281
+ try {
25282
+ const ready = credential?.headers(init.method ?? "GET", url, actingSession);
25283
+ presented = ready instanceof Promise ? await ready : ready;
25284
+ } catch (error) {
25285
+ unminted = error;
25286
+ }
25287
+ for (const [name, value] of Object.entries(presented ?? {}))
25288
+ headers.set(name, value);
22803
25289
  response = await config.fetch(url, {
22804
25290
  ...init,
22805
25291
  headers,
@@ -22808,6 +25294,11 @@ function createEnvoyClient(config) {
22808
25294
  } catch (error) {
22809
25295
  return { unanswered: error };
22810
25296
  }
25297
+ if (unminted !== undefined && (response.status === 401 || response.status === 403)) {
25298
+ return {
25299
+ unanswered: new Error(`${init.method ?? "GET"} ${url} answered ${response.status}, and this machine's Envoy credential could not be minted: ${messageFor(unminted)}`, { cause: unminted })
25300
+ };
25301
+ }
22811
25302
  try {
22812
25303
  return { response, body: await response.text() };
22813
25304
  } catch (error) {
@@ -22821,7 +25312,7 @@ function createEnvoyClient(config) {
22821
25312
  const url = `${baseUrl}${path}`;
22822
25313
  const tries = options.retry === false ? 1 : attempts;
22823
25314
  for (let attempt = 0;attempt < tries; attempt += 1) {
22824
- const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs);
25315
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession);
22825
25316
  if ("unanswered" in outcome) {
22826
25317
  options.onUnanswered?.();
22827
25318
  if (attempt + 1 < tries) {
@@ -22870,12 +25361,12 @@ function createEnvoyClient(config) {
22870
25361
  host: machineID(),
22871
25362
  plugin: input.plugin.name,
22872
25363
  plugin_version: input.plugin.version
22873
- }))),
25364
+ }, { actingSession: input.sessionID }))),
22874
25365
  unsubscribe: async (input) => {
22875
25366
  await post("/v1/interests/unsubscribe", {
22876
25367
  session_id: input.sessionID,
22877
25368
  topics: expandSubscriptionTopics(input.topics)
22878
- });
25369
+ }, { actingSession: input.sessionID });
22879
25370
  },
22880
25371
  getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
22881
25372
  send: async (input) => {
@@ -22893,7 +25384,8 @@ function createEnvoyClient(config) {
22893
25384
  }, {
22894
25385
  onUnanswered: () => {
22895
25386
  unanswered = true;
22896
- }
25387
+ },
25388
+ ...input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID }
22897
25389
  });
22898
25390
  response = EnvelopeResponseSchema.parse(JSON.parse(answer));
22899
25391
  } catch (error) {
@@ -22920,7 +25412,7 @@ function createEnvoyClient(config) {
22920
25412
  idempotency_key: idempotencyKey,
22921
25413
  ...messageMetadata(input),
22922
25414
  ...input.keep === undefined ? {} : { keep: input.keep }
22923
- })));
25415
+ }, input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID })));
22924
25416
  return {
22925
25417
  envelope: response,
22926
25418
  ...response.holder === undefined ? {} : { holder: response.holder },
@@ -22930,9 +25422,7 @@ function createEnvoyClient(config) {
22930
25422
  },
22931
25423
  unregisterSession: async (input) => {
22932
25424
  const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
22933
- await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, {
22934
- method: "DELETE"
22935
- });
25425
+ await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, { actingSession: input.sessionID });
22936
25426
  },
22937
25427
  setRole: async (input) => {
22938
25428
  const soft = input.soft === true;
@@ -22945,7 +25435,7 @@ function createEnvoyClient(config) {
22945
25435
  };
22946
25436
  let raw;
22947
25437
  try {
22948
- raw = await post("/v1/roles/set", body);
25438
+ raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
22949
25439
  } catch (error) {
22950
25440
  if (error instanceof EnvoyApiError && error.details.status === 409) {
22951
25441
  let answer;
@@ -22976,7 +25466,11 @@ function createEnvoyClient(config) {
22976
25466
  session_id: input.sessionID,
22977
25467
  subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
22978
25468
  ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
22979
- }, { timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS, retry: false })))
25469
+ }, {
25470
+ timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
25471
+ retry: false,
25472
+ actingSession: input.sessionID
25473
+ })))
22980
25474
  };
22981
25475
  }
22982
25476
  function waitForRetry() {
@@ -23098,7 +25592,7 @@ async function runDispatchCli(argv, rawEnv, io) {
23098
25592
  }
23099
25593
  const file = (env.DISPATCH_HOST === undefined ? null : handedConfigFile(env)) ?? sessionConfigFile(host, env);
23100
25594
  if (parsed.dryRun) {
23101
- const settings = file.path === null ? null : sessionDispatchSettings(file, env, { cwd: io.cwd }).dispatch;
25595
+ const settings = file.path === null ? null : sessionDispatchSettings(file, env, { cwd: io.cwd, session: sessionId }).dispatch;
23102
25596
  const { problems } = await checkDispatchCall({
23103
25597
  tool: parsed.tool,
23104
25598
  args: parsed.args,
@@ -23115,7 +25609,10 @@ async function runDispatchCli(argv, rawEnv, io) {
23115
25609
  if (file.path === null) {
23116
25610
  return refuse(`dispatch: ${file.error}`, USAGE, parsed.tool);
23117
25611
  }
23118
- const { dispatch: resolution, warnings } = sessionDispatchSettings(file, env, { cwd: io.cwd });
25612
+ const { dispatch: resolution, warnings } = sessionDispatchSettings(file, env, {
25613
+ cwd: io.cwd,
25614
+ session: sessionId
25615
+ });
23119
25616
  for (const warning of warnings)
23120
25617
  print(`dispatch: ${warning}`);
23121
25618
  if (!resolution.enabled) {
@@ -23171,13 +25668,17 @@ async function runDispatchCli(argv, rawEnv, io) {
23171
25668
  let topics;
23172
25669
  const readTopics = async () => {
23173
25670
  try {
23174
- const envoy = sessionEnvoySettings(file, env, { cwd: io.cwd, nats: false });
25671
+ const envoy = sessionEnvoySettings(file, env, {
25672
+ cwd: io.cwd,
25673
+ nats: false,
25674
+ session: sessionId
25675
+ });
23175
25676
  if (!envoy.enabled)
23176
25677
  return null;
23177
25678
  const listener = createEnvoyClient({
23178
25679
  baseUrl: envoy.url,
23179
25680
  fetch: io.fetchImpl ?? fetch,
23180
- token: envoy.token,
25681
+ credential: envoy.credential,
23181
25682
  timeoutMs: SUBSCRIPTIONS_TIMEOUT_MS,
23182
25683
  retry: false
23183
25684
  });