@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/envoy.js CHANGED
@@ -30702,7 +30702,7 @@ var dispatchToolSpecs = [
30702
30702
  {
30703
30703
  name: "dispatch_whoami",
30704
30704
  example: {},
30705
- 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.",
30705
+ 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.",
30706
30706
  arguments: () => ({}),
30707
30707
  strict: true
30708
30708
  },
@@ -31346,6 +31346,2432 @@ function mintMarker(store, input, now) {
31346
31346
  return file;
31347
31347
  }
31348
31348
 
31349
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
31350
+ var encoder2 = new TextEncoder;
31351
+ var decoder = new TextDecoder;
31352
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
31353
+ var MAX_INT32 = 2 ** 32;
31354
+ function concat(...buffers) {
31355
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
31356
+ const buf = new Uint8Array(size);
31357
+ let i = 0;
31358
+ for (const buffer of buffers) {
31359
+ buf.set(buffer, i);
31360
+ i += buffer.length;
31361
+ }
31362
+ return buf;
31363
+ }
31364
+ function encode3(string) {
31365
+ const bytes = new Uint8Array(string.length);
31366
+ for (let i = 0;i < string.length; i++) {
31367
+ const code = string.charCodeAt(i);
31368
+ if (code > 127) {
31369
+ throw new TypeError("non-ASCII string encountered in encode()");
31370
+ }
31371
+ bytes[i] = code;
31372
+ }
31373
+ return bytes;
31374
+ }
31375
+
31376
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
31377
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
31378
+ function checkUsage(key, usage) {
31379
+ if (usage && !key.usages.includes(usage)) {
31380
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
31381
+ }
31382
+ }
31383
+ function checkModulusLength(alg, key) {
31384
+ const { modulusLength } = key.algorithm;
31385
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
31386
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
31387
+ }
31388
+ }
31389
+ function checkCryptoKey(key, expected, usage) {
31390
+ const algorithm = key.algorithm;
31391
+ if (algorithm.name !== expected.name) {
31392
+ throw unusable(expected.name);
31393
+ }
31394
+ if (expected.hash && algorithm.hash?.name !== expected.hash) {
31395
+ throw unusable(expected.hash, "algorithm.hash");
31396
+ }
31397
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
31398
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
31399
+ }
31400
+ if (expected.length !== undefined && algorithm.length !== expected.length) {
31401
+ throw unusable(expected.length, "algorithm.length");
31402
+ }
31403
+ checkUsage(key, usage);
31404
+ }
31405
+
31406
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
31407
+ function message(msg, actual, ...types) {
31408
+ if (types.length > 2) {
31409
+ const last = types.pop();
31410
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
31411
+ } else if (types.length === 2) {
31412
+ msg += `one of type ${types[0]} or ${types[1]}.`;
31413
+ } else {
31414
+ msg += `of type ${types[0]}.`;
31415
+ }
31416
+ if (actual == null) {
31417
+ msg += ` Received ${actual}`;
31418
+ } else if (typeof actual === "function" && actual.name) {
31419
+ msg += ` Received function ${actual.name}`;
31420
+ } else if (typeof actual === "object" && actual != null) {
31421
+ if (actual.constructor?.name) {
31422
+ msg += ` Received an instance of ${actual.constructor.name}`;
31423
+ }
31424
+ }
31425
+ return msg;
31426
+ }
31427
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
31428
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
31429
+
31430
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
31431
+ class JOSEError extends Error {
31432
+ static code = "ERR_JOSE_GENERIC";
31433
+ code = "ERR_JOSE_GENERIC";
31434
+ constructor(message, options) {
31435
+ super(message, options);
31436
+ this.name = this.constructor.name;
31437
+ Error.captureStackTrace?.(this, this.constructor);
31438
+ }
31439
+ }
31440
+ class JOSENotSupported extends JOSEError {
31441
+ static code = "ERR_JOSE_NOT_SUPPORTED";
31442
+ code = "ERR_JOSE_NOT_SUPPORTED";
31443
+ }
31444
+ class JWSInvalid extends JOSEError {
31445
+ static code = "ERR_JWS_INVALID";
31446
+ code = "ERR_JWS_INVALID";
31447
+ }
31448
+
31449
+ class JWTInvalid extends JOSEError {
31450
+ static code = "ERR_JWT_INVALID";
31451
+ code = "ERR_JWT_INVALID";
31452
+ }
31453
+
31454
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
31455
+ var isCryptoKey = (key) => {
31456
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
31457
+ return true;
31458
+ try {
31459
+ return key instanceof CryptoKey;
31460
+ } catch {
31461
+ return false;
31462
+ }
31463
+ };
31464
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
31465
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
31466
+
31467
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
31468
+ function encodeBase64(input) {
31469
+ if (Uint8Array.prototype.toBase64) {
31470
+ return input.toBase64();
31471
+ }
31472
+ const CHUNK_SIZE = 32768;
31473
+ const arr = [];
31474
+ for (let i = 0;i < input.length; i += CHUNK_SIZE) {
31475
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
31476
+ }
31477
+ return btoa(arr.join(""));
31478
+ }
31479
+ function decodeBase64(encoded) {
31480
+ if (Uint8Array.fromBase64) {
31481
+ return Uint8Array.fromBase64(encoded);
31482
+ }
31483
+ const binary = atob(encoded);
31484
+ const bytes = new Uint8Array(binary.length);
31485
+ for (let i = 0;i < binary.length; i++) {
31486
+ bytes[i] = binary.charCodeAt(i);
31487
+ }
31488
+ return bytes;
31489
+ }
31490
+
31491
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
31492
+ var invalid = "The input to be decoded is not correctly encoded.";
31493
+ function decode3(input) {
31494
+ if (Uint8Array.fromBase64) {
31495
+ try {
31496
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
31497
+ alphabet: "base64url"
31498
+ });
31499
+ } catch (cause) {
31500
+ throw new TypeError(invalid, { cause });
31501
+ }
31502
+ }
31503
+ let encoded = input;
31504
+ if (encoded instanceof Uint8Array) {
31505
+ encoded = decoder.decode(encoded);
31506
+ }
31507
+ if (encoded.includes("+") || encoded.includes("/")) {
31508
+ throw new TypeError(invalid);
31509
+ }
31510
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
31511
+ try {
31512
+ return decodeBase64(encoded);
31513
+ } catch {
31514
+ throw new TypeError(invalid);
31515
+ }
31516
+ }
31517
+ function encode4(input) {
31518
+ let unencoded = input;
31519
+ if (typeof unencoded === "string") {
31520
+ unencoded = encoder2.encode(unencoded);
31521
+ }
31522
+ if (Uint8Array.prototype.toBase64) {
31523
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
31524
+ }
31525
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
31526
+ }
31527
+
31528
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
31529
+ function isObject2(input) {
31530
+ if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
31531
+ return false;
31532
+ }
31533
+ const prototype = Object.getPrototypeOf(input);
31534
+ if (prototype === null) {
31535
+ return true;
31536
+ }
31537
+ let proto = prototype;
31538
+ while (Object.getPrototypeOf(proto) !== null) {
31539
+ proto = Object.getPrototypeOf(proto);
31540
+ }
31541
+ return prototype === proto;
31542
+ }
31543
+ function isDisjoint(...headers) {
31544
+ const parameters = new Set;
31545
+ for (const header of headers) {
31546
+ if (!header)
31547
+ continue;
31548
+ for (const parameter of Object.keys(header)) {
31549
+ if (parameters.has(parameter)) {
31550
+ return false;
31551
+ }
31552
+ parameters.add(parameter);
31553
+ }
31554
+ }
31555
+ return true;
31556
+ }
31557
+ var isJWK = (key) => isObject2(key) && typeof key.kty === "string";
31558
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
31559
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
31560
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
31561
+
31562
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/helpers.js
31563
+ var unprotected = Symbol();
31564
+ function assertNotSet(value, name) {
31565
+ if (value) {
31566
+ throw new TypeError(`${name} can only be called once`);
31567
+ }
31568
+ }
31569
+
31570
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwk_to_key.js
31571
+ async function jwkToKey(entry, jwk) {
31572
+ if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== undefined) {
31573
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
31574
+ }
31575
+ if (!entry.kty.includes(jwk.kty)) {
31576
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
31577
+ }
31578
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle;
31579
+ const isPrivate = !!(jwk.d || jwk.priv);
31580
+ const keyData = { ...jwk };
31581
+ if (keyData.kty !== "AKP") {
31582
+ delete keyData.alg;
31583
+ }
31584
+ delete keyData.use;
31585
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
31586
+ }
31587
+
31588
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key.js
31589
+ var tag = (key) => key[Symbol.toStringTag];
31590
+ var jwkMatchesOp = (entry, key, usage) => {
31591
+ const { alg } = entry;
31592
+ if (key.use !== undefined) {
31593
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
31594
+ if (key.use !== expected) {
31595
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
31596
+ }
31597
+ }
31598
+ if (key.alg !== undefined && key.alg !== alg) {
31599
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
31600
+ }
31601
+ if (Array.isArray(key.key_ops)) {
31602
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
31603
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
31604
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
31605
+ }
31606
+ }
31607
+ };
31608
+ function checkKeyType(entry, key, usage) {
31609
+ const { alg, secret } = entry;
31610
+ const privateKey = usage === "decrypt" || usage === "sign";
31611
+ if (secret && key instanceof Uint8Array)
31612
+ return [BYTES, key];
31613
+ if (isJWK(key)) {
31614
+ if (secret ? !isSecretJWK(key) : !(privateKey ? isPrivateJWK(key) : isPublicJWK(key))) {
31615
+ 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`);
31616
+ }
31617
+ jwkMatchesOp(entry, key, usage);
31618
+ return [JWK, key];
31619
+ }
31620
+ if (!isKeyLike(key)) {
31621
+ throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
31622
+ }
31623
+ if (secret) {
31624
+ if (key.type !== "secret") {
31625
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
31626
+ }
31627
+ } else {
31628
+ if (key.type === "secret") {
31629
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
31630
+ }
31631
+ const expectedType = privateKey ? "private" : "public";
31632
+ if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
31633
+ const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
31634
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
31635
+ }
31636
+ }
31637
+ return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
31638
+ }
31639
+ var BYTES = 0;
31640
+ var CRYPTO = 1;
31641
+ var KEYOBJECT = 2;
31642
+ var JWK = 3;
31643
+ var cache;
31644
+ var nist = {
31645
+ __proto__: null,
31646
+ prime256v1: "P-256",
31647
+ secp384r1: "P-384",
31648
+ secp521r1: "P-521"
31649
+ };
31650
+ function cached2(key, alg, value) {
31651
+ cache ||= new WeakMap;
31652
+ const entry = cache.get(key);
31653
+ if (value) {
31654
+ if (entry) {
31655
+ entry[alg] = value;
31656
+ } else {
31657
+ cache.set(key, { __proto__: null, [alg]: value });
31658
+ }
31659
+ }
31660
+ return value ?? entry?.[alg];
31661
+ }
31662
+ var handleJWK = async (key, jwk, entry) => cached2(key, entry.alg) ?? cached2(key, entry.alg, await jwkToKey(entry, { ...jwk, alg: entry.alg }));
31663
+ var handleKeyObject = (keyObject, entry) => {
31664
+ const hit = cached2(keyObject, entry.alg);
31665
+ if (hit)
31666
+ return hit;
31667
+ const isPublic = keyObject.type === "public";
31668
+ const usages = entry.usages[isPublic ? 0 : 1];
31669
+ const { asymmetricKeyType } = keyObject;
31670
+ const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
31671
+ const params = entry.resolve?.({ crv, asymmetricKeyType }) ?? entry.subtle;
31672
+ return cached2(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
31673
+ };
31674
+ async function prepareKey(entry, key, usage) {
31675
+ const tagged = checkKeyType(entry, key, usage);
31676
+ switch (tagged[0]) {
31677
+ case BYTES:
31678
+ case CRYPTO:
31679
+ return tagged[1];
31680
+ case JWK: {
31681
+ const key = tagged[1];
31682
+ if (key.k) {
31683
+ return decode3(key.k);
31684
+ }
31685
+ if (!Object.isFrozen(key)) {
31686
+ const { key_ops } = key;
31687
+ if (Array.isArray(key_ops))
31688
+ Object.freeze(key_ops);
31689
+ Object.freeze(key);
31690
+ }
31691
+ return handleJWK(key, key, entry);
31692
+ }
31693
+ case KEYOBJECT: {
31694
+ const keyObject = tagged[1];
31695
+ if (keyObject.type === "secret") {
31696
+ return keyObject.export();
31697
+ }
31698
+ if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
31699
+ return handleKeyObject(keyObject, entry);
31700
+ }
31701
+ return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
31702
+ }
31703
+ }
31704
+ }
31705
+
31706
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_descriptor.js
31707
+ function table(entries) {
31708
+ const out = { __proto__: null };
31709
+ for (const alg in entries) {
31710
+ out[alg] = { ...entries[alg], alg };
31711
+ }
31712
+ return out;
31713
+ }
31714
+
31715
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwe_algorithms.js
31716
+ var wrap = [
31717
+ ["encrypt", "wrapKey"],
31718
+ ["decrypt", "unwrapKey"]
31719
+ ];
31720
+ var derive = [[], ["deriveBits"]];
31721
+ var none = [[], []];
31722
+ function rsaes(bits) {
31723
+ return {
31724
+ kty: ["RSA"],
31725
+ subtle: { name: "RSA-OAEP", hash: `SHA-${bits}` },
31726
+ usages: wrap,
31727
+ ops: ["wrapKey", "unwrapKey"]
31728
+ };
31729
+ }
31730
+ function ecdh() {
31731
+ return {
31732
+ kty: ["EC", "OKP"],
31733
+ subtle: { name: "ECDH" },
31734
+ resolve: ({ kty, crv, asymmetricKeyType }) => {
31735
+ if (crv === "X25519" || asymmetricKeyType === "x25519") {
31736
+ return { name: "X25519" };
31737
+ }
31738
+ if (kty === "OKP") {
31739
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
31740
+ }
31741
+ return { name: "ECDH", namedCurve: crv };
31742
+ },
31743
+ usages: derive,
31744
+ ops: [undefined, "deriveBits"]
31745
+ };
31746
+ }
31747
+ function aeskw(bits, gcm = false) {
31748
+ return {
31749
+ kty: ["oct"],
31750
+ secret: true,
31751
+ subtle: { name: gcm ? "AES-GCM" : "AES-KW", length: bits },
31752
+ usages: none,
31753
+ ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
31754
+ };
31755
+ }
31756
+ function pbes2() {
31757
+ return {
31758
+ kty: ["oct"],
31759
+ secret: true,
31760
+ subtle: { name: "PBKDF2" },
31761
+ usages: none,
31762
+ ops: ["deriveBits", "deriveBits"]
31763
+ };
31764
+ }
31765
+ var JWE = table({
31766
+ dir: {
31767
+ kty: ["oct"],
31768
+ secret: true,
31769
+ subtle: { name: "AES-GCM" },
31770
+ usages: none,
31771
+ ops: ["encrypt", "decrypt"]
31772
+ },
31773
+ "RSA-OAEP": rsaes(1),
31774
+ "RSA-OAEP-256": rsaes(256),
31775
+ "RSA-OAEP-384": rsaes(384),
31776
+ "RSA-OAEP-512": rsaes(512),
31777
+ "ECDH-ES": ecdh(),
31778
+ "ECDH-ES+A128KW": ecdh(),
31779
+ "ECDH-ES+A192KW": ecdh(),
31780
+ "ECDH-ES+A256KW": ecdh(),
31781
+ A128KW: aeskw(128),
31782
+ A192KW: aeskw(192),
31783
+ A256KW: aeskw(256),
31784
+ A128GCMKW: aeskw(128, true),
31785
+ A192GCMKW: aeskw(192, true),
31786
+ A256GCMKW: aeskw(256, true),
31787
+ "PBES2-HS256+A128KW": pbes2(),
31788
+ "PBES2-HS384+A192KW": pbes2(),
31789
+ "PBES2-HS512+A256KW": pbes2()
31790
+ });
31791
+ var contentOps = ["encrypt", "decrypt"];
31792
+ function contentEncryption(bits, cbc = false) {
31793
+ return {
31794
+ kty: ["oct"],
31795
+ secret: true,
31796
+ subtle: { name: cbc ? "AES-CBC" : "AES-GCM", length: bits },
31797
+ usages: none,
31798
+ ops: contentOps,
31799
+ cekBits: bits,
31800
+ ivBits: cbc ? 128 : 96,
31801
+ cbc
31802
+ };
31803
+ }
31804
+ var ENC = table({
31805
+ A128GCM: contentEncryption(128),
31806
+ A192GCM: contentEncryption(192),
31807
+ A256GCM: contentEncryption(256),
31808
+ "A128CBC-HS256": contentEncryption(256, true),
31809
+ "A192CBC-HS384": contentEncryption(384, true),
31810
+ "A256CBC-HS512": contentEncryption(512, true)
31811
+ });
31812
+
31813
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/options.js
31814
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
31815
+ function validateCritDuplicates(Err, protectedHeader) {
31816
+ const { crit } = protectedHeader ?? {};
31817
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length) {
31818
+ throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
31819
+ }
31820
+ }
31821
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
31822
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
31823
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
31824
+ }
31825
+ if (!protectedHeader || protectedHeader.crit === undefined) {
31826
+ return [];
31827
+ }
31828
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
31829
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
31830
+ }
31831
+ const recognized = recognizedOption === undefined ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
31832
+ for (const parameter of protectedHeader.crit) {
31833
+ if (!(parameter in recognized)) {
31834
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
31835
+ }
31836
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === undefined) {
31837
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
31838
+ }
31839
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === undefined)) {
31840
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
31841
+ }
31842
+ }
31843
+ return protectedHeader.crit;
31844
+ }
31845
+
31846
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/signing.js
31847
+ async function getSigKey(entry, key, usage) {
31848
+ if (key instanceof Uint8Array) {
31849
+ return crypto.subtle.importKey("raw", key, entry.subtle, false, [
31850
+ usage
31851
+ ]);
31852
+ }
31853
+ checkCryptoKey(key, entry.subtle, usage);
31854
+ if (entry.minRsaBits)
31855
+ checkModulusLength(entry.alg, key);
31856
+ return key;
31857
+ }
31858
+ async function sign(entry, key, data) {
31859
+ const cryptoKey = await getSigKey(entry, key, "sign");
31860
+ const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
31861
+ return new Uint8Array(signature);
31862
+ }
31863
+
31864
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_algorithms.js
31865
+ var sig = [["verify"], ["sign"]];
31866
+ function hmac(bits) {
31867
+ const subtle = { name: "HMAC", hash: `SHA-${bits}` };
31868
+ return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
31869
+ }
31870
+ function rsa(bits, saltLength) {
31871
+ const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
31872
+ const subtle = { name, hash: `SHA-${bits}` };
31873
+ return {
31874
+ kty: ["RSA"],
31875
+ subtle,
31876
+ signing: saltLength ? { ...subtle, saltLength } : subtle,
31877
+ usages: sig,
31878
+ minRsaBits: 2048
31879
+ };
31880
+ }
31881
+ function ecdsa(crv, bits) {
31882
+ return {
31883
+ kty: ["EC"],
31884
+ crv,
31885
+ subtle: { name: "ECDSA", namedCurve: crv },
31886
+ signing: { name: "ECDSA", hash: `SHA-${bits}` },
31887
+ usages: sig
31888
+ };
31889
+ }
31890
+ function eddsa() {
31891
+ const subtle = { name: "Ed25519" };
31892
+ return {
31893
+ kty: ["OKP"],
31894
+ crv: "Ed25519",
31895
+ subtle,
31896
+ signing: subtle,
31897
+ usages: sig
31898
+ };
31899
+ }
31900
+ function mldsa(bits) {
31901
+ const name = `ML-DSA-${bits}`;
31902
+ const subtle = { name };
31903
+ return {
31904
+ kty: ["AKP"],
31905
+ subtle,
31906
+ signing: subtle,
31907
+ usages: sig
31908
+ };
31909
+ }
31910
+ var JWS = table({
31911
+ HS256: hmac(256),
31912
+ HS384: hmac(384),
31913
+ HS512: hmac(512),
31914
+ RS256: rsa(256),
31915
+ RS384: rsa(384),
31916
+ RS512: rsa(512),
31917
+ PS256: rsa(256, 32),
31918
+ PS384: rsa(384, 48),
31919
+ PS512: rsa(512, 64),
31920
+ ES256: ecdsa("P-256", 256),
31921
+ ES384: ecdsa("P-384", 384),
31922
+ ES512: ecdsa("P-521", 512),
31923
+ EdDSA: eddsa(),
31924
+ Ed25519: eddsa(),
31925
+ "ML-DSA-44": mldsa(44),
31926
+ "ML-DSA-65": mldsa(65),
31927
+ "ML-DSA-87": mldsa(87)
31928
+ });
31929
+ function jwsAlgorithm(alg) {
31930
+ const entry = typeof alg === "string" ? JWS[alg] : undefined;
31931
+ if (!entry) {
31932
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
31933
+ }
31934
+ return entry;
31935
+ }
31936
+
31937
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
31938
+ var epoch = (date) => Math.floor(date.getTime() / 1000);
31939
+ var multipliers = {
31940
+ s: 1,
31941
+ m: 60,
31942
+ h: 3600,
31943
+ d: 86400,
31944
+ w: 604800,
31945
+ y: 31557600
31946
+ };
31947
+ 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;
31948
+ function secs(str) {
31949
+ const matched = REGEX.exec(str);
31950
+ if (!matched || matched[4] && matched[1]) {
31951
+ throw new TypeError("Invalid time period format");
31952
+ }
31953
+ const value = parseFloat(matched[2]);
31954
+ const numericDate = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
31955
+ if (matched[1] === "-" || matched[4] === "ago") {
31956
+ return -numericDate;
31957
+ }
31958
+ return numericDate;
31959
+ }
31960
+ function validateInput(label, input) {
31961
+ if (!Number.isFinite(input)) {
31962
+ throw new TypeError(`Invalid ${label} input`);
31963
+ }
31964
+ return input;
31965
+ }
31966
+ function numericDate(value, label) {
31967
+ if (typeof value === "number")
31968
+ return validateInput(label, value);
31969
+ if (value instanceof Date)
31970
+ return validateInput(label, epoch(value));
31971
+ return epoch(new Date) + secs(value);
31972
+ }
31973
+ class JWTClaimsBuilder {
31974
+ #payload;
31975
+ constructor(payload) {
31976
+ if (!isObject2(payload)) {
31977
+ throw new TypeError("JWT Claims Set MUST be an object");
31978
+ }
31979
+ this.#payload = structuredClone(payload);
31980
+ }
31981
+ data() {
31982
+ return encoder2.encode(JSON.stringify(this.#payload));
31983
+ }
31984
+ get iss() {
31985
+ return this.#payload.iss;
31986
+ }
31987
+ set iss(value) {
31988
+ this.#payload.iss = value;
31989
+ }
31990
+ get sub() {
31991
+ return this.#payload.sub;
31992
+ }
31993
+ set sub(value) {
31994
+ this.#payload.sub = value;
31995
+ }
31996
+ get aud() {
31997
+ return this.#payload.aud;
31998
+ }
31999
+ set aud(value) {
32000
+ this.#payload.aud = value;
32001
+ }
32002
+ set jti(value) {
32003
+ this.#payload.jti = value;
32004
+ }
32005
+ set nbf(value) {
32006
+ this.#payload.nbf = numericDate(value, "setNotBefore");
32007
+ }
32008
+ set exp(value) {
32009
+ this.#payload.exp = numericDate(value, "setExpirationTime");
32010
+ }
32011
+ set iat(value) {
32012
+ if (value === undefined) {
32013
+ this.#payload.iat = epoch(new Date);
32014
+ } else if (typeof value === "string") {
32015
+ this.#payload.iat = validateInput("setIssuedAt", epoch(new Date) + secs(value));
32016
+ } else {
32017
+ this.#payload.iat = numericDate(value, "setIssuedAt");
32018
+ }
32019
+ }
32020
+ }
32021
+
32022
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_sign.js
32023
+ function unencodedPayload(protectedHeader) {
32024
+ return protectedHeader?.b64 === false && Array.isArray(protectedHeader.crit) && protectedHeader.crit.includes("b64");
32025
+ }
32026
+ async function createSignature(input, key) {
32027
+ const { protectedHeader, unprotectedHeader } = input;
32028
+ if (!protectedHeader && !unprotectedHeader) {
32029
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
32030
+ }
32031
+ if (!isDisjoint(protectedHeader, unprotectedHeader)) {
32032
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
32033
+ }
32034
+ const joseHeader = { ...protectedHeader, ...unprotectedHeader };
32035
+ validateCritDuplicates(JWSInvalid, protectedHeader);
32036
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, input.crit, protectedHeader, joseHeader);
32037
+ let b64 = true;
32038
+ if (extensions.includes("b64")) {
32039
+ b64 = protectedHeader.b64;
32040
+ if (typeof b64 !== "boolean") {
32041
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
32042
+ }
32043
+ }
32044
+ const { alg } = joseHeader;
32045
+ if (typeof alg !== "string" || !alg) {
32046
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
32047
+ }
32048
+ const entry = jwsAlgorithm(alg);
32049
+ let payloadS;
32050
+ let payloadB;
32051
+ if (b64) {
32052
+ const encoded = input.encoded ??= [];
32053
+ encoded[0] ??= encode4(input.payload);
32054
+ encoded[1] ??= encode3(encoded[0]);
32055
+ payloadS = encoded[0];
32056
+ payloadB = encoded[1];
32057
+ } else {
32058
+ payloadB = input.payload;
32059
+ payloadS = "";
32060
+ }
32061
+ let protectedHeaderString;
32062
+ let protectedHeaderBytes;
32063
+ if (protectedHeader) {
32064
+ protectedHeaderString = encode4(JSON.stringify(protectedHeader));
32065
+ protectedHeaderBytes = encode3(protectedHeaderString);
32066
+ } else {
32067
+ protectedHeaderString = "";
32068
+ protectedHeaderBytes = new Uint8Array;
32069
+ }
32070
+ const data = concat(protectedHeaderBytes, encode3("."), payloadB);
32071
+ const k = await prepareKey(entry, key, "sign");
32072
+ const signature = await sign(entry, k, data);
32073
+ const jws = {
32074
+ signature: encode4(signature),
32075
+ payload: payloadS
32076
+ };
32077
+ if (protectedHeader) {
32078
+ jws.protected = protectedHeaderString;
32079
+ }
32080
+ if (unprotectedHeader) {
32081
+ jws.header = unprotectedHeader;
32082
+ }
32083
+ return jws;
32084
+ }
32085
+
32086
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/flattened/sign.js
32087
+ class FlattenedSign {
32088
+ #payload;
32089
+ #protectedHeader;
32090
+ #unprotectedHeader;
32091
+ constructor(payload) {
32092
+ if (!(payload instanceof Uint8Array)) {
32093
+ throw new TypeError("payload must be an instance of Uint8Array");
32094
+ }
32095
+ this.#payload = payload;
32096
+ }
32097
+ setProtectedHeader(protectedHeader) {
32098
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
32099
+ this.#protectedHeader = protectedHeader;
32100
+ return this;
32101
+ }
32102
+ setUnprotectedHeader(unprotectedHeader) {
32103
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
32104
+ this.#unprotectedHeader = unprotectedHeader;
32105
+ return this;
32106
+ }
32107
+ async sign(key, options) {
32108
+ return createSignature({
32109
+ payload: this.#payload,
32110
+ protectedHeader: this.#protectedHeader,
32111
+ unprotectedHeader: this.#unprotectedHeader,
32112
+ crit: options?.crit
32113
+ }, key);
32114
+ }
32115
+ }
32116
+
32117
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/compact/sign.js
32118
+ class CompactSign {
32119
+ #flattened;
32120
+ #protectedHeader;
32121
+ constructor(payload) {
32122
+ this.#flattened = new FlattenedSign(payload);
32123
+ }
32124
+ setProtectedHeader(protectedHeader) {
32125
+ this.#flattened.setProtectedHeader(protectedHeader);
32126
+ this.#protectedHeader = protectedHeader;
32127
+ return this;
32128
+ }
32129
+ async sign(key, options) {
32130
+ if (unencodedPayload(this.#protectedHeader)) {
32131
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
32132
+ }
32133
+ const jws = await this.#flattened.sign(key, options);
32134
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
32135
+ }
32136
+ }
32137
+
32138
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jwt/sign.js
32139
+ class SignJWT {
32140
+ #protectedHeader;
32141
+ #jwt;
32142
+ constructor(payload = {}) {
32143
+ this.#jwt = new JWTClaimsBuilder(payload);
32144
+ }
32145
+ setIssuer(issuer) {
32146
+ this.#jwt.iss = issuer;
32147
+ return this;
32148
+ }
32149
+ setSubject(subject) {
32150
+ this.#jwt.sub = subject;
32151
+ return this;
32152
+ }
32153
+ setAudience(audience) {
32154
+ this.#jwt.aud = audience;
32155
+ return this;
32156
+ }
32157
+ setJti(jwtId) {
32158
+ this.#jwt.jti = jwtId;
32159
+ return this;
32160
+ }
32161
+ setNotBefore(input) {
32162
+ this.#jwt.nbf = input;
32163
+ return this;
32164
+ }
32165
+ setExpirationTime(input) {
32166
+ this.#jwt.exp = input;
32167
+ return this;
32168
+ }
32169
+ setIssuedAt(input) {
32170
+ this.#jwt.iat = input;
32171
+ return this;
32172
+ }
32173
+ setProtectedHeader(protectedHeader) {
32174
+ this.#protectedHeader = protectedHeader;
32175
+ return this;
32176
+ }
32177
+ async sign(key, options) {
32178
+ const sig = new CompactSign(this.#jwt.data());
32179
+ sig.setProtectedHeader(this.#protectedHeader);
32180
+ if (unencodedPayload(this.#protectedHeader)) {
32181
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
32182
+ }
32183
+ return sig.sign(key, options);
32184
+ }
32185
+ }
32186
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_algorithm.js
32187
+ var algArgument = '"alg" (Algorithm)';
32188
+ function unsupportedAlg(source = 'JWK "alg" (Algorithm) Parameter') {
32189
+ throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
32190
+ }
32191
+ function keyAlgorithm(alg, source) {
32192
+ return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : undefined) ?? unsupportedAlg(source);
32193
+ }
32194
+
32195
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
32196
+ function omitUndefinedProperties(jwk) {
32197
+ return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
32198
+ }
32199
+ async function keyToJWK(key) {
32200
+ if (isKeyObject(key)) {
32201
+ if (key.type === "secret") {
32202
+ key = key.export();
32203
+ } else {
32204
+ return key.export({ format: "jwk" });
32205
+ }
32206
+ }
32207
+ if (key instanceof Uint8Array) {
32208
+ return {
32209
+ kty: "oct",
32210
+ k: encode4(key)
32211
+ };
32212
+ }
32213
+ if (!isCryptoKey(key)) {
32214
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
32215
+ }
32216
+ if (!key.extractable) {
32217
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
32218
+ }
32219
+ const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
32220
+ if (jwk.kty === "AKP") {
32221
+ jwk.alg = alg;
32222
+ }
32223
+ return jwk;
32224
+ }
32225
+ function exportJWK(key) {
32226
+ return keyToJWK(key);
32227
+ }
32228
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/generate_key_pair.js
32229
+ function getModulusLengthOption(options) {
32230
+ const modulusLength = options?.modulusLength ?? 2048;
32231
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
32232
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
32233
+ }
32234
+ return modulusLength;
32235
+ }
32236
+ async function generateKeyPair(alg, options) {
32237
+ const entry = keyAlgorithm(alg, algArgument);
32238
+ if (entry.secret) {
32239
+ unsupportedAlg(algArgument);
32240
+ }
32241
+ let algorithm;
32242
+ if (entry.resolve) {
32243
+ const crv = options?.crv ?? "P-256";
32244
+ switch (crv) {
32245
+ case "P-256":
32246
+ case "P-384":
32247
+ case "P-521":
32248
+ algorithm = { name: "ECDH", namedCurve: crv };
32249
+ break;
32250
+ case "X25519":
32251
+ algorithm = { name: "X25519" };
32252
+ break;
32253
+ default:
32254
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
32255
+ }
32256
+ } else {
32257
+ if (entry.crv !== undefined && options?.crv !== undefined && options.crv !== entry.crv) {
32258
+ throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);
32259
+ }
32260
+ algorithm = entry.kty[0] === "RSA" ? {
32261
+ ...entry.subtle,
32262
+ publicExponent: Uint8Array.of(1, 0, 1),
32263
+ modulusLength: getModulusLengthOption(options)
32264
+ } : entry.subtle;
32265
+ }
32266
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [
32267
+ ...entry.usages[1],
32268
+ ...entry.usages[0]
32269
+ ]);
32270
+ }
32271
+ // ../broker-client/src/dpop.ts
32272
+ var ALGORITHM = "ES256";
32273
+ function targetUri(url) {
32274
+ const parsed = new URL(url);
32275
+ parsed.search = "";
32276
+ parsed.hash = "";
32277
+ return parsed.toString();
32278
+ }
32279
+ async function accessTokenHash(accessToken) {
32280
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
32281
+ return Buffer.from(digest).toString("base64url");
32282
+ }
32283
+ async function newDpopKey() {
32284
+ const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
32285
+ const publicJwk = await exportJWK(publicKey);
32286
+ return {
32287
+ publicJwk,
32288
+ async proof(request) {
32289
+ const claims = {
32290
+ jti: crypto.randomUUID(),
32291
+ htm: request.method.toUpperCase(),
32292
+ htu: targetUri(request.url),
32293
+ iat: Math.floor(Date.now() / 1000)
32294
+ };
32295
+ if (request.nonce !== undefined && request.nonce !== "")
32296
+ claims["nonce"] = request.nonce;
32297
+ if (request.accessToken !== undefined && request.accessToken !== "") {
32298
+ claims["ath"] = await accessTokenHash(request.accessToken);
32299
+ }
32300
+ return await new SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk }).sign(privateKey);
32301
+ }
32302
+ };
32303
+ }
32304
+
32305
+ // ../broker-client/src/metadata-identity.ts
32306
+ import { Agent, request } from "http";
32307
+
32308
+ // ../broker-client/src/wire.ts
32309
+ var TOKEN_PATH = "/v1/oauth/token";
32310
+ var GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
32311
+ var EXCHANGE_CLIENT_ID = "dispatch-token-exchange";
32312
+ var FORM_SESSION = "session";
32313
+ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
32314
+ var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
32315
+ var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
32316
+ var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
32317
+ var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
32318
+ var TOKEN_TYPE_DPOP = "DPoP";
32319
+
32320
+ // ../broker-client/src/metadata-identity.ts
32321
+ var METADATA_HOST_VAR = "GCE_METADATA_HOST";
32322
+ var DEFAULT_METADATA_HOST = "metadata.google.internal";
32323
+ var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
32324
+ var TIMEOUT_MS = 1e4;
32325
+ var MAX_ANSWER_BYTES = 1 << 20;
32326
+ var agent = new Agent({ keepAlive: false });
32327
+ function tokenUrl(audience, env) {
32328
+ const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
32329
+ return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
32330
+ }
32331
+ function get(url, signal) {
32332
+ const { promise, resolve, reject } = Promise.withResolvers();
32333
+ const call = request(url, {
32334
+ agent,
32335
+ method: "GET",
32336
+ headers: { "Metadata-Flavor": "Google" },
32337
+ timeout: TIMEOUT_MS,
32338
+ ...signal === undefined ? {} : { signal }
32339
+ }, (answer) => {
32340
+ const chunks = [];
32341
+ let read = 0;
32342
+ answer.on("data", (chunk) => {
32343
+ read += chunk.length;
32344
+ if (read <= MAX_ANSWER_BYTES)
32345
+ chunks.push(chunk);
32346
+ });
32347
+ answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
32348
+ answer.on("error", reject);
32349
+ });
32350
+ call.on("timeout", () => call.destroy(new Error(`no answer within ${TIMEOUT_MS} ms`)));
32351
+ call.on("error", reject);
32352
+ call.end();
32353
+ return promise;
32354
+ }
32355
+ function metadataIdentity(audience, env = process.env) {
32356
+ return {
32357
+ async read(signal) {
32358
+ const url = tokenUrl(audience, env);
32359
+ let answer;
32360
+ try {
32361
+ answer = await get(url, signal);
32362
+ } catch (error) {
32363
+ throw new Error(`the metadata server at ${url} could not be reached (${METADATA_HOST_VAR} names its host): ${error.message}`);
32364
+ }
32365
+ if (answer.status < 200 || answer.status > 299) {
32366
+ throw new Error(`the metadata server at ${url} answered HTTP ${answer.status}`);
32367
+ }
32368
+ const token = answer.body.trim();
32369
+ if (token === "") {
32370
+ throw new Error(`the metadata server at ${url} answered an empty identity token`);
32371
+ }
32372
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
32373
+ },
32374
+ describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
32375
+ };
32376
+ }
32377
+
32378
+ // ../broker-client/src/projected-token.ts
32379
+ import { readFile } from "fs/promises";
32380
+ function projectedToken(path) {
32381
+ return {
32382
+ async read(signal) {
32383
+ let contents;
32384
+ try {
32385
+ contents = await readFile(path, {
32386
+ encoding: "utf8",
32387
+ ...signal === undefined ? {} : { signal }
32388
+ });
32389
+ } catch (error) {
32390
+ throw new Error(`read the projected service-account token ${path}: ${error.message}`);
32391
+ }
32392
+ const token = contents.trim();
32393
+ if (token === "")
32394
+ throw new Error(`the projected service-account token ${path} is empty`);
32395
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
32396
+ },
32397
+ describe: () => `the projected service-account token ${path}`
32398
+ };
32399
+ }
32400
+
32401
+ // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
32402
+ var USER_AGENT;
32403
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
32404
+ const NAME = "oauth4webapi";
32405
+ const VERSION = "v3.8.8";
32406
+ USER_AGENT = `${NAME}/${VERSION}`;
32407
+ }
32408
+ function looseInstanceOf(input, expected) {
32409
+ if (input == null) {
32410
+ return false;
32411
+ }
32412
+ try {
32413
+ return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
32414
+ } catch {
32415
+ return false;
32416
+ }
32417
+ }
32418
+ var ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
32419
+ var ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
32420
+ function CodedTypeError(message, code, cause) {
32421
+ const err = new TypeError(message, { cause });
32422
+ Object.assign(err, { code });
32423
+ return err;
32424
+ }
32425
+ var allowInsecureRequests = Symbol();
32426
+ var clockSkew = Symbol();
32427
+ var clockTolerance = Symbol();
32428
+ var customFetch = Symbol();
32429
+ var modifyAssertion = Symbol();
32430
+ var jweDecrypt = Symbol();
32431
+ var jwksCache = Symbol();
32432
+ var encoder3 = new TextEncoder;
32433
+ var decoder2 = new TextDecoder;
32434
+ function buf(input) {
32435
+ if (typeof input === "string") {
32436
+ return encoder3.encode(input);
32437
+ }
32438
+ return decoder2.decode(input);
32439
+ }
32440
+ var encodeBase64Url;
32441
+ if (Uint8Array.prototype.toBase64) {
32442
+ encodeBase64Url = (input) => {
32443
+ if (input instanceof ArrayBuffer) {
32444
+ input = new Uint8Array(input);
32445
+ }
32446
+ return input.toBase64({ alphabet: "base64url", omitPadding: true });
32447
+ };
32448
+ } else {
32449
+ const CHUNK_SIZE = 32768;
32450
+ encodeBase64Url = (input) => {
32451
+ if (input instanceof ArrayBuffer) {
32452
+ input = new Uint8Array(input);
32453
+ }
32454
+ const arr = [];
32455
+ for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
32456
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
32457
+ }
32458
+ return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
32459
+ };
32460
+ }
32461
+ var decodeBase64Url;
32462
+ if (Uint8Array.fromBase64) {
32463
+ decodeBase64Url = (input) => {
32464
+ try {
32465
+ return Uint8Array.fromBase64(input, { alphabet: "base64url" });
32466
+ } catch (cause) {
32467
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
32468
+ }
32469
+ };
32470
+ } else {
32471
+ decodeBase64Url = (input) => {
32472
+ try {
32473
+ const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
32474
+ const bytes = new Uint8Array(binary.length);
32475
+ for (let i = 0;i < binary.length; i++) {
32476
+ bytes[i] = binary.charCodeAt(i);
32477
+ }
32478
+ return bytes;
32479
+ } catch (cause) {
32480
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
32481
+ }
32482
+ };
32483
+ }
32484
+ function b64u(input) {
32485
+ if (typeof input === "string") {
32486
+ return decodeBase64Url(input);
32487
+ }
32488
+ return encodeBase64Url(input);
32489
+ }
32490
+
32491
+ class UnsupportedOperationError extends Error {
32492
+ code;
32493
+ constructor(message, options) {
32494
+ super(message, options);
32495
+ this.name = this.constructor.name;
32496
+ this.code = UNSUPPORTED_OPERATION;
32497
+ Error.captureStackTrace?.(this, this.constructor);
32498
+ }
32499
+ }
32500
+
32501
+ class OperationProcessingError extends Error {
32502
+ code;
32503
+ constructor(message, options) {
32504
+ super(message, options);
32505
+ this.name = this.constructor.name;
32506
+ if (options?.code) {
32507
+ this.code = options?.code;
32508
+ }
32509
+ Error.captureStackTrace?.(this, this.constructor);
32510
+ }
32511
+ }
32512
+ function OPE(message, code, cause) {
32513
+ return new OperationProcessingError(message, { code, cause });
32514
+ }
32515
+ function isJsonObject(input) {
32516
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
32517
+ return false;
32518
+ }
32519
+ return true;
32520
+ }
32521
+ function prepareHeaders(input) {
32522
+ if (looseInstanceOf(input, Headers)) {
32523
+ input = Object.fromEntries(input.entries());
32524
+ }
32525
+ const headers = new Headers(input ?? {});
32526
+ if (USER_AGENT && !headers.has("user-agent")) {
32527
+ headers.set("user-agent", USER_AGENT);
32528
+ }
32529
+ if (headers.has("authorization")) {
32530
+ throw CodedTypeError('"options.headers" must not include the "authorization" header name', ERR_INVALID_ARG_VALUE);
32531
+ }
32532
+ return headers;
32533
+ }
32534
+ function signal(url, value) {
32535
+ if (value !== undefined) {
32536
+ if (typeof value === "function") {
32537
+ value = value(url.href);
32538
+ }
32539
+ if (!(value instanceof AbortSignal)) {
32540
+ throw CodedTypeError('"options.signal" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);
32541
+ }
32542
+ return value;
32543
+ }
32544
+ return;
32545
+ }
32546
+ function assertNumber(input, allow0, it, code, cause) {
32547
+ try {
32548
+ if (typeof input !== "number" || !Number.isFinite(input)) {
32549
+ throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);
32550
+ }
32551
+ if (input > 0)
32552
+ return;
32553
+ if (allow0) {
32554
+ if (input !== 0) {
32555
+ throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);
32556
+ }
32557
+ return;
32558
+ }
32559
+ throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);
32560
+ } catch (err) {
32561
+ if (code) {
32562
+ throw OPE(err.message, code, cause);
32563
+ }
32564
+ throw err;
32565
+ }
32566
+ }
32567
+ function assertString(input, it, code, cause) {
32568
+ try {
32569
+ if (typeof input !== "string") {
32570
+ throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);
32571
+ }
32572
+ if (input.length === 0) {
32573
+ throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);
32574
+ }
32575
+ } catch (err) {
32576
+ if (code) {
32577
+ throw OPE(err.message, code, cause);
32578
+ }
32579
+ throw err;
32580
+ }
32581
+ }
32582
+ function assertApplicationJson(response) {
32583
+ assertContentType(response, "application/json");
32584
+ }
32585
+ function notJson(response, ...types) {
32586
+ let msg = '"response" content-type must be ';
32587
+ if (types.length > 2) {
32588
+ const last = types.pop();
32589
+ msg += `${types.join(", ")}, or ${last}`;
32590
+ } else if (types.length === 2) {
32591
+ msg += `${types[0]} or ${types[1]}`;
32592
+ } else {
32593
+ msg += types[0];
32594
+ }
32595
+ return OPE(msg, RESPONSE_IS_NOT_JSON, response);
32596
+ }
32597
+ function assertContentType(response, contentType) {
32598
+ if (getContentType(response) !== contentType) {
32599
+ throw notJson(response, contentType);
32600
+ }
32601
+ }
32602
+ function getClockSkew(client) {
32603
+ const skew = client?.[clockSkew];
32604
+ return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
32605
+ }
32606
+ function getClockTolerance(client) {
32607
+ const tolerance = client?.[clockTolerance];
32608
+ return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
32609
+ }
32610
+ function epochTime() {
32611
+ return Math.floor(Date.now() / 1000);
32612
+ }
32613
+ function assertAs(as) {
32614
+ if (typeof as !== "object" || as === null) {
32615
+ throw CodedTypeError('"as" must be an object', ERR_INVALID_ARG_TYPE);
32616
+ }
32617
+ assertString(as.issuer, '"as.issuer"');
32618
+ }
32619
+ function assertClient(client) {
32620
+ if (typeof client !== "object" || client === null) {
32621
+ throw CodedTypeError('"client" must be an object', ERR_INVALID_ARG_TYPE);
32622
+ }
32623
+ assertString(client.client_id, '"client.client_id"');
32624
+ }
32625
+ function ClientSecretPost(clientSecret) {
32626
+ assertString(clientSecret, '"clientSecret"');
32627
+ return (_as, client, body, _headers) => {
32628
+ body.set("client_id", client.client_id);
32629
+ body.set("client_secret", clientSecret);
32630
+ };
32631
+ }
32632
+ function None() {
32633
+ return (_as, client, body, _headers) => {
32634
+ body.set("client_id", client.client_id);
32635
+ };
32636
+ }
32637
+ var URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
32638
+ try {
32639
+ return new URL(url, base);
32640
+ } catch {
32641
+ return null;
32642
+ }
32643
+ };
32644
+ function checkProtocol(url, enforceHttps) {
32645
+ if (enforceHttps && url.protocol !== "https:") {
32646
+ throw OPE("only requests to HTTPS are allowed", HTTP_REQUEST_FORBIDDEN, url);
32647
+ }
32648
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
32649
+ throw OPE("only HTTP and HTTPS requests are allowed", REQUEST_PROTOCOL_FORBIDDEN, url);
32650
+ }
32651
+ }
32652
+ function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
32653
+ let url;
32654
+ if (typeof value !== "string" || !(url = URLParse(value))) {
32655
+ 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 });
32656
+ }
32657
+ checkProtocol(url, enforceHttps);
32658
+ return url;
32659
+ }
32660
+ function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
32661
+ if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {
32662
+ return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
32663
+ }
32664
+ return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
32665
+ }
32666
+ function isDPoPNonceError(err) {
32667
+ if (err instanceof WWWAuthenticateChallengeError) {
32668
+ return err.cause.some((challenge) => challenge.scheme === "dpop" && challenge.parameters.error === "use_dpop_nonce");
32669
+ }
32670
+ if (err instanceof ResponseBodyError) {
32671
+ return err.error === "use_dpop_nonce";
32672
+ }
32673
+ return false;
32674
+ }
32675
+ class ResponseBodyError extends Error {
32676
+ cause;
32677
+ code;
32678
+ error;
32679
+ status;
32680
+ error_description;
32681
+ response;
32682
+ constructor(message, options) {
32683
+ super(message, options);
32684
+ this.name = this.constructor.name;
32685
+ this.code = RESPONSE_BODY_ERROR;
32686
+ this.cause = options.cause;
32687
+ this.error = options.cause.error;
32688
+ this.status = options.response.status;
32689
+ this.error_description = options.cause.error_description;
32690
+ Object.defineProperty(this, "response", { enumerable: false, value: options.response });
32691
+ Error.captureStackTrace?.(this, this.constructor);
32692
+ }
32693
+ }
32694
+
32695
+ class AuthorizationResponseError extends Error {
32696
+ cause;
32697
+ code;
32698
+ error;
32699
+ error_description;
32700
+ constructor(message, options) {
32701
+ super(message, options);
32702
+ this.name = this.constructor.name;
32703
+ this.code = AUTHORIZATION_RESPONSE_ERROR;
32704
+ this.cause = options.cause;
32705
+ this.error = options.cause.get("error");
32706
+ this.error_description = options.cause.get("error_description") ?? undefined;
32707
+ Error.captureStackTrace?.(this, this.constructor);
32708
+ }
32709
+ }
32710
+
32711
+ class WWWAuthenticateChallengeError extends Error {
32712
+ cause;
32713
+ code;
32714
+ response;
32715
+ status;
32716
+ constructor(message, options) {
32717
+ super(message, options);
32718
+ this.name = this.constructor.name;
32719
+ this.code = WWW_AUTHENTICATE_CHALLENGE;
32720
+ this.cause = options.cause;
32721
+ this.status = options.response.status;
32722
+ this.response = options.response;
32723
+ Object.defineProperty(this, "response", { enumerable: false });
32724
+ Error.captureStackTrace?.(this, this.constructor);
32725
+ }
32726
+ }
32727
+ var tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
32728
+ var token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}";
32729
+ var quotedMatch = '"((?:[^"\\\\]|\\\\[\\s\\S])*)"';
32730
+ var quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*" + quotedMatch;
32731
+ var paramMatcher = "(" + tokenMatch + ")\\s*=\\s*(" + tokenMatch + ")";
32732
+ var schemeRE = new RegExp("^[,\\s]*(" + tokenMatch + ")");
32733
+ var quotedParamRE = new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");
32734
+ var unquotedParamRE = new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");
32735
+ var token68ParamRE = new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");
32736
+ function parseWwwAuthenticateChallenges(response) {
32737
+ if (!looseInstanceOf(response, Response)) {
32738
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
32739
+ }
32740
+ const header = response.headers.get("www-authenticate");
32741
+ if (header === null) {
32742
+ return;
32743
+ }
32744
+ const challenges = [];
32745
+ let rest = header;
32746
+ while (rest) {
32747
+ let match = rest.match(schemeRE);
32748
+ const scheme = match?.["1"].toLowerCase();
32749
+ if (!scheme) {
32750
+ return;
32751
+ }
32752
+ const afterScheme = rest.substring(match[0].length);
32753
+ if (afterScheme && !afterScheme.match(/^[\s,]/)) {
32754
+ return;
32755
+ }
32756
+ const spaceMatch = afterScheme.match(/^\s+(.*)$/);
32757
+ const hasParameters = !!spaceMatch;
32758
+ rest = spaceMatch ? spaceMatch[1] : undefined;
32759
+ const parameters = {};
32760
+ let token68;
32761
+ if (hasParameters) {
32762
+ while (rest) {
32763
+ let key;
32764
+ let value;
32765
+ if (match = rest.match(quotedParamRE)) {
32766
+ [, key, value, rest] = match;
32767
+ if (value.includes("\\")) {
32768
+ value = value.replace(/\\([\s\S])/g, "$1");
32769
+ }
32770
+ parameters[key.toLowerCase()] = value;
32771
+ continue;
32772
+ }
32773
+ if (match = rest.match(unquotedParamRE)) {
32774
+ [, key, value, rest] = match;
32775
+ parameters[key.toLowerCase()] = value;
32776
+ continue;
32777
+ }
32778
+ if (match = rest.match(token68ParamRE)) {
32779
+ if (Object.keys(parameters).length) {
32780
+ break;
32781
+ }
32782
+ [, token68, rest] = match;
32783
+ break;
32784
+ }
32785
+ return;
32786
+ }
32787
+ } else {
32788
+ rest = afterScheme || undefined;
32789
+ }
32790
+ const challenge = { scheme, parameters };
32791
+ if (token68) {
32792
+ challenge.token68 = token68;
32793
+ }
32794
+ challenges.push(challenge);
32795
+ }
32796
+ if (!challenges.length) {
32797
+ return;
32798
+ }
32799
+ return challenges;
32800
+ }
32801
+ async function parseOAuthResponseErrorBody(response) {
32802
+ if (response.status > 399 && response.status < 500) {
32803
+ assertReadableResponse(response);
32804
+ assertApplicationJson(response);
32805
+ try {
32806
+ const json = await response.clone().json();
32807
+ if (isJsonObject(json) && typeof json.error === "string" && json.error.length) {
32808
+ return json;
32809
+ }
32810
+ } catch {}
32811
+ }
32812
+ return;
32813
+ }
32814
+ async function checkOAuthBodyError(response, expected, label) {
32815
+ if (response.status !== expected) {
32816
+ checkAuthenticationChallenges(response);
32817
+ let err;
32818
+ if (err = await parseOAuthResponseErrorBody(response)) {
32819
+ await response.body?.cancel();
32820
+ throw new ResponseBodyError("server responded with an error in the response body", {
32821
+ cause: err,
32822
+ response
32823
+ });
32824
+ }
32825
+ throw OPE(`"response" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);
32826
+ }
32827
+ }
32828
+ function assertDPoP(option) {
32829
+ if (!branded.has(option)) {
32830
+ throw CodedTypeError('"options.DPoP" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);
32831
+ }
32832
+ }
32833
+ var skipSubjectCheck = Symbol();
32834
+ function getContentType(input) {
32835
+ return input.headers.get("content-type")?.split(";")[0];
32836
+ }
32837
+ async function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {
32838
+ await clientAuthentication(as, client, body, headers);
32839
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
32840
+ return (options?.[customFetch] || fetch)(url.href, {
32841
+ body,
32842
+ headers: Object.fromEntries(headers.entries()),
32843
+ method: "POST",
32844
+ redirect: "manual",
32845
+ signal: signal(url, options?.signal)
32846
+ });
32847
+ }
32848
+ async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
32849
+ const url = resolveEndpoint(as, "token_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
32850
+ parameters.set("grant_type", grantType);
32851
+ const headers = prepareHeaders(options?.headers);
32852
+ headers.set("accept", "application/json");
32853
+ if (options?.DPoP !== undefined) {
32854
+ assertDPoP(options.DPoP);
32855
+ await options.DPoP.addProof(url, headers, "POST");
32856
+ }
32857
+ const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);
32858
+ options?.DPoP?.cacheNonce(response, url);
32859
+ return response;
32860
+ }
32861
+ var idTokenClaims = new WeakMap;
32862
+ var jwtRefs = new WeakMap;
32863
+ function getValidatedIdTokenClaims(ref) {
32864
+ if (!ref.id_token) {
32865
+ return;
32866
+ }
32867
+ const claims = idTokenClaims.get(ref);
32868
+ if (!claims) {
32869
+ throw CodedTypeError('"ref" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);
32870
+ }
32871
+ return claims;
32872
+ }
32873
+ async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
32874
+ assertAs(as);
32875
+ assertClient(client);
32876
+ if (!looseInstanceOf(response, Response)) {
32877
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
32878
+ }
32879
+ await checkOAuthBodyError(response, 200, "Token Endpoint");
32880
+ assertReadableResponse(response);
32881
+ const json = await getResponseJsonBody(response);
32882
+ assertString(json.access_token, '"response" body "access_token" property', INVALID_RESPONSE, {
32883
+ body: json
32884
+ });
32885
+ assertString(json.token_type, '"response" body "token_type" property', INVALID_RESPONSE, {
32886
+ body: json
32887
+ });
32888
+ json.token_type = json.token_type.toLowerCase();
32889
+ if (json.expires_in !== undefined) {
32890
+ let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
32891
+ assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
32892
+ body: json
32893
+ });
32894
+ json.expires_in = expiresIn;
32895
+ }
32896
+ if (json.refresh_token !== undefined) {
32897
+ assertString(json.refresh_token, '"response" body "refresh_token" property', INVALID_RESPONSE, {
32898
+ body: json
32899
+ });
32900
+ }
32901
+ if (json.scope !== undefined && typeof json.scope !== "string") {
32902
+ throw OPE('"response" body "scope" property must be a string', INVALID_RESPONSE, { body: json });
32903
+ }
32904
+ if (json.id_token !== undefined) {
32905
+ assertString(json.id_token, '"response" body "id_token" property', INVALID_RESPONSE, {
32906
+ body: json
32907
+ });
32908
+ const requiredClaims = [];
32909
+ if (client.require_auth_time === true) {
32910
+ requiredClaims.push("auth_time");
32911
+ }
32912
+ if (client.default_max_age !== undefined) {
32913
+ assertNumber(client.default_max_age, true, '"client.default_max_age"');
32914
+ requiredClaims.push("auth_time");
32915
+ }
32916
+ if (additionalRequiredIdTokenClaims?.length) {
32917
+ requiredClaims.push(...additionalRequiredIdTokenClaims);
32918
+ }
32919
+ const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);
32920
+ validateIdTokenAuthorizedParty(client, claims);
32921
+ validateIdTokenAuthTimeClaim(claims);
32922
+ jwtRefs.set(response, jwt);
32923
+ idTokenClaims.set(json, claims);
32924
+ }
32925
+ if (recognizedTokenTypes?.[json.token_type] !== undefined) {
32926
+ recognizedTokenTypes[json.token_type](response, json);
32927
+ } else if (json.token_type !== "dpop" && json.token_type !== "bearer") {
32928
+ throw new UnsupportedOperationError("unsupported `token_type` value", { cause: { body: json } });
32929
+ }
32930
+ return json;
32931
+ }
32932
+ function checkAuthenticationChallenges(response) {
32933
+ let challenges;
32934
+ if (challenges = parseWwwAuthenticateChallenges(response)) {
32935
+ throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", { cause: challenges, response });
32936
+ }
32937
+ }
32938
+ function validateAudience(expected, result) {
32939
+ if (Array.isArray(result.claims.aud)) {
32940
+ if (!result.claims.aud.includes(expected)) {
32941
+ throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
32942
+ expected,
32943
+ claims: result.claims,
32944
+ claim: "aud"
32945
+ });
32946
+ }
32947
+ } else if (result.claims.aud !== expected) {
32948
+ throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
32949
+ expected,
32950
+ claims: result.claims,
32951
+ claim: "aud"
32952
+ });
32953
+ }
32954
+ return result;
32955
+ }
32956
+ function validateIssuer(as, result) {
32957
+ const expected = as[_expectedIssuer]?.(result) ?? as.issuer;
32958
+ if (result.claims.iss !== expected) {
32959
+ throw OPE('unexpected JWT "iss" (issuer) claim value', JWT_CLAIM_COMPARISON, {
32960
+ expected,
32961
+ claims: result.claims,
32962
+ claim: "iss"
32963
+ });
32964
+ }
32965
+ return result;
32966
+ }
32967
+ var branded = new WeakSet;
32968
+ var nopkce = Symbol();
32969
+ var jwtClaimNames = {
32970
+ aud: "audience",
32971
+ c_hash: "code hash",
32972
+ client_id: "client id",
32973
+ exp: "expiration time",
32974
+ iat: "issued at",
32975
+ iss: "issuer",
32976
+ jti: "jwt id",
32977
+ nonce: "nonce",
32978
+ s_hash: "state hash",
32979
+ sub: "subject",
32980
+ ath: "access token hash",
32981
+ htm: "http method",
32982
+ htu: "http uri",
32983
+ cnf: "confirmation",
32984
+ auth_time: "authentication time"
32985
+ };
32986
+ function validatePresence(required, result) {
32987
+ for (const claim of required) {
32988
+ if (result.claims[claim] === undefined) {
32989
+ throw OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {
32990
+ claims: result.claims
32991
+ });
32992
+ }
32993
+ }
32994
+ return result;
32995
+ }
32996
+ function validateStringClaim(claim, result) {
32997
+ if (typeof result.claims[claim] !== "string") {
32998
+ throw OPE(`unexpected JWT "${claim}" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, {
32999
+ claims: result.claims
33000
+ });
33001
+ }
33002
+ return result;
33003
+ }
33004
+ function validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {
33005
+ 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"));
33006
+ }
33007
+ function validateIdTokenAuthTimeClaim(claims) {
33008
+ if (claims.auth_time !== undefined) {
33009
+ assertNumber(claims.auth_time, true, 'ID Token "auth_time" (authentication time)', INVALID_RESPONSE, { claims });
33010
+ }
33011
+ }
33012
+ function validateIdTokenAuthorizedParty(client, claims) {
33013
+ if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
33014
+ if (claims.azp === undefined) {
33015
+ throw OPE('ID Token "aud" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: "aud" });
33016
+ }
33017
+ if (claims.azp !== client.client_id) {
33018
+ throw OPE('unexpected ID Token "azp" (authorized party) claim value', JWT_CLAIM_COMPARISON, {
33019
+ expected: client.client_id,
33020
+ claims,
33021
+ claim: "azp"
33022
+ });
33023
+ }
33024
+ }
33025
+ }
33026
+ var expectNoNonce = Symbol();
33027
+ var skipAuthTimeCheck = Symbol();
33028
+ var WWW_AUTHENTICATE_CHALLENGE = "OAUTH_WWW_AUTHENTICATE_CHALLENGE";
33029
+ var RESPONSE_BODY_ERROR = "OAUTH_RESPONSE_BODY_ERROR";
33030
+ var UNSUPPORTED_OPERATION = "OAUTH_UNSUPPORTED_OPERATION";
33031
+ var AUTHORIZATION_RESPONSE_ERROR = "OAUTH_AUTHORIZATION_RESPONSE_ERROR";
33032
+ var PARSE_ERROR = "OAUTH_PARSE_ERROR";
33033
+ var INVALID_RESPONSE = "OAUTH_INVALID_RESPONSE";
33034
+ var RESPONSE_IS_NOT_JSON = "OAUTH_RESPONSE_IS_NOT_JSON";
33035
+ var RESPONSE_IS_NOT_CONFORM = "OAUTH_RESPONSE_IS_NOT_CONFORM";
33036
+ var HTTP_REQUEST_FORBIDDEN = "OAUTH_HTTP_REQUEST_FORBIDDEN";
33037
+ var REQUEST_PROTOCOL_FORBIDDEN = "OAUTH_REQUEST_PROTOCOL_FORBIDDEN";
33038
+ var JWT_TIMESTAMP_CHECK = "OAUTH_JWT_TIMESTAMP_CHECK_FAILED";
33039
+ var JWT_CLAIM_COMPARISON = "OAUTH_JWT_CLAIM_COMPARISON_FAILED";
33040
+ var JSON_ATTRIBUTE_COMPARISON = "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";
33041
+ var MISSING_SERVER_METADATA = "OAUTH_MISSING_SERVER_METADATA";
33042
+ var INVALID_SERVER_METADATA = "OAUTH_INVALID_SERVER_METADATA";
33043
+ async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
33044
+ assertAs(as);
33045
+ assertClient(client);
33046
+ assertString(grantType, '"grantType"');
33047
+ return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);
33048
+ }
33049
+ async function processGenericTokenEndpointResponse(as, client, response, options) {
33050
+ return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
33051
+ }
33052
+ function assertReadableResponse(response) {
33053
+ if (response.bodyUsed) {
33054
+ throw CodedTypeError('"response" body has been used already', ERR_INVALID_ARG_VALUE);
33055
+ }
33056
+ }
33057
+ async function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {
33058
+ let { 0: protectedHeader, 1: payload, length } = jws.split(".");
33059
+ if (length === 5) {
33060
+ if (decryptJwt !== undefined) {
33061
+ jws = await decryptJwt(jws);
33062
+ ({ 0: protectedHeader, 1: payload, length } = jws.split("."));
33063
+ } else {
33064
+ throw new UnsupportedOperationError("JWE decryption is not configured", { cause: jws });
33065
+ }
33066
+ }
33067
+ if (length !== 3) {
33068
+ throw OPE("Invalid JWT", INVALID_RESPONSE, jws);
33069
+ }
33070
+ let header;
33071
+ try {
33072
+ header = JSON.parse(buf(b64u(protectedHeader)));
33073
+ } catch (cause) {
33074
+ throw OPE("failed to parse JWT Header body as base64url encoded JSON", PARSE_ERROR, cause);
33075
+ }
33076
+ if (!isJsonObject(header)) {
33077
+ throw OPE("JWT Header must be a top level object", INVALID_RESPONSE, jws);
33078
+ }
33079
+ checkAlg(header);
33080
+ if (header.crit !== undefined) {
33081
+ throw new UnsupportedOperationError('no JWT "crit" header parameter extensions are supported', {
33082
+ cause: { header }
33083
+ });
33084
+ }
33085
+ let claims;
33086
+ try {
33087
+ claims = JSON.parse(buf(b64u(payload)));
33088
+ } catch (cause) {
33089
+ throw OPE("failed to parse JWT Payload body as base64url encoded JSON", PARSE_ERROR, cause);
33090
+ }
33091
+ if (!isJsonObject(claims)) {
33092
+ throw OPE("JWT Payload must be a top level object", INVALID_RESPONSE, jws);
33093
+ }
33094
+ const now = epochTime() + clockSkew;
33095
+ if (claims.exp !== undefined) {
33096
+ if (typeof claims.exp !== "number") {
33097
+ throw OPE('unexpected JWT "exp" (expiration time) claim type', INVALID_RESPONSE, { claims });
33098
+ }
33099
+ if (claims.exp <= now - clockTolerance) {
33100
+ throw OPE('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: "exp" });
33101
+ }
33102
+ }
33103
+ if (claims.iat !== undefined) {
33104
+ if (typeof claims.iat !== "number") {
33105
+ throw OPE('unexpected JWT "iat" (issued at) claim type', INVALID_RESPONSE, { claims });
33106
+ }
33107
+ }
33108
+ if (claims.iss !== undefined) {
33109
+ if (typeof claims.iss !== "string") {
33110
+ throw OPE('unexpected JWT "iss" (issuer) claim type', INVALID_RESPONSE, { claims });
33111
+ }
33112
+ }
33113
+ if (claims.nbf !== undefined) {
33114
+ if (typeof claims.nbf !== "number") {
33115
+ throw OPE('unexpected JWT "nbf" (not before) claim type', INVALID_RESPONSE, { claims });
33116
+ }
33117
+ if (claims.nbf > now + clockTolerance) {
33118
+ throw OPE('unexpected JWT "nbf" (not before) claim value', JWT_TIMESTAMP_CHECK, {
33119
+ claims,
33120
+ now,
33121
+ tolerance: clockTolerance,
33122
+ claim: "nbf"
33123
+ });
33124
+ }
33125
+ }
33126
+ if (claims.aud !== undefined) {
33127
+ if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) {
33128
+ throw OPE('unexpected JWT "aud" (audience) claim type', INVALID_RESPONSE, { claims });
33129
+ }
33130
+ }
33131
+ return { header, claims, jwt: jws };
33132
+ }
33133
+ function checkSigningAlgorithm(client, issuer, fallback, header) {
33134
+ if (client !== undefined) {
33135
+ if (typeof client === "string" ? header.alg !== client : !client.includes(header.alg)) {
33136
+ throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
33137
+ header,
33138
+ expected: client,
33139
+ reason: "client configuration"
33140
+ });
33141
+ }
33142
+ return;
33143
+ }
33144
+ if (Array.isArray(issuer)) {
33145
+ if (!issuer.includes(header.alg)) {
33146
+ throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
33147
+ header,
33148
+ expected: issuer,
33149
+ reason: "authorization server metadata"
33150
+ });
33151
+ }
33152
+ return;
33153
+ }
33154
+ if (fallback !== undefined) {
33155
+ if (typeof fallback === "string" ? header.alg !== fallback : typeof fallback === "function" ? !fallback(header.alg) : !fallback.includes(header.alg)) {
33156
+ throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
33157
+ header,
33158
+ expected: fallback,
33159
+ reason: "default value"
33160
+ });
33161
+ }
33162
+ return;
33163
+ }
33164
+ throw OPE('missing client or server configuration to verify used JWT "alg" header parameter', undefined, { client, issuer, fallback });
33165
+ }
33166
+ var skipStateCheck = Symbol();
33167
+ var expectNoState = Symbol();
33168
+ async function getResponseJsonBody(response, check = assertApplicationJson) {
33169
+ let json;
33170
+ try {
33171
+ json = await response.json();
33172
+ } catch (cause) {
33173
+ check(response);
33174
+ throw OPE('failed to parse "response" body as JSON', PARSE_ERROR, cause);
33175
+ }
33176
+ if (!isJsonObject(json)) {
33177
+ throw OPE('"response" body must be a top level object', INVALID_RESPONSE, { body: json });
33178
+ }
33179
+ return json;
33180
+ }
33181
+ var _nodiscoverycheck = Symbol();
33182
+ var _expectedIssuer = Symbol();
33183
+
33184
+ // ../../node_modules/.bun/openid-client@6.8.7/node_modules/openid-client/build/index.js
33185
+ var headers;
33186
+ var USER_AGENT2;
33187
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
33188
+ const NAME = "openid-client";
33189
+ const VERSION = "v6.8.7";
33190
+ USER_AGENT2 = `${NAME}/${VERSION}`;
33191
+ headers = { "user-agent": USER_AGENT2 };
33192
+ }
33193
+ var int2 = (config) => {
33194
+ return props.get(config);
33195
+ };
33196
+ var props;
33197
+ var tbi;
33198
+ function ClientSecretPost2(clientSecret) {
33199
+ if (clientSecret !== undefined) {
33200
+ return ClientSecretPost(clientSecret);
33201
+ }
33202
+ tbi ||= new WeakMap;
33203
+ return (as, client, body, headers) => {
33204
+ let auth;
33205
+ if (!(auth = tbi.get(client))) {
33206
+ assertString2(client.client_secret, '"metadata.client_secret"');
33207
+ auth = ClientSecretPost(client.client_secret);
33208
+ tbi.set(client, auth);
33209
+ }
33210
+ return auth(as, client, body, headers);
33211
+ };
33212
+ }
33213
+ function assertString2(input, it) {
33214
+ if (typeof input !== "string") {
33215
+ throw CodedTypeError2(`${it} must be a string`, ERR_INVALID_ARG_TYPE2);
33216
+ }
33217
+ if (input.length === 0) {
33218
+ throw CodedTypeError2(`${it} must not be empty`, ERR_INVALID_ARG_VALUE2);
33219
+ }
33220
+ }
33221
+ function None2() {
33222
+ return None();
33223
+ }
33224
+ var customFetch2 = customFetch;
33225
+ var ERR_INVALID_ARG_VALUE2 = "ERR_INVALID_ARG_VALUE";
33226
+ var ERR_INVALID_ARG_TYPE2 = "ERR_INVALID_ARG_TYPE";
33227
+ function CodedTypeError2(message, code, cause) {
33228
+ const err = new TypeError(message, { cause });
33229
+ Object.assign(err, { code });
33230
+ return err;
33231
+ }
33232
+ class ClientError extends Error {
33233
+ code;
33234
+ constructor(message, options) {
33235
+ super(message, options);
33236
+ this.name = this.constructor.name;
33237
+ this.code = options?.code;
33238
+ Error.captureStackTrace?.(this, this.constructor);
33239
+ }
33240
+ }
33241
+ var decoder3 = new TextDecoder;
33242
+ function e(msg, cause, code) {
33243
+ return new ClientError(msg, { cause, code });
33244
+ }
33245
+ function errorHandler(err) {
33246
+ if (err instanceof TypeError || err instanceof ClientError || err instanceof ResponseBodyError || err instanceof AuthorizationResponseError || err instanceof WWWAuthenticateChallengeError) {
33247
+ throw err;
33248
+ }
33249
+ if (err instanceof OperationProcessingError) {
33250
+ switch (err.code) {
33251
+ case HTTP_REQUEST_FORBIDDEN:
33252
+ throw e("only requests to HTTPS are allowed", err, err.code);
33253
+ case REQUEST_PROTOCOL_FORBIDDEN:
33254
+ throw e("only requests to HTTP or HTTPS are allowed", err, err.code);
33255
+ case RESPONSE_IS_NOT_CONFORM:
33256
+ throw e("unexpected HTTP response status code", err.cause, err.code);
33257
+ case RESPONSE_IS_NOT_JSON:
33258
+ throw e("unexpected response content-type", err.cause, err.code);
33259
+ case PARSE_ERROR:
33260
+ throw e("parsing error occured", err, err.code);
33261
+ case INVALID_RESPONSE:
33262
+ throw e("invalid response encountered", err, err.code);
33263
+ case JWT_CLAIM_COMPARISON:
33264
+ throw e("unexpected JWT claim value encountered", err, err.code);
33265
+ case JSON_ATTRIBUTE_COMPARISON:
33266
+ throw e("unexpected JSON attribute value encountered", err, err.code);
33267
+ case JWT_TIMESTAMP_CHECK:
33268
+ throw e("JWT timestamp claim value failed validation", err, err.code);
33269
+ default:
33270
+ throw e(err.message, err, err.code);
33271
+ }
33272
+ }
33273
+ if (err instanceof UnsupportedOperationError) {
33274
+ throw e("unsupported operation", err, err.code);
33275
+ }
33276
+ if (err instanceof DOMException) {
33277
+ switch (err.name) {
33278
+ case "OperationError":
33279
+ throw e("runtime operation error", err, UNSUPPORTED_OPERATION);
33280
+ case "NotSupportedError":
33281
+ throw e("runtime unsupported operation", err, UNSUPPORTED_OPERATION);
33282
+ case "TimeoutError":
33283
+ throw e("operation timed out", err, "OAUTH_TIMEOUT");
33284
+ case "AbortError":
33285
+ throw e("operation aborted", err, "OAUTH_ABORT");
33286
+ }
33287
+ }
33288
+ throw new ClientError("something went wrong", { cause: err });
33289
+ }
33290
+ function getServerHelpers(metadata) {
33291
+ return {
33292
+ supportsPKCE: {
33293
+ __proto__: null,
33294
+ value(method = "S256") {
33295
+ return metadata.code_challenge_methods_supported?.includes(method) === true;
33296
+ }
33297
+ }
33298
+ };
33299
+ }
33300
+ function addServerHelpers(metadata) {
33301
+ Object.defineProperties(metadata, getServerHelpers(metadata));
33302
+ }
33303
+ var kEntraId = Symbol();
33304
+
33305
+ class Configuration {
33306
+ constructor(server, clientId, metadata, clientAuthentication) {
33307
+ if (typeof clientId !== "string" || !clientId.length) {
33308
+ throw CodedTypeError2('"clientId" must be a non-empty string', ERR_INVALID_ARG_TYPE2);
33309
+ }
33310
+ if (typeof metadata === "string") {
33311
+ metadata = { client_secret: metadata };
33312
+ }
33313
+ if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {
33314
+ throw CodedTypeError2('"clientId" and "metadata.client_id" must be the same', ERR_INVALID_ARG_VALUE2);
33315
+ }
33316
+ const client = {
33317
+ ...structuredClone(metadata),
33318
+ client_id: clientId
33319
+ };
33320
+ client[clockSkew] = metadata?.[clockSkew] ?? 0;
33321
+ client[clockTolerance] = metadata?.[clockTolerance] ?? 30;
33322
+ let auth;
33323
+ if (clientAuthentication) {
33324
+ auth = clientAuthentication;
33325
+ } else {
33326
+ if (typeof client.client_secret === "string" && client.client_secret.length) {
33327
+ auth = ClientSecretPost2(client.client_secret);
33328
+ } else {
33329
+ auth = None2();
33330
+ }
33331
+ }
33332
+ let c = Object.freeze(client);
33333
+ const clone = structuredClone(server);
33334
+ if (kEntraId in server) {
33335
+ clone[_expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace("{tenantid}", tid);
33336
+ }
33337
+ let as = Object.freeze(clone);
33338
+ props ||= new WeakMap;
33339
+ props.set(this, {
33340
+ __proto__: null,
33341
+ as,
33342
+ c,
33343
+ auth,
33344
+ tlsOnly: true,
33345
+ jwksCache: {}
33346
+ });
33347
+ }
33348
+ serverMetadata() {
33349
+ const metadata = structuredClone(int2(this).as);
33350
+ addServerHelpers(metadata);
33351
+ return metadata;
33352
+ }
33353
+ clientMetadata() {
33354
+ const metadata = structuredClone(int2(this).c);
33355
+ return metadata;
33356
+ }
33357
+ get timeout() {
33358
+ return int2(this).timeout;
33359
+ }
33360
+ set timeout(value) {
33361
+ int2(this).timeout = value;
33362
+ }
33363
+ get [customFetch2]() {
33364
+ return int2(this).fetch;
33365
+ }
33366
+ set [customFetch2](value) {
33367
+ int2(this).fetch = value;
33368
+ }
33369
+ }
33370
+ Object.freeze(Configuration.prototype);
33371
+ function getHelpers(response) {
33372
+ let exp = undefined;
33373
+ if (response.expires_in !== undefined) {
33374
+ const now = new Date;
33375
+ now.setSeconds(now.getSeconds() + response.expires_in);
33376
+ exp = now.getTime();
33377
+ }
33378
+ return {
33379
+ expiresIn: {
33380
+ __proto__: null,
33381
+ value() {
33382
+ if (exp) {
33383
+ const now = Date.now();
33384
+ if (exp > now) {
33385
+ return Math.floor((exp - now) / 1000);
33386
+ }
33387
+ return 0;
33388
+ }
33389
+ return;
33390
+ }
33391
+ },
33392
+ claims: {
33393
+ __proto__: null,
33394
+ value() {
33395
+ return getValidatedIdTokenClaims(response);
33396
+ }
33397
+ }
33398
+ };
33399
+ }
33400
+ function addHelpers(response) {
33401
+ Object.defineProperties(response, getHelpers(response));
33402
+ }
33403
+ function allowInsecureRequests2(config) {
33404
+ int2(config).tlsOnly = false;
33405
+ }
33406
+ function checkConfig(input) {
33407
+ if (!(input instanceof Configuration)) {
33408
+ throw CodedTypeError2('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE2);
33409
+ }
33410
+ if (Object.getPrototypeOf(input) !== Configuration.prototype) {
33411
+ throw CodedTypeError2("subclassing Configuration is not allowed", ERR_INVALID_ARG_VALUE2);
33412
+ }
33413
+ }
33414
+ function signal2(timeout) {
33415
+ return timeout ? AbortSignal.timeout(timeout * 1000) : undefined;
33416
+ }
33417
+ function retryable(err, options) {
33418
+ if (options?.DPoP && options.flag !== retry) {
33419
+ return isDPoPNonceError(err);
33420
+ }
33421
+ return false;
33422
+ }
33423
+ var retry = Symbol();
33424
+ async function genericGrantRequest(config, grantType, parameters, options) {
33425
+ checkConfig(config);
33426
+ const { as, c, auth, fetch: fetch2, tlsOnly, timeout, decrypt, nonRepudiation } = int2(config);
33427
+ const response = await genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {
33428
+ [customFetch]: fetch2,
33429
+ [allowInsecureRequests]: !tlsOnly,
33430
+ DPoP: options?.DPoP,
33431
+ headers: new Headers(headers),
33432
+ signal: signal2(timeout)
33433
+ }).catch(errorHandler);
33434
+ let recognizedTokenTypes;
33435
+ if (grantType === "urn:ietf:params:oauth:grant-type:token-exchange") {
33436
+ recognizedTokenTypes = { n_a: () => {} };
33437
+ }
33438
+ const p = processGenericTokenEndpointResponse(as, c, response, {
33439
+ [jweDecrypt]: decrypt,
33440
+ recognizedTokenTypes
33441
+ });
33442
+ let result;
33443
+ try {
33444
+ result = await p;
33445
+ } catch (err) {
33446
+ if (retryable(err, options)) {
33447
+ return genericGrantRequest(config, grantType, parameters, {
33448
+ ...options,
33449
+ flag: retry
33450
+ });
33451
+ }
33452
+ errorHandler(err);
33453
+ }
33454
+ result.id_token && await nonRepudiation?.(response);
33455
+ addHelpers(result);
33456
+ return result;
33457
+ }
33458
+
33459
+ // ../broker-client/src/token-client.ts
33460
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
33461
+ var TOO_MANY_REQUESTS = 429;
33462
+ var INVALID_DPOP_PROOF = "invalid_dpop_proof";
33463
+ var USE_DPOP_NONCE = "use_dpop_nonce";
33464
+
33465
+ class BrokerRefusedError extends Error {
33466
+ status;
33467
+ code;
33468
+ description;
33469
+ constructor(status, code, description) {
33470
+ 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}`);
33471
+ this.status = status;
33472
+ this.code = code;
33473
+ this.description = description;
33474
+ this.name = "BrokerRefusedError";
33475
+ }
33476
+ get permanent() {
33477
+ return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE;
33478
+ }
33479
+ }
33480
+ function statusOf(error) {
33481
+ let cause = error;
33482
+ for (let depth = 0;depth < 4; depth += 1) {
33483
+ if (cause instanceof Response)
33484
+ return cause.status;
33485
+ if (typeof cause !== "object" || cause === null || !("cause" in cause))
33486
+ return 0;
33487
+ cause = cause.cause;
33488
+ }
33489
+ return 0;
33490
+ }
33491
+ function withoutTrailingSlashes(url) {
33492
+ let end = url.length;
33493
+ while (end > 0 && url[end - 1] === "/")
33494
+ end -= 1;
33495
+ return url.slice(0, end);
33496
+ }
33497
+
33498
+ class BrokerTokenClient {
33499
+ #brokerUrl;
33500
+ #key;
33501
+ #subject;
33502
+ #actor;
33503
+ #session;
33504
+ #launcherCredential;
33505
+ #renewBeforeMs;
33506
+ #now;
33507
+ #fetch;
33508
+ #nonce = "";
33509
+ #held = null;
33510
+ #trading = null;
33511
+ constructor(options) {
33512
+ const brokerUrl = withoutTrailingSlashes(options.brokerUrl.trim());
33513
+ if (brokerUrl === "")
33514
+ throw new Error("broker client: no broker URL");
33515
+ this.#brokerUrl = brokerUrl;
33516
+ this.#key = options.key;
33517
+ this.#subject = options.subject;
33518
+ this.#actor = options.actor;
33519
+ this.#session = options.session ?? "";
33520
+ this.#launcherCredential = options.launcherCredential ?? true;
33521
+ this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
33522
+ this.#now = options.now ?? Date.now;
33523
+ this.#fetch = options.fetch ?? fetch;
33524
+ }
33525
+ get key() {
33526
+ return this.#key;
33527
+ }
33528
+ describe() {
33529
+ return this.#subject.describe();
33530
+ }
33531
+ async token(signal) {
33532
+ const held = this.#held;
33533
+ if (held !== null && this.#now() < held.expiresAt.getTime() - this.#renewBeforeMs)
33534
+ return held;
33535
+ if (this.#trading !== null)
33536
+ return await this.#trading;
33537
+ const trading = this.#renew(signal);
33538
+ this.#trading = trading;
33539
+ try {
33540
+ return await trading;
33541
+ } finally {
33542
+ this.#trading = null;
33543
+ }
33544
+ }
33545
+ async#renew(signal) {
33546
+ try {
33547
+ const token = await this.#trade(signal);
33548
+ this.#held = token;
33549
+ return token;
33550
+ } catch (error) {
33551
+ const held = this.#held;
33552
+ if (!(error instanceof BrokerRefusedError && error.permanent) && held !== null && this.#now() < held.expiresAt.getTime()) {
33553
+ return held;
33554
+ }
33555
+ this.#held = null;
33556
+ throw error;
33557
+ }
33558
+ }
33559
+ async#trade(signal) {
33560
+ const subject = await this.#subject.read(signal);
33561
+ const form = {
33562
+ subject_token: subject.token,
33563
+ subject_token_type: subject.tokenType
33564
+ };
33565
+ if (this.#session !== "")
33566
+ form[FORM_SESSION] = this.#session;
33567
+ if (!this.#launcherCredential) {
33568
+ form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
33569
+ }
33570
+ if (this.#actor !== undefined) {
33571
+ let actor;
33572
+ try {
33573
+ actor = await this.#actor.read(signal);
33574
+ } catch (error) {
33575
+ const said = error instanceof Error ? error.message : String(error);
33576
+ throw new Error(`read the machine this person signed in on: ${said}`, { cause: error });
33577
+ }
33578
+ form["actor_token"] = actor.token;
33579
+ form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
33580
+ }
33581
+ const endpoint = this.#brokerUrl + TOKEN_PATH;
33582
+ const raw = { body: undefined };
33583
+ const config = new Configuration({ issuer: this.#brokerUrl, token_endpoint: endpoint }, EXCHANGE_CLIENT_ID, {}, None2());
33584
+ allowInsecureRequests2(config);
33585
+ config[customFetch2] = (url, options) => this.#send(url, options, signal, raw);
33586
+ let answered;
33587
+ try {
33588
+ answered = await genericGrantRequest(config, GRANT_TYPE_TOKEN_EXCHANGE, form);
33589
+ } catch (error) {
33590
+ throw this.#refusal(endpoint, error);
33591
+ }
33592
+ return this.#read(endpoint, answered, raw.body);
33593
+ }
33594
+ #refusal(endpoint, error) {
33595
+ if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
33596
+ return new BrokerRefusedError(error.status, error.error, error.error_description ?? "");
33597
+ }
33598
+ const status = statusOf(error);
33599
+ const message = error instanceof Error ? error.message : String(error);
33600
+ const said = status === 0 ? message : `HTTP ${status}: ${message}`;
33601
+ return new Error(`trade ${this.#subject.describe()} at ${endpoint}: ${said}`, {
33602
+ cause: error
33603
+ });
33604
+ }
33605
+ async#send(url, options, signal, raw) {
33606
+ const send = async () => {
33607
+ const headers = new Headers(options.headers);
33608
+ headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
33609
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
33610
+ const body = options.body;
33611
+ return await this.#fetch(url, {
33612
+ method: options.method,
33613
+ headers,
33614
+ body,
33615
+ redirect: options.redirect,
33616
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
33617
+ });
33618
+ };
33619
+ let answer = await send();
33620
+ const given = answer.headers.get("DPoP-Nonce") ?? "";
33621
+ if (given !== "")
33622
+ this.#nonce = given;
33623
+ if (answer.status === 400 && given !== "") {
33624
+ const body = await answer.clone().json().catch(() => null);
33625
+ const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
33626
+ if (asked)
33627
+ answer = await send();
33628
+ }
33629
+ raw.body = await answer.clone().json().catch(() => {
33630
+ return;
33631
+ });
33632
+ return answer;
33633
+ }
33634
+ #read(endpoint, answered, raw) {
33635
+ const written = typeof raw === "object" && raw !== null && "token_type" in raw ? raw.token_type : undefined;
33636
+ const tokenType = typeof written === "string" ? written : "";
33637
+ if (tokenType.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
33638
+ throw new Error(`the broker at ${endpoint} answered token_type ${JSON.stringify(tokenType)}, and this grant mints DPoP-bound tokens alone`);
33639
+ }
33640
+ if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
33641
+ throw new Error(`the broker at ${endpoint} answered a refresh token, which this grant never issues; a renewal trades a fresh identity token instead`);
33642
+ }
33643
+ const seconds = answered.expires_in ?? 0;
33644
+ if (!(seconds > 0)) {
33645
+ throw new Error(`the broker at ${endpoint} answered no usable expires_in (${JSON.stringify(answered.expires_in)})`);
33646
+ }
33647
+ const expiresAtText = typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "";
33648
+ let credentialExpiresAt = null;
33649
+ if (expiresAtText !== "") {
33650
+ credentialExpiresAt = new Date(expiresAtText);
33651
+ if (Number.isNaN(credentialExpiresAt.getTime())) {
33652
+ throw new Error(`the broker at ${endpoint} answered a credential_expires_at that is no RFC 3339 time (${JSON.stringify(expiresAtText)})`);
33653
+ }
33654
+ }
33655
+ return {
33656
+ accessToken: answered.access_token,
33657
+ tokenType,
33658
+ expiresAt: new Date(this.#now() + seconds * 1000),
33659
+ credentialId: typeof answered["credential_id"] === "string" ? answered["credential_id"] : "",
33660
+ credentialExpiresAt
33661
+ };
33662
+ }
33663
+ }
33664
+
33665
+ // ../broker-client/src/environment.ts
33666
+ var BROKER_URL_VAR = "AGENT_SECRETS_URL";
33667
+ var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
33668
+ var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
33669
+ var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
33670
+ var SESSION_VAR = "AGENT_SECRETS_SESSION";
33671
+ var IDENTITY_KUBERNETES = "kubernetes";
33672
+ var IDENTITY_METADATA = "metadata";
33673
+ var IDENTITY_POOL = "pool";
33674
+ function value(env, name) {
33675
+ return (env[name] ?? "").trim();
33676
+ }
33677
+ function required2(env, name, kind) {
33678
+ const named = value(env, name);
33679
+ if (named === "")
33680
+ throw new Error(`${name} is required by ${IDENTITY_VAR}=${kind}`);
33681
+ return named;
33682
+ }
33683
+ function machineIdentity(env) {
33684
+ const kind = value(env, IDENTITY_VAR);
33685
+ switch (kind) {
33686
+ case "":
33687
+ return;
33688
+ case IDENTITY_KUBERNETES:
33689
+ return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind));
33690
+ case IDENTITY_METADATA:
33691
+ return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
33692
+ case IDENTITY_POOL:
33693
+ 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}`);
33694
+ default:
33695
+ throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
33696
+ }
33697
+ }
33698
+ function tradeSession(env, own = "") {
33699
+ const acting = own.trim();
33700
+ return acting !== "" ? acting : value(env, SESSION_VAR);
33701
+ }
33702
+ async function brokerTokenClient(env, own = "") {
33703
+ const brokerUrl = value(env, BROKER_URL_VAR);
33704
+ const subject = machineIdentity(env);
33705
+ if (brokerUrl === "" || subject === undefined)
33706
+ return;
33707
+ return new BrokerTokenClient({
33708
+ brokerUrl,
33709
+ key: await newDpopKey(),
33710
+ subject,
33711
+ session: tradeSession(env, own),
33712
+ launcherCredential: false
33713
+ });
33714
+ }
33715
+
33716
+ // ../envoy-client/src/broker-credential.ts
33717
+ function sessionName(naming) {
33718
+ if (naming === undefined)
33719
+ return "";
33720
+ return (typeof naming === "string" ? naming : naming()).trim();
33721
+ }
33722
+ function brokerRouteConfigured(env) {
33723
+ if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
33724
+ return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
33725
+ }
33726
+ if ((env[IDENTITY_VAR] ?? "").trim() === IDENTITY_POOL) {
33727
+ return {
33728
+ traded: false,
33729
+ gap: `${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), never by this process`
33730
+ };
33731
+ }
33732
+ if (machineIdentity(env) === undefined) {
33733
+ return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
33734
+ }
33735
+ return { traded: true };
33736
+ }
33737
+ var CLIENTS = new Map;
33738
+ function forgetBrokerSession(session) {
33739
+ CLIENTS.delete(session.trim());
33740
+ }
33741
+ function clientFor(env, own) {
33742
+ const session = tradeSession(env, own);
33743
+ const key = JSON.stringify([
33744
+ env.AGENT_SECRETS_URL,
33745
+ env.AGENT_SECRETS_MACHINE_IDENTITY,
33746
+ env.AGENT_SECRETS_MACHINE_TOKEN_FILE,
33747
+ env.AGENT_SECRETS_MACHINE_AUDIENCE
33748
+ ]);
33749
+ const held = CLIENTS.get(session) ?? new Map;
33750
+ CLIENTS.set(session, held);
33751
+ const made = held.get(key) ?? brokerTokenClient(env, session);
33752
+ held.set(key, made);
33753
+ return made;
33754
+ }
33755
+ function brokerCredential(env, session) {
33756
+ let held = "";
33757
+ return {
33758
+ scheme: "DPoP",
33759
+ async headers(method, url, acting) {
33760
+ const client = await clientFor(env, (acting ?? "").trim() || sessionName(session));
33761
+ if (client === undefined) {
33762
+ throw new Error("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
33763
+ }
33764
+ const token = await client.token();
33765
+ held = token.accessToken;
33766
+ return {
33767
+ Authorization: `DPoP ${token.accessToken}`,
33768
+ DPoP: await client.key.proof({ method, url, accessToken: token.accessToken })
33769
+ };
33770
+ },
33771
+ secret: () => held
33772
+ };
33773
+ }
33774
+
31349
33775
  // ../../node_modules/.bun/@toon-format+toon@4.1.1/node_modules/@toon-format/toon/dist/index.mjs
31350
33776
  var NULL_LITERAL = "null";
31351
33777
  var DELIMITERS = {
@@ -31457,7 +33883,7 @@ function isEncodablePrimitive(value) {
31457
33883
  function isJsonArray(value) {
31458
33884
  return Array.isArray(value);
31459
33885
  }
31460
- function isJsonObject(value) {
33886
+ function isJsonObject2(value) {
31461
33887
  return value !== null && typeof value === "object" && !Array.isArray(value) && !isRawString(value);
31462
33888
  }
31463
33889
  function isEmptyObject(value) {
@@ -31476,7 +33902,7 @@ function isArrayOfArrays(value) {
31476
33902
  return value.length === 0 || value.every((item) => isJsonArray(item));
31477
33903
  }
31478
33904
  function isArrayOfObjects(value) {
31479
- return value.length === 0 || value.every((item) => isJsonObject(item));
33905
+ return value.length === 0 || value.every((item) => isJsonObject2(item));
31480
33906
  }
31481
33907
  var NUMERIC_LIKE_PATTERN = /^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
31482
33908
  function assertValidDelimiter(delimiter) {
@@ -31578,7 +34004,7 @@ function extractKeyedTabularFields(value) {
31578
34004
  const entryValues = Object.values(value);
31579
34005
  if (entryValues.length < 2)
31580
34006
  return;
31581
- if (!entryValues.every((entryValue) => isJsonObject(entryValue) && !isEmptyObject(entryValue)))
34007
+ if (!entryValues.every((entryValue) => isJsonObject2(entryValue) && !isEmptyObject(entryValue)))
31582
34008
  return;
31583
34009
  return extractTabularFields(entryValues);
31584
34010
  }
@@ -31590,7 +34016,7 @@ function collectRowLeaves(row, fields) {
31590
34016
  function classifyColumn(name, values) {
31591
34017
  if (values.every((value) => isEncodablePrimitive(value)))
31592
34018
  return { name };
31593
- if (!values.every((value) => isJsonObject(value) && !isEmptyObject(value)))
34019
+ if (!values.every((value) => isJsonObject2(value) && !isEmptyObject(value)))
31594
34020
  return;
31595
34021
  const children = extractTabularFields(values);
31596
34022
  if (!children)
@@ -31618,7 +34044,7 @@ function* encodeJsonValue(value, options, depth) {
31618
34044
  }
31619
34045
  if (isJsonArray(value))
31620
34046
  yield* encodeArrayLines(undefined, value, depth, options);
31621
- else if (isJsonObject(value)) {
34047
+ else if (isJsonObject2(value)) {
31622
34048
  const keyedFields = extractKeyedTabularFields(value);
31623
34049
  if (keyedFields) {
31624
34050
  yield* encodeKeyedObjectLines(undefined, value, keyedFields, depth, options);
@@ -31637,7 +34063,7 @@ function* encodeKeyValuePairLines(key, value, depth, options) {
31637
34063
  yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value, options.delimiter)}`, options.indentSize);
