@sjawhar/codex-envoy 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23780,7 +23780,7 @@ function scrubProcessStreams() {
23780
23780
  import { spawn as spawn2 } from "child_process";
23781
23781
  import { unwatchFile as unwatchFile3, watchFile as watchFile3 } from "fs";
23782
23782
  import { homedir as homedir4 } from "os";
23783
- import { join as join18, resolve as resolve3 } from "path";
23783
+ import { join as join20, resolve as resolve3 } from "path";
23784
23784
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/core/core.js
23785
23785
  var NEVER = Object.freeze({
23786
23786
  status: "aborted"
@@ -40489,162 +40489,703 @@ function fileBearer(bearer, url, section, env, commands = "run") {
40489
40489
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
40490
40490
  }
40491
40491
 
40492
- // ../cipher-client/src/dpop.ts
40493
- import {
40494
- createHash,
40495
- createPrivateKey,
40496
- createPublicKey,
40497
- generateKeyPairSync,
40498
- randomUUID,
40499
- sign
40500
- } from "crypto";
40501
- var ALGORITHM = "ES256";
40502
- var CONNECTION_PROOF_METHOD = "CONNECT";
40503
- var CONNECTION_PROOF_TARGET = "nats:connect";
40504
- function targetUri(url) {
40505
- const parsed = new URL(url);
40506
- parsed.search = "";
40507
- parsed.hash = "";
40508
- return parsed.toString();
40492
+ // ../cipher-client/src/device-login.ts
40493
+ import { generateKeyPairSync as generateKeyPairSync2, randomUUID as randomUUID4 } from "crypto";
40494
+
40495
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
40496
+ var encoder2 = new TextEncoder;
40497
+ var decoder = new TextDecoder;
40498
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
40499
+ var MAX_INT32 = 2 ** 32;
40500
+ function concat(...buffers) {
40501
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
40502
+ const buf = new Uint8Array(size);
40503
+ let i = 0;
40504
+ for (const buffer of buffers) {
40505
+ buf.set(buffer, i);
40506
+ i += buffer.length;
40507
+ }
40508
+ return buf;
40509
+ }
40510
+ function encode3(string) {
40511
+ const bytes = new Uint8Array(string.length);
40512
+ for (let i = 0;i < string.length; i++) {
40513
+ const code = string.charCodeAt(i);
40514
+ if (code > 127) {
40515
+ throw new TypeError("non-ASCII string encountered in encode()");
40516
+ }
40517
+ bytes[i] = code;
40518
+ }
40519
+ return bytes;
40509
40520
  }
40510
- function dpopKey(privateKey, publicJwk) {
40511
- const header = Buffer.from(JSON.stringify({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk })).toString("base64url");
40512
- const signed = (htm, htu, nonce, accessToken) => {
40513
- const claims = {
40514
- jti: randomUUID(),
40515
- htm,
40516
- htu,
40517
- iat: Math.floor(Date.now() / 1000)
40518
- };
40519
- if (nonce !== undefined && nonce !== "")
40520
- claims["nonce"] = nonce;
40521
- if (accessToken !== undefined && accessToken !== "") {
40522
- claims["ath"] = createHash("sha256").update(accessToken).digest("base64url");
40523
- }
40524
- const signingInput = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
40525
- const signature = sign("sha256", Buffer.from(signingInput), {
40526
- key: privateKey,
40527
- dsaEncoding: "ieee-p1363"
40528
- });
40529
- return `${signingInput}.${signature.toString("base64url")}`;
40530
- };
40531
- return {
40532
- publicJwk,
40533
- async proof(request) {
40534
- return signed(request.method.toUpperCase(), targetUri(request.url), request.nonce, request.accessToken);
40535
- },
40536
- connectionProof({ accessToken, nonce }) {
40537
- if (accessToken === "")
40538
- throw new Error("no access token to prove a NATS connection for");
40539
- if (nonce === "")
40540
- throw new Error("the NATS server sent no nonce to sign");
40541
- return signed(CONNECTION_PROOF_METHOD, CONNECTION_PROOF_TARGET, nonce, accessToken);
40521
+
40522
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
40523
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
40524
+ function checkUsage(key, usage) {
40525
+ if (usage && !key.usages.includes(usage)) {
40526
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
40527
+ }
40528
+ }
40529
+ function checkModulusLength(alg, key) {
40530
+ const { modulusLength } = key.algorithm;
40531
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
40532
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
40533
+ }
40534
+ }
40535
+ function checkCryptoKey(key, expected, usage) {
40536
+ const algorithm = key.algorithm;
40537
+ if (algorithm.name !== expected.name) {
40538
+ throw unusable(expected.name);
40539
+ }
40540
+ if (expected.hash && algorithm.hash?.name !== expected.hash) {
40541
+ throw unusable(expected.hash, "algorithm.hash");
40542
+ }
40543
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
40544
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
40545
+ }
40546
+ if (expected.length !== undefined && algorithm.length !== expected.length) {
40547
+ throw unusable(expected.length, "algorithm.length");
40548
+ }
40549
+ checkUsage(key, usage);
40550
+ }
40551
+
40552
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
40553
+ function message(msg, actual, ...types) {
40554
+ if (types.length > 2) {
40555
+ const last = types.pop();
40556
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
40557
+ } else if (types.length === 2) {
40558
+ msg += `one of type ${types[0]} or ${types[1]}.`;
40559
+ } else {
40560
+ msg += `of type ${types[0]}.`;
40561
+ }
40562
+ if (actual == null) {
40563
+ msg += ` Received ${actual}`;
40564
+ } else if (typeof actual === "function" && actual.name) {
40565
+ msg += ` Received function ${actual.name}`;
40566
+ } else if (typeof actual === "object" && actual != null) {
40567
+ if (actual.constructor?.name) {
40568
+ msg += ` Received an instance of ${actual.constructor.name}`;
40542
40569
  }
40543
- };
40570
+ }
40571
+ return msg;
40544
40572
  }
40545
- function publicJwkOf(privateKey, name) {
40546
- const { kty, crv, x, y } = createPublicKey(privateKey).export({ format: "jwk" });
40547
- if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
40548
- throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
40573
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
40574
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
40575
+
40576
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
40577
+ class JOSEError extends Error {
40578
+ static code = "ERR_JOSE_GENERIC";
40579
+ code = "ERR_JOSE_GENERIC";
40580
+ constructor(message, options) {
40581
+ super(message, options);
40582
+ this.name = this.constructor.name;
40583
+ Error.captureStackTrace?.(this, this.constructor);
40549
40584
  }
40550
- return { kty, crv, x, y };
40551
40585
  }
40552
- async function newDpopKey() {
40553
- const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
40554
- return dpopKey(privateKey, publicJwkOf(privateKey, "this process's key"));
40586
+ class JOSENotSupported extends JOSEError {
40587
+ static code = "ERR_JOSE_NOT_SUPPORTED";
40588
+ code = "ERR_JOSE_NOT_SUPPORTED";
40555
40589
  }
40556
- async function importDpopKey(pkcs8Pem, name) {
40557
- let privateKey;
40590
+ class JWSInvalid extends JOSEError {
40591
+ static code = "ERR_JWS_INVALID";
40592
+ code = "ERR_JWS_INVALID";
40593
+ }
40594
+ class JWKInvalid extends JOSEError {
40595
+ static code = "ERR_JWK_INVALID";
40596
+ code = "ERR_JWK_INVALID";
40597
+ }
40598
+
40599
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
40600
+ var isCryptoKey = (key) => {
40601
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
40602
+ return true;
40558
40603
  try {
40559
- privateKey = createPrivateKey(pkcs8Pem);
40604
+ return key instanceof CryptoKey;
40560
40605
  } catch {
40561
- throw new Error(`read ${name}: it does not parse as a PKCS#8 PEM private key`);
40606
+ return false;
40562
40607
  }
40563
- return dpopKey(privateKey, publicJwkOf(privateKey, name));
40608
+ };
40609
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
40610
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
40611
+
40612
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
40613
+ function encodeBase64(input) {
40614
+ if (Uint8Array.prototype.toBase64) {
40615
+ return input.toBase64();
40616
+ }
40617
+ const CHUNK_SIZE = 32768;
40618
+ const arr = [];
40619
+ for (let i = 0;i < input.length; i += CHUNK_SIZE) {
40620
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
40621
+ }
40622
+ return btoa(arr.join(""));
40623
+ }
40624
+ function decodeBase64(encoded) {
40625
+ if (Uint8Array.fromBase64) {
40626
+ return Uint8Array.fromBase64(encoded);
40627
+ }
40628
+ const binary = atob(encoded);
40629
+ const bytes = new Uint8Array(binary.length);
40630
+ for (let i = 0;i < binary.length; i++) {
40631
+ bytes[i] = binary.charCodeAt(i);
40632
+ }
40633
+ return bytes;
40564
40634
  }
40565
40635
 
40566
- // ../cipher-client/src/metadata-identity.ts
40567
- import { Agent, request } from "http";
40636
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
40637
+ var invalid = "The input to be decoded is not correctly encoded.";
40638
+ function decode3(input) {
40639
+ if (Uint8Array.fromBase64) {
40640
+ try {
40641
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
40642
+ alphabet: "base64url"
40643
+ });
40644
+ } catch (cause) {
40645
+ throw new TypeError(invalid, { cause });
40646
+ }
40647
+ }
40648
+ let encoded = input;
40649
+ if (encoded instanceof Uint8Array) {
40650
+ encoded = decoder.decode(encoded);
40651
+ }
40652
+ if (encoded.includes("+") || encoded.includes("/")) {
40653
+ throw new TypeError(invalid);
40654
+ }
40655
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
40656
+ try {
40657
+ return decodeBase64(encoded);
40658
+ } catch {
40659
+ throw new TypeError(invalid);
40660
+ }
40661
+ }
40662
+ function encode4(input) {
40663
+ let unencoded = input;
40664
+ if (typeof unencoded === "string") {
40665
+ unencoded = encoder2.encode(unencoded);
40666
+ }
40667
+ if (Uint8Array.prototype.toBase64) {
40668
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
40669
+ }
40670
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
40671
+ }
40568
40672
 
40569
- // ../cipher-client/src/wire.ts
40570
- var TOKEN_PATH = "/v1/oauth/token";
40571
- var GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
40572
- var EXCHANGE_CLIENT_ID = "dispatch-token-exchange";
40573
- var FORM_SESSION = "session";
40574
- var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
40575
- var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
40576
- var FORM_PROJECTS = "projects";
40577
- var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
40578
- var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
40579
- var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
40580
- var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
40581
- var TOKEN_TYPE_DPOP = "DPoP";
40582
- var POD_SESSION_NOT_REGISTERED = "pod_session_not_registered";
40583
- var SESSION_NAME_NOT_THIS_REGISTRARS = "session_name_not_this_registrars";
40673
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
40674
+ function isObject2(input) {
40675
+ if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
40676
+ return false;
40677
+ }
40678
+ const prototype = Object.getPrototypeOf(input);
40679
+ if (prototype === null) {
40680
+ return true;
40681
+ }
40682
+ let proto = prototype;
40683
+ while (Object.getPrototypeOf(proto) !== null) {
40684
+ proto = Object.getPrototypeOf(proto);
40685
+ }
40686
+ return prototype === proto;
40687
+ }
40688
+ function isDisjoint(...headers) {
40689
+ const parameters = new Set;
40690
+ for (const header of headers) {
40691
+ if (!header)
40692
+ continue;
40693
+ for (const parameter of Object.keys(header)) {
40694
+ if (parameters.has(parameter)) {
40695
+ return false;
40696
+ }
40697
+ parameters.add(parameter);
40698
+ }
40699
+ }
40700
+ return true;
40701
+ }
40702
+ var isJWK = (key) => isObject2(key) && typeof key.kty === "string";
40703
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
40704
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
40705
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
40584
40706
 
40585
- // ../cipher-client/src/metadata-identity.ts
40586
- var METADATA_HOST_VAR = "GCE_METADATA_HOST";
40587
- var DEFAULT_METADATA_HOST = "metadata.google.internal";
40588
- var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
40589
- var TIMEOUT_MS = 1e4;
40590
- var MAX_ANSWER_BYTES = 1 << 20;
40591
- var agent = new Agent({ keepAlive: false });
40592
- function tokenUrl(audience, env) {
40593
- const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
40594
- return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
40707
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/helpers.js
40708
+ var unprotected = Symbol();
40709
+ function assertNotSet(value, name) {
40710
+ if (value) {
40711
+ throw new TypeError(`${name} can only be called once`);
40712
+ }
40595
40713
  }
40596
- function serverNamed(env) {
40597
- return (env[METADATA_HOST_VAR] ?? "").trim() === "" ? `at ${DEFAULT_METADATA_HOST}` : `${METADATA_HOST_VAR} names`;
40714
+ async function digest(algorithm, data) {
40715
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
40716
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
40598
40717
  }
40599
- function get(url, signal, lookup) {
40600
- const { promise, resolve, reject } = Promise.withResolvers();
40601
- const call = request(url, {
40602
- agent,
40603
- method: "GET",
40604
- headers: { "Metadata-Flavor": "Google" },
40605
- timeout: TIMEOUT_MS,
40606
- ...signal === undefined ? {} : { signal },
40607
- ...lookup === undefined ? {} : { lookup }
40608
- }, (answer) => {
40609
- const chunks = [];
40610
- let read = 0;
40611
- answer.on("data", (chunk) => {
40612
- read += chunk.length;
40613
- if (read <= MAX_ANSWER_BYTES)
40614
- chunks.push(chunk);
40615
- });
40616
- answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
40617
- answer.on("error", reject);
40618
- });
40619
- call.on("timeout", () => call.destroy(Object.assign(new Error(`no answer within ${TIMEOUT_MS} ms`), { code: "ETIMEDOUT" })));
40620
- call.on("error", reject);
40621
- call.end();
40622
- return promise;
40718
+
40719
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwk_to_key.js
40720
+ async function jwkToKey(entry, jwk) {
40721
+ if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== undefined) {
40722
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
40723
+ }
40724
+ if (!entry.kty.includes(jwk.kty)) {
40725
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
40726
+ }
40727
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle;
40728
+ const isPrivate = !!(jwk.d || jwk.priv);
40729
+ const keyData = { ...jwk };
40730
+ if (keyData.kty !== "AKP") {
40731
+ delete keyData.alg;
40732
+ }
40733
+ delete keyData.use;
40734
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
40623
40735
  }
40624
- function metadataIdentity(audience, env = process.env, options = {}) {
40625
- return {
40626
- async read(signal) {
40627
- const url = tokenUrl(audience, env);
40628
- const named = `the metadata server ${serverNamed(env)}`;
40629
- let answer;
40630
- try {
40631
- answer = await get(url, signal, options.lookup);
40632
- } catch (error) {
40633
- throw new Error(`${named} could not be reached: ${errorClass(error)}`);
40736
+
40737
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key.js
40738
+ var tag = (key) => key[Symbol.toStringTag];
40739
+ var jwkMatchesOp = (entry, key, usage) => {
40740
+ const { alg } = entry;
40741
+ if (key.use !== undefined) {
40742
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
40743
+ if (key.use !== expected) {
40744
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
40745
+ }
40746
+ }
40747
+ if (key.alg !== undefined && key.alg !== alg) {
40748
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
40749
+ }
40750
+ if (Array.isArray(key.key_ops)) {
40751
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
40752
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
40753
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
40754
+ }
40755
+ }
40756
+ };
40757
+ function checkKeyType(entry, key, usage) {
40758
+ const { alg, secret } = entry;
40759
+ const privateKey = usage === "decrypt" || usage === "sign";
40760
+ if (secret && key instanceof Uint8Array)
40761
+ return [BYTES, key];
40762
+ if (isJWK(key)) {
40763
+ if (secret ? !isSecretJWK(key) : !(privateKey ? isPrivateJWK(key) : isPublicJWK(key))) {
40764
+ 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`);
40765
+ }
40766
+ jwkMatchesOp(entry, key, usage);
40767
+ return [JWK, key];
40768
+ }
40769
+ if (!isKeyLike(key)) {
40770
+ throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
40771
+ }
40772
+ if (secret) {
40773
+ if (key.type !== "secret") {
40774
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
40775
+ }
40776
+ } else {
40777
+ if (key.type === "secret") {
40778
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
40779
+ }
40780
+ const expectedType = privateKey ? "private" : "public";
40781
+ if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
40782
+ const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
40783
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
40784
+ }
40785
+ }
40786
+ return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
40787
+ }
40788
+ var BYTES = 0;
40789
+ var CRYPTO = 1;
40790
+ var KEYOBJECT = 2;
40791
+ var JWK = 3;
40792
+ var cache;
40793
+ var nist = {
40794
+ __proto__: null,
40795
+ prime256v1: "P-256",
40796
+ secp384r1: "P-384",
40797
+ secp521r1: "P-521"
40798
+ };
40799
+ function cached2(key, alg, value) {
40800
+ cache ||= new WeakMap;
40801
+ const entry = cache.get(key);
40802
+ if (value) {
40803
+ if (entry) {
40804
+ entry[alg] = value;
40805
+ } else {
40806
+ cache.set(key, { __proto__: null, [alg]: value });
40807
+ }
40808
+ }
40809
+ return value ?? entry?.[alg];
40810
+ }
40811
+ var handleJWK = async (key, jwk, entry) => cached2(key, entry.alg) ?? cached2(key, entry.alg, await jwkToKey(entry, { ...jwk, alg: entry.alg }));
40812
+ var handleKeyObject = (keyObject, entry) => {
40813
+ const hit = cached2(keyObject, entry.alg);
40814
+ if (hit)
40815
+ return hit;
40816
+ const isPublic = keyObject.type === "public";
40817
+ const usages = entry.usages[isPublic ? 0 : 1];
40818
+ const { asymmetricKeyType } = keyObject;
40819
+ const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
40820
+ const params = entry.resolve?.({ crv, asymmetricKeyType }) ?? entry.subtle;
40821
+ return cached2(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
40822
+ };
40823
+ async function prepareKey(entry, key, usage) {
40824
+ const tagged = checkKeyType(entry, key, usage);
40825
+ switch (tagged[0]) {
40826
+ case BYTES:
40827
+ case CRYPTO:
40828
+ return tagged[1];
40829
+ case JWK: {
40830
+ const key = tagged[1];
40831
+ if (key.k) {
40832
+ return decode3(key.k);
40634
40833
  }
40635
- if (answer.status < 200 || answer.status > 299) {
40636
- throw new Error(`${named} answered HTTP ${answer.status}`);
40834
+ if (!Object.isFrozen(key)) {
40835
+ const { key_ops } = key;
40836
+ if (Array.isArray(key_ops))
40837
+ Object.freeze(key_ops);
40838
+ Object.freeze(key);
40637
40839
  }
40638
- const token = answer.body.trim();
40639
- if (token === "") {
40640
- throw new Error(`${named} answered an empty identity token`);
40840
+ return handleJWK(key, key, entry);
40841
+ }
40842
+ case KEYOBJECT: {
40843
+ const keyObject = tagged[1];
40844
+ if (keyObject.type === "secret") {
40845
+ return keyObject.export();
40641
40846
  }
40642
- return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
40643
- },
40644
- describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
40847
+ if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
40848
+ return handleKeyObject(keyObject, entry);
40849
+ }
40850
+ return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
40851
+ }
40852
+ }
40853
+ }
40854
+
40855
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_descriptor.js
40856
+ function table(entries) {
40857
+ const out = { __proto__: null };
40858
+ for (const alg in entries) {
40859
+ out[alg] = { ...entries[alg], alg };
40860
+ }
40861
+ return out;
40862
+ }
40863
+
40864
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/options.js
40865
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
40866
+ function validateCritDuplicates(Err, protectedHeader) {
40867
+ const { crit } = protectedHeader ?? {};
40868
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length) {
40869
+ throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
40870
+ }
40871
+ }
40872
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
40873
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
40874
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
40875
+ }
40876
+ if (!protectedHeader || protectedHeader.crit === undefined) {
40877
+ return [];
40878
+ }
40879
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
40880
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
40881
+ }
40882
+ const recognized = recognizedOption === undefined ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
40883
+ for (const parameter of protectedHeader.crit) {
40884
+ if (!(parameter in recognized)) {
40885
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
40886
+ }
40887
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === undefined) {
40888
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
40889
+ }
40890
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === undefined)) {
40891
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
40892
+ }
40893
+ }
40894
+ return protectedHeader.crit;
40895
+ }
40896
+
40897
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/signing.js
40898
+ async function getSigKey(entry, key, usage) {
40899
+ if (key instanceof Uint8Array) {
40900
+ return crypto.subtle.importKey("raw", key, entry.subtle, false, [
40901
+ usage
40902
+ ]);
40903
+ }
40904
+ checkCryptoKey(key, entry.subtle, usage);
40905
+ if (entry.minRsaBits)
40906
+ checkModulusLength(entry.alg, key);
40907
+ return key;
40908
+ }
40909
+ async function sign(entry, key, data) {
40910
+ const cryptoKey = await getSigKey(entry, key, "sign");
40911
+ const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
40912
+ return new Uint8Array(signature);
40913
+ }
40914
+
40915
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_algorithms.js
40916
+ var sig = [["verify"], ["sign"]];
40917
+ function hmac(bits) {
40918
+ const subtle = { name: "HMAC", hash: `SHA-${bits}` };
40919
+ return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
40920
+ }
40921
+ function rsa(bits, saltLength) {
40922
+ const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
40923
+ const subtle = { name, hash: `SHA-${bits}` };
40924
+ return {
40925
+ kty: ["RSA"],
40926
+ subtle,
40927
+ signing: saltLength ? { ...subtle, saltLength } : subtle,
40928
+ usages: sig,
40929
+ minRsaBits: 2048
40930
+ };
40931
+ }
40932
+ function ecdsa(crv, bits) {
40933
+ return {
40934
+ kty: ["EC"],
40935
+ crv,
40936
+ subtle: { name: "ECDSA", namedCurve: crv },
40937
+ signing: { name: "ECDSA", hash: `SHA-${bits}` },
40938
+ usages: sig
40939
+ };
40940
+ }
40941
+ function eddsa() {
40942
+ const subtle = { name: "Ed25519" };
40943
+ return {
40944
+ kty: ["OKP"],
40945
+ crv: "Ed25519",
40946
+ subtle,
40947
+ signing: subtle,
40948
+ usages: sig
40645
40949
  };
40646
40950
  }
40951
+ function mldsa(bits) {
40952
+ const name = `ML-DSA-${bits}`;
40953
+ const subtle = { name };
40954
+ return {
40955
+ kty: ["AKP"],
40956
+ subtle,
40957
+ signing: subtle,
40958
+ usages: sig
40959
+ };
40960
+ }
40961
+ var JWS = table({
40962
+ HS256: hmac(256),
40963
+ HS384: hmac(384),
40964
+ HS512: hmac(512),
40965
+ RS256: rsa(256),
40966
+ RS384: rsa(384),
40967
+ RS512: rsa(512),
40968
+ PS256: rsa(256, 32),
40969
+ PS384: rsa(384, 48),
40970
+ PS512: rsa(512, 64),
40971
+ ES256: ecdsa("P-256", 256),
40972
+ ES384: ecdsa("P-384", 384),
40973
+ ES512: ecdsa("P-521", 512),
40974
+ EdDSA: eddsa(),
40975
+ Ed25519: eddsa(),
40976
+ "ML-DSA-44": mldsa(44),
40977
+ "ML-DSA-65": mldsa(65),
40978
+ "ML-DSA-87": mldsa(87)
40979
+ });
40980
+ function jwsAlgorithm(alg) {
40981
+ const entry = typeof alg === "string" ? JWS[alg] : undefined;
40982
+ if (!entry) {
40983
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
40984
+ }
40985
+ return entry;
40986
+ }
40987
+
40988
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_sign.js
40989
+ function unencodedPayload(protectedHeader) {
40990
+ return protectedHeader?.b64 === false && Array.isArray(protectedHeader.crit) && protectedHeader.crit.includes("b64");
40991
+ }
40992
+ async function createSignature(input, key) {
40993
+ const { protectedHeader, unprotectedHeader } = input;
40994
+ if (!protectedHeader && !unprotectedHeader) {
40995
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
40996
+ }
40997
+ if (!isDisjoint(protectedHeader, unprotectedHeader)) {
40998
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
40999
+ }
41000
+ const joseHeader = { ...protectedHeader, ...unprotectedHeader };
41001
+ validateCritDuplicates(JWSInvalid, protectedHeader);
41002
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, input.crit, protectedHeader, joseHeader);
41003
+ let b64 = true;
41004
+ if (extensions.includes("b64")) {
41005
+ b64 = protectedHeader.b64;
41006
+ if (typeof b64 !== "boolean") {
41007
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
41008
+ }
41009
+ }
41010
+ const { alg } = joseHeader;
41011
+ if (typeof alg !== "string" || !alg) {
41012
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
41013
+ }
41014
+ const entry = jwsAlgorithm(alg);
41015
+ let payloadS;
41016
+ let payloadB;
41017
+ if (b64) {
41018
+ const encoded = input.encoded ??= [];
41019
+ encoded[0] ??= encode4(input.payload);
41020
+ encoded[1] ??= encode3(encoded[0]);
41021
+ payloadS = encoded[0];
41022
+ payloadB = encoded[1];
41023
+ } else {
41024
+ payloadB = input.payload;
41025
+ payloadS = "";
41026
+ }
41027
+ let protectedHeaderString;
41028
+ let protectedHeaderBytes;
41029
+ if (protectedHeader) {
41030
+ protectedHeaderString = encode4(JSON.stringify(protectedHeader));
41031
+ protectedHeaderBytes = encode3(protectedHeaderString);
41032
+ } else {
41033
+ protectedHeaderString = "";
41034
+ protectedHeaderBytes = new Uint8Array;
41035
+ }
41036
+ const data = concat(protectedHeaderBytes, encode3("."), payloadB);
41037
+ const k = await prepareKey(entry, key, "sign");
41038
+ const signature = await sign(entry, k, data);
41039
+ const jws = {
41040
+ signature: encode4(signature),
41041
+ payload: payloadS
41042
+ };
41043
+ if (protectedHeader) {
41044
+ jws.protected = protectedHeaderString;
41045
+ }
41046
+ if (unprotectedHeader) {
41047
+ jws.header = unprotectedHeader;
41048
+ }
41049
+ return jws;
41050
+ }
41051
+
41052
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/flattened/sign.js
41053
+ class FlattenedSign {
41054
+ #payload;
41055
+ #protectedHeader;
41056
+ #unprotectedHeader;
41057
+ constructor(payload) {
41058
+ if (!(payload instanceof Uint8Array)) {
41059
+ throw new TypeError("payload must be an instance of Uint8Array");
41060
+ }
41061
+ this.#payload = payload;
41062
+ }
41063
+ setProtectedHeader(protectedHeader) {
41064
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
41065
+ this.#protectedHeader = protectedHeader;
41066
+ return this;
41067
+ }
41068
+ setUnprotectedHeader(unprotectedHeader) {
41069
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
41070
+ this.#unprotectedHeader = unprotectedHeader;
41071
+ return this;
41072
+ }
41073
+ async sign(key, options) {
41074
+ return createSignature({
41075
+ payload: this.#payload,
41076
+ protectedHeader: this.#protectedHeader,
41077
+ unprotectedHeader: this.#unprotectedHeader,
41078
+ crit: options?.crit
41079
+ }, key);
41080
+ }
41081
+ }
41082
+
41083
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/compact/sign.js
41084
+ class CompactSign {
41085
+ #flattened;
41086
+ #protectedHeader;
41087
+ constructor(payload) {
41088
+ this.#flattened = new FlattenedSign(payload);
41089
+ }
41090
+ setProtectedHeader(protectedHeader) {
41091
+ this.#flattened.setProtectedHeader(protectedHeader);
41092
+ this.#protectedHeader = protectedHeader;
41093
+ return this;
41094
+ }
41095
+ async sign(key, options) {
41096
+ if (unencodedPayload(this.#protectedHeader)) {
41097
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
41098
+ }
41099
+ const jws = await this.#flattened.sign(key, options);
41100
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
41101
+ }
41102
+ }
41103
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
41104
+ function omitUndefinedProperties(jwk) {
41105
+ return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
41106
+ }
41107
+ async function keyToJWK(key) {
41108
+ if (isKeyObject(key)) {
41109
+ if (key.type === "secret") {
41110
+ key = key.export();
41111
+ } else {
41112
+ return key.export({ format: "jwk" });
41113
+ }
41114
+ }
41115
+ if (key instanceof Uint8Array) {
41116
+ return {
41117
+ kty: "oct",
41118
+ k: encode4(key)
41119
+ };
41120
+ }
41121
+ if (!isCryptoKey(key)) {
41122
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
41123
+ }
41124
+ if (!key.extractable) {
41125
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
41126
+ }
41127
+ const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
41128
+ if (jwk.kty === "AKP") {
41129
+ jwk.alg = alg;
41130
+ }
41131
+ return jwk;
41132
+ }
41133
+ function exportJWK(key) {
41134
+ return keyToJWK(key);
41135
+ }
40647
41136
 
41137
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jwk/thumbprint.js
41138
+ var check2 = (value, description) => {
41139
+ if (typeof value !== "string" || !value) {
41140
+ throw new JWKInvalid(`${description} missing or invalid`);
41141
+ }
41142
+ };
41143
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
41144
+ let jwk;
41145
+ if (isJWK(key)) {
41146
+ jwk = key;
41147
+ } else if (isKeyLike(key)) {
41148
+ jwk = await exportJWK(key);
41149
+ } else {
41150
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
41151
+ }
41152
+ digestAlgorithm ??= "sha256";
41153
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
41154
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
41155
+ }
41156
+ let components;
41157
+ switch (jwk.kty) {
41158
+ case "AKP":
41159
+ check2(jwk.alg, '"alg" (Algorithm) Parameter');
41160
+ check2(jwk.pub, '"pub" (Public key) Parameter');
41161
+ components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
41162
+ break;
41163
+ case "EC":
41164
+ check2(jwk.crv, '"crv" (Curve) Parameter');
41165
+ check2(jwk.x, '"x" (X Coordinate) Parameter');
41166
+ check2(jwk.y, '"y" (Y Coordinate) Parameter');
41167
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
41168
+ break;
41169
+ case "OKP":
41170
+ check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
41171
+ check2(jwk.x, '"x" (Public Key) Parameter');
41172
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
41173
+ break;
41174
+ case "RSA":
41175
+ check2(jwk.e, '"e" (Exponent) Parameter');
41176
+ check2(jwk.n, '"n" (Modulus) Parameter');
41177
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
41178
+ break;
41179
+ case "oct":
41180
+ check2(jwk.k, '"k" (Key Value) Parameter');
41181
+ components = { k: jwk.k, kty: jwk.kty };
41182
+ break;
41183
+ default:
41184
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
41185
+ }
41186
+ const data = encode3(JSON.stringify(components));
41187
+ return encode4(await digest(digestAlgorithm, data));
41188
+ }
40648
41189
  // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
40649
41190
  var USER_AGENT;
40650
41191
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
@@ -40676,13 +41217,13 @@ var customFetch = Symbol();
40676
41217
  var modifyAssertion = Symbol();
40677
41218
  var jweDecrypt = Symbol();
40678
41219
  var jwksCache = Symbol();
40679
- var encoder2 = new TextEncoder;
40680
- var decoder = new TextDecoder;
41220
+ var encoder3 = new TextEncoder;
41221
+ var decoder2 = new TextDecoder;
40681
41222
  function buf(input) {
40682
41223
  if (typeof input === "string") {
40683
- return encoder2.encode(input);
41224
+ return encoder3.encode(input);
40684
41225
  }
40685
- return decoder.decode(input);
41226
+ return decoder2.decode(input);
40686
41227
  }
40687
41228
  var encodeBase64Url;
40688
41229
  if (Uint8Array.prototype.toBase64) {
@@ -41492,6 +42033,47 @@ function checkSigningAlgorithm(client, issuer, fallback, header) {
41492
42033
  }
41493
42034
  var skipStateCheck = Symbol();
41494
42035
  var expectNoState = Symbol();
42036
+ async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
42037
+ assertAs(as);
42038
+ assertClient(client);
42039
+ const url = resolveEndpoint(as, "device_authorization_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
42040
+ const body = new URLSearchParams(parameters);
42041
+ body.set("client_id", client.client_id);
42042
+ const headers = prepareHeaders(options?.headers);
42043
+ headers.set("accept", "application/json");
42044
+ return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
42045
+ }
42046
+ async function processDeviceAuthorizationResponse(as, client, response) {
42047
+ assertAs(as);
42048
+ assertClient(client);
42049
+ if (!looseInstanceOf(response, Response)) {
42050
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
42051
+ }
42052
+ await checkOAuthBodyError(response, 200, "Device Authorization Endpoint");
42053
+ assertReadableResponse(response);
42054
+ const json = await getResponseJsonBody(response);
42055
+ assertString(json.device_code, '"response" body "device_code" property', INVALID_RESPONSE, {
42056
+ body: json
42057
+ });
42058
+ assertString(json.user_code, '"response" body "user_code" property', INVALID_RESPONSE, {
42059
+ body: json
42060
+ });
42061
+ assertString(json.verification_uri, '"response" body "verification_uri" property', INVALID_RESPONSE, { body: json });
42062
+ let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
42063
+ assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
42064
+ body: json
42065
+ });
42066
+ json.expires_in = expiresIn;
42067
+ if (json.verification_uri_complete !== undefined) {
42068
+ assertString(json.verification_uri_complete, '"response" body "verification_uri_complete" property', INVALID_RESPONSE, { body: json });
42069
+ }
42070
+ if (json.interval !== undefined) {
42071
+ assertNumber(json.interval, false, '"response" body "interval" property', INVALID_RESPONSE, {
42072
+ body: json
42073
+ });
42074
+ }
42075
+ return json;
42076
+ }
41495
42077
  async function getResponseJsonBody(response, check = assertApplicationJson) {
41496
42078
  let json;
41497
42079
  try {
@@ -41565,7 +42147,7 @@ class ClientError extends Error {
41565
42147
  Error.captureStackTrace?.(this, this.constructor);
41566
42148
  }
41567
42149
  }
41568
- var decoder2 = new TextDecoder;
42150
+ var decoder3 = new TextDecoder;
41569
42151
  function e(msg, cause, code) {
41570
42152
  return new ClientError(msg, { cause, code });
41571
42153
  }
@@ -41794,6 +42376,16 @@ function getHelpers(response) {
41794
42376
  function addHelpers(response) {
41795
42377
  Object.defineProperties(response, getHelpers(response));
41796
42378
  }
42379
+ async function initiateDeviceAuthorization(config, parameters) {
42380
+ checkConfig(config);
42381
+ const { as, c, auth, fetch: fetch2, tlsOnly, timeout } = int2(config);
42382
+ return deviceAuthorizationRequest(as, c, auth, parameters, {
42383
+ [customFetch]: fetch2,
42384
+ [allowInsecureRequests]: !tlsOnly,
42385
+ headers: new Headers(headers),
42386
+ signal: signal2(timeout)
42387
+ }).then((response) => processDeviceAuthorizationResponse(as, c, response)).catch(errorHandler);
42388
+ }
41797
42389
  function allowInsecureRequests2(config) {
41798
42390
  int2(config).tlsOnly = false;
41799
42391
  }
@@ -41881,6 +42473,63 @@ async function genericGrantRequest(config, grantType, parameters, options) {
41881
42473
  return result;
41882
42474
  }
41883
42475
 
42476
+ // ../cipher-client/src/device-login-file.ts
42477
+ import { createPrivateKey, randomUUID as randomUUID2 } from "crypto";
42478
+ import { constants as constants2 } from "fs";
42479
+ import {
42480
+ access,
42481
+ lstat as lstat2,
42482
+ mkdir,
42483
+ open as open2,
42484
+ readFile as readFile2,
42485
+ readlink,
42486
+ rename as rename2,
42487
+ rm as rm2,
42488
+ stat as stat2
42489
+ } from "fs/promises";
42490
+ import { userInfo } from "os";
42491
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4 } from "path";
42492
+
42493
+ // ../cipher-client/src/device-login-lock.ts
42494
+ import { randomUUID } from "crypto";
42495
+ import { constants } from "fs";
42496
+ import {
42497
+ link,
42498
+ lstat,
42499
+ open,
42500
+ readdir as readdir2,
42501
+ rename,
42502
+ rm,
42503
+ stat,
42504
+ utimes
42505
+ } from "fs/promises";
42506
+ import { basename, dirname as dirname2, join as join3 } from "path";
42507
+
42508
+ // ../cipher-client/src/wire.ts
42509
+ var TOKEN_PATH = "/v1/oauth/token";
42510
+ var GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
42511
+ var EXCHANGE_CLIENT_ID = "dispatch-token-exchange";
42512
+ var FORM_SESSION = "session";
42513
+ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
42514
+ var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
42515
+ var FORM_PROJECTS = "projects";
42516
+ var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
42517
+ var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
42518
+ var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
42519
+ var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
42520
+ var TOKEN_TYPE_DPOP = "DPoP";
42521
+ var SUBJECT_TYPE_ACCESS = "urn:ietf:params:oauth:token-type:access_token";
42522
+ var DEVICE_AUTHORIZATION_PATH = "/v1/oauth/device_authorization";
42523
+ var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
42524
+ var GRANT_TYPE_REFRESH = "refresh_token";
42525
+ var MACHINE_LOGIN_CLIENT_ID = "agent-secrets-helper";
42526
+ var MACHINE_LOGIN_SCOPE = "machine";
42527
+ var REQUEST_OBJECT_TYPE = "agent-secrets-request+jwt";
42528
+ var LAUNCHER_CREDENTIAL_DETAIL = "launcher_credential";
42529
+ var REQUEST_OBJECT_LIFETIME_SECONDS = 600;
42530
+ var POD_SESSION_NOT_REGISTERED = "pod_session_not_registered";
42531
+ var SESSION_NAME_NOT_THIS_REGISTRARS = "session_name_not_this_registrars";
42532
+
41884
42533
  // ../cipher-client/src/refusal-text.ts
41885
42534
  var KNOWN_BROKER_REFUSALS = new Set([
41886
42535
  "no entry lists the account this token names",
@@ -42190,6 +42839,8 @@ var INVALID_DPOP_PROOF = "invalid_dpop_proof";
42190
42839
  var USE_DPOP_NONCE = "use_dpop_nonce";
42191
42840
  var INVALID_GRANT = "invalid_grant";
42192
42841
  var MEMBERSHIP_HELD = "membership_held";
42842
+ var TOKEN_NOT_VALID = "Token is not valid or has expired.";
42843
+ var MACHINE_LOGIN_ENDED = "The machine login the subject token belongs to has ended.";
42193
42844
 
42194
42845
  class BrokerRefusedError extends Error {
42195
42846
  status;
@@ -42197,6 +42848,7 @@ class BrokerRefusedError extends Error {
42197
42848
  code;
42198
42849
  shownCode;
42199
42850
  podSessionUnregistered;
42851
+ subjectNotHonoured;
42200
42852
  constructor(status, code, description, refused, context = {}) {
42201
42853
  const shownCode = shownOAuthCode(code);
42202
42854
  const said = description === "" ? "" : isKnownBrokerRefusal(description, context) ? scrub(description) : REFUSAL_TEXT_WITHHELD;
@@ -42207,6 +42859,7 @@ class BrokerRefusedError extends Error {
42207
42859
  this.shownCode = shownCode;
42208
42860
  this.said = said;
42209
42861
  this.podSessionUnregistered = code === INVALID_GRANT && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
42862
+ this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT && description.endsWith(MACHINE_LOGIN_ENDED));
42210
42863
  }
42211
42864
  get permanent() {
42212
42865
  return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE && this.code !== MEMBERSHIP_HELD && !this.podSessionUnregistered;
@@ -42260,8 +42913,23 @@ class SignInEndedError extends Error {
42260
42913
  this.name = "SignInEndedError";
42261
42914
  }
42262
42915
  }
42916
+ var DEVICE_LOGIN_COMMAND = "dispatch login --device";
42917
+
42918
+ class DeviceLoginEndedError extends Error {
42919
+ constructor(login) {
42920
+ super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${DEVICE_LOGIN_COMMAND}`);
42921
+ this.name = "DeviceLoginEndedError";
42922
+ }
42923
+ }
42924
+
42925
+ class LockHeldError extends Error {
42926
+ constructor(lock, options) {
42927
+ super(`another process of this machine held ${lock} for all of this trade's time, so nothing was sent to the secrets broker`, options);
42928
+ this.name = "LockHeldError";
42929
+ }
42930
+ }
42263
42931
  function isFinalRefusal(error) {
42264
- return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
42932
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
42265
42933
  }
42266
42934
 
42267
42935
  // ../cipher-client/src/token-client.ts
@@ -42273,7 +42941,7 @@ var PENDING_FIRST_WAIT_MS = 2000;
42273
42941
  var PENDING_MAX_WAIT_MS = 30000;
42274
42942
  var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
42275
42943
  var TRADE_ATTEMPT_MS = 30000;
42276
- function sleep2(ms, signal) {
42944
+ function sleep2(ms, signal, holdsProcess = false) {
42277
42945
  const { promise, resolve } = Promise.withResolvers();
42278
42946
  if (signal?.aborted) {
42279
42947
  resolve();
@@ -42285,7 +42953,8 @@ function sleep2(ms, signal) {
42285
42953
  resolve();
42286
42954
  };
42287
42955
  const timer = setTimeout(done, ms);
42288
- timer.unref();
42956
+ if (!holdsProcess)
42957
+ timer.unref();
42289
42958
  signal?.addEventListener("abort", done, { once: true });
42290
42959
  return promise;
42291
42960
  }
@@ -42294,12 +42963,24 @@ function statusOf(error) {
42294
42963
  for (let depth = 0;depth < 4; depth += 1) {
42295
42964
  if (cause instanceof Response)
42296
42965
  return cause.status;
42966
+ if (cause instanceof ResponseBodyError || cause instanceof WWWAuthenticateChallengeError) {
42967
+ return cause.status;
42968
+ }
42297
42969
  if (typeof cause !== "object" || cause === null || !("cause" in cause))
42298
42970
  return 0;
42299
42971
  cause = cause.cause;
42300
42972
  }
42301
42973
  return 0;
42302
42974
  }
42975
+ function brokerRefusal(doing, refused, endpoint, error, context = {}) {
42976
+ if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
42977
+ const description = error.error_description;
42978
+ return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", refused, context);
42979
+ }
42980
+ const status = statusOf(error);
42981
+ const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
42982
+ return new BrokerTradeFailedError(`${doing} ${refused} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
42983
+ }
42303
42984
  function requestInit(options, signal, headers) {
42304
42985
  const signals = [options.signal, signal].filter((one) => one !== undefined);
42305
42986
  return {
@@ -42310,6 +42991,24 @@ function requestInit(options, signal, headers) {
42310
42991
  ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
42311
42992
  };
42312
42993
  }
42994
+ async function sendWithProof(proved, url, options, signal) {
42995
+ const send = async () => {
42996
+ const headers = new Headers(options.headers);
42997
+ headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
42998
+ return await proved.fetch(url, requestInit(options, signal, headers));
42999
+ };
43000
+ let answer = await send();
43001
+ const given = answer.headers.get("DPoP-Nonce") ?? "";
43002
+ if (given !== "")
43003
+ proved.nonce.value = given;
43004
+ if (answer.status === 400 && given !== "") {
43005
+ const body = await answer.clone().json().catch(() => null);
43006
+ const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
43007
+ if (asked)
43008
+ answer = await send();
43009
+ }
43010
+ return answer;
43011
+ }
42313
43012
 
42314
43013
  class BrokerTokenClient {
42315
43014
  #brokerUrl;
@@ -42326,7 +43025,7 @@ class BrokerTokenClient {
42326
43025
  #log;
42327
43026
  #fetch;
42328
43027
  #random;
42329
- #nonce = "";
43028
+ #nonce = { value: "" };
42330
43029
  #held = null;
42331
43030
  #loop = null;
42332
43031
  #waiters = new Set;
@@ -42550,6 +43249,12 @@ class BrokerTokenClient {
42550
43249
  }
42551
43250
  return { kind: "busy", said: error.message };
42552
43251
  }
43252
+ if (error instanceof LockHeldError) {
43253
+ return {
43254
+ kind: "unsent",
43255
+ said: `the trade of ${this.describe()} could not be made: ${scrub(error.message)}`
43256
+ };
43257
+ }
42553
43258
  if (timedOut) {
42554
43259
  return {
42555
43260
  kind: "unanswered",
@@ -42564,7 +43269,13 @@ class BrokerTokenClient {
42564
43269
  };
42565
43270
  }
42566
43271
  async#trade(signal) {
42567
- const subject = await this.#subject.read(signal);
43272
+ const source = this.#subject;
43273
+ if (source.spend !== undefined) {
43274
+ return await source.spend((subject) => this.#exchange(subject, signal), signal);
43275
+ }
43276
+ return await this.#exchange(await source.read(signal), signal);
43277
+ }
43278
+ async#exchange(subject, signal) {
42568
43279
  holdSecret(subject.token, heldUntil(subject.token));
42569
43280
  const form = {
42570
43281
  subject_token: subject.token,
@@ -42598,38 +43309,15 @@ class BrokerTokenClient {
42598
43309
  try {
42599
43310
  answered = await genericGrantRequest(config, GRANT_TYPE_TOKEN_EXCHANGE, form);
42600
43311
  } catch (error) {
42601
- throw this.#refusal(endpoint, error);
42602
- }
42603
- return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
42604
- }
42605
- #refusal(endpoint, error) {
42606
- if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
42607
- const description = error.error_description;
42608
- return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", this.#subject.describe(), {
43312
+ throw brokerRefusal("trade", this.#subject.describe(), endpoint, error, {
42609
43313
  ...this.#subject.person === undefined ? {} : { person: this.#subject.person },
42610
43314
  ...this.#session === "" ? {} : { session: this.#session }
42611
43315
  });
42612
43316
  }
42613
- const status = statusOf(error);
42614
- const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
42615
- return new BrokerTradeFailedError(`trade ${this.#subject.describe()} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
43317
+ return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
42616
43318
  }
42617
43319
  async#send(url, options, signal, raw) {
42618
- const send = async () => {
42619
- const headers = new Headers(options.headers);
42620
- headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
42621
- return await this.#fetch(url, requestInit(options, signal, headers));
42622
- };
42623
- let answer = await send();
42624
- const given = answer.headers.get("DPoP-Nonce") ?? "";
42625
- if (given !== "")
42626
- this.#nonce = given;
42627
- if (answer.status === 400 && given !== "") {
42628
- const body = await answer.clone().json().catch(() => null);
42629
- const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
42630
- if (asked)
42631
- answer = await send();
42632
- }
43320
+ const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
42633
43321
  raw.body = await answer.clone().json().catch(() => {
42634
43322
  return;
42635
43323
  });
@@ -42678,6 +43366,1046 @@ function heldUntil(token) {
42678
43366
  }
42679
43367
  }
42680
43368
 
43369
+ // ../cipher-client/src/device-login-lock.ts
43370
+ var DEVICE_LOGIN_STALE_LOCK_MS = TRADE_ATTEMPT_MS / 2;
43371
+ var LOCK_HEARTBEAT_MS = DEVICE_LOGIN_STALE_LOCK_MS / 3;
43372
+ var DEVICE_LOGIN_MOST_BYTES = 64 * 1024;
43373
+ var LOCK_READ = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY | constants.O_NOFOLLOW;
43374
+ var LOCK_RETRY_MS = 100;
43375
+ var STEAL_STALE_MS = 5000;
43376
+ async function statOrNone(path, what) {
43377
+ try {
43378
+ return await lstat(path);
43379
+ } catch (error) {
43380
+ if (readErrorCode(error) === "ENOENT")
43381
+ return null;
43382
+ throw new Error(`read ${what}: ${readErrorCode(error)}`);
43383
+ }
43384
+ }
43385
+ async function createOwn(path, value, named) {
43386
+ let handle;
43387
+ try {
43388
+ handle = await open(path, "wx", 384);
43389
+ } catch (error) {
43390
+ if (readErrorCode(error) === "EEXIST")
43391
+ return false;
43392
+ throw new Error(`take the lock beside ${named}: ${readErrorCode(error)}`);
43393
+ }
43394
+ try {
43395
+ await handle.writeFile(value);
43396
+ } finally {
43397
+ await handle.close();
43398
+ }
43399
+ return true;
43400
+ }
43401
+ async function look(path, what) {
43402
+ let handle;
43403
+ try {
43404
+ handle = await open(path, LOCK_READ);
43405
+ } catch (error) {
43406
+ if (readErrorCode(error) === "ENOENT")
43407
+ return null;
43408
+ const stats = await statOrNone(path, what);
43409
+ return stats === null ? null : { stats, value: "" };
43410
+ }
43411
+ let seen;
43412
+ try {
43413
+ const stats = await handle.stat();
43414
+ const readable = stats.isFile() && stats.size <= DEVICE_LOGIN_MOST_BYTES;
43415
+ seen = { stats, value: readable ? await handle.readFile("utf8").catch(() => "") : "" };
43416
+ } catch (error) {
43417
+ await handle.close().catch(() => {});
43418
+ throw new Error(`read ${what}: ${readErrorCode(error)}`);
43419
+ }
43420
+ await handle.close().catch((error) => {
43421
+ throw new Error(`read ${what}: ${readErrorCode(error)}`);
43422
+ });
43423
+ return seen;
43424
+ }
43425
+ function sameFile(was) {
43426
+ return (seen) => seen.stats.dev === was.stats.dev && seen.stats.ino === was.stats.ino && seen.stats.mtimeMs === was.stats.mtimeMs && seen.value === was.value;
43427
+ }
43428
+ async function removeIfStill(path, isIt, what) {
43429
+ const moved = `${path}.stale-${randomUUID()}`;
43430
+ try {
43431
+ await rename(path, moved);
43432
+ } catch (error) {
43433
+ if (readErrorCode(error) === "ENOENT")
43434
+ return true;
43435
+ throw new Error(`move ${what} aside: ${readErrorCode(error)}`);
43436
+ }
43437
+ const took = await look(moved, what);
43438
+ const same = took !== null && isIt(took);
43439
+ if (!same)
43440
+ await link(moved, path).catch(() => {});
43441
+ await rm(moved, { force: true }).catch((error) => {
43442
+ throw new Error(`remove ${what}, moved aside: ${readErrorCode(error)}`);
43443
+ });
43444
+ return same;
43445
+ }
43446
+ async function removeOwn(path, value, what) {
43447
+ const seen = await look(path, what);
43448
+ if (seen === null || seen.value !== value)
43449
+ return;
43450
+ await removeIfStill(path, (took) => took.value === value, what);
43451
+ }
43452
+ async function takeStale(lock, mine, named, options) {
43453
+ const locked = `the lock beside ${named}`;
43454
+ const found = await statOrNone(lock, locked);
43455
+ if (found === null)
43456
+ return true;
43457
+ if (Date.now() - found.mtimeMs <= DEVICE_LOGIN_STALE_LOCK_MS)
43458
+ return false;
43459
+ await options.at?.("lock-stale");
43460
+ const steal = `${lock}.steal`;
43461
+ const stealing = `the take-over lock beside ${named}`;
43462
+ if (!await createOwn(steal, mine, named)) {
43463
+ const taking = await look(steal, stealing);
43464
+ if (taking !== null && Date.now() - taking.stats.mtimeMs > STEAL_STALE_MS) {
43465
+ await options.at?.("steal-stale");
43466
+ await removeIfStill(steal, sameFile(taking), `the dead take-over lock beside ${named}`);
43467
+ }
43468
+ return false;
43469
+ }
43470
+ try {
43471
+ const again = await look(lock, locked);
43472
+ if (again === null)
43473
+ return true;
43474
+ if (Date.now() - again.stats.mtimeMs <= DEVICE_LOGIN_STALE_LOCK_MS)
43475
+ return false;
43476
+ await options.at?.("taking");
43477
+ return await removeIfStill(lock, sameFile(again), `the stale lock beside ${named}`);
43478
+ } finally {
43479
+ await removeOwn(steal, mine, stealing);
43480
+ }
43481
+ }
43482
+ function keepReleaseFailure(failed, released) {
43483
+ if (!(failed instanceof Error))
43484
+ return;
43485
+ Reflect.defineProperty(failed, failed.cause === undefined ? "cause" : "releaseFailure", {
43486
+ value: released,
43487
+ writable: true,
43488
+ enumerable: true,
43489
+ configurable: true
43490
+ });
43491
+ }
43492
+ async function withLoginLock(path, named, work, options = {}) {
43493
+ const lock = `${path}.lock`;
43494
+ const locked = `the lock beside ${named}`;
43495
+ const mine = `${process.pid} ${randomUUID()}
43496
+ `;
43497
+ const wait = options.sleep ?? ((ms, signal) => sleep2(ms, signal, true));
43498
+ while (true) {
43499
+ if (options.signal?.aborted === true) {
43500
+ throw new LockHeldError(locked, { cause: options.signal.reason });
43501
+ }
43502
+ if (await createOwn(lock, mine, named))
43503
+ break;
43504
+ if (await takeStale(lock, mine, named, options))
43505
+ continue;
43506
+ await wait(LOCK_RETRY_MS, options.signal);
43507
+ }
43508
+ const beat = setInterval(async () => {
43509
+ const now = new Date;
43510
+ await utimes(lock, now, now).catch(() => {});
43511
+ }, LOCK_HEARTBEAT_MS);
43512
+ beat.unref();
43513
+ let answer;
43514
+ try {
43515
+ answer = await work(async () => (await look(lock, locked))?.value === mine);
43516
+ } catch (error) {
43517
+ clearInterval(beat);
43518
+ await removeOwn(lock, mine, locked).catch((released) => keepReleaseFailure(error, released));
43519
+ throw error;
43520
+ }
43521
+ clearInterval(beat);
43522
+ await removeOwn(lock, mine, locked);
43523
+ return answer;
43524
+ }
43525
+ function namedWithUuid(name, prefix) {
43526
+ return name.startsWith(prefix) && /^[0-9a-f-]{36}$/.test(name.slice(prefix.length));
43527
+ }
43528
+ async function removeUntouched(dir, left) {
43529
+ const names = await readdir2(dir).catch(() => []);
43530
+ for (const name of names.filter(left)) {
43531
+ const path = join3(dir, name);
43532
+ const info = await stat(path).catch(() => null);
43533
+ if (info !== null && Date.now() - info.mtimeMs > DEVICE_LOGIN_STALE_LOCK_MS) {
43534
+ await rm(path, { force: true }).catch(() => {});
43535
+ }
43536
+ }
43537
+ }
43538
+ async function removeLeftLocks(path) {
43539
+ const name = basename(path);
43540
+ await removeUntouched(dirname2(path), (one) => namedWithUuid(one, `${name}.lock.stale-`) || namedWithUuid(one, `${name}.lock.steal.stale-`));
43541
+ }
43542
+
43543
+ // ../cipher-client/src/device-login-file.ts
43544
+ var DEVICE_LOGIN_FILE_VAR = "AGENT_SECRETS_DEVICE_LOGIN_FILE";
43545
+ var DEVICE_LOGIN_FILE_NAMED = `the device login ${DEVICE_LOGIN_FILE_VAR} names (default ~/.config/legion/device-login.json)`;
43546
+ function isTemporaryCopy(name) {
43547
+ return /^\.device-login-[0-9a-f-]{36}\.json\.tmp$/.test(name);
43548
+ }
43549
+ function deviceLoginFile(env) {
43550
+ const named = (env[DEVICE_LOGIN_FILE_VAR] ?? "").trim();
43551
+ if (named !== "")
43552
+ return named;
43553
+ const home = (env["HOME"] ?? "").trim();
43554
+ if (home === "") {
43555
+ throw new Error(`${DEVICE_LOGIN_FILE_VAR} names no file and HOME names no home directory, so this machine has nowhere to keep its device login`);
43556
+ }
43557
+ return join4(home, ".config", "legion", "device-login.json");
43558
+ }
43559
+ function member(json, name) {
43560
+ const value = json[name];
43561
+ return typeof value === "string" ? value : "";
43562
+ }
43563
+ function checkPrivate(info, what, forbidden, opens, notOwned) {
43564
+ const mode = info.mode & 511;
43565
+ if ((mode & forbidden) !== 0) {
43566
+ throw new Error(`${what} is mode ${mode.toString(8).padStart(4, "0")}, which ${opens}`);
43567
+ }
43568
+ const uid = process.getuid?.();
43569
+ if (uid !== undefined && info.uid !== uid) {
43570
+ throw new Error(`${what} is owned by uid ${info.uid}, not this user (uid ${uid}); ${notOwned}`);
43571
+ }
43572
+ }
43573
+ var STICKY = 512;
43574
+ var INITIAL_UID_MAP = "0 0 4294967295";
43575
+ var DEFAULT_OVERFLOW_UID = 65534;
43576
+ var systemFiles = new Map;
43577
+ async function systemFile(file) {
43578
+ let info;
43579
+ try {
43580
+ info = await stat2(file);
43581
+ } catch {
43582
+ return null;
43583
+ }
43584
+ const status = [info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs].join(":");
43585
+ const kept = systemFiles.get(file);
43586
+ if (kept?.status === status)
43587
+ return kept.text;
43588
+ const text = await readFile2(file, "utf8").catch(() => null);
43589
+ if (text === null)
43590
+ systemFiles.delete(file);
43591
+ else
43592
+ systemFiles.set(file, { status, text });
43593
+ return text;
43594
+ }
43595
+ async function safeOwner(uid, mine) {
43596
+ if (uid === mine || uid === 0)
43597
+ return true;
43598
+ const map = (await systemFile("/proc/self/uid_map") ?? "").trim().split(`
43599
+ `).map((line) => line.trim().split(/\s+/).join(" "));
43600
+ if (map[0] === "" || map.length === 1 && map[0] === INITIAL_UID_MAP)
43601
+ return false;
43602
+ const named = Number.parseInt(await systemFile("/proc/sys/kernel/overflowuid") ?? "", 10);
43603
+ return uid === (Number.isNaN(named) ? DEFAULT_OVERFLOW_UID : named);
43604
+ }
43605
+ async function records(file, fields, numbers) {
43606
+ const text = await systemFile(file);
43607
+ if (text === null)
43608
+ return null;
43609
+ const read = [];
43610
+ for (const line of text.split(`
43611
+ `)) {
43612
+ if (line.trim() === "" || line.startsWith("#"))
43613
+ continue;
43614
+ const record = line.split(":");
43615
+ if (record.length < fields || /^[+-]/.test(line))
43616
+ return null;
43617
+ if (numbers.some((at) => !/^\d+$/.test(record[at] ?? "")))
43618
+ return null;
43619
+ read.push(record);
43620
+ }
43621
+ return read;
43622
+ }
43623
+ async function privateGroup(gid, mine) {
43624
+ const [users, groups] = await Promise.all([
43625
+ records("/etc/passwd", 7, [2, 3]),
43626
+ records("/etc/group", 4, [2])
43627
+ ]);
43628
+ if (users === null || groups === null)
43629
+ return false;
43630
+ const named = groups.filter((group) => Number(group[2]) === gid);
43631
+ if (named.length === 0)
43632
+ return false;
43633
+ const myNames = new Set(users.filter((user) => Number(user[2]) === mine).map((user) => user[0]));
43634
+ let members = 0;
43635
+ for (const user of users) {
43636
+ if (Number(user[3]) !== gid)
43637
+ continue;
43638
+ if (Number(user[2]) !== mine)
43639
+ return false;
43640
+ members += 1;
43641
+ }
43642
+ for (const group of named) {
43643
+ for (const name of (group[3] ?? "").split(",")) {
43644
+ if (name.trim() === "")
43645
+ continue;
43646
+ if (!myNames.has(name.trim()))
43647
+ return false;
43648
+ members += 1;
43649
+ }
43650
+ }
43651
+ return members > 0;
43652
+ }
43653
+ async function checkOnTheWay(info, what) {
43654
+ const onTheWay = `a directory on the way to ${what}`;
43655
+ const mode = info.mode & 4095;
43656
+ const shown = mode.toString(8).padStart(4, "0");
43657
+ const uid = process.getuid?.();
43658
+ if ((mode & STICKY) === 0 && (mode & 2) !== 0) {
43659
+ throw new Error(`${onTheWay} is mode ${shown}, which lets others replace what is in it; remove their write access (chmod go-w) or set its sticky bit (chmod +t), or keep the login elsewhere`);
43660
+ }
43661
+ if ((mode & STICKY) === 0 && (mode & 16) !== 0 && (uid === undefined || !await privateGroup(info.gid, uid))) {
43662
+ throw new Error(`${onTheWay} is mode ${shown}, and its group, gid ${info.gid}, is not one that /etc/passwd and /etc/group show this user alone is in, so another member may replace what is in it; remove the group's write access (chmod g-w) or set its sticky bit (chmod +t), or keep the login elsewhere`);
43663
+ }
43664
+ if (uid !== undefined && !await safeOwner(info.uid, uid)) {
43665
+ throw new Error(`${onTheWay} is owned by uid ${info.uid}, neither this user (uid ${uid}) nor root; keep the login under directories of this user's own`);
43666
+ }
43667
+ }
43668
+ async function checkLinkOnTheWay(info, what) {
43669
+ const uid = process.getuid?.();
43670
+ if (uid !== undefined && !await safeOwner(info.uid, uid)) {
43671
+ throw new Error(`a link on the way to ${what} is owned by uid ${info.uid}, neither this user (uid ${uid}) nor root; keep the login under directories and links of this user's own`);
43672
+ }
43673
+ }
43674
+ async function lstatOnTheWay(path, what) {
43675
+ try {
43676
+ return await lstat2(path);
43677
+ } catch (error) {
43678
+ if (readErrorCode(error) === "ENOENT")
43679
+ return null;
43680
+ throw refusedBy(error, `read a directory on the way to ${what}`);
43681
+ }
43682
+ }
43683
+ async function walkTheWay(path, what, meet) {
43684
+ const names = (isAbsolute2(path) ? path : `${process.cwd()}/${path}`).split("/");
43685
+ let reached = "/";
43686
+ let info = await lstatOnTheWay(reached, what);
43687
+ let followed = 0;
43688
+ for (let name = names.shift();name !== undefined; name = names.shift()) {
43689
+ if (info === null)
43690
+ return null;
43691
+ if (name === "" || name === ".")
43692
+ continue;
43693
+ if (name === "..") {
43694
+ reached = dirname3(reached);
43695
+ info = await lstatOnTheWay(reached, what);
43696
+ continue;
43697
+ }
43698
+ await meet?.directory(reached, info);
43699
+ const next = reached === "/" ? `/${name}` : `${reached}/${name}`;
43700
+ const here = await lstatOnTheWay(next, what);
43701
+ if (here === null || !here.isSymbolicLink()) {
43702
+ reached = next;
43703
+ info = here;
43704
+ continue;
43705
+ }
43706
+ await meet?.link(reached, here);
43707
+ followed += 1;
43708
+ if (followed > LINKS_FOLLOWED_AT_MOST)
43709
+ throw notARegularFile("a loop of links");
43710
+ let target;
43711
+ try {
43712
+ target = await readlink(next);
43713
+ } catch (error) {
43714
+ const code = readErrorCode(error);
43715
+ if (code !== "EINVAL" && code !== "ENOENT") {
43716
+ throw refusedBy(error, `read a directory on the way to ${what}`);
43717
+ }
43718
+ names.unshift(name);
43719
+ continue;
43720
+ }
43721
+ names.unshift(...target.split("/"));
43722
+ if (isAbsolute2(target)) {
43723
+ reached = "/";
43724
+ info = await lstatOnTheWay(reached, what);
43725
+ }
43726
+ }
43727
+ return info === null ? null : reached;
43728
+ }
43729
+ async function homeReached() {
43730
+ const uid = process.getuid?.();
43731
+ const passwd = await records("/etc/passwd", 7, [2, 3]);
43732
+ let home = passwd?.find((user) => Number(user[2]) === uid)?.[5];
43733
+ if (home === undefined) {
43734
+ try {
43735
+ home = userInfo().homedir;
43736
+ } catch {
43737
+ return null;
43738
+ }
43739
+ }
43740
+ if (!isAbsolute2(home))
43741
+ return null;
43742
+ return await walkTheWay(home, "the home directory").catch(() => null);
43743
+ }
43744
+ async function checkDirectoriesOnTheWay(dir, what) {
43745
+ const home = await homeReached();
43746
+ const aboveHome = (at) => home !== null && home !== at && (at === "/" || home.startsWith(`${at}/`));
43747
+ await walkTheWay(dir, what, {
43748
+ directory: async (at, info) => {
43749
+ if (!aboveHome(at))
43750
+ await checkOnTheWay(info, what);
43751
+ },
43752
+ link: async (inside, info) => {
43753
+ if (!aboveHome(inside))
43754
+ await checkLinkOnTheWay(info, what);
43755
+ }
43756
+ });
43757
+ }
43758
+ async function checkLoginDirectory(dir, absent, what = `the directory of ${DEVICE_LOGIN_FILE_NAMED}`) {
43759
+ let info;
43760
+ try {
43761
+ info = await stat2(dir);
43762
+ } catch (error) {
43763
+ if (absent !== undefined && readErrorCode(error) === "ENOENT")
43764
+ throw absent();
43765
+ throw refusedBy(error, `read ${what}`);
43766
+ }
43767
+ checkPrivate(info, what, 18, "lets others replace the login in it; run chmod 700 on it", "keep the login in a directory of this user's own");
43768
+ await checkDirectoriesOnTheWay(dir, what);
43769
+ }
43770
+ function notARegularFile(there) {
43771
+ const what = typeof there === "string" ? there : there.isDirectory() ? "a directory" : there.isFIFO() ? "a named pipe" : there.isSocket() ? "a socket" : there.isCharacterDevice() || there.isBlockDevice() ? "a device" : "something";
43772
+ return new Error(`${DEVICE_LOGIN_FILE_NAMED} is ${what}, not a regular file, so no login can be kept in its place; remove it, or set ${DEVICE_LOGIN_FILE_VAR} to a file's path`);
43773
+ }
43774
+ function refusedBy(error, doing) {
43775
+ const code = readErrorCode(error);
43776
+ if (code === "ENXIO")
43777
+ return notARegularFile("a socket or a device");
43778
+ if (code === "ELOOP")
43779
+ return notARegularFile("a loop of links");
43780
+ if (code === "ENOTDIR") {
43781
+ return new Error(`${DEVICE_LOGIN_FILE_NAMED} has a file, not a directory, in its path, so no login can be kept there; set ${DEVICE_LOGIN_FILE_VAR} to a path in a directory`);
43782
+ }
43783
+ return new Error(`${doing}: ${code}`);
43784
+ }
43785
+ async function deviceLoginDirectory(path) {
43786
+ const dir = dirname3(path);
43787
+ try {
43788
+ await mkdir(dir, { recursive: true, mode: 448 });
43789
+ } catch (error) {
43790
+ throw refusedBy(error, `make the directory of ${DEVICE_LOGIN_FILE_NAMED}`);
43791
+ }
43792
+ await checkLoginDirectory(dir);
43793
+ }
43794
+ async function deviceLoginPlace(path) {
43795
+ await deviceLoginDirectory(path);
43796
+ const dir = dirname3(path);
43797
+ try {
43798
+ await access(dir, constants2.W_OK | constants2.X_OK);
43799
+ } catch (error) {
43800
+ const code = readErrorCode(error);
43801
+ throw new Error(`this user cannot enter and write to the directory of ${DEVICE_LOGIN_FILE_NAMED}: ${code}${code === "EACCES" ? "; run chmod 700 on it" : ""}`);
43802
+ }
43803
+ let info;
43804
+ try {
43805
+ info = await stat2(path);
43806
+ } catch (error) {
43807
+ if (readErrorCode(error) === "ENOENT")
43808
+ return;
43809
+ throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
43810
+ }
43811
+ if (!info.isFile())
43812
+ throw notARegularFile(info);
43813
+ }
43814
+ var LOGIN_READ = constants2.O_RDONLY | constants2.O_NONBLOCK | constants2.O_NOCTTY;
43815
+ var LINKS_FOLLOWED_AT_MOST = 40;
43816
+ async function checkLinkDirectories(path, absent) {
43817
+ let checked = dirname3(path);
43818
+ let at = path;
43819
+ for (let followed = 0;; followed += 1) {
43820
+ if (dirname3(at) !== checked) {
43821
+ checked = dirname3(at);
43822
+ await checkLoginDirectory(checked, absent, `the directory of a file ${DEVICE_LOGIN_FILE_NAMED} links to`);
43823
+ }
43824
+ let info;
43825
+ try {
43826
+ info = await lstat2(at);
43827
+ } catch (error) {
43828
+ if (readErrorCode(error) === "ENOENT")
43829
+ return;
43830
+ throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
43831
+ }
43832
+ if (!info.isSymbolicLink())
43833
+ return;
43834
+ if (followed === LINKS_FOLLOWED_AT_MOST)
43835
+ throw notARegularFile("a loop of links");
43836
+ let target;
43837
+ try {
43838
+ target = await readlink(at);
43839
+ } catch (error) {
43840
+ const code = readErrorCode(error);
43841
+ if (code === "EINVAL" || code === "ENOENT")
43842
+ return;
43843
+ throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
43844
+ }
43845
+ at = isAbsolute2(target) ? target : `${dirname3(at)}/${target}`;
43846
+ }
43847
+ }
43848
+ async function readDeviceLogin(path) {
43849
+ const absent = () => new Error(`this machine has no device login: ${DEVICE_LOGIN_FILE_NAMED} is not there; log this machine in with: ${DEVICE_LOGIN_COMMAND}`);
43850
+ const failed = (error) => new Error(`read ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
43851
+ await checkLoginDirectory(dirname3(path), absent);
43852
+ await checkLinkDirectories(path, absent);
43853
+ let handle;
43854
+ try {
43855
+ handle = await open2(path, LOGIN_READ);
43856
+ } catch (error) {
43857
+ throw readErrorCode(error) === "ENOENT" ? absent() : refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
43858
+ }
43859
+ let data;
43860
+ try {
43861
+ const info = await handle.stat().catch((error) => {
43862
+ throw failed(error);
43863
+ });
43864
+ if (!info.isFile())
43865
+ throw notARegularFile(info);
43866
+ checkPrivate(info, DEVICE_LOGIN_FILE_NAMED, 63, "lets others read the login's key; run chmod 600 on it", `remove it and log in again with: ${DEVICE_LOGIN_COMMAND}`);
43867
+ if (info.size > DEVICE_LOGIN_MOST_BYTES) {
43868
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED} is not a device login: it is over ${DEVICE_LOGIN_MOST_BYTES / 1024} KiB, many times a login's size; set ${DEVICE_LOGIN_FILE_VAR} to the login's own file, or log this machine in again with: ${DEVICE_LOGIN_COMMAND}`);
43869
+ }
43870
+ data = await handle.readFile("utf8").catch((error) => {
43871
+ throw failed(error);
43872
+ });
43873
+ } catch (error) {
43874
+ await handle.close().catch(() => {});
43875
+ throw error;
43876
+ }
43877
+ await handle.close().catch((error) => {
43878
+ throw failed(error);
43879
+ });
43880
+ let json;
43881
+ try {
43882
+ const parsed = JSON.parse(data);
43883
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
43884
+ throw new Error;
43885
+ json = parsed;
43886
+ } catch {
43887
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED} is not a device login: it does not read as one JSON object of the login's fields`);
43888
+ }
43889
+ const credentialId = member(json, "credential_id");
43890
+ const refreshToken = member(json, "refresh_token");
43891
+ const broker = member(json, "broker");
43892
+ const expiresAt = new Date(member(json, "expires_at"));
43893
+ if (credentialId === "" || refreshToken === "" || broker === "" || Number.isNaN(expiresAt.getTime())) {
43894
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: credential_id, refresh_token, broker and an RFC 3339 expires_at are all required`);
43895
+ }
43896
+ let key;
43897
+ try {
43898
+ key = createPrivateKey({
43899
+ key: Buffer.from(member(json, "key"), "base64"),
43900
+ format: "der",
43901
+ type: "pkcs8"
43902
+ });
43903
+ } catch {
43904
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a base64 PKCS#8 key`);
43905
+ }
43906
+ if (key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
43907
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a P-256 key`);
43908
+ }
43909
+ const accessToken = member(json, "access_token");
43910
+ const accessText = member(json, "access_expires_at");
43911
+ const accessExpiresAt = accessToken === "" || accessText === "" ? null : new Date(accessText);
43912
+ const accessUsable = accessExpiresAt !== null && !Number.isNaN(accessExpiresAt.getTime());
43913
+ return {
43914
+ key,
43915
+ credentialId,
43916
+ refreshToken: holdSecret(refreshToken, expiresAt),
43917
+ expiresAt,
43918
+ broker,
43919
+ accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
43920
+ accessExpiresAt: accessUsable ? accessExpiresAt : null
43921
+ };
43922
+ }
43923
+ function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
43924
+ return new Error(`the lock beside ${DEVICE_LOGIN_FILE_NAMED} is no longer this process's: it stopped for over ${DEVICE_LOGIN_STALE_LOCK_MS / 1000} s while it held it (a laptop asleep, a process stopped), and another process took it; ${then}`);
43925
+ }
43926
+
43927
+ class KeptCopyError extends Error {
43928
+ suffix;
43929
+ constructor(suffix, failed) {
43930
+ super(`${messageOf(failed)}; a copy of the new login is kept beside ${DEVICE_LOGIN_FILE_NAMED}, under that file's name with ${suffix} added: move the copy over the file to use the login`);
43931
+ this.suffix = suffix;
43932
+ }
43933
+ }
43934
+ async function keptCopy(temp, path, error) {
43935
+ const suffix = `.kept-${randomUUID2()}`;
43936
+ try {
43937
+ await rename2(temp, `${path}${suffix}`);
43938
+ } catch {
43939
+ return error;
43940
+ }
43941
+ return new KeptCopyError(suffix, error);
43942
+ }
43943
+ async function saveDeviceLogin(path, login, held, keep = false) {
43944
+ const dir = dirname3(path);
43945
+ const data = JSON.stringify({
43946
+ key: login.key.export({ format: "der", type: "pkcs8" }).toString("base64"),
43947
+ credential_id: login.credentialId,
43948
+ refresh_token: login.refreshToken,
43949
+ expires_at: login.expiresAt.toISOString(),
43950
+ broker: login.broker,
43951
+ ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
43952
+ access_token: login.accessToken,
43953
+ access_expires_at: login.accessExpiresAt.toISOString()
43954
+ }
43955
+ });
43956
+ await deviceLoginPlace(path);
43957
+ await removeUntouched(dir, isTemporaryCopy);
43958
+ await removeLeftLocks(path);
43959
+ const temp = join4(dir, `.device-login-${randomUUID2()}.json.tmp`);
43960
+ const saveFailed = (error) => new Error(`save ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
43961
+ let whole = false;
43962
+ try {
43963
+ try {
43964
+ const handle = await open2(temp, "wx", 384);
43965
+ try {
43966
+ await handle.writeFile(data);
43967
+ await handle.sync();
43968
+ } finally {
43969
+ await handle.close();
43970
+ }
43971
+ } catch (error) {
43972
+ throw saveFailed(error);
43973
+ }
43974
+ whole = true;
43975
+ if (!await held())
43976
+ throw keep ? lockLost("the new login was not kept in its place") : lockLost();
43977
+ await rename2(temp, path).catch((error) => {
43978
+ throw saveFailed(error);
43979
+ });
43980
+ } catch (error) {
43981
+ throw keep && whole ? await keptCopy(temp, path, error) : error;
43982
+ } finally {
43983
+ await rm2(temp, { force: true }).catch(() => {});
43984
+ }
43985
+ try {
43986
+ const handle = await open2(dir, "r");
43987
+ try {
43988
+ await handle.sync();
43989
+ } finally {
43990
+ await handle.close();
43991
+ }
43992
+ } catch {}
43993
+ }
43994
+
43995
+ // ../cipher-client/src/dpop.ts
43996
+ import {
43997
+ createHash,
43998
+ createPrivateKey as createPrivateKey2,
43999
+ createPublicKey,
44000
+ generateKeyPairSync,
44001
+ randomUUID as randomUUID3,
44002
+ sign as sign2
44003
+ } from "crypto";
44004
+ var ALGORITHM = "ES256";
44005
+ var CONNECTION_PROOF_METHOD = "CONNECT";
44006
+ var CONNECTION_PROOF_TARGET = "nats:connect";
44007
+ function targetUri(url) {
44008
+ const parsed = new URL(url);
44009
+ parsed.search = "";
44010
+ parsed.hash = "";
44011
+ return parsed.toString();
44012
+ }
44013
+ function dpopKey(privateKey, publicJwk) {
44014
+ const header = Buffer.from(JSON.stringify({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk })).toString("base64url");
44015
+ const signed = (htm, htu, nonce, accessToken) => {
44016
+ const claims = {
44017
+ jti: randomUUID3(),
44018
+ htm,
44019
+ htu,
44020
+ iat: Math.floor(Date.now() / 1000)
44021
+ };
44022
+ if (nonce !== undefined && nonce !== "")
44023
+ claims["nonce"] = nonce;
44024
+ if (accessToken !== undefined && accessToken !== "") {
44025
+ claims["ath"] = createHash("sha256").update(accessToken).digest("base64url");
44026
+ }
44027
+ const signingInput = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
44028
+ const signature = sign2("sha256", Buffer.from(signingInput), {
44029
+ key: privateKey,
44030
+ dsaEncoding: "ieee-p1363"
44031
+ });
44032
+ return `${signingInput}.${signature.toString("base64url")}`;
44033
+ };
44034
+ return {
44035
+ publicJwk,
44036
+ async proof(request) {
44037
+ return signed(request.method.toUpperCase(), targetUri(request.url), request.nonce, request.accessToken);
44038
+ },
44039
+ connectionProof({ accessToken, nonce }) {
44040
+ if (accessToken === "")
44041
+ throw new Error("no access token to prove a NATS connection for");
44042
+ if (nonce === "")
44043
+ throw new Error("the NATS server sent no nonce to sign");
44044
+ return signed(CONNECTION_PROOF_METHOD, CONNECTION_PROOF_TARGET, nonce, accessToken);
44045
+ }
44046
+ };
44047
+ }
44048
+ function publicJwkOf(privateKey, name) {
44049
+ const { kty, crv, x, y } = createPublicKey(privateKey).export({ format: "jwk" });
44050
+ if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
44051
+ throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
44052
+ }
44053
+ return { kty, crv, x, y };
44054
+ }
44055
+ async function newDpopKey() {
44056
+ const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
44057
+ return dpopKeyOf(privateKey, "this process's key");
44058
+ }
44059
+ function dpopKeyOf(privateKey, name) {
44060
+ return dpopKey(privateKey, publicJwkOf(privateKey, name));
44061
+ }
44062
+ async function importDpopKey(pkcs8Pem, name) {
44063
+ let privateKey;
44064
+ try {
44065
+ privateKey = createPrivateKey2(pkcs8Pem);
44066
+ } catch {
44067
+ throw new Error(`read ${name}: it does not parse as a PKCS#8 PEM private key`);
44068
+ }
44069
+ return dpopKey(privateKey, publicJwkOf(privateKey, name));
44070
+ }
44071
+
44072
+ // ../cipher-client/src/device-login.ts
44073
+ var BROKER_SETTING = "AGENT_SECRETS_URL";
44074
+ var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
44075
+ var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
44076
+ var DEFAULT_POLL_SECONDS = 5;
44077
+ var LEAST_POLL_SECONDS = 1;
44078
+ var MOST_POLL_SECONDS = 60;
44079
+ var MOST_LIFETIME_SECONDS = 3600;
44080
+ var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
44081
+ var UNPRINTABLE = /[\p{Cc}\p{Cf}]/u;
44082
+ function deviceLoginSessionName(thumbprint) {
44083
+ return `device-login-${thumbprint.slice(0, 12)}`;
44084
+ }
44085
+ function deviceLoginHost(name) {
44086
+ const labels = name.trim().toLowerCase().replace(/[^a-z0-9.-]+/g, "-").split(".").map((label) => label.replace(/^-+/, "").slice(0, 63).replace(/-+$/, "")).filter((label) => label !== "");
44087
+ const host = labels.join(".").slice(0, 253).replace(/[.-]+$/, "");
44088
+ return host === "" ? "device" : host;
44089
+ }
44090
+ function deviceLoginBroker(brokerUrl) {
44091
+ const trimmed = withoutTrailingSlashes(brokerUrl.trim());
44092
+ if (!isHttpUrl(trimmed))
44093
+ throw new Error(`${BROKER_SETTING} is not an http or https URL`);
44094
+ const { protocol, hostname } = new URL(trimmed);
44095
+ if (protocol === "http:" && !LOOPBACK_HOST.test(hostname)) {
44096
+ throw new Error(`${BROKER_SETTING} is an http URL of a host off this machine's loopback: a device login sends its refresh token and access tokens to the broker, so it takes https, or http to 127.0.0.1, ::1 or localhost`);
44097
+ }
44098
+ return holdUrlUserinfo(trimmed);
44099
+ }
44100
+ function loginDpopKey(key) {
44101
+ return dpopKeyOf(key, "this machine's device login key");
44102
+ }
44103
+ function printable(value, what, endpoint) {
44104
+ if (UNPRINTABLE.test(value)) {
44105
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered a ${what} holding a control or format character, which this machine does not print`);
44106
+ }
44107
+ return value;
44108
+ }
44109
+ function page(uri, endpoint) {
44110
+ if (!isHttpUrl(uri)) {
44111
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered a page to type the code in that is no http or https URL`);
44112
+ }
44113
+ return printable(uri, "page to type the code in", endpoint);
44114
+ }
44115
+ async function withDeviceLoginLock(path, work, options = {}) {
44116
+ await deviceLoginDirectory(path);
44117
+ return await withLoginLock(path, DEVICE_LOGIN_FILE_NAMED, work, options);
44118
+ }
44119
+ function brokerConfiguration(brokerUrl, fetchImpl, proved) {
44120
+ const config = new Configuration({
44121
+ issuer: brokerUrl,
44122
+ token_endpoint: brokerUrl + TOKEN_PATH,
44123
+ device_authorization_endpoint: brokerUrl + DEVICE_AUTHORIZATION_PATH
44124
+ }, MACHINE_LOGIN_CLIENT_ID, {}, None2());
44125
+ if (new URL(brokerUrl).protocol === "http:")
44126
+ allowInsecureRequests2(config);
44127
+ config[customFetch2] = (url, options) => {
44128
+ const deadline = AbortSignal.timeout(BROKER_REQUEST_MS);
44129
+ return proved === undefined ? fetchImpl(url, requestInit(options, deadline, options.headers)) : sendWithProof({ key: proved.key, fetch: fetchImpl, nonce: proved.nonce }, url, options, deadline);
44130
+ };
44131
+ return config;
44132
+ }
44133
+ function loginOf(key, broker, answered, now) {
44134
+ const endpoint = broker + TOKEN_PATH;
44135
+ const credentialId = typeof answered["credential_id"] === "string" ? answered["credential_id"] : "";
44136
+ const expiresAt = new Date(typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "");
44137
+ const refreshToken = answered.refresh_token ?? "";
44138
+ const seconds = Math.min(answered.expires_in ?? 0, MOST_LIFETIME_SECONDS);
44139
+ if (credentialId === "" || Number.isNaN(expiresAt.getTime()) || refreshToken === "" || !(seconds > 0) || answered.token_type.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
44140
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered the device login without a credential_id, an RFC 3339 credential_expires_at, a refresh_token, a positive expires_in or a DPoP-bound token`);
44141
+ }
44142
+ const accessExpiresAt = new Date(now + seconds * 1000);
44143
+ return {
44144
+ key,
44145
+ credentialId: printable(credentialId, "credential_id", endpoint),
44146
+ refreshToken: holdSecret(refreshToken, expiresAt),
44147
+ expiresAt,
44148
+ broker,
44149
+ accessToken: holdSecret(answered.access_token, accessExpiresAt),
44150
+ accessExpiresAt
44151
+ };
44152
+ }
44153
+ async function startDeviceLogin(options) {
44154
+ const brokerUrl = deviceLoginBroker(options.brokerUrl);
44155
+ const endpoint = brokerUrl + DEVICE_AUTHORIZATION_PATH;
44156
+ const person = options.person.trim();
44157
+ const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
44158
+ const jwk = loginDpopKey(privateKey).publicJwk;
44159
+ const thumbprint = await calculateJwkThumbprint(jwk);
44160
+ const iat = Math.floor(Date.now() / 1000);
44161
+ const claims = {
44162
+ iss: thumbprint,
44163
+ aud: brokerUrl,
44164
+ jti: randomUUID4(),
44165
+ iat,
44166
+ exp: iat + REQUEST_OBJECT_LIFETIME_SECONDS,
44167
+ authorization_details: [{ type: LAUNCHER_CREDENTIAL_DETAIL, identifier: options.host }],
44168
+ login_hint: person
44169
+ };
44170
+ const request = await new CompactSign(new TextEncoder().encode(JSON.stringify(claims))).setProtectedHeader({ alg: "ES256", typ: REQUEST_OBJECT_TYPE, jwk }).sign(privateKey);
44171
+ const config = brokerConfiguration(brokerUrl, options.fetch ?? fetch);
44172
+ let answered;
44173
+ try {
44174
+ answered = await initiateDeviceAuthorization(config, {
44175
+ scope: MACHINE_LOGIN_SCOPE,
44176
+ dpop_jkt: thumbprint,
44177
+ request
44178
+ });
44179
+ } catch (error) {
44180
+ throw brokerRefusal("ask for a code for", "this machine's device login", endpoint, error);
44181
+ }
44182
+ const expiresAt = new Date(Date.now() + Math.min(answered.expires_in, MOST_LIFETIME_SECONDS) * 1000);
44183
+ return {
44184
+ brokerUrl,
44185
+ person,
44186
+ userCode: printable(answered.user_code, "user code", endpoint),
44187
+ verificationUri: page(answered.verification_uri, endpoint),
44188
+ verificationUriComplete: answered.verification_uri_complete === undefined ? undefined : page(answered.verification_uri_complete, endpoint),
44189
+ expiresAt,
44190
+ intervalSeconds: Math.min(Math.max(answered.interval ?? DEFAULT_POLL_SECONDS, LEAST_POLL_SECONDS), MOST_POLL_SECONDS),
44191
+ deviceCode: holdSecret(answered.device_code, expiresAt),
44192
+ key: privateKey
44193
+ };
44194
+ }
44195
+ async function finishDeviceLogin(started, options) {
44196
+ const wait = options.sleep ?? ((ms) => sleep2(ms, undefined, true));
44197
+ const config = brokerConfiguration(started.brokerUrl, options.fetch ?? fetch, {
44198
+ key: loginDpopKey(started.key),
44199
+ nonce: { value: "" }
44200
+ });
44201
+ const endpoint = started.brokerUrl + TOKEN_PATH;
44202
+ const expired = new Error(`the code ${started.userCode} expired before ${started.person} approved this machine; ask again with: ${DEVICE_LOGIN_COMMAND}`);
44203
+ let interval = started.intervalSeconds;
44204
+ while (true) {
44205
+ if (Date.now() >= started.expiresAt.getTime())
44206
+ throw expired;
44207
+ await wait(interval * 1000);
44208
+ let answered;
44209
+ try {
44210
+ answered = await genericGrantRequest(config, GRANT_TYPE_DEVICE_CODE, {
44211
+ device_code: started.deviceCode
44212
+ });
44213
+ } catch (error) {
44214
+ const code = error instanceof ResponseBodyError ? error.error : "";
44215
+ if (code === "access_denied") {
44216
+ throw new Error(`this machine's device login was denied, not approved as ${started.person}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
44217
+ }
44218
+ if (code === "expired_token" || code === "invalid_grant")
44219
+ throw expired;
44220
+ if (code === "slow_down")
44221
+ interval += 5;
44222
+ const status = statusOf(error);
44223
+ const pollAgain = code === "authorization_pending" || code === "slow_down" || status === 0 || status === 429 || status >= 500;
44224
+ if (!pollAgain) {
44225
+ const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
44226
+ throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
44227
+ }
44228
+ continue;
44229
+ }
44230
+ const login = loginOf(started.key, started.brokerUrl, answered, Date.now());
44231
+ let replaced = "";
44232
+ let saved = false;
44233
+ try {
44234
+ await withDeviceLoginLock(options.path, async (held) => {
44235
+ replaced = await readDeviceLogin(options.path).then((kept) => kept.credentialId, () => "");
44236
+ await saveDeviceLogin(options.path, login, held, true);
44237
+ saved = true;
44238
+ });
44239
+ } catch (error) {
44240
+ if (saved) {
44241
+ const lockLeft = `this process could not let go of the lock beside ${DEVICE_LOGIN_FILE_NAMED} (${messageOf(error)}); another process takes it over once it is ${DEVICE_LOGIN_STALE_LOCK_MS / 1000} s old`;
44242
+ return { ...login, replaced, lockLeft };
44243
+ }
44244
+ const revoke = `Machine logins on ${started.verificationUri}`;
44245
+ throw new Error(error instanceof KeptCopyError ? `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it in its place: ${messageOf(error)}, which then needs no revoke. Where the copy is not used, delete it, since it holds the login's key and refresh token, and revoke the credential in ${revoke}: it stays live until it lapses or is revoked` : `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it: ${messageOf(error)}. The credential stays live until it lapses or is revoked: revoke it in ${revoke}, and log in again with: ${DEVICE_LOGIN_COMMAND}`, { cause: error });
44246
+ }
44247
+ return { ...login, replaced, lockLeft: "" };
44248
+ }
44249
+ }
44250
+
44251
+ class DeviceLoginIdentity {
44252
+ #path;
44253
+ #brokerUrl;
44254
+ #key;
44255
+ constructor(options) {
44256
+ this.#path = options.path;
44257
+ this.#brokerUrl = deviceLoginBroker(options.brokerUrl);
44258
+ }
44259
+ describe() {
44260
+ return `this machine's device login (${DEVICE_LOGIN_FILE_NAMED})`;
44261
+ }
44262
+ async key() {
44263
+ return (await this.#loaded()).key;
44264
+ }
44265
+ async thumbprint() {
44266
+ return (await this.#loaded()).thumbprint;
44267
+ }
44268
+ #loaded() {
44269
+ if (this.#key === undefined) {
44270
+ const loading = readDeviceLogin(this.#path).then(async ({ key }) => {
44271
+ const dpop = loginDpopKey(key);
44272
+ return { key: dpop, thumbprint: await calculateJwkThumbprint(dpop.publicJwk) };
44273
+ });
44274
+ this.#key = loading;
44275
+ loading.catch(() => {
44276
+ if (this.#key === loading)
44277
+ this.#key = undefined;
44278
+ });
44279
+ }
44280
+ return this.#key;
44281
+ }
44282
+ async spend(trade, signal) {
44283
+ const { thumbprint } = await this.#loaded();
44284
+ return await withDeviceLoginLock(this.#path, async (held) => {
44285
+ let login = await readDeviceLogin(this.#path);
44286
+ if (withoutTrailingSlashes(login.broker) !== this.#brokerUrl) {
44287
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED} was made at another secrets broker than ${BROKER_SETTING} names; log this machine in at this one with: ${DEVICE_LOGIN_COMMAND}`);
44288
+ }
44289
+ if (await calculateJwkThumbprint(loginDpopKey(login.key).publicJwk) !== thumbprint) {
44290
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED} holds another login than the one this process started with, since ${DEVICE_LOGIN_COMMAND} ran again; start this session again to trade the new one`);
44291
+ }
44292
+ const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
44293
+ const expires = login.accessExpiresAt?.getTime() ?? 0;
44294
+ let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
44295
+ if (refreshed)
44296
+ login = await refresh();
44297
+ while (true) {
44298
+ try {
44299
+ return await trade({ token: login.accessToken, tokenType: SUBJECT_TYPE_ACCESS });
44300
+ } catch (error) {
44301
+ if (!(error instanceof BrokerRefusedError) || !error.subjectNotHonoured)
44302
+ throw error;
44303
+ if (!await held())
44304
+ throw lockLost();
44305
+ if (refreshed)
44306
+ throw error;
44307
+ login = await refresh();
44308
+ refreshed = true;
44309
+ }
44310
+ }
44311
+ }, { signal });
44312
+ }
44313
+ async read(signal) {
44314
+ return await this.spend(async (subject) => subject, signal);
44315
+ }
44316
+ }
44317
+ async function refreshDeviceLogin(path, login, options) {
44318
+ const config = brokerConfiguration(login.broker, fetch, {
44319
+ key: loginDpopKey(login.key),
44320
+ nonce: { value: "" }
44321
+ });
44322
+ const endpoint = login.broker + TOKEN_PATH;
44323
+ let answered;
44324
+ for (let sent = 0;answered === undefined; sent += 1) {
44325
+ if (!await options.held())
44326
+ throw lockLost();
44327
+ try {
44328
+ answered = await genericGrantRequest(config, GRANT_TYPE_REFRESH, {
44329
+ refresh_token: login.refreshToken
44330
+ });
44331
+ } catch (error) {
44332
+ if (error instanceof ResponseBodyError && error.error === "invalid_grant") {
44333
+ throw new DeviceLoginEndedError(options.describe);
44334
+ }
44335
+ if (sent === 0 && statusOf(error) === 0)
44336
+ continue;
44337
+ throw brokerRefusal("refresh", options.describe, endpoint, error);
44338
+ }
44339
+ }
44340
+ const next = loginOf(login.key, login.broker, answered, Date.now());
44341
+ await saveDeviceLogin(path, next, options.held);
44342
+ return next;
44343
+ }
44344
+
44345
+ // ../cipher-client/src/metadata-identity.ts
44346
+ import { Agent, request } from "http";
44347
+ var METADATA_HOST_VAR = "GCE_METADATA_HOST";
44348
+ var DEFAULT_METADATA_HOST = "metadata.google.internal";
44349
+ var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
44350
+ var TIMEOUT_MS = 1e4;
44351
+ var MAX_ANSWER_BYTES = 1 << 20;
44352
+ var agent = new Agent({ keepAlive: false });
44353
+ function tokenUrl(audience, env) {
44354
+ const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
44355
+ return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
44356
+ }
44357
+ function serverNamed(env) {
44358
+ return (env[METADATA_HOST_VAR] ?? "").trim() === "" ? `at ${DEFAULT_METADATA_HOST}` : `${METADATA_HOST_VAR} names`;
44359
+ }
44360
+ function get(url, signal, lookup) {
44361
+ const { promise, resolve, reject } = Promise.withResolvers();
44362
+ const call = request(url, {
44363
+ agent,
44364
+ method: "GET",
44365
+ headers: { "Metadata-Flavor": "Google" },
44366
+ timeout: TIMEOUT_MS,
44367
+ ...signal === undefined ? {} : { signal },
44368
+ ...lookup === undefined ? {} : { lookup }
44369
+ }, (answer) => {
44370
+ const chunks = [];
44371
+ let read = 0;
44372
+ answer.on("data", (chunk) => {
44373
+ read += chunk.length;
44374
+ if (read <= MAX_ANSWER_BYTES)
44375
+ chunks.push(chunk);
44376
+ });
44377
+ answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
44378
+ answer.on("error", reject);
44379
+ });
44380
+ call.on("timeout", () => call.destroy(Object.assign(new Error(`no answer within ${TIMEOUT_MS} ms`), { code: "ETIMEDOUT" })));
44381
+ call.on("error", reject);
44382
+ call.end();
44383
+ return promise;
44384
+ }
44385
+ function metadataIdentity(audience, env = process.env, options = {}) {
44386
+ return {
44387
+ async read(signal) {
44388
+ const url = tokenUrl(audience, env);
44389
+ const named = `the metadata server ${serverNamed(env)}`;
44390
+ let answer;
44391
+ try {
44392
+ answer = await get(url, signal, options.lookup);
44393
+ } catch (error) {
44394
+ throw new Error(`${named} could not be reached: ${errorClass(error)}`);
44395
+ }
44396
+ if (answer.status < 200 || answer.status > 299) {
44397
+ throw new Error(`${named} answered HTTP ${answer.status}`);
44398
+ }
44399
+ const token = answer.body.trim();
44400
+ if (token === "") {
44401
+ throw new Error(`${named} answered an empty identity token`);
44402
+ }
44403
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
44404
+ },
44405
+ describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
44406
+ };
44407
+ }
44408
+
42681
44409
  // ../cipher-client/src/person-identity.ts
42682
44410
  var ISSUER_TIMEOUT_SECONDS = 30;
42683
44411
  var INVALID_GRANT2 = "invalid_grant";
@@ -42892,14 +44620,14 @@ function poolIdentity(options) {
42892
44620
  }
42893
44621
 
42894
44622
  // ../cipher-client/src/projected-token.ts
42895
- import { readFile as readFile2 } from "fs/promises";
44623
+ import { readFile as readFile3 } from "fs/promises";
42896
44624
  function projectedToken(path, variable) {
42897
44625
  const named = `the projected service-account token ${variable} names`;
42898
44626
  return {
42899
44627
  async read(signal) {
42900
44628
  let contents;
42901
44629
  try {
42902
- contents = await readFile2(path, {
44630
+ contents = await readFile3(path, {
42903
44631
  encoding: "utf8",
42904
44632
  ...signal === undefined ? {} : { signal }
42905
44633
  });
@@ -42928,6 +44656,7 @@ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
42928
44656
  var IDENTITY_KUBERNETES = "kubernetes";
42929
44657
  var IDENTITY_METADATA = "metadata";
42930
44658
  var IDENTITY_POOL = "pool";
44659
+ var IDENTITY_DEVICE_LOGIN = "device-login";
42931
44660
  var BROKER_VARIABLES = [
42932
44661
  BROKER_URL_VAR,
42933
44662
  IDENTITY_VAR,
@@ -42937,6 +44666,7 @@ var BROKER_VARIABLES = [
42937
44666
  PROJECTS_VAR,
42938
44667
  POOL_AUDIENCE_VAR,
42939
44668
  POOL_ACCOUNT_VAR,
44669
+ DEVICE_LOGIN_FILE_VAR,
42940
44670
  SIGNIN_DIR_VAR,
42941
44671
  "XDG_STATE_HOME",
42942
44672
  "HOME",
@@ -42976,8 +44706,12 @@ function machineIdentity(env) {
42976
44706
  tokenAudience
42977
44707
  });
42978
44708
  }
44709
+ case IDENTITY_DEVICE_LOGIN: {
44710
+ const brokerUrl = required2(env, BROKER_URL_VAR, kind);
44711
+ return new DeviceLoginIdentity({ path: deviceLoginFile(env), brokerUrl });
44712
+ }
42979
44713
  default:
42980
- throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${IDENTITY_POOL}`);
44714
+ throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA}, ${IDENTITY_POOL} or ${IDENTITY_DEVICE_LOGIN}`);
42981
44715
  }
42982
44716
  }
42983
44717
  function tradeSession(env, own = "") {
@@ -43009,6 +44743,19 @@ async function brokerTokenClient(env, own = "") {
43009
44743
  return;
43010
44744
  if (!isHttpUrl(brokerUrl))
43011
44745
  throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
44746
+ if (machine instanceof DeviceLoginIdentity) {
44747
+ if (personTradeOff(env)) {
44748
+ throw new Error(`${PERSON_TRADE_VAR}=off turns off every trade made as a person, and ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} trades this machine's device login as the person who approved it; unset one of them`);
44749
+ }
44750
+ const client = new BrokerTokenClient({
44751
+ brokerUrl,
44752
+ key: await machine.key(),
44753
+ subject: machine,
44754
+ session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
44755
+ projects: tradeProjects(env)
44756
+ });
44757
+ return { client, signIn: undefined };
44758
+ }
43012
44759
  const record = await chooseSignIn(env);
43013
44760
  if (record === undefined) {
43014
44761
  const client = new BrokerTokenClient({
@@ -44673,26 +46420,26 @@ class DispatchClient {
44673
46420
  }
44674
46421
 
44675
46422
  // ../envoy-client/src/dispatch-session-directory.ts
44676
- import { randomUUID as randomUUID2 } from "crypto";
46423
+ import { randomUUID as randomUUID5 } from "crypto";
44677
46424
  import { renameSync, rmSync as rmSync2, writeFileSync } from "fs";
44678
46425
  import { homedir as homedir2 } from "os";
44679
- import { join as join3 } from "path";
46426
+ import { join as join5 } from "path";
44680
46427
  var SESSION_ID_PATH_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/;
44681
46428
  var PRIVATE_FILE = 384;
44682
46429
  function sessionStateRoot(env) {
44683
46430
  const stateDir = env["DISPATCH_STATE_DIR"];
44684
46431
  if (stateDir)
44685
46432
  return stateDir;
44686
- return join3(env["XDG_STATE_HOME"] || join3(homedir2(), ".local", "state"), "dispatch");
46433
+ return join5(env["XDG_STATE_HOME"] || join5(homedir2(), ".local", "state"), "dispatch");
44687
46434
  }
44688
46435
  function sessionDirectory(env, sessionId) {
44689
46436
  if (!SESSION_ID_PATH_SEGMENT.test(sessionId) || sessionId === "." || sessionId === "..") {
44690
46437
  throw new Error(`dispatch: the session id ${JSON.stringify(sessionId)} is not 1-128 letters, digits, ".", "_" or "-"`);
44691
46438
  }
44692
- return join3(sessionStateRoot(env), "sessions", sessionId);
46439
+ return join5(sessionStateRoot(env), "sessions", sessionId);
44693
46440
  }
44694
46441
  function writeAtomically(path, text) {
44695
- const temporary = `${path}.${process.pid}.${randomUUID2()}.tmp`;
46442
+ const temporary = `${path}.${process.pid}.${randomUUID5()}.tmp`;
44696
46443
  try {
44697
46444
  writeFileSync(temporary, text, { mode: PRIVATE_FILE });
44698
46445
  renameSync(temporary, path);
@@ -44717,13 +46464,13 @@ import {
44717
46464
  statSync as statSync3,
44718
46465
  writeFileSync as writeFileSync3
44719
46466
  } from "fs";
44720
- import { join as join6 } from "path";
46467
+ import { join as join8 } from "path";
44721
46468
 
44722
46469
  // ../envoy-client/src/askgate-marker.ts
44723
46470
  import { createHash as createHash2, randomBytes } from "crypto";
44724
46471
  import {
44725
46472
  closeSync as closeSync2,
44726
- constants,
46473
+ constants as constants3,
44727
46474
  mkdirSync,
44728
46475
  openSync as openSync2,
44729
46476
  readdirSync,
@@ -44736,7 +46483,7 @@ import {
44736
46483
  utimesSync,
44737
46484
  writeFileSync as writeFileSync2
44738
46485
  } from "fs";
44739
- import { isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "path";
46486
+ import { isAbsolute as isAbsolute3, join as join6, resolve as resolve2 } from "path";
44740
46487
  var ASKGATE_RECORD = "askgate";
44741
46488
  var MARKER_MAX_AGE_MS = 2 * 60 * 60000;
44742
46489
  var STORE_BEAT_MS = 10 * 60000;
@@ -44765,12 +46512,12 @@ function gatedWrite(tool, args) {
44765
46512
  return uploadIsDocument(args);
44766
46513
  return false;
44767
46514
  }
44768
- var digest = (value) => createHash2("sha256").update(JSON.stringify(value)).digest("hex");
46515
+ var digest2 = (value) => createHash2("sha256").update(JSON.stringify(value)).digest("hex");
44769
46516
  function argvDigest(argv) {
44770
- return digest(argv);
46517
+ return digest2(argv);
44771
46518
  }
44772
46519
  function argsDigest(args) {
44773
- return digest(args);
46520
+ return digest2(args);
44774
46521
  }
44775
46522
  function fileOperands(argv) {
44776
46523
  const [command, ...flags] = argv;
@@ -44791,7 +46538,7 @@ function fileOperands(argv) {
44791
46538
  function operandPath(cwd, file) {
44792
46539
  if (file.flag === "--path")
44793
46540
  return resolve2(cwd, file.operand);
44794
- return isAbsolute2(file.operand) ? file.operand : `${cwd}/${file.operand}`;
46541
+ return isAbsolute3(file.operand) ? file.operand : `${cwd}/${file.operand}`;
44795
46542
  }
44796
46543
  function bytesDigest(bytes) {
44797
46544
  return createHash2("sha256").update(bytes).digest("hex");
@@ -44858,7 +46605,7 @@ var STORE_NAME = /^([1-9][0-9]*)(?:-([0-9]+)(?:-([0-9]+))?)?$/;
44858
46605
  function storeTouched(store) {
44859
46606
  const own = statSync2(store).mtimeMs;
44860
46607
  try {
44861
- return Math.max(own, statSync2(join4(store, MARKERS)).mtimeMs);
46608
+ return Math.max(own, statSync2(join6(store, MARKERS)).mtimeMs);
44862
46609
  } catch (error) {
44863
46610
  if (hasErrnoCode(error, "ENOENT"))
44864
46611
  return own;
@@ -44867,7 +46614,7 @@ function storeTouched(store) {
44867
46614
  }
44868
46615
  var UNNAMESPACED_STORE_MAX_AGE_MS = 14 * 86400000;
44869
46616
  function sweepStores(root, now) {
44870
- const parent = join4(root, "askgate");
46617
+ const parent = join6(root, "askgate");
44871
46618
  let names;
44872
46619
  try {
44873
46620
  names = readdirSync(parent);
@@ -44878,7 +46625,7 @@ function sweepStores(root, now) {
44878
46625
  const match = STORE_NAME.exec(name);
44879
46626
  if (match === null)
44880
46627
  continue;
44881
- const store = join4(parent, name);
46628
+ const store = join6(parent, name);
44882
46629
  try {
44883
46630
  const owner = { pid: Number(match[1]), start: match[2] ?? null, ns: match[3] ?? null, store };
44884
46631
  if (ownerLive(owner, now))
@@ -44892,7 +46639,7 @@ function sweepStores(root, now) {
44892
46639
  }
44893
46640
  }
44894
46641
  function recordNamesStore(dir) {
44895
- const record = join4(dir, ASKGATE_RECORD);
46642
+ const record = join6(dir, ASKGATE_RECORD);
44896
46643
  let names;
44897
46644
  try {
44898
46645
  names = readdirSync(record);
@@ -44903,7 +46650,7 @@ function recordNamesStore(dir) {
44903
46650
  if (!name.endsWith(OWNER_FILE))
44904
46651
  continue;
44905
46652
  try {
44906
- const parsed = parseOwner(readFileSync3(join4(record, name), "utf-8"));
46653
+ const parsed = parseOwner(readFileSync3(join6(record, name), "utf-8"));
44907
46654
  if (parsed === undefined)
44908
46655
  return true;
44909
46656
  statSync2(parsed.owner.store);
@@ -44916,7 +46663,7 @@ function recordNamesStore(dir) {
44916
46663
  return false;
44917
46664
  }
44918
46665
  function askgateState(dir, now = Date.now()) {
44919
- const record = join4(dir, ASKGATE_RECORD);
46666
+ const record = join6(dir, ASKGATE_RECORD);
44920
46667
  let names;
44921
46668
  try {
44922
46669
  names = readdirSync(record);
@@ -44929,7 +46676,7 @@ function askgateState(dir, now = Date.now()) {
44929
46676
  for (const name of names) {
44930
46677
  if (!name.endsWith(OWNER_FILE))
44931
46678
  continue;
44932
- const file = join4(record, name);
46679
+ const file = join6(record, name);
44933
46680
  let text;
44934
46681
  try {
44935
46682
  text = readFileSync3(file, "utf-8");
@@ -44949,7 +46696,7 @@ function askgateState(dir, now = Date.now()) {
44949
46696
  return { kind: "off" };
44950
46697
  for (const { file, store } of live) {
44951
46698
  try {
44952
- if (!statSync2(join4(store, MARKERS)).isDirectory())
46699
+ if (!statSync2(join6(store, MARKERS)).isDirectory())
44953
46700
  throw new Error("not a directory");
44954
46701
  } catch (error) {
44955
46702
  return {
@@ -44968,7 +46715,7 @@ var isFileDigest = (value) => typeof value === "object" && value !== null && typ
44968
46715
  function readMarker(file) {
44969
46716
  let text;
44970
46717
  try {
44971
- const fd = openSync2(file, constants.O_RDONLY | constants.O_NOFOLLOW);
46718
+ const fd = openSync2(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
44972
46719
  try {
44973
46720
  text = readFileSync3(fd, "utf-8");
44974
46721
  } finally {
@@ -45001,11 +46748,11 @@ function consumeMarker(stores, argv, args, files, now) {
45001
46748
  let expired = false;
45002
46749
  const usable = [];
45003
46750
  for (const store of stores) {
45004
- const dir = join4(store, MARKERS);
46751
+ const dir = join6(store, MARKERS);
45005
46752
  for (const name of readdirSync(dir)) {
45006
46753
  if (!name.startsWith(`${key}.`))
45007
46754
  continue;
45008
- const file = join4(dir, name);
46755
+ const file = join6(dir, name);
45009
46756
  const marker = readMarker(file);
45010
46757
  if (marker === undefined || marker.argv !== key)
45011
46758
  continue;
@@ -45562,6 +47309,8 @@ function commandsHelp() {
45562
47309
  }),
45563
47310
  "",
45564
47311
  "Run dispatch <command> --help for its flags and an example; --dry-run checks a command's arguments as the call would and prints them as given, sending nothing, except that dispatch result's dry run of a record also prints the pull-request body line Dispatch would write for it, recording nothing.",
47312
+ "",
47313
+ "dispatch login --device logs a machine with no identity of its own, such as a laptop, in at the secrets broker, once per machine; it is no Dispatch call, and needs no host or session (dispatch login --help).",
45565
47314
  ""
45566
47315
  ].join(`
45567
47316
  `);
@@ -45797,7 +47546,7 @@ function parseDispatchRef(ref) {
45797
47546
  }
45798
47547
 
45799
47548
  // ../envoy-client/src/dispatch-picture-tools.ts
45800
- import { basename, resolve as resolvePath } from "path";
47549
+ import { basename as basename2, resolve as resolvePath } from "path";
45801
47550
 
45802
47551
  // ../../node_modules/.bun/@toon-format+toon@4.1.1/node_modules/@toon-format/toon/dist/index.mjs
45803
47552
  var NULL_LITERAL = "null";
@@ -46303,7 +48052,7 @@ function transformArray(arr, replacer, path) {
46303
48052
  }
46304
48053
  return result;
46305
48054
  }
46306
- function encode3(input, options) {
48055
+ function encode5(input, options) {
46307
48056
  return Array.from(encodeLines(input, options)).join(`
46308
48057
  `);
46309
48058
  }
@@ -46639,7 +48388,7 @@ function eventPictures(event) {
46639
48388
  }
46640
48389
  function carriedItem(event) {
46641
48390
  const resource = event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("message.") ? "message" : undefined;
46642
- if (resource === undefined || !isObject2(event.payload))
48391
+ if (resource === undefined || !isObject3(event.payload))
46643
48392
  return;
46644
48393
  const id = event.payload["id"];
46645
48394
  if (typeof id !== "string" || id === "")
@@ -46647,10 +48396,10 @@ function carriedItem(event) {
46647
48396
  return { resource, id, issueKey: event.issue_key };
46648
48397
  }
46649
48398
  function payloadWasOmitted(payload) {
46650
- return isObject2(payload) && payload["payload_omitted"] === true;
48399
+ return isObject3(payload) && payload["payload_omitted"] === true;
46651
48400
  }
46652
48401
  function bodyWasCut(payload) {
46653
- return isObject2(payload) && payload["body_truncated"] === true || payloadWasOmitted(payload);
48402
+ return isObject3(payload) && payload["body_truncated"] === true || payloadWasOmitted(payload);
46654
48403
  }
46655
48404
  function wholeItemRoute(item) {
46656
48405
  return `GET /api/v1/${item.resource === "comment" ? "comments" : "messages"}/${item.id}`;
@@ -46868,7 +48617,7 @@ function dispatchPayload(event) {
46868
48617
  return parsed.success ? parsed.data : event.payload;
46869
48618
  }
46870
48619
  function hasTarget(value) {
46871
- return isObject2(value) && "target" in value;
48620
+ return isObject3(value) && "target" in value;
46872
48621
  }
46873
48622
  function dispatchPayloadForReader(event, sessionID) {
46874
48623
  const payload = dispatchPayload(event);
@@ -46906,11 +48655,11 @@ function dispatchReplyRef(event, topic, inReplyTo, comment) {
46906
48655
  return inReplyTo;
46907
48656
  return dispatchChildRef(dispatchDocumentRef(document.project, document.slug), kind, inReplyTo);
46908
48657
  }
46909
- function isObject2(value) {
48658
+ function isObject3(value) {
46910
48659
  return typeof value === "object" && value !== null;
46911
48660
  }
46912
48661
  function withWholeBody(event, body) {
46913
- if (body === undefined || !isObject2(event.payload) || !bodyWasCut(event.payload))
48662
+ if (body === undefined || !isObject3(event.payload) || !bodyWasCut(event.payload))
46914
48663
  return event;
46915
48664
  const { body_truncated: _cut, payload_omitted: _omitted, ...carried } = event.payload;
46916
48665
  return { ...event, payload: { ...carried, body } };
@@ -46922,7 +48671,7 @@ function parseDispatchFrame(rawPayload, wholeBody) {
46922
48671
  } catch {
46923
48672
  return { raw: rawPayload };
46924
48673
  }
46925
- if (isObject2(value) && "delivery" in value) {
48674
+ if (isObject3(value) && "delivery" in value) {
46926
48675
  const targeted = DispatchTargetedFrameSchema.safeParse(value);
46927
48676
  if (targeted.success) {
46928
48677
  const wireFrame = value;
@@ -46980,7 +48729,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
46980
48729
  } catch {
46981
48730
  return {
46982
48731
  skip: false,
46983
- content: encode3({
48732
+ content: encode5({
46984
48733
  envoy: { topic: subject ?? "unknown", unrecognised: "payload was not JSON" }
46985
48734
  })
46986
48735
  };
@@ -46995,7 +48744,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
46995
48744
  if (!tolerant.success) {
46996
48745
  return {
46997
48746
  skip: false,
46998
- content: encode3({ envoy: { unrecognised: parseIssues.join(", ") || "envelope" } })
48747
+ content: encode5({ envoy: { unrecognised: parseIssues.join(", ") || "envelope" } })
46999
48748
  };
47000
48749
  }
47001
48750
  const data = tolerant.data;
@@ -47204,7 +48953,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
47204
48953
  };
47205
48954
  return {
47206
48955
  skip: false,
47207
- content: trailer === "" ? encode3({ envoy: rendered }) : `${encode3({ envoy: rendered })}
48956
+ content: trailer === "" ? encode5({ envoy: rendered }) : `${encode5({ envoy: rendered })}
47208
48957
 
47209
48958
  ${trailer}`,
47210
48959
  envelope,
@@ -47255,7 +49004,7 @@ async function localPicture(path, cwd) {
47255
49004
  if (type === undefined) {
47256
49005
  return `images: ${path} is not ${PICTURE_TYPE_NAMES} picture (judged by its bytes, not its name)`;
47257
49006
  }
47258
- return { path, name: basename(absolute), file: Bun.file(absolute, { type }) };
49007
+ return { path, name: basename2(absolute), file: Bun.file(absolute, { type }) };
47259
49008
  }
47260
49009
  async function textWithPictures(text, pictures, owner, upload, actor) {
47261
49010
  if (pictures.length === 0)
@@ -51824,7 +53573,7 @@ async function reviewCommand(context) {
51824
53573
 
51825
53574
  // ../envoy-client/src/session-answers.ts
51826
53575
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "fs";
51827
- import { join as join5 } from "path";
53576
+ import { join as join7 } from "path";
51828
53577
  var SESSION_ANSWERS_WINDOW_MS = 72 * 3600000;
51829
53578
  var SESSION_ANSWERS_MAX_CHARS = 8000;
51830
53579
  var SESSION_ANSWERS_DEADLINE_MS = 800;
@@ -51945,7 +53694,7 @@ processGlobal2[STATE_KEY] = state;
51945
53694
  var CACHE_FILE = "answers.json";
51946
53695
  function readCacheFile(directory, url) {
51947
53696
  try {
51948
- const value = JSON.parse(readFileSync4(join5(directory, CACHE_FILE), "utf-8"));
53697
+ const value = JSON.parse(readFileSync4(join7(directory, CACHE_FILE), "utf-8"));
51949
53698
  if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
51950
53699
  return {
51951
53700
  dispatch_url: value.dispatch_url,
@@ -52059,7 +53808,7 @@ async function readSessionAnswers(options) {
52059
53808
  if (directory !== undefined) {
52060
53809
  try {
52061
53810
  mkdirSync2(directory, { recursive: true, mode: 448 });
52062
- writeAtomically(join5(directory, CACHE_FILE), JSON.stringify(cache));
53811
+ writeAtomically(join7(directory, CACHE_FILE), JSON.stringify(cache));
52063
53812
  } catch {}
52064
53813
  }
52065
53814
  return { cache };
@@ -52434,7 +54183,7 @@ function stringList(value) {
52434
54183
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
52435
54184
  }
52436
54185
  function loadSessionMemory(dir, sessionId) {
52437
- const path = join6(dir, "state.json");
54186
+ const path = join8(dir, "state.json");
52438
54187
  const text = readIfPresent(path);
52439
54188
  if (text === undefined)
52440
54189
  return new Set;
@@ -52458,7 +54207,7 @@ function writeMemory(dir, sessionId, follows) {
52458
54207
  pictures: [...shownPictures(sessionId)],
52459
54208
  follows: [...follows]
52460
54209
  };
52461
- writeAtomically(join6(dir, "state.json"), `${JSON.stringify(state)}
54210
+ writeAtomically(join8(dir, "state.json"), `${JSON.stringify(state)}
52462
54211
  `);
52463
54212
  }
52464
54213
  function appendResult(dir, entry) {
@@ -52467,7 +54216,7 @@ function appendResult(dir, entry) {
52467
54216
  }
52468
54217
  function writeResult(dir, entry) {
52469
54218
  const line = { at: new Date().toISOString(), ...entry };
52470
- appendFileSync(join6(dir, "results.jsonl"), `${JSON.stringify(line)}
54219
+ appendFileSync(join8(dir, "results.jsonl"), `${JSON.stringify(line)}
52471
54220
  `, { mode: PRIVATE_FILE2 });
52472
54221
  }
52473
54222
  function recordOutcome(dir, sessionId, follows, entry) {
@@ -52478,8 +54227,8 @@ function recordOutcome(dir, sessionId, follows, entry) {
52478
54227
  function writePicture(dir, image) {
52479
54228
  const bytes = Buffer.from(image.data, "base64");
52480
54229
  const name = createHash3("sha256").update(bytes).digest("hex").slice(0, 16);
52481
- const pictures = join6(dir, "pictures");
52482
- const path = join6(pictures, `${name}.${PICTURE_EXTENSIONS[image.mimeType]}`);
54230
+ const pictures = join8(dir, "pictures");
54231
+ const path = join8(pictures, `${name}.${PICTURE_EXTENSIONS[image.mimeType]}`);
52483
54232
  ensureDirectory(pictures);
52484
54233
  try {
52485
54234
  writeFileSync3(path, bytes, { mode: PRIVATE_FILE2, flag: "wx" });
@@ -52490,21 +54239,21 @@ function writePicture(dir, image) {
52490
54239
  return { path, bytes: bytes.length };
52491
54240
  }
52492
54241
  function writeLongOutput(dir, text) {
52493
- const out = join6(dir, "out");
54242
+ const out = join8(dir, "out");
52494
54243
  ensureDirectory(out);
52495
- const path = join6(out, `${new Date().toISOString().replaceAll(":", "-")}-${process.pid}.md`);
54244
+ const path = join8(out, `${new Date().toISOString().replaceAll(":", "-")}-${process.pid}.md`);
52496
54245
  writeFileSync3(path, text, { mode: PRIVATE_FILE2 });
52497
54246
  return path;
52498
54247
  }
52499
54248
  function writeSessionTitle(dir, title) {
52500
54249
  ensureDirectory(dir);
52501
- writeAtomically(join6(dir, "title"), title);
54250
+ writeAtomically(join8(dir, "title"), title);
52502
54251
  }
52503
54252
  function readSessionTitle(dir) {
52504
- return readIfPresent(join6(dir, "title")) || undefined;
54253
+ return readIfPresent(join8(dir, "title")) || undefined;
52505
54254
  }
52506
54255
  function pruneSessions(root, now) {
52507
- const stamp = join6(root, PRUNED_STAMP);
54256
+ const stamp = join8(root, PRUNED_STAMP);
52508
54257
  try {
52509
54258
  if (now - statSync3(stamp).mtimeMs < PRUNE_INTERVAL_MS)
52510
54259
  return;
@@ -52512,7 +54261,7 @@ function pruneSessions(root, now) {
52512
54261
  if (!hasErrnoCode(error, "ENOENT"))
52513
54262
  throw error;
52514
54263
  }
52515
- const sessions = join6(root, "sessions");
54264
+ const sessions = join8(root, "sessions");
52516
54265
  let entries = [];
52517
54266
  try {
52518
54267
  entries = readdirSync2(sessions, { withFileTypes: true });
@@ -52523,7 +54272,7 @@ function pruneSessions(root, now) {
52523
54272
  for (const entry of entries) {
52524
54273
  if (!entry.isDirectory())
52525
54274
  continue;
52526
- const dir = join6(sessions, entry.name);
54275
+ const dir = join8(sessions, entry.name);
52527
54276
  try {
52528
54277
  const idle = now - statSync3(dir).mtimeMs > IDLE_SESSION_MS;
52529
54278
  if (idle && askgateState(dir, now).kind === "off" && !recordNamesStore(dir)) {
@@ -53007,7 +54756,7 @@ function natsCredential(env, section, namedNatsUrls, filePath, session) {
53007
54756
  throw new NoSessionNamedError(auth.source);
53008
54757
  return { kind: "broker", broker: brokerNatsCredential(env, session, auth.source) };
53009
54758
  }
53010
- var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
54759
+ var LOOPBACK_HOST2 = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
53011
54760
  function natsConflictText(source, natsSetting) {
53012
54761
  return `${source} is listener, and ${natsSetting} names NATS servers: set one of the two`;
53013
54762
  }
@@ -53032,7 +54781,7 @@ function listenerInbound(source, natsSetting, credential, session) {
53032
54781
  }
53033
54782
  function plainHttpOffMachine(url) {
53034
54783
  const host = URL.canParse(url) ? new URL(url) : undefined;
53035
- return host?.protocol === "http:" && !LOOPBACK_HOST.test(host.hostname) ? host.hostname : undefined;
54784
+ return host?.protocol === "http:" && !LOOPBACK_HOST2.test(host.hostname) ? host.hostname : undefined;
53036
54785
  }
53037
54786
  function envoySettings(env, config, options = {}) {
53038
54787
  if (config.kind === "failed")
@@ -56337,7 +58086,7 @@ function failureNoticeFields(notice) {
56337
58086
  };
56338
58087
  }
56339
58088
  function envoyNoticeText(fields) {
56340
- return encode3({ envoy: fields });
58089
+ return encode5({ envoy: fields });
56341
58090
  }
56342
58091
  async function closeReplayedRemoval(frame, host) {
56343
58092
  const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.relay?.followedBefore(topic, frame.storedAtMs) !== false && host.close(topic));
@@ -56435,7 +58184,7 @@ var RelayHeader = {
56435
58184
  var RELAY_PROGRESS_INTERVAL_MS = 20000;
56436
58185
  var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
56437
58186
  var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
56438
- var decoder3 = new TextDecoder;
58187
+ var decoder4 = new TextDecoder;
56439
58188
  var DECIMAL = /^[0-9]+$/;
56440
58189
  var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
56441
58190
  function positiveInteger(text) {
@@ -56484,7 +58233,7 @@ function decodeRelayFrame(message) {
56484
58233
  storedAt,
56485
58234
  storedAtMs,
56486
58235
  gap: headers.get(RelayHeader.gap) === "true",
56487
- data: typeof message.data === "string" ? message.data : decoder3.decode(message.data),
58236
+ data: typeof message.data === "string" ? message.data : decoder4.decode(message.data),
56488
58237
  reply
56489
58238
  }
56490
58239
  };
@@ -57941,7 +59690,7 @@ function claudeProjectDirectory(environment, fallback) {
57941
59690
 
57942
59691
  // src/envoy-channel-server.ts
57943
59692
  import { unwatchFile, watchFile } from "fs";
57944
- import { rm as rm2 } from "fs/promises";
59693
+ import { rm as rm4 } from "fs/promises";
57945
59694
  import { setImmediate as nextTurn } from "timers/promises";
57946
59695
 
57947
59696
  // ../envoy-client/src/relay-registration.ts
@@ -58497,7 +60246,7 @@ import { execFile as execFile2 } from "child_process";
58497
60246
  import { promisify as promisify2 } from "util";
58498
60247
 
58499
60248
  // ../pi-shared/src/git-lock.ts
58500
- import { lstat } from "fs/promises";
60249
+ import { lstat as lstat3 } from "fs/promises";
58501
60250
  var GIT_LOCK_REPORTS = [
58502
60251
  /The lockfile at '([^']+)' might need manual deletion/g,
58503
60252
  /Unable to create '([^']+)': File exists/g
@@ -58522,7 +60271,7 @@ async function staleGitLockNote(output, now = Date.now()) {
58522
60271
  }
58523
60272
  const notes = [];
58524
60273
  for (const lock of locks) {
58525
- const written = await lstat(lock).then((info) => info.mtimeMs, () => {
60274
+ const written = await lstat3(lock).then((info) => info.mtimeMs, () => {
58526
60275
  return;
58527
60276
  });
58528
60277
  if (written === undefined)
@@ -58683,7 +60432,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
58683
60432
 
58684
60433
  // package.json
58685
60434
  var name2 = "@sjawhar/claude-envoy";
58686
- var version2 = "5.0.0";
60435
+ var version2 = "5.1.0";
58687
60436
  var legion = {
58688
60437
  daemonApiVersion: 205
58689
60438
  };
@@ -58737,10 +60486,10 @@ var package_default = {
58737
60486
  };
58738
60487
 
58739
60488
  // ../pi-shared/src/agent-stream.ts
58740
- var encoder3 = new TextEncoder;
60489
+ var encoder4 = new TextEncoder;
58741
60490
  var REPLAY_ARRAY_BYTES = 2;
58742
60491
  function jsonBytes(value) {
58743
- return encoder3.encode(JSON.stringify(value)).length;
60492
+ return encoder4.encode(JSON.stringify(value)).length;
58744
60493
  }
58745
60494
  var SEQ_PER_MS = 1000;
58746
60495
  function modelReference(provider, id) {
@@ -59424,8 +61173,8 @@ function rememberBoundedEntry(remembered, key, value, max) {
59424
61173
  }
59425
61174
 
59426
61175
  // src/control-subscription.ts
59427
- var encoder4 = new TextEncoder;
59428
- var decoder4 = new TextDecoder;
61176
+ var encoder5 = new TextEncoder;
61177
+ var decoder5 = new TextDecoder;
59429
61178
  var RESUBSCRIBE_MS = 1000;
59430
61179
  function controlSubscription(options) {
59431
61180
  let connection = options.connection;
@@ -59435,7 +61184,7 @@ function controlSubscription(options) {
59435
61184
  try {
59436
61185
  for await (const message of taken) {
59437
61186
  try {
59438
- const parsed = JSON.parse(decoder4.decode(message.data));
61187
+ const parsed = JSON.parse(decoder5.decode(message.data));
59439
61188
  if (typeof parsed !== "object" || parsed === null)
59440
61189
  continue;
59441
61190
  const request = parsed;
@@ -59445,7 +61194,7 @@ function controlSubscription(options) {
59445
61194
  const answer = options.answer(request, reply !== undefined, forSession);
59446
61195
  if (answer === undefined || reply === undefined)
59447
61196
  continue;
59448
- connection.publish(reply, encoder4.encode(answer));
61197
+ connection.publish(reply, encoder5.encode(answer));
59449
61198
  } catch (error) {
59450
61199
  options.warn(`a live view control message failed \u2014 ${messageFor(error)}`);
59451
61200
  }
@@ -59488,7 +61237,7 @@ function controlSubscription(options) {
59488
61237
  },
59489
61238
  publish(subject, payload) {
59490
61239
  if (!stopped && !connection.isClosed())
59491
- connection.publish(subject, encoder4.encode(payload));
61240
+ connection.publish(subject, encoder5.encode(payload));
59492
61241
  },
59493
61242
  start() {
59494
61243
  subscribeWhenAdmitted(options.session());
@@ -59743,53 +61492,53 @@ function createChannelTopics(connection, options = {}) {
59743
61492
  }
59744
61493
 
59745
61494
  // src/session-identity.ts
59746
- import { readFile as readFile3 } from "fs/promises";
59747
- import { basename as basename2, join as join8 } from "path";
61495
+ import { readFile as readFile4 } from "fs/promises";
61496
+ import { basename as basename3, join as join10 } from "path";
59748
61497
 
59749
61498
  // src/session-state.ts
59750
61499
  import { readFileSync as readFileSync6 } from "fs";
59751
- import { mkdir, readdir as readdir2, rename, rm, stat, utimes, writeFile } from "fs/promises";
59752
- import { dirname as dirname2, join as join7 } from "path";
61500
+ import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm3, stat as stat3, utimes as utimes2, writeFile } from "fs/promises";
61501
+ import { dirname as dirname4, join as join9 } from "path";
59753
61502
  async function writeAtomicStateFile(file, contents) {
59754
- await mkdir(dirname2(file), { recursive: true, mode: 448 });
61503
+ await mkdir2(dirname4(file), { recursive: true, mode: 448 });
59755
61504
  const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
59756
61505
  await writeFile(temporary, contents, { mode: 384 });
59757
- await rename(temporary, file);
61506
+ await rename3(temporary, file);
59758
61507
  }
59759
61508
  async function touchStateFile(file) {
59760
61509
  const now = new Date;
59761
- await utimes(file, now, now);
61510
+ await utimes2(file, now, now);
59762
61511
  }
59763
61512
  async function pruneStateDirectory(directory, isStale) {
59764
- const entries = await readdir2(directory).catch((error) => {
61513
+ const entries = await readdir3(directory).catch((error) => {
59765
61514
  if (hasErrnoCode(error, "ENOENT"))
59766
61515
  return [];
59767
61516
  throw error;
59768
61517
  });
59769
61518
  for (const entry of entries) {
59770
- const file = join7(directory, entry);
61519
+ const file = join9(directory, entry);
59771
61520
  if (!await isStale(file))
59772
61521
  continue;
59773
- await rm(file, { recursive: true, force: true });
61522
+ await rm3(file, { recursive: true, force: true });
59774
61523
  }
59775
61524
  }
59776
61525
  var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
59777
61526
  async function writtenLongAgo(file) {
59778
- const modified = await stat(file).then((stats) => stats.mtimeMs, () => {
61527
+ const modified = await stat3(file).then((stats) => stats.mtimeMs, () => {
59779
61528
  return;
59780
61529
  });
59781
61530
  return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
59782
61531
  }
59783
61532
  var TITLES_DIRECTORY = "titles";
59784
61533
  function sessionTitleFile(stateDirectory, sessionId) {
59785
- return join7(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
61534
+ return join9(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
59786
61535
  }
59787
61536
  async function writeChosenTitle(file, title) {
59788
61537
  await writeAtomicStateFile(file, `${title}
59789
61538
  `);
59790
61539
  }
59791
61540
  async function removeChosenTitle(file) {
59792
- await rm(file, { force: true });
61541
+ await rm3(file, { force: true });
59793
61542
  }
59794
61543
  function readChosenTitleSync(file) {
59795
61544
  try {
@@ -59810,7 +61559,7 @@ async function recordChosenTitle(sessionId, title) {
59810
61559
  await writeChosenTitle(file, chosen);
59811
61560
  }
59812
61561
  async function pruneStaleSessionTitles(stateDirectory) {
59813
- await pruneStateDirectory(join7(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
61562
+ await pruneStateDirectory(join9(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
59814
61563
  }
59815
61564
 
59816
61565
  // src/session-identity.ts
@@ -59835,14 +61584,14 @@ class SessionIdentity {
59835
61584
  }
59836
61585
  }
59837
61586
  function sessionHandoffDirectory(stateDirectory, claudePid) {
59838
- return join8(stateDirectory, "sessions", String(claudePid));
61587
+ return join10(stateDirectory, "sessions", String(claudePid));
59839
61588
  }
59840
61589
  function sessionHandoffFile(stateDirectory, claudePid) {
59841
- return join8(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
61590
+ return join10(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
59842
61591
  }
59843
61592
  var ROLES_DIRECTORY = "roles";
59844
61593
  function roleStateFile(stateDirectory, sessionId) {
59845
- return join8(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
61594
+ return join10(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
59846
61595
  }
59847
61596
 
59848
61597
  class UnparseableRoleRecordError extends Error {
@@ -59854,7 +61603,7 @@ class UnparseableRoleRecordError extends Error {
59854
61603
  async function readPersistedRole(roleFile) {
59855
61604
  let bytes;
59856
61605
  try {
59857
- bytes = await readFile3(roleFile, "utf8");
61606
+ bytes = await readFile4(roleFile, "utf8");
59858
61607
  } catch (error) {
59859
61608
  if (hasErrnoCode(error, "ENOENT"))
59860
61609
  return;
@@ -59876,7 +61625,7 @@ async function writeSessionHandoff(file, sessionId) {
59876
61625
  }
59877
61626
  async function readSessionHandoff(file) {
59878
61627
  try {
59879
- const id = (await readFile3(file, "utf8")).trim();
61628
+ const id = (await readFile4(file, "utf8")).trim();
59880
61629
  return id.length === 0 ? undefined : id;
59881
61630
  } catch (error) {
59882
61631
  if (hasErrnoCode(error, "ENOENT"))
@@ -59893,14 +61642,14 @@ function processExists(pid) {
59893
61642
  }
59894
61643
  }
59895
61644
  async function pruneStaleSessionHandoffs(stateDirectory) {
59896
- await pruneStateDirectory(join8(stateDirectory, "sessions"), (file) => {
59897
- const pid = basename2(file);
61645
+ await pruneStateDirectory(join10(stateDirectory, "sessions"), (file) => {
61646
+ const pid = basename3(file);
59898
61647
  return /^\d+$/.test(pid) && !processExists(Number(pid));
59899
61648
  });
59900
61649
  }
59901
61650
  async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
59902
61651
  const own = roleStateFile(stateDirectory, currentSessionId);
59903
- await pruneStateDirectory(join8(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
61652
+ await pruneStateDirectory(join10(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
59904
61653
  }
59905
61654
 
59906
61655
  // src/envoy-off.ts
@@ -59972,8 +61721,8 @@ function installedPluginVersion(bundlePath) {
59972
61721
  }
59973
61722
 
59974
61723
  // src/legion-claim.ts
59975
- import { readdir as readdir3, stat as stat2 } from "fs/promises";
59976
- import { join as join10 } from "path";
61724
+ import { readdir as readdir4, stat as stat4 } from "fs/promises";
61725
+ import { join as join12 } from "path";
59977
61726
  import { setTimeout as delay2 } from "timers/promises";
59978
61727
 
59979
61728
  // ../pi-shared/src/stall-limits.ts
@@ -61348,12 +63097,12 @@ function listenerAskedToClaimAgain(error) {
61348
63097
  }
61349
63098
 
61350
63099
  // src/legion-phase-hook.ts
61351
- import { randomUUID as randomUUID4 } from "crypto";
63100
+ import { randomUUID as randomUUID7 } from "crypto";
61352
63101
  import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
61353
- import { dirname as dirname3, join as join9 } from "path";
63102
+ import { dirname as dirname5, join as join11 } from "path";
61354
63103
 
61355
63104
  // ../pi-shared/src/phase-reminder.ts
61356
- import { randomUUID as randomUUID3 } from "crypto";
63105
+ import { randomUUID as randomUUID6 } from "crypto";
61357
63106
 
61358
63107
  // ../pi-shared/src/phase-stall.ts
61359
63108
  var WAITING_REPLY = /^\W*WAITING\b/m;
@@ -61552,7 +63301,7 @@ function createPhaseReminder(deps) {
61552
63301
  });
61553
63302
  return;
61554
63303
  }
61555
- reportKey ??= randomUUID3();
63304
+ reportKey ??= randomUUID6();
61556
63305
  const key = reportKey;
61557
63306
  writeEntry();
61558
63307
  const phase = record?.phase ?? "unknown";
@@ -61806,7 +63555,7 @@ function phaseHookToolDefinition() {
61806
63555
  };
61807
63556
  }
61808
63557
  function phaseStallFile(configDir, sessionID) {
61809
- return join9(configDir, `legion-phase-stall-${sessionID}.json`);
63558
+ return join11(configDir, `legion-phase-stall-${sessionID}.json`);
61810
63559
  }
61811
63560
  function paneReminderLog(write) {
61812
63561
  const line = (level, message, context) => {
@@ -61859,7 +63608,7 @@ function readPhaseStallRecord(file, log) {
61859
63608
  };
61860
63609
  }
61861
63610
  function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
61862
- const temporary = join9(dirname3(file), `.legion-phase-stall-${randomUUID4()}`);
63611
+ const temporary = join11(dirname5(file), `.legion-phase-stall-${randomUUID7()}`);
61863
63612
  try {
61864
63613
  writeFileSync4(temporary, JSON.stringify({ ...entry, ...recreatedNoticeSent ? { recreatedNoticeSent } : {} }), { mode: 384 });
61865
63614
  renameSync3(temporary, file);
@@ -62067,12 +63816,12 @@ function stopPane(why) {
62067
63816
  endPane();
62068
63817
  }
62069
63818
  async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
62070
- const projects = join10(configDir, "projects");
63819
+ const projects = join12(configDir, "projects");
62071
63820
  const name = `${sessionID}.jsonl`;
62072
63821
  for (;; ) {
62073
63822
  signal.throwIfAborted();
62074
- for (const directory of await readdir3(projects).catch(() => [])) {
62075
- const file = join10(projects, directory, name);
63823
+ for (const directory of await readdir4(projects).catch(() => [])) {
63824
+ const file = join12(projects, directory, name);
62076
63825
  if (await isFile(file))
62077
63826
  return file;
62078
63827
  }
@@ -62090,7 +63839,7 @@ async function waitForSavedTranscript(transcript, signal, pollMs = 100) {
62090
63839
  }
62091
63840
  }
62092
63841
  function isFile(file) {
62093
- return stat2(file).then((info) => info.isFile(), () => false);
63842
+ return stat4(file).then((info) => info.isFile(), () => false);
62094
63843
  }
62095
63844
  var ROLE_CLAIM_RETRY_MS = 1e4;
62096
63845
  var ROLE_CLAIM_WAIT_MS = SESSION_LIVE_WINDOW_MS + ROLE_CLAIM_RETRY_MS;
@@ -62171,7 +63920,7 @@ function startLegionClaim(deps) {
62171
63920
  }
62172
63921
 
62173
63922
  // src/legion-inbox.ts
62174
- import { randomUUID as randomUUID5 } from "crypto";
63923
+ import { randomUUID as randomUUID8 } from "crypto";
62175
63924
  import { createConnection } from "net";
62176
63925
  var INBOX_VARIABLE = "LEGION_CLAUDE_INBOX";
62177
63926
  var INBOX_CAPABILITIES = [
@@ -62230,7 +63979,7 @@ function createInboxNotifier(socketPath) {
62230
63979
  };
62231
63980
  return {
62232
63981
  notification(notification) {
62233
- const id = notification.eventId ?? randomUUID5();
63982
+ const id = notification.eventId ?? randomUUID8();
62234
63983
  const settle = Promise.withResolvers();
62235
63984
  waiting.push({ id, settle });
62236
63985
  connected().write(`${JSON.stringify({
@@ -62643,13 +64392,13 @@ async function executeLegionTool(runtime, input, signal) {
62643
64392
  }
62644
64393
 
62645
64394
  // src/mod-link.ts
62646
- import { randomUUID as randomUUID6 } from "crypto";
62647
- import { chmod, lstat as lstat2, mkdir as mkdir2, stat as stat3, unlink } from "fs/promises";
64395
+ import { randomUUID as randomUUID9 } from "crypto";
64396
+ import { chmod, lstat as lstat4, mkdir as mkdir3, stat as stat5, unlink } from "fs/promises";
62648
64397
  import {
62649
64398
  createServer,
62650
64399
  request as httpRequest
62651
64400
  } from "http";
62652
- import { dirname as dirname4 } from "path";
64401
+ import { dirname as dirname6 } from "path";
62653
64402
 
62654
64403
  // hooks/mod-protocol.ts
62655
64404
  var MOD_HEALTH_MARKER = "claude-envoy-mod";
@@ -62850,15 +64599,15 @@ function createEventStream(limit) {
62850
64599
  }
62851
64600
  async function exists(path) {
62852
64601
  try {
62853
- await stat3(path);
64602
+ await stat5(path);
62854
64603
  return true;
62855
64604
  } catch {
62856
64605
  return false;
62857
64606
  }
62858
64607
  }
62859
64608
  async function privateDirectory(path) {
62860
- await mkdir2(path, { recursive: true, mode: 448 });
62861
- const directory = await lstat2(path);
64609
+ await mkdir3(path, { recursive: true, mode: 448 });
64610
+ const directory = await lstat4(path);
62862
64611
  if (!directory.isDirectory()) {
62863
64612
  throw new Error(`${path} is not a directory of its own, so the socket has no private home`);
62864
64613
  }
@@ -62871,7 +64620,7 @@ async function privateDirectory(path) {
62871
64620
  }
62872
64621
  }
62873
64622
  async function bind(server, socketPath) {
62874
- await privateDirectory(dirname4(socketPath));
64623
+ await privateDirectory(dirname6(socketPath));
62875
64624
  if (await exists(socketPath)) {
62876
64625
  if (await probeHealth(socketPath, MOD_PROBE_TIMEOUT_MS)) {
62877
64626
  throw new Error(`another claude-envoy server already serves this session at ${socketPath}`);
@@ -63077,7 +64826,7 @@ async function startModLink(options) {
63077
64826
  if (closed)
63078
64827
  return Promise.reject(new Error("the mod link is closed"));
63079
64828
  const timeoutMs = requestOptions?.timeoutMs ?? MOD_REQUEST_TIMEOUT_MS;
63080
- const id = randomUUID6();
64829
+ const id = randomUUID9();
63081
64830
  const settle = Promise.withResolvers();
63082
64831
  const request = { id, call, args };
63083
64832
  const timer = setTimeout(() => {
@@ -63262,14 +65011,14 @@ function modSession(options) {
63262
65011
  }
63263
65012
 
63264
65013
  // src/replay-state.ts
63265
- import { join as join11 } from "path";
65014
+ import { join as join13 } from "path";
63266
65015
 
63267
65016
  // src/state-file.ts
63268
- import { readFile as readFile4 } from "fs/promises";
65017
+ import { readFile as readFile5 } from "fs/promises";
63269
65018
  async function readStateFile(file, schema, empty, refusal) {
63270
65019
  let text;
63271
65020
  try {
63272
- text = await readFile4(file, "utf8");
65021
+ text = await readFile5(file, "utf8");
63273
65022
  } catch (error) {
63274
65023
  if (hasErrnoCode(error, "ENOENT"))
63275
65024
  return empty;
@@ -63292,7 +65041,7 @@ var ReplayStateFileSchema = LedgerSnapshotSchema.extend({
63292
65041
  consumer: ConsumerDeliverySnapshotSchema.optional()
63293
65042
  });
63294
65043
  function replayStateFile(stateDirectory, sessionId) {
63295
- return join11(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
65044
+ return join13(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
63296
65045
  }
63297
65046
  async function readReplayState(file) {
63298
65047
  return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no delivery state");
@@ -63320,7 +65069,7 @@ function replayStateWriter(file, restored) {
63320
65069
  }
63321
65070
 
63322
65071
  // src/session-title.ts
63323
- import { basename as basename3 } from "path";
65072
+ import { basename as basename4 } from "path";
63324
65073
 
63325
65074
  // ../envoy-client/src/process-ancestry.ts
63326
65075
  import { execFileSync } from "child_process";
@@ -63479,7 +65228,7 @@ async function sessionTitle(environment, directory, sources = {}) {
63479
65228
  return () => explicit;
63480
65229
  const { serverPid, socket } = tmuxServer(configuredValue(environment.TMUX));
63481
65230
  const pane = configuredValue(environment.TMUX_PANE)?.trim();
63482
- const directoryName = oneLine(basename3(directory) || directory);
65231
+ const directoryName = oneLine(basename4(directory) || directory);
63483
65232
  const name = (socket === "" || serverPid === "" || pane === undefined ? undefined : await tmuxPaneTitle(socket, serverPid, pane, ownPane, query)) ?? (visible(directoryName) ? directoryName : "session");
63484
65233
  return (sessionId) => {
63485
65234
  const own = oneLine(chosen(sessionId) ?? "");
@@ -63807,7 +65556,7 @@ function createUserTurnRouter(options) {
63807
65556
  }
63808
65557
 
63809
65558
  // src/user-turn-state.ts
63810
- import { join as join12 } from "path";
65559
+ import { join as join14 } from "path";
63811
65560
  var TURNS_DIRECTORY = "turns";
63812
65561
  var HANDLED_ATTEMPTS_MAX = 1000;
63813
65562
  var DELIVERED_ROWS_MAX = 1000;
@@ -63817,7 +65566,7 @@ var UserTurnStateSchema = object({
63817
65566
  rows: array(DeliveredRowSchema).default([])
63818
65567
  });
63819
65568
  function userTurnStateFile(stateDirectory, sessionId) {
63820
- return join12(stateDirectory, TURNS_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
65569
+ return join14(stateDirectory, TURNS_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
63821
65570
  }
63822
65571
  async function readUserTurnState(file) {
63823
65572
  return await readStateFile(file, UserTurnStateSchema, { handled: [], rows: [] }, "holds no record of this session's turns");
@@ -63855,13 +65604,13 @@ function userTurnState(file, restored) {
63855
65604
  };
63856
65605
  }
63857
65606
  async function pruneStaleSessionTurns(stateDirectory) {
63858
- await pruneStateDirectory(join12(stateDirectory, TURNS_DIRECTORY), writtenLongAgo);
65607
+ await pruneStateDirectory(join14(stateDirectory, TURNS_DIRECTORY), writtenLongAgo);
63859
65608
  }
63860
65609
 
63861
65610
  // src/envoy-channel-server.ts
63862
65611
  var CHANNEL_INSTRUCTIONS = "Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch.";
63863
65612
  var CHANNEL_INBOX_LIMIT = 50;
63864
- var encoder5 = new TextEncoder;
65613
+ var encoder6 = new TextEncoder;
63865
65614
  var HANDOFF_POLL_MS = 250;
63866
65615
  var HANDOFF_FLUSH_TIMEOUT_MS = 1e4;
63867
65616
  async function withTimeout(promise, ms, what) {
@@ -64244,7 +65993,7 @@ async function startChannelSession(options) {
64244
65993
  `);
64245
65994
  }
64246
65995
  },
64247
- publish: (reply, body) => connection.publish(reply, encoder5.encode(body)),
65996
+ publish: (reply, body) => connection.publish(reply, encoder6.encode(body)),
64248
65997
  persist: (snapshot) => {
64249
65998
  if (relay !== owner)
64250
65999
  return false;
@@ -64501,13 +66250,13 @@ async function startChannelSession(options) {
64501
66250
  if (claim.holder === identity.id)
64502
66251
  return "pending";
64503
66252
  if (claim.holder !== persisted.session_id)
64504
- await rm2(previousFile, { force: true });
66253
+ await rm4(previousFile, { force: true });
64505
66254
  return "settled";
64506
66255
  }
64507
66256
  heldRole = persisted.role;
64508
66257
  const currentFile = roleStateFile(options.stateDirectory, identity.id);
64509
66258
  if (previousFile !== currentFile)
64510
- await rm2(previousFile, { force: true });
66259
+ await rm4(previousFile, { force: true });
64511
66260
  await writeRoleRecord(currentFile, persisted.role);
64512
66261
  return "settled";
64513
66262
  };
@@ -64555,7 +66304,7 @@ async function startChannelSession(options) {
64555
66304
  if (!result.claimed) {
64556
66305
  if (result.holder !== identity.id) {
64557
66306
  heldRole = undefined;
64558
- await rm2(roleStateFile(options.stateDirectory, identity.id), { force: true });
66307
+ await rm4(roleStateFile(options.stateDirectory, identity.id), { force: true });
64559
66308
  return;
64560
66309
  }
64561
66310
  await refreshRoleRecord();
@@ -65575,7 +67324,7 @@ function startCodexAgentStream(options) {
65575
67324
  import { spawn } from "child_process";
65576
67325
  import { randomBytes as randomBytes2 } from "crypto";
65577
67326
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
65578
- import { join as join13 } from "path";
67327
+ import { join as join15 } from "path";
65579
67328
  var QUEUE_TIMEOUT_MS = 30000;
65580
67329
  function codexProcessEnv(pid, fallback, read = (path) => readFileSync9(path, "utf8")) {
65581
67330
  let raw;
@@ -65644,7 +67393,7 @@ function fitArgument(text, spillDirectory) {
65644
67393
  throw new Error(`the message is ${Buffer.byteLength(text)} bytes, over what codex queue takes`);
65645
67394
  }
65646
67395
  mkdirSync4(spillDirectory, { mode: 448, recursive: true });
65647
- const file = join13(spillDirectory, `${Date.now()}-${randomBytes2(4).toString("hex")}.txt`);
67396
+ const file = join15(spillDirectory, `${Date.now()}-${randomBytes2(4).toString("hex")}.txt`);
65648
67397
  writeFileSync5(file, text, { mode: 384 });
65649
67398
  return `${text.slice(0, QUEUE_HEAD_CHARS)}
65650
67399
 
@@ -65769,11 +67518,11 @@ function askSideQuestion(command, threadId, question, timeoutMs = SIDE_QUESTION_
65769
67518
 
65770
67519
  // src/codex/codex-inbox.ts
65771
67520
  import { randomBytes as randomBytes3 } from "crypto";
65772
- import { mkdir as mkdir3, readdir as readdir4, readFile as readFile5, rename as rename2, rm as rm3, writeFile as writeFile2 } from "fs/promises";
65773
- import { join as join14 } from "path";
67521
+ import { mkdir as mkdir4, readdir as readdir5, readFile as readFile6, rename as rename4, rm as rm5, writeFile as writeFile2 } from "fs/promises";
67522
+ import { join as join16 } from "path";
65774
67523
  var TAKEN_DIRECTORY = { hook: "taken", server: "queued" };
65775
67524
  function codexInboxDirectory(stateDirectory, sessionId) {
65776
- return join14(stateDirectory, "codex-inbox", encodeURIComponent(sessionId));
67525
+ return join16(stateDirectory, "codex-inbox", encodeURIComponent(sessionId));
65777
67526
  }
65778
67527
  var lastOrder = 0;
65779
67528
  function inboxItemName() {
@@ -65782,17 +67531,17 @@ function inboxItemName() {
65782
67531
  return `${String(order).padStart(15, "0")}-${randomBytes3(4).toString("hex")}.json`;
65783
67532
  }
65784
67533
  async function putInbox(directory, item, name = inboxItemName()) {
65785
- const waiting = join14(directory, "waiting");
65786
- await mkdir3(waiting, { recursive: true, mode: 448 });
65787
- const temporary = join14(directory, `.${name}.tmp`);
67534
+ const waiting = join16(directory, "waiting");
67535
+ await mkdir4(waiting, { recursive: true, mode: 448 });
67536
+ const temporary = join16(directory, `.${name}.tmp`);
65788
67537
  await writeFile2(temporary, JSON.stringify(item), { mode: 384 });
65789
- await rename2(temporary, join14(waiting, name));
67538
+ await rename4(temporary, join16(waiting, name));
65790
67539
  return name;
65791
67540
  }
65792
67541
  async function takenBy(directory, name) {
65793
67542
  for (const taker of ["hook", "server"]) {
65794
67543
  try {
65795
- await readFile5(join14(directory, TAKEN_DIRECTORY[taker], name));
67544
+ await readFile6(join16(directory, TAKEN_DIRECTORY[taker], name));
65796
67545
  return taker;
65797
67546
  } catch {}
65798
67547
  }
@@ -65800,17 +67549,17 @@ async function takenBy(directory, name) {
65800
67549
  }
65801
67550
  async function withdrawWaiting(directory, name) {
65802
67551
  try {
65803
- await rm3(join14(directory, "waiting", name));
67552
+ await rm5(join16(directory, "waiting", name));
65804
67553
  return true;
65805
67554
  } catch {
65806
67555
  return false;
65807
67556
  }
65808
67557
  }
65809
67558
  async function discardWaiting(directory, keep = () => false) {
65810
- const waiting = join14(directory, "waiting");
67559
+ const waiting = join16(directory, "waiting");
65811
67560
  let names;
65812
67561
  try {
65813
- names = await readdir4(waiting);
67562
+ names = await readdir5(waiting);
65814
67563
  } catch {
65815
67564
  return 0;
65816
67565
  }
@@ -65819,7 +67568,7 @@ async function discardWaiting(directory, keep = () => false) {
65819
67568
  if (!name.endsWith(".json") || keep(name))
65820
67569
  continue;
65821
67570
  try {
65822
- await rm3(join14(waiting, name));
67571
+ await rm5(join16(waiting, name));
65823
67572
  removed++;
65824
67573
  } catch {}
65825
67574
  }
@@ -65827,23 +67576,23 @@ async function discardWaiting(directory, keep = () => false) {
65827
67576
  }
65828
67577
  var HOOK_CONTEXT_MAX_BYTES = 8000;
65829
67578
  async function takeInbox(directory, taker, maxContextBytes) {
65830
- const waiting = join14(directory, "waiting");
67579
+ const waiting = join16(directory, "waiting");
65831
67580
  let names;
65832
67581
  try {
65833
- names = (await readdir4(waiting)).filter((name) => name.endsWith(".json")).sort();
67582
+ names = (await readdir5(waiting)).filter((name) => name.endsWith(".json")).sort();
65834
67583
  } catch {
65835
67584
  return [];
65836
67585
  }
65837
67586
  if (names.length === 0)
65838
67587
  return [];
65839
- const destination = join14(directory, TAKEN_DIRECTORY[taker]);
65840
- await mkdir3(destination, { recursive: true, mode: 448 });
67588
+ const destination = join16(directory, TAKEN_DIRECTORY[taker]);
67589
+ await mkdir4(destination, { recursive: true, mode: 448 });
65841
67590
  const taken = [];
65842
67591
  for (const name of names) {
65843
67592
  if (maxContextBytes !== undefined) {
65844
67593
  let waitingItem;
65845
67594
  try {
65846
- waitingItem = JSON.parse(await readFile5(join14(waiting, name), "utf8"));
67595
+ waitingItem = JSON.parse(await readFile6(join16(waiting, name), "utf8"));
65847
67596
  } catch {
65848
67597
  continue;
65849
67598
  }
@@ -65854,12 +67603,12 @@ async function takeInbox(directory, taker, maxContextBytes) {
65854
67603
  break;
65855
67604
  }
65856
67605
  try {
65857
- await rename2(join14(waiting, name), join14(destination, name));
67606
+ await rename4(join16(waiting, name), join16(destination, name));
65858
67607
  } catch {
65859
67608
  continue;
65860
67609
  }
65861
67610
  try {
65862
- const parsed = JSON.parse(await readFile5(join14(destination, name), "utf8"));
67611
+ const parsed = JSON.parse(await readFile6(join16(destination, name), "utf8"));
65863
67612
  if (typeof parsed === "object" && parsed !== null && typeof parsed.content === "string") {
65864
67613
  taken.push({ item: parsed, name });
65865
67614
  }
@@ -66016,15 +67765,15 @@ function createCodexDelivery(options) {
66016
67765
  }
66017
67766
 
66018
67767
  // src/codex/codex-owner.ts
66019
- import { link, mkdir as mkdir5, readdir as readdir5, readFile as readFile7, rm as rm4, stat as stat4, writeFile as writeFile4 } from "fs/promises";
66020
- import { join as join16 } from "path";
67768
+ import { link as link2, mkdir as mkdir6, readdir as readdir6, readFile as readFile8, rm as rm6, stat as stat6, writeFile as writeFile4 } from "fs/promises";
67769
+ import { join as join18 } from "path";
66021
67770
 
66022
67771
  // src/codex/codex-session-record.ts
66023
67772
  import { spawnSync } from "child_process";
66024
67773
  import { readFileSync as readFileSync10, readlinkSync as readlinkSync3, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
66025
- import { mkdir as mkdir4, readFile as readFile6, rename as rename3, utimes as utimes2, writeFile as writeFile3 } from "fs/promises";
67774
+ import { mkdir as mkdir5, readFile as readFile7, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
66026
67775
  import { homedir as homedir3 } from "os";
66027
- import { basename as basename4, dirname as dirname5, join as join15 } from "path";
67776
+ import { basename as basename5, dirname as dirname7, join as join17 } from "path";
66028
67777
  var CodexSessionRecord = object({
66029
67778
  session_id: string2().min(1),
66030
67779
  transcript_path: string2().nullable(),
@@ -66035,17 +67784,17 @@ var CodexSessionRecord = object({
66035
67784
  codex_started: string2().nullable().default(null)
66036
67785
  });
66037
67786
  function codexSessionRecordFile(stateDirectory, pid) {
66038
- return join15(stateDirectory, "codex-sessions", `${pid}.json`);
67787
+ return join17(stateDirectory, "codex-sessions", `${pid}.json`);
66039
67788
  }
66040
67789
  function codexEndedFile(stateDirectory, pid, sessionId) {
66041
- return join15(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
67790
+ return join17(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
66042
67791
  }
66043
67792
  async function markSessionEnded(stateDirectory, pid, sessionId) {
66044
67793
  const marker = codexEndedFile(stateDirectory, pid, sessionId);
66045
- await mkdir4(dirname5(marker), { mode: 448, recursive: true });
67794
+ await mkdir5(dirname7(marker), { mode: 448, recursive: true });
66046
67795
  await writeFile3(marker, "", { mode: 384 });
66047
67796
  const now = new Date;
66048
- await utimes2(codexSessionRecordFile(stateDirectory, pid), now, now);
67797
+ await utimes3(codexSessionRecordFile(stateDirectory, pid), now, now);
66049
67798
  }
66050
67799
  function watchRecord(file, pid, ended, changed, intervalMs) {
66051
67800
  const look = () => {
@@ -66061,21 +67810,21 @@ function watchRecord(file, pid, ended, changed, intervalMs) {
66061
67810
  }
66062
67811
  async function sessionEnded(file) {
66063
67812
  try {
66064
- await readFile6(file);
67813
+ await readFile7(file);
66065
67814
  return true;
66066
67815
  } catch {
66067
67816
  return false;
66068
67817
  }
66069
67818
  }
66070
67819
  async function writeCodexSessionRecord(file, value) {
66071
- await mkdir4(dirname5(file), { recursive: true, mode: 448 });
67820
+ await mkdir5(dirname7(file), { recursive: true, mode: 448 });
66072
67821
  const temporary = `${file}.${process.pid}.tmp`;
66073
67822
  await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
66074
- await rename3(temporary, file);
67823
+ await rename5(temporary, file);
66075
67824
  }
66076
67825
  async function readCodexSessionRecord(file) {
66077
67826
  try {
66078
- const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile6(file, "utf8")));
67827
+ const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile7(file, "utf8")));
66079
67828
  return parsed.success ? parsed.data : undefined;
66080
67829
  } catch {
66081
67830
  return;
@@ -66083,17 +67832,17 @@ async function readCodexSessionRecord(file) {
66083
67832
  }
66084
67833
  function codexHome(env) {
66085
67834
  const set = env["CODEX_HOME"];
66086
- return set !== undefined && set !== "" ? set : join15(env["HOME"] || homedir3(), ".codex");
67835
+ return set !== undefined && set !== "" ? set : join17(env["HOME"] || homedir3(), ".codex");
66087
67836
  }
66088
67837
  function codexPluginDataDirectory(pluginRoot) {
66089
67838
  const version = pluginRoot;
66090
- const plugin = dirname5(version);
66091
- const marketplace = dirname5(plugin);
66092
- const cache = dirname5(marketplace);
66093
- const plugins = dirname5(cache);
66094
- if (basename4(cache) !== "cache" || basename4(plugins) !== "plugins")
67839
+ const plugin = dirname7(version);
67840
+ const marketplace = dirname7(plugin);
67841
+ const cache = dirname7(marketplace);
67842
+ const plugins = dirname7(cache);
67843
+ if (basename5(cache) !== "cache" || basename5(plugins) !== "plugins")
66095
67844
  return;
66096
- return join15(plugins, "data", `${basename4(plugin)}-${basename4(marketplace)}`);
67845
+ return join17(plugins, "data", `${basename5(plugin)}-${basename5(marketplace)}`);
66097
67846
  }
66098
67847
  var MAX_ANCESTORS2 = 16;
66099
67848
  function codexProcessId(readComm = procComm, readParent = procParent) {
@@ -66189,12 +67938,12 @@ function codexSubcommand(args) {
66189
67938
  }
66190
67939
  var SHARED_APP_SERVER_NOTE = "Codex runs this session in its shared app server (`codex app-server`), which runs several sessions in one process, so the Envoy plugin does not register it with Envoy: it receives no Envoy messages and does not show on Dispatch's Agents page. Its `dispatch` tool works, acting as this session.";
66191
67940
  async function pruneCodexSessionRecords(stateDirectory) {
66192
- await pruneStateDirectory(join15(stateDirectory, "codex-sessions"), (file) => {
66193
- const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename4(file));
67941
+ await pruneStateDirectory(join17(stateDirectory, "codex-sessions"), (file) => {
67942
+ const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename5(file));
66194
67943
  return match !== null && !processExists(Number(match[1]));
66195
67944
  });
66196
- await pruneStateDirectory(join15(stateDirectory, "codex-servers"), (file) => {
66197
- const name = basename4(file);
67945
+ await pruneStateDirectory(join17(stateDirectory, "codex-servers"), (file) => {
67946
+ const name = basename5(file);
66198
67947
  return /^\d+$/.test(name) && !processExists(Number(name));
66199
67948
  });
66200
67949
  }
@@ -66208,21 +67957,21 @@ function codexExecutable(pid) {
66208
67957
 
66209
67958
  // src/codex/codex-owner.ts
66210
67959
  function codexServersDirectory(stateDirectory, codexPid) {
66211
- return join16(stateDirectory, "codex-servers", String(codexPid));
67960
+ return join18(stateDirectory, "codex-servers", String(codexPid));
66212
67961
  }
66213
67962
  var ENTRY_NAME = /^(\d+)\.json$/;
66214
67963
  function entryName(entry) {
66215
67964
  return `${entry.seq}.json`;
66216
67965
  }
66217
67966
  async function registerServer(directory, pid, started) {
66218
- await mkdir5(directory, { mode: 448, recursive: true });
66219
- const temporary = join16(directory, `.${pid}.${process.hrtime.bigint()}.tmp`);
67967
+ await mkdir6(directory, { mode: 448, recursive: true });
67968
+ const temporary = join18(directory, `.${pid}.${process.hrtime.bigint()}.tmp`);
66220
67969
  await writeFile4(temporary, JSON.stringify({ pid, started }), { mode: 384 });
66221
67970
  try {
66222
67971
  let seq = Math.max(0, ...(await entryNames(directory)).map(({ seq: taken }) => taken)) + 1;
66223
67972
  for (;; ) {
66224
67973
  try {
66225
- await place(temporary, join16(directory, entryName({ seq })), pid, started);
67974
+ await place(temporary, join18(directory, entryName({ seq })), pid, started);
66226
67975
  return { pid, seq, started };
66227
67976
  } catch (error) {
66228
67977
  if (error.code !== "EEXIST")
@@ -66231,14 +67980,14 @@ async function registerServer(directory, pid, started) {
66231
67980
  }
66232
67981
  }
66233
67982
  } finally {
66234
- await rm4(temporary, { force: true });
67983
+ await rm6(temporary, { force: true });
66235
67984
  }
66236
67985
  }
66237
67986
  var linkRefused = false;
66238
67987
  async function place(temporary, target, pid, started) {
66239
67988
  if (!linkRefused) {
66240
67989
  try {
66241
- await link(temporary, target);
67990
+ await link2(temporary, target);
66242
67991
  return;
66243
67992
  } catch (error) {
66244
67993
  const code = error.code;
@@ -66250,7 +67999,7 @@ async function place(temporary, target, pid, started) {
66250
67999
  await writeFile4(target, JSON.stringify({ pid, started }), { flag: "wx", mode: 384 });
66251
68000
  }
66252
68001
  async function unregisterServer(directory, self2) {
66253
- await rm4(join16(directory, entryName(self2)), { force: true });
68002
+ await rm6(join18(directory, entryName(self2)), { force: true });
66254
68003
  }
66255
68004
  var startedOf = new Map;
66256
68005
  var SYSTEM_PROBE = {
@@ -66281,7 +68030,7 @@ function serverAlive(entry, probe = SYSTEM_PROBE) {
66281
68030
  async function entryNames(directory) {
66282
68031
  let names;
66283
68032
  try {
66284
- names = await readdir5(directory);
68033
+ names = await readdir6(directory);
66285
68034
  } catch {
66286
68035
  return [];
66287
68036
  }
@@ -66296,7 +68045,7 @@ async function readEntries(directory, now = Date.now) {
66296
68045
  for (const { name, seq } of await entryNames(directory)) {
66297
68046
  let text;
66298
68047
  try {
66299
- text = await readFile7(join16(directory, name), "utf8");
68048
+ text = await readFile8(join18(directory, name), "utf8");
66300
68049
  } catch {
66301
68050
  continue;
66302
68051
  }
@@ -66307,7 +68056,7 @@ async function readEntries(directory, now = Date.now) {
66307
68056
  parsed = undefined;
66308
68057
  }
66309
68058
  if (typeof parsed?.pid !== "number") {
66310
- const written = await stat4(join16(directory, name)).then((info) => info.mtimeMs, () => {
68059
+ const written = await stat6(join18(directory, name)).then((info) => info.mtimeMs, () => {
66311
68060
  return;
66312
68061
  });
66313
68062
  if (written === undefined || now() - written > UNREADABLE_ENTRY_MS)
@@ -66373,8 +68122,8 @@ async function stillOwner(directory, self2, probe = SYSTEM_PROBE) {
66373
68122
 
66374
68123
  // src/codex/codex-transcript.ts
66375
68124
  import { watch } from "fs";
66376
- import { open } from "fs/promises";
66377
- import { join as join17 } from "path";
68125
+ import { open as open3 } from "fs/promises";
68126
+ import { join as join19 } from "path";
66378
68127
  function record3(value) {
66379
68128
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
66380
68129
  }
@@ -66511,7 +68260,7 @@ function followTranscript(path, onLine, options = {}) {
66511
68260
  again = false;
66512
68261
  let handle;
66513
68262
  try {
66514
- handle = await open(path, "r");
68263
+ handle = await open3(path, "r");
66515
68264
  } catch {
66516
68265
  return;
66517
68266
  }
@@ -66578,7 +68327,7 @@ async function latestTurnCwd(transcriptPath) {
66578
68327
  return;
66579
68328
  let handle;
66580
68329
  try {
66581
- handle = await open(transcriptPath, "r");
68330
+ handle = await open3(transcriptPath, "r");
66582
68331
  let end = (await handle.stat()).size;
66583
68332
  let carry = Buffer.alloc(0);
66584
68333
  let dropping = false;
@@ -66644,7 +68393,7 @@ async function findTranscript(home, threadId) {
66644
68393
  const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);
66645
68394
  const found = [];
66646
68395
  try {
66647
- for await (const file of glob.scan({ absolute: true, cwd: join17(home, "sessions") })) {
68396
+ for await (const file of glob.scan({ absolute: true, cwd: join19(home, "sessions") })) {
66648
68397
  found.push(file);
66649
68398
  }
66650
68399
  } catch {
@@ -66789,7 +68538,7 @@ function runDispatchCommand(script, args, stdin, options) {
66789
68538
  });
66790
68539
  }
66791
68540
  function stateDirectoryFor(pluginRoot) {
66792
- return configuredValue(process.env["PLUGIN_DATA"]) ?? codexPluginDataDirectory(pluginRoot) ?? join18(configuredValue(process.env["XDG_STATE_HOME"]) ?? join18(homedir4(), ".local", "state"), "claude-envoy", "codex");
68541
+ return configuredValue(process.env["PLUGIN_DATA"]) ?? codexPluginDataDirectory(pluginRoot) ?? join20(configuredValue(process.env["XDG_STATE_HOME"]) ?? join20(homedir4(), ".local", "state"), "claude-envoy", "codex");
66793
68542
  }
66794
68543
  function waitForRecord(file, pid, signal, ended) {
66795
68544
  return new Promise((done) => {
@@ -66877,7 +68626,7 @@ async function runCodexEnvoyServer() {
66877
68626
  env["DISPATCH_HOST"] = "codex";
66878
68627
  if (configFile.path !== null)
66879
68628
  env["ENVOY_CONFIG_FILE"] = configFile.path;
66880
- const { code, output } = await runDispatchCommand(join18(pluginRoot, "dist", "dispatch.js"), parsed.data.args, parsed.data.stdin ?? "", { cwd: await latestTurnCwd(transcript) ?? own?.cwd ?? current?.cwd ?? homedir4(), env });
68629
+ const { code, output } = await runDispatchCommand(join20(pluginRoot, "dist", "dispatch.js"), parsed.data.args, parsed.data.stdin ?? "", { cwd: await latestTurnCwd(transcript) ?? own?.cwd ?? current?.cwd ?? homedir4(), env });
66881
68630
  return `${output}${output.endsWith(`
66882
68631
  `) || output === "" ? "" : `
66883
68632
  `}[exit ${code}]`;
@@ -67017,7 +68766,7 @@ async function runCodexEnvoyServer() {
67017
68766
  const runningSession = () => record?.session_id ?? bound.session_id;
67018
68767
  const codexDelivery = createCodexDelivery({
67019
68768
  inboxDirectory: (sessionId) => codexInboxDirectory(stateDirectory, sessionId),
67020
- queue: (text) => queueMessage(command(), runningSession(), text, join18(stateDirectory, "codex-long-messages")),
68769
+ queue: (text) => queueMessage(command(), runningSession(), text, join20(stateDirectory, "codex-long-messages")),
67021
68770
  sessionId: runningSession,
67022
68771
  taken: (item) => stream?.delivered(item.content, item.dispatchMessageId),
67023
68772
  warn