31638
34064
  else if (isJsonArray(value))
31639
34065
  yield* encodeArrayLines(key, value, depth, options);
31640
- else if (isJsonObject(value)) {
34066
+ else if (isJsonObject2(value)) {
31641
34067
  const keyedFields = extractKeyedTabularFields(value);
31642
34068
  if (keyedFields) {
31643
34069
  yield* encodeKeyedObjectLines(key, value, keyedFields, depth, options);
@@ -31752,7 +34178,7 @@ function* encodeObjectAsListItemLines(obj, depth, options) {
31752
34178
  return;
31753
34179
  }
31754
34180
  }
31755
- if (isJsonObject(firstValue)) {
34181
+ if (isJsonObject2(firstValue)) {
31756
34182
  const keyedFields = extractKeyedTabularFields(firstValue);
31757
34183
  if (keyedFields) {
31758
34184
  const keyedEntries = Object.entries(firstValue);
@@ -31781,7 +34207,7 @@ function* encodeObjectAsListItemLines(obj, depth, options) {
31781
34207
  for (const item of firstValue)
31782
34208
  yield* encodeListItemValueLines(item, depth + 2, options);
31783
34209
  }
31784
- else if (isJsonObject(firstValue)) {
34210
+ else if (isJsonObject2(firstValue)) {
31785
34211
  yield indentedListItem(depth, `${encodedKey}:`, options.indentSize);
31786
34212
  if (!isEmptyObject(firstValue))
31787
34213
  yield* encodeObjectLines(firstValue, depth + 2, options);
@@ -31800,7 +34226,7 @@ function* encodeListItemValueLines(value, depth, options) {
31800
34226
  for (const item of value)
31801
34227
  yield* encodeListItemValueLines(item, depth + 1, options);
31802
34228
  }
31803
- else if (isJsonObject(value))
34229
+ else if (isJsonObject2(value))
31804
34230
  yield* encodeObjectAsListItemLines(value, depth, options);
31805
34231
  }
31806
34232
  function indentedLine(depth, content, indentSize) {
@@ -31821,7 +34247,7 @@ function transformReplaced(original, replaced, replacer, path) {
31821
34247
  return transformChildren(normalizeValue(replaced), replacer, path);
31822
34248
  }
31823
34249
  function transformChildren(value, replacer, path) {
31824
- if (isJsonObject(value))
34250
+ if (isJsonObject2(value))
31825
34251
  return transformObject(value, replacer, path);
31826
34252
  if (isJsonArray(value))
31827
34253
  return transformArray(value, replacer, path);
@@ -31850,7 +34276,7 @@ function transformArray(arr, replacer, path) {
31850
34276
  }
31851
34277
  return result;
31852
34278
  }
31853
- function encode3(input, options) {
34279
+ function encode5(input, options) {
31854
34280
  return Array.from(encodeLines(input, options)).join(`
31855
34281
  `);
31856
34282
  }
@@ -32443,21 +34869,24 @@ function excerpt(text, token) {
32443
34869
  }
32444
34870
 
32445
34871
  class DispatchClient {
32446
- token;
32447
34872
  fetchImpl;
32448
34873
  writeRetry;
32449
34874
  #baseUrl;
32450
34875
  #resolvedIssues = new Map;
32451
34876
  #signal;
34877
+ #credential;
32452
34878
  #madeAt;
32453
- constructor(baseUrl, token, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
32454
- this.token = token;
34879
+ constructor(baseUrl, credential, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
32455
34880
  this.fetchImpl = fetchImpl;
32456
34881
  this.writeRetry = writeRetry;
34882
+ this.#credential = credential;
32457
34883
  this.#baseUrl = baseUrl.replace(/\/+$/, "");
32458
34884
  this.#signal = requestSignal(signal);
32459
34885
  this.#madeAt = this.#now();
32460
34886
  }
34887
+ get token() {
34888
+ return this.#credential.secret();
34889
+ }
32461
34890
  async issue(input) {
32462
34891
  const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
32463
34892
  return { ...answer.payload, created: answer.status === 201 };
@@ -32868,16 +35297,14 @@ class DispatchClient {
32868
35297
  return this.#response(method, url, response);
32869
35298
  }
32870
35299
  async#send(method, url, body, accept = "application/json", signal, callerKey) {
32871
- const headers = {
32872
- Accept: accept,
32873
- Authorization: `Bearer ${this.token}`
32874
- };
35300
+ const headers = { Accept: accept };
35301
+ let presented = await this.#credential.headers(method, url);
32875
35302
  if (body !== undefined)
32876
35303
  headers["Content-Type"] = body.type;
32877
35304
  if (method !== "POST" && method !== "PATCH") {
32878
35305
  return this.fetchImpl(url, {
32879
35306
  method,
32880
- headers,
35307
+ headers: { ...headers, ...presented },
32881
35308
  signal: signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]),
32882
35309
  ...body === undefined ? {} : { body: body.content }
32883
35310
  });
@@ -32898,7 +35325,10 @@ class DispatchClient {
32898
35325
  let answer;
32899
35326
  let thrown;
32900
35327
  try {
32901
- answer = await writeAnswer(await this.#attempt(url, method, headers, body, silenceMs), key);
35328
+ if (attempt > 1)
35329
+ presented = await this.#credential.headers(method, url);
35330
+ const sent = { ...headers, ...presented };
35331
+ answer = await writeAnswer(await this.#attempt(url, method, sent, body, silenceMs), key);
32902
35332
  if (answer.echoed)
32903
35333
  KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
32904
35334
  if (!answer.again)
@@ -32998,9 +35428,10 @@ class DispatchClient {
32998
35428
  }
32999
35429
  async#probeKeyedLayer() {
33000
35430
  try {
33001
- const response = await this.fetchImpl(`${this.#baseUrl}/healthz`, {
35431
+ const probe = `${this.#baseUrl}/healthz`;
35432
+ const response = await this.fetchImpl(probe, {
33002
35433
  method: "GET",
33003
- headers: { Accept: "application/json", Authorization: `Bearer ${this.token}` },
35434
+ headers: { Accept: "application/json", ...await this.#credential.headers("GET", probe) },
33004
35435
  signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
33005
35436
  });
33006
35437
  if (!isJson(response))
@@ -33304,7 +35735,8 @@ function dispatchReplyPath(resource, id) {
33304
35735
  return `/api/v1/${collection}/${encodeURIComponent(id)}/reply`;
33305
35736
  }
33306
35737
  async function postDeliveryReply(config, sessionId, delivery, result) {
33307
- await new DispatchClient(config.url, config.token).deliveryReply(delivery.resource, delivery.id, {
35738
+ const client = new DispatchClient(config.url, config.credential);
35739
+ await client.deliveryReply(delivery.resource, delivery.id, {
33308
35740
  actor: { kind: "session", id: sessionId },
33309
35741
  attempt: delivery.attempt,
33310
35742
  ...delivery.replyFields,
@@ -33670,7 +36102,7 @@ function dispatchPayload(event) {
33670
36102
  return parsed.success ? parsed.data : event.payload;
33671
36103
  }
33672
36104
  function hasTarget(value) {
33673
- return isObject2(value) && "target" in value;
36105
+ return isObject3(value) && "target" in value;
33674
36106
  }
33675
36107
  function dispatchPayloadForReader(event, sessionID) {
33676
36108
  const payload = dispatchPayload(event);
@@ -33708,7 +36140,7 @@ function dispatchReplyRef(event, topic, inReplyTo, comment) {
33708
36140
  return inReplyTo;
33709
36141
  return dispatchChildRef(dispatchDocumentRef(document.project, document.slug), kind, inReplyTo);
33710
36142
  }
33711
- function isObject2(value) {
36143
+ function isObject3(value) {
33712
36144
  return typeof value === "object" && value !== null;
33713
36145
  }
33714
36146
  function parseDispatchFrame(rawPayload) {
@@ -33718,7 +36150,7 @@ function parseDispatchFrame(rawPayload) {
33718
36150
  } catch {
33719
36151
  return { raw: rawPayload };
33720
36152
  }
33721
- if (isObject2(value) && "delivery" in value) {
36153
+ if (isObject3(value) && "delivery" in value) {
33722
36154
  const targeted = DispatchTargetedFrameSchema.safeParse(value);
33723
36155
  if (targeted.success) {
33724
36156
  const wireFrame = value;
@@ -33776,7 +36208,7 @@ function renderInbound(raw, sessionID, subject) {
33776
36208
  } catch {
33777
36209
  return {
33778
36210
  skip: false,
33779
- content: encode3({
36211
+ content: encode5({
33780
36212
  envoy: { topic: subject ?? "unknown", unrecognised: "payload was not JSON" }
33781
36213
  })
33782
36214
  };
@@ -33791,7 +36223,7 @@ function renderInbound(raw, sessionID, subject) {
33791
36223
  if (!tolerant.success) {
33792
36224
  return {
33793
36225
  skip: false,
33794
- content: encode3({ envoy: { unrecognised: parseIssues.join(", ") || "envelope" } })
36226
+ content: encode5({ envoy: { unrecognised: parseIssues.join(", ") || "envelope" } })
33795
36227
  };
33796
36228
  }
33797
36229
  const data = tolerant.data;
@@ -33984,7 +36416,7 @@ function renderInbound(raw, sessionID, subject) {
33984
36416
  };
33985
36417
  return {
33986
36418
  skip: false,
33987
- content: trailer === "" ? encode3({ envoy: rendered }) : `${encode3({ envoy: rendered })}
36419
+ content: trailer === "" ? encode5({ envoy: rendered }) : `${encode5({ envoy: rendered })}
33988
36420
 
33989
36421
  ${trailer}`,
33990
36422
  envelope,
@@ -34516,6 +36948,13 @@ function askgateSetting(filePath) {
34516
36948
  }
34517
36949
 
34518
36950
  // ../envoy-client/src/bearer.ts
36951
+ function bearerCredential(token) {
36952
+ return {
36953
+ scheme: "Bearer",
36954
+ headers: () => ({ Authorization: `Bearer ${token}` }),
36955
+ secret: () => token
36956
+ };
36957
+ }
34519
36958
  function bearerSource(env, section, written) {
34520
36959
  const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
34521
36960
  if (pointer !== undefined) {
@@ -34616,7 +37055,7 @@ function envoySettings(env, config, options = {}) {
34616
37055
  }
34617
37056
  const listener = section.url ?? DEFAULT_ENVOY_URL;
34618
37057
  const url = namedUrl ?? listener;
34619
- let token;
37058
+ let credential;
34620
37059
  try {
34621
37060
  const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
34622
37061
  token: section.token,
@@ -34625,7 +37064,11 @@ function envoySettings(env, config, options = {}) {
34625
37064
  server: listener,
34626
37065
  checkout: false
34627
37066
  });
34628
- token = source.kind === "none" ? undefined : source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env);
37067
+ if (source.kind === "none") {
37068
+ credential = brokerRouteConfigured(env).traded ? brokerCredential(env, options.session) : undefined;
37069
+ } else {
37070
+ credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
37071
+ }
34629
37072
  } catch (error) {
34630
37073
  return offWithError(messageFor(error));
34631
37074
  }
@@ -34648,7 +37091,7 @@ function envoySettings(env, config, options = {}) {
34648
37091
  return {
34649
37092
  enabled: true,
34650
37093
  url: normalizeEnvoyUrl(url),
34651
- token,
37094
+ credential,
34652
37095
  inbound,
34653
37096
  heartbeatMs,
34654
37097
  passDeadlineMs: Math.min(Math.max(namedPassDeadlineMs ?? MIN_PASS_DEADLINE_MS, heartbeatMs), MAX_INTERVAL_MS),
@@ -34836,14 +37279,22 @@ class EnvoySendUnconfirmedError extends Error {
34836
37279
  function createEnvoyClient(config) {
34837
37280
  const baseUrl = normalizeEnvoyUrl(config.baseUrl);
34838
37281
  const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
34839
- const apiToken = config.token;
34840
37282
  const attempts = config.retry === false ? 1 : 2;
34841
- const attemptOnce = async (url, init, deadlineMs) => {
34842
- const headers = new Headers(init.headers);
34843
- if (apiToken)
34844
- headers.set("Authorization", `Bearer ${apiToken}`);
37283
+ const credential = config.credential;
37284
+ const attemptOnce = async (url, init, deadlineMs, actingSession) => {
34845
37285
  let response;
37286
+ let unminted;
34846
37287
  try {
37288
+ const headers = new Headers(init.headers);
37289
+ let presented;
37290
+ try {
37291
+ const ready = credential?.headers(init.method ?? "GET", url, actingSession);
37292
+ presented = ready instanceof Promise ? await ready : ready;
37293
+ } catch (error) {
37294
+ unminted = error;
37295
+ }
37296
+ for (const [name, value] of Object.entries(presented ?? {}))
37297
+ headers.set(name, value);
34847
37298
  response = await config.fetch(url, {
34848
37299
  ...init,
34849
37300
  headers,
@@ -34852,6 +37303,11 @@ function createEnvoyClient(config) {
34852
37303
  } catch (error) {
34853
37304
  return { unanswered: error };
34854
37305
  }
37306
+ if (unminted !== undefined && (response.status === 401 || response.status === 403)) {
37307
+ return {
37308
+ unanswered: new Error(`${init.method ?? "GET"} ${url} answered ${response.status}, and this machine's Envoy credential could not be minted: ${messageFor(unminted)}`, { cause: unminted })
37309
+ };
37310
+ }
34855
37311
  try {
34856
37312
  return { response, body: await response.text() };
34857
37313
  } catch (error) {
@@ -34865,7 +37321,7 @@ function createEnvoyClient(config) {
34865
37321
  const url = `${baseUrl}${path}`;
34866
37322
  const tries = options.retry === false ? 1 : attempts;
34867
37323
  for (let attempt = 0;attempt < tries; attempt += 1) {
34868
- const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs);
37324
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession);
34869
37325
  if ("unanswered" in outcome) {
34870
37326
  options.onUnanswered?.();
34871
37327
  if (attempt + 1 < tries) {
@@ -34914,12 +37370,12 @@ function createEnvoyClient(config) {
34914
37370
  host: machineID(),
34915
37371
  plugin: input.plugin.name,
34916
37372
  plugin_version: input.plugin.version
34917
- }))),
37373
+ }, { actingSession: input.sessionID }))),
34918
37374
  unsubscribe: async (input) => {
34919
37375
  await post("/v1/interests/unsubscribe", {
34920
37376
  session_id: input.sessionID,
34921
37377
  topics: expandSubscriptionTopics(input.topics)
34922
- });
37378
+ }, { actingSession: input.sessionID });
34923
37379
  },
34924
37380
  getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
34925
37381
  send: async (input) => {
@@ -34937,7 +37393,8 @@ function createEnvoyClient(config) {
34937
37393
  }, {
34938
37394
  onUnanswered: () => {
34939
37395
  unanswered = true;
34940
- }
37396
+ },
37397
+ ...input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID }
34941
37398
  });
34942
37399
  response = EnvelopeResponseSchema.parse(JSON.parse(answer));
34943
37400
  } catch (error) {
@@ -34964,7 +37421,7 @@ function createEnvoyClient(config) {
34964
37421
  idempotency_key: idempotencyKey,
34965
37422
  ...messageMetadata(input),
34966
37423
  ...input.keep === undefined ? {} : { keep: input.keep }
34967
- })));
37424
+ }, input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID })));
34968
37425
  return {
34969
37426
  envelope: response,
34970
37427
  ...response.holder === undefined ? {} : { holder: response.holder },
@@ -34974,9 +37431,7 @@ function createEnvoyClient(config) {
34974
37431
  },
34975
37432
  unregisterSession: async (input) => {
34976
37433
  const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
34977
- await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, {
34978
- method: "DELETE"
34979
- });
37434
+ await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, { actingSession: input.sessionID });
34980
37435
  },
34981
37436
  setRole: async (input) => {
34982
37437
  const soft = input.soft === true;
@@ -34989,7 +37444,7 @@ function createEnvoyClient(config) {
34989
37444
  };
34990
37445
  let raw;
34991
37446
  try {
34992
- raw = await post("/v1/roles/set", body);
37447
+ raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
34993
37448
  } catch (error) {
34994
37449
  if (error instanceof EnvoyApiError && error.details.status === 409) {
34995
37450
  let answer;
@@ -35020,7 +37475,11 @@ function createEnvoyClient(config) {
35020
37475
  session_id: input.sessionID,
35021
37476
  subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
35022
37477
  ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
35023
- }, { timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS, retry: false })))
37478
+ }, {
37479
+ timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
37480
+ retry: false,
37481
+ actingSession: input.sessionID
37482
+ })))
35024
37483
  };
35025
37484
  }
35026
37485
  function waitForRetry() {
@@ -35731,7 +38190,7 @@ function replayNoticeFields(notice) {
35731
38190
  };
35732
38191
  }
35733
38192
  function envoyNoticeText(fields) {
35734
- return encode3({ envoy: fields });
38193
+ return encode5({ envoy: fields });
35735
38194
  }
35736
38195
  var PRIVATE_STREAM_SUBJECTS = [
35737
38196
  `${AGENT_TOPIC_PREFIX}>`,
@@ -35878,7 +38337,7 @@ var RelayHeader = {
35878
38337
  var RELAY_PROGRESS_INTERVAL_MS = 20000;
35879
38338
  var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
35880
38339
  var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
35881
- var decoder = new TextDecoder;
38340
+ var decoder4 = new TextDecoder;
35882
38341
  var DECIMAL = /^[0-9]+$/;
35883
38342
  var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
35884
38343
  function positiveInteger(text) {
@@ -35927,7 +38386,7 @@ function decodeRelayFrame(message) {
35927
38386
  storedAt,
35928
38387
  storedAtMs,
35929
38388
  gap: headers.get(RelayHeader.gap) === "true",
35930
- data: typeof message.data === "string" ? message.data : decoder.decode(message.data),
38389
+ data: typeof message.data === "string" ? message.data : decoder4.decode(message.data),
35931
38390
  reply
35932
38391
  }
35933
38392
  };
@@ -36298,6 +38757,12 @@ function registeredWithoutRelay(ledger, delivery, topics) {
36298
38757
 
36299
38758
  // ../envoy-client/src/dispatch-config.ts
36300
38759
  var DEFAULT_SERVER_URL = "http://localhost:8766";
38760
+ function withoutTrailingSlashes2(url) {
38761
+ let end = url.length;
38762
+ while (end > 0 && url[end - 1] === "/")
38763
+ end -= 1;
38764
+ return url.slice(0, end);
38765
+ }
36301
38766
  function checkoutPair(checkout, serverUrl) {
36302
38767
  const { token } = checkout.dispatch;
36303
38768
  if (token === undefined) {
@@ -36344,9 +38809,9 @@ function dispatchSettings(env, config, options = {}) {
36344
38809
  if (!target.enabled)
36345
38810
  return target;
36346
38811
  const { url, source } = target;
36347
- let token;
38812
+ let credential;
36348
38813
  try {
36349
- token = source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands);
38814
+ credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
36350
38815
  } catch (error) {
36351
38816
  return offWithError(messageFor(error));
36352
38817
  }
@@ -36358,13 +38823,24 @@ function dispatchSettings(env, config, options = {}) {
36358
38823
  return {
36359
38824
  enabled: true,
36360
38825
  url,
36361
- token,
38826
+ credential,
36362
38827
  ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
36363
38828
  };
36364
38829
  }
38830
+ function brokerRouteForced(env) {
38831
+ const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
38832
+ if (written === "")
38833
+ return false;
38834
+ if (written === "1")
38835
+ return true;
38836
+ 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`);
38837
+ }
36365
38838
  function dispatchTarget(env, config) {
36366
38839
  if (config.kind === "failed")
36367
38840
  return offWithError(config.error);
38841
+ const forced = brokerRouteForced(env);
38842
+ if (typeof forced !== "boolean")
38843
+ return forced;
36368
38844
  const explicitUrl = nonEmpty(env.DISPATCH_URL);
36369
38845
  const checkoutFile = explicitUrl === undefined ? config.checkout : null;
36370
38846
  if (checkoutFile?.kind === "invalid")
@@ -36388,13 +38864,28 @@ function dispatchTarget(env, config) {
36388
38864
  if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
36389
38865
  return offWithError("DISPATCH_URL must be an http or https URL");
36390
38866
  }
36391
- let source;
36392
- try {
36393
- source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
36394
- } catch (error) {
36395
- return offWithError(messageFor(error));
38867
+ let source = { kind: "none" };
38868
+ if (!forced) {
38869
+ try {
38870
+ source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
38871
+ } catch (error) {
38872
+ return offWithError(messageFor(error));
38873
+ }
36396
38874
  }
36397
38875
  if (source.kind === "none") {
38876
+ let route;
38877
+ try {
38878
+ route = brokerRouteConfigured(env);
38879
+ } catch (error) {
38880
+ return offWithError(messageFor(error));
38881
+ }
38882
+ if (route.traded) {
38883
+ const brokered = withoutTrailingSlashes2(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
38884
+ return { enabled: true, url: brokered, source: { kind: "broker" } };
38885
+ }
38886
+ if (forced) {
38887
+ 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`);
38888
+ }
36398
38889
  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}`);
36399
38890
  }
36400
38891
  const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
@@ -37051,7 +39542,7 @@ async function readSessionAnswers(options) {
37051
39542
  }
37052
39543
  let read = current.inFlight;
37053
39544
  if (read === undefined) {
37054
- const client = new DispatchClient(url, dispatch.token, options.fetchImpl ?? fetch);
39545
+ const client = new DispatchClient(url, dispatch.credential, options.fetchImpl ?? fetch);
37055
39546
  const started = client.sessionAnswers(session, {
37056
39547
  maxChars: SESSION_ANSWERS_MAX_CHARS,
37057
39548
  signal: AbortSignal.timeout(READ_TIMEOUT_MS)
@@ -37775,8 +40266,8 @@ function sessionSettings(file, env, options) {
37775
40266
  return { dispatch: off, envoy: off, notice: `${file.error}: Dispatch and Envoy are off` };
37776
40267
  }
37777
40268
  const config = readEnvoyConfig(file.path, env, options);
37778
- const dispatch = dispatchSettings(env, config);
37779
- const envoy = envoySettings(env, config, { nats: options.nats });
40269
+ const dispatch = dispatchSettings(env, config, { session: options.session });
40270
+ const envoy = envoySettings(env, config, { nats: options.nats, session: options.session });
37780
40271
  return {
37781
40272
  dispatch,
37782
40273
  envoy,
@@ -37788,7 +40279,10 @@ function sessionDispatchSettings(file, env, options) {
37788
40279
  return { dispatch: offWithError(file.error), warnings: [], missing: null };
37789
40280
  const config = readEnvoyConfig(file.path, env, options);
37790
40281
  return {
37791
- dispatch: dispatchSettings(env, config, { commands: options.commands }),
40282
+ dispatch: dispatchSettings(env, config, {
40283
+ commands: options.commands,
40284
+ session: options.session
40285
+ }),
37792
40286
  warnings: config.kind === "read" ? config.warnings : [],
37793
40287
  missing: config.kind === "read" ? config.missing : null
37794
40288
  };
@@ -38250,6 +40744,11 @@ function parseEnvoyToolArguments(operation, parameters) {
38250
40744
  return data;
38251
40745
  }
38252
40746
 
40747
+ // ../pi-shared/src/dispatch-session-id.ts
40748
+ function currentSessionID() {
40749
+ return process.env.DISPATCH_SESSION_ID ?? "";
40750
+ }
40751
+
38253
40752
  // ../pi-shared/src/interface.ts
38254
40753
  import { logger } from "@oh-my-pi/pi-utils";
38255
40754
 
@@ -38540,7 +41039,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
38540
41039
 
38541
41040
  // package.json
38542
41041
  var name = "@sjawhar/pi-envoy";
38543
- var version2 = "16.5.0";
41042
+ var version2 = "16.6.0";
38544
41043
  var package_default = {
38545
41044
  name,
38546
41045
  version: version2,
@@ -38589,10 +41088,10 @@ var package_default = {
38589
41088
  };
38590
41089
 
38591
41090
  // src/agent-stream.ts
38592
- var encoder2 = new TextEncoder;
41091
+ var encoder4 = new TextEncoder;
38593
41092
  var REPLAY_ARRAY_BYTES = 2;
38594
41093
  function jsonBytes(value) {
38595
- return encoder2.encode(JSON.stringify(value)).length;
41094
+ return encoder4.encode(JSON.stringify(value)).length;
38596
41095
  }
38597
41096
  var SEQ_PER_MS = 1000;
38598
41097
  function modelReference(provider, id) {
@@ -39269,7 +41768,7 @@ function withDelivery(text, delivered, clockOffset) {
39269
41768
  if (said.length > 0)
39270
41769
  fields.clocks = `${said.join("; ")}; ${whose}`;
39271
41770
  }
39272
- const added = encode3(fields).split(`
41771
+ const added = encode5(fields).split(`
39273
41772
  `).map((line) => ` ${line}`);
39274
41773
  return [...lines.slice(0, sentIndex + 1), ...added, ...lines.slice(sentIndex + 1)].join(`
39275
41774
  `);
@@ -39607,10 +42106,10 @@ function withDispatchFirst(messages, context) {
39607
42106
  }
39608
42107
 
39609
42108
  // src/dispatch-session.ts
39610
- function sessionDispatchClient(file, cwd, signal) {
39611
- const config = activeDispatchSettings(sessionDispatchSettings(file, process.env, { cwd }).dispatch);
42109
+ function sessionDispatchClient(file, cwd, signal, session) {
42110
+ const config = activeDispatchSettings(sessionDispatchSettings(file, process.env, { cwd, session }).dispatch);
39612
42111
  return config === null ? undefined : {
39613
- client: new DispatchClient(config.url, config.token, fetch, signal),
42112
+ client: new DispatchClient(config.url, config.credential, fetch, signal),
39614
42113
  serverUrls: dispatchServerUrls(config)
39615
42114
  };
39616
42115
  }
@@ -43997,7 +46496,7 @@ function registerAskGate(pi, host) {
43997
46496
  const record = createDecisionRecorder({
43998
46497
  env: process.env,
43999
46498
  now: Date.now,
44000
- dispatchClient: (directory, signal) => sessionDispatchClient(host.configFile, directory, signal)
46499
+ dispatchClient: (directory, signal) => sessionDispatchClient(host.configFile, directory, signal, host.session)
44001
46500
  });
44002
46501
  const loading = loadAskGate(pi, host, record);
44003
46502
  const gate = loading.then((handler) => handler, (error) => {
@@ -44132,7 +46631,7 @@ async function loadAskGate(pi, host, record) {
44132
46631
  logger: host.logger,
44133
46632
  runtimeLogger: host.runtimeLogger,
44134
46633
  configFile: host.configFile.path,
44135
- dispatchClient: (directory, signal) => sessionDispatchClient(host.configFile, directory, signal),
46634
+ dispatchClient: (directory, signal) => sessionDispatchClient(host.configFile, directory, signal, host.session),
44136
46635
  recordDecision: record,
44137
46636
  appendFile: appendDump,
44138
46637
  complete,
@@ -44362,15 +46861,19 @@ process.env.DISPATCH_HOST = "omp";
44362
46861
  var CONFIG_FILE = sessionConfigFile("omp", process.env);
44363
46862
  if (CONFIG_FILE.path !== null)
44364
46863
  process.env.ENVOY_CONFIG_FILE = CONFIG_FILE.path;
44365
- var timedDispatchClient = (ms) => sessionDispatchClient(CONFIG_FILE, process.cwd(), AbortSignal.timeout(ms))?.client;
46864
+ var timedDispatchClient = (ms) => sessionDispatchClient(CONFIG_FILE, process.cwd(), AbortSignal.timeout(ms), currentSessionID)?.client;
44366
46865
  function envoyExtension(pi) {
44367
46866
  logger3.debug("extension instance loaded", { extension: import.meta.url });
44368
46867
  const publishedInterface = publishEnvoyPluginInterface(import.meta.url);
44369
- const atStart = sessionSettings(CONFIG_FILE, process.env, { cwd: process.cwd() });
46868
+ const atStart = sessionSettings(CONFIG_FILE, process.env, {
46869
+ cwd: process.cwd(),
46870
+ session: currentSessionID
46871
+ });
44370
46872
  const { envoy } = atStart;
44371
46873
  const currentDispatchConfig = () => {
44372
46874
  const resolution = sessionDispatchSettings(CONFIG_FILE, process.env, {
44373
- cwd: process.cwd()
46875
+ cwd: process.cwd(),
46876
+ session: currentSessionID
44374
46877
  }).dispatch;
44375
46878
  const config = activeDispatchSettings(resolution);
44376
46879
  if (config === null) {
@@ -44405,7 +46908,7 @@ function envoyExtension(pi) {
44405
46908
  client: createEnvoyClient({
44406
46909
  baseUrl: envoy.url,
44407
46910
  fetch: serverClock.observing(fetch),
44408
- token: envoy.token
46911
+ credential: envoy.credential
44409
46912
  })
44410
46913
  } : undefined;
44411
46914
  const requireEnvoy = () => {
@@ -45682,7 +48185,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45682
48185
  notifiedSessions.add(current);
45683
48186
  pi.sendMessage({
45684
48187
  customType: "envoy-message",
45685
- content: encode3({
48188
+ content: encode5({
45686
48189
  envoy: {
45687
48190
  notice: "session id changed",
45688
48191
  previous_session_id: previous,
@@ -45716,10 +48219,12 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45716
48219
  continues.set(host, from);
45717
48220
  }
45718
48221
  knownSessions.add(from);
48222
+ leftSessions.add(from);
45719
48223
  }
45720
48224
  knownSessions.add(host);
45721
48225
  };
45722
48226
  const knownSessions = new Set;
48227
+ const leftSessions = new Set;
45723
48228
  const reconcile = (context, cause = {}) => registrationState.passes.run((handle) => reconcileNow(context, cause, handle)).then((decided) => decided ?? false);
45724
48229
  const reconcileNow = async (context, cause, handle) => {
45725
48230
  const host = context.sessionManager.getSessionId();
@@ -45738,6 +48243,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45738
48243
  }
45739
48244
  for (const other of handle.forgetOtherAgentSessions(host)) {
45740
48245
  closeIntentionally(agentSubject(other));
48246
+ leftSessions.add(other);
45741
48247
  }
45742
48248
  if (relay !== undefined && relay.sessionID !== host)
45743
48249
  closeRelay();
@@ -45779,6 +48285,10 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45779
48285
  triggerReplay();
45780
48286
  const decided = await registrationState.roleMoves.run((move) => settleRole(context, host, cause, registration === undefined, move)) ?? false;
45781
48287
  handle.check();
48288
+ leftSessions.delete(host);
48289
+ for (const other of leftSessions)
48290
+ forgetBrokerSession(other);
48291
+ leftSessions.clear();
45782
48292
  if (registration !== undefined) {
45783
48293
  throw new RegistrationError(messageFor(registration.error), { cause: registration.error });
45784
48294
  }
@@ -46082,7 +48592,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
46082
48592
  session,
46083
48593
  dispatch: sessionDispatchSettings(CONFIG_FILE, process.env, {
46084
48594
  cwd: process.cwd(),
46085
- commands: "kept"
48595
+ commands: "kept",
48596
+ session: currentSessionID
46086
48597
  }).dispatch,
46087
48598
  env: process.env
46088
48599
  });
@@ -46275,7 +48786,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
46275
48786
  const registration = registerAskGate(pi, {
46276
48787
  configFile: gateFile,
46277
48788
  logger: gateLogger,
46278
- runtimeLogger: logger3
48789
+ runtimeLogger: logger3,
48790
+ session: currentSessionID
46279
48791
  });
46280
48792
  askgateRecorder = registration;
46281
48793
  askgateLoad = registration.loaded.catch((error) => {