@sjawhar/codex-envoy 5.0.0 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -980,7 +980,7 @@ __export(exports_coerce, {
980
980
  });
981
981
 
982
982
  // hooks/codex-hook.ts
983
- import { rm as rm2 } from "fs/promises";
983
+ import { rm as rm4 } from "fs/promises";
984
984
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/core/core.js
985
985
  var NEVER = Object.freeze({
986
986
  status: "aborted"
@@ -17814,6 +17814,8 @@ function commandsHelp() {
17814
17814
  }),
17815
17815
  "",
17816
17816
  "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.",
17817
+ "",
17818
+ "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).",
17817
17819
  ""
17818
17820
  ].join(`
17819
17821
  `);
@@ -18612,6 +18614,15 @@ var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identi
18612
18614
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
18613
18615
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
18614
18616
  var TOKEN_TYPE_DPOP = "DPoP";
18617
+ var SUBJECT_TYPE_ACCESS = "urn:ietf:params:oauth:token-type:access_token";
18618
+ var DEVICE_AUTHORIZATION_PATH = "/v1/oauth/device_authorization";
18619
+ var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
18620
+ var GRANT_TYPE_REFRESH = "refresh_token";
18621
+ var MACHINE_LOGIN_CLIENT_ID = "agent-secrets-helper";
18622
+ var MACHINE_LOGIN_SCOPE = "machine";
18623
+ var REQUEST_OBJECT_TYPE = "agent-secrets-request+jwt";
18624
+ var LAUNCHER_CREDENTIAL_DETAIL = "launcher_credential";
18625
+ var REQUEST_OBJECT_LIFETIME_SECONDS = 600;
18615
18626
  var POD_SESSION_NOT_REGISTERED = "pod_session_not_registered";
18616
18627
  var SESSION_NAME_NOT_THIS_REGISTRARS = "session_name_not_this_registrars";
18617
18628
 
@@ -18944,6 +18955,8 @@ var INVALID_DPOP_PROOF = "invalid_dpop_proof";
18944
18955
  var USE_DPOP_NONCE = "use_dpop_nonce";
18945
18956
  var INVALID_GRANT = "invalid_grant";
18946
18957
  var MEMBERSHIP_HELD = "membership_held";
18958
+ var TOKEN_NOT_VALID = "Token is not valid or has expired.";
18959
+ var MACHINE_LOGIN_ENDED = "The machine login the subject token belongs to has ended.";
18947
18960
 
18948
18961
  class BrokerRefusedError extends Error {
18949
18962
  status;
@@ -18951,6 +18964,7 @@ class BrokerRefusedError extends Error {
18951
18964
  code;
18952
18965
  shownCode;
18953
18966
  podSessionUnregistered;
18967
+ subjectNotHonoured;
18954
18968
  constructor(status, code, description, refused, context = {}) {
18955
18969
  const shownCode = shownOAuthCode(code);
18956
18970
  const said = description === "" ? "" : isKnownBrokerRefusal(description, context) ? scrub(description) : REFUSAL_TEXT_WITHHELD;
@@ -18961,6 +18975,7 @@ class BrokerRefusedError extends Error {
18961
18975
  this.shownCode = shownCode;
18962
18976
  this.said = said;
18963
18977
  this.podSessionUnregistered = code === INVALID_GRANT && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
18978
+ this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT && description.endsWith(MACHINE_LOGIN_ENDED));
18964
18979
  }
18965
18980
  get permanent() {
18966
18981
  return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE && this.code !== MEMBERSHIP_HELD && !this.podSessionUnregistered;
@@ -19014,8 +19029,23 @@ class SignInEndedError extends Error {
19014
19029
  this.name = "SignInEndedError";
19015
19030
  }
19016
19031
  }
19032
+ var DEVICE_LOGIN_COMMAND = "dispatch login --device";
19033
+
19034
+ class DeviceLoginEndedError extends Error {
19035
+ constructor(login) {
19036
+ super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${DEVICE_LOGIN_COMMAND}`);
19037
+ this.name = "DeviceLoginEndedError";
19038
+ }
19039
+ }
19040
+
19041
+ class LockHeldError extends Error {
19042
+ constructor(lock, options) {
19043
+ super(`another process of this machine held ${lock} for all of this trade's time, so nothing was sent to the secrets broker`, options);
19044
+ this.name = "LockHeldError";
19045
+ }
19046
+ }
19017
19047
  function isFinalRefusal(error) {
19018
- return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
19048
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
19019
19049
  }
19020
19050
 
19021
19051
  // ../envoy-client/src/envoy-config.ts
@@ -26926,249 +26956,808 @@ async function executeDispatchTool(input) {
26926
26956
  return command.origin === "none" ? command.run(session) : command.run(await commandContext(session));
26927
26957
  }
26928
26958
 
26929
- // ../cipher-client/src/dpop.ts
26930
- import {
26931
- createHash,
26932
- createPrivateKey,
26933
- createPublicKey,
26934
- generateKeyPairSync,
26935
- randomUUID as randomUUID2,
26936
- sign
26937
- } from "crypto";
26938
- var ALGORITHM = "ES256";
26939
- var CONNECTION_PROOF_METHOD = "CONNECT";
26940
- var CONNECTION_PROOF_TARGET = "nats:connect";
26941
- function targetUri(url) {
26942
- const parsed = new URL(url);
26943
- parsed.search = "";
26944
- parsed.hash = "";
26945
- return parsed.toString();
26959
+ // ../cipher-client/src/device-login.ts
26960
+ import { generateKeyPairSync as generateKeyPairSync2, randomUUID as randomUUID5 } from "crypto";
26961
+
26962
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
26963
+ var encoder2 = new TextEncoder;
26964
+ var decoder = new TextDecoder;
26965
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
26966
+ var MAX_INT32 = 2 ** 32;
26967
+ function concat(...buffers) {
26968
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
26969
+ const buf = new Uint8Array(size);
26970
+ let i = 0;
26971
+ for (const buffer of buffers) {
26972
+ buf.set(buffer, i);
26973
+ i += buffer.length;
26974
+ }
26975
+ return buf;
26976
+ }
26977
+ function encode4(string) {
26978
+ const bytes = new Uint8Array(string.length);
26979
+ for (let i = 0;i < string.length; i++) {
26980
+ const code = string.charCodeAt(i);
26981
+ if (code > 127) {
26982
+ throw new TypeError("non-ASCII string encountered in encode()");
26983
+ }
26984
+ bytes[i] = code;
26985
+ }
26986
+ return bytes;
26946
26987
  }
26947
- function dpopKey(privateKey, publicJwk) {
26948
- const header = Buffer.from(JSON.stringify({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk })).toString("base64url");
26949
- const signed = (htm, htu, nonce, accessToken) => {
26950
- const claims = {
26951
- jti: randomUUID2(),
26952
- htm,
26953
- htu,
26954
- iat: Math.floor(Date.now() / 1000)
26955
- };
26956
- if (nonce !== undefined && nonce !== "")
26957
- claims["nonce"] = nonce;
26958
- if (accessToken !== undefined && accessToken !== "") {
26959
- claims["ath"] = createHash("sha256").update(accessToken).digest("base64url");
26960
- }
26961
- const signingInput = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
26962
- const signature = sign("sha256", Buffer.from(signingInput), {
26963
- key: privateKey,
26964
- dsaEncoding: "ieee-p1363"
26965
- });
26966
- return `${signingInput}.${signature.toString("base64url")}`;
26967
- };
26968
- return {
26969
- publicJwk,
26970
- async proof(request) {
26971
- return signed(request.method.toUpperCase(), targetUri(request.url), request.nonce, request.accessToken);
26972
- },
26973
- connectionProof({ accessToken, nonce }) {
26974
- if (accessToken === "")
26975
- throw new Error("no access token to prove a NATS connection for");
26976
- if (nonce === "")
26977
- throw new Error("the NATS server sent no nonce to sign");
26978
- return signed(CONNECTION_PROOF_METHOD, CONNECTION_PROOF_TARGET, nonce, accessToken);
26979
- }
26980
- };
26988
+
26989
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
26990
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
26991
+ function checkUsage(key, usage) {
26992
+ if (usage && !key.usages.includes(usage)) {
26993
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
26994
+ }
26981
26995
  }
26982
- function publicJwkOf(privateKey, name) {
26983
- const { kty, crv, x, y } = createPublicKey(privateKey).export({ format: "jwk" });
26984
- if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
26985
- throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
26996
+ function checkModulusLength(alg, key) {
26997
+ const { modulusLength } = key.algorithm;
26998
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
26999
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
26986
27000
  }
26987
- return { kty, crv, x, y };
26988
27001
  }
26989
- async function newDpopKey() {
26990
- const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
26991
- return dpopKey(privateKey, publicJwkOf(privateKey, "this process's key"));
27002
+ function checkCryptoKey(key, expected, usage) {
27003
+ const algorithm = key.algorithm;
27004
+ if (algorithm.name !== expected.name) {
27005
+ throw unusable(expected.name);
27006
+ }
27007
+ if (expected.hash && algorithm.hash?.name !== expected.hash) {
27008
+ throw unusable(expected.hash, "algorithm.hash");
27009
+ }
27010
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
27011
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
27012
+ }
27013
+ if (expected.length !== undefined && algorithm.length !== expected.length) {
27014
+ throw unusable(expected.length, "algorithm.length");
27015
+ }
27016
+ checkUsage(key, usage);
26992
27017
  }
26993
- async function importDpopKey(pkcs8Pem, name) {
26994
- let privateKey;
26995
- try {
26996
- privateKey = createPrivateKey(pkcs8Pem);
26997
- } catch {
26998
- throw new Error(`read ${name}: it does not parse as a PKCS#8 PEM private key`);
27018
+
27019
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
27020
+ function message(msg, actual, ...types) {
27021
+ if (types.length > 2) {
27022
+ const last = types.pop();
27023
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
27024
+ } else if (types.length === 2) {
27025
+ msg += `one of type ${types[0]} or ${types[1]}.`;
27026
+ } else {
27027
+ msg += `of type ${types[0]}.`;
26999
27028
  }
27000
- return dpopKey(privateKey, publicJwkOf(privateKey, name));
27029
+ if (actual == null) {
27030
+ msg += ` Received ${actual}`;
27031
+ } else if (typeof actual === "function" && actual.name) {
27032
+ msg += ` Received function ${actual.name}`;
27033
+ } else if (typeof actual === "object" && actual != null) {
27034
+ if (actual.constructor?.name) {
27035
+ msg += ` Received an instance of ${actual.constructor.name}`;
27036
+ }
27037
+ }
27038
+ return msg;
27001
27039
  }
27040
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
27041
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
27002
27042
 
27003
- // ../cipher-client/src/metadata-identity.ts
27004
- import { Agent, request } from "http";
27005
- var METADATA_HOST_VAR = "GCE_METADATA_HOST";
27006
- var DEFAULT_METADATA_HOST = "metadata.google.internal";
27007
- var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
27008
- var TIMEOUT_MS = 1e4;
27009
- var MAX_ANSWER_BYTES = 1 << 20;
27010
- var agent = new Agent({ keepAlive: false });
27011
- function tokenUrl(audience, env) {
27012
- const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
27013
- return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
27043
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
27044
+ class JOSEError extends Error {
27045
+ static code = "ERR_JOSE_GENERIC";
27046
+ code = "ERR_JOSE_GENERIC";
27047
+ constructor(message, options) {
27048
+ super(message, options);
27049
+ this.name = this.constructor.name;
27050
+ Error.captureStackTrace?.(this, this.constructor);
27051
+ }
27014
27052
  }
27015
- function serverNamed(env) {
27016
- return (env[METADATA_HOST_VAR] ?? "").trim() === "" ? `at ${DEFAULT_METADATA_HOST}` : `${METADATA_HOST_VAR} names`;
27053
+ class JOSENotSupported extends JOSEError {
27054
+ static code = "ERR_JOSE_NOT_SUPPORTED";
27055
+ code = "ERR_JOSE_NOT_SUPPORTED";
27017
27056
  }
27018
- function get(url, signal, lookup) {
27019
- const { promise, resolve, reject } = Promise.withResolvers();
27020
- const call = request(url, {
27021
- agent,
27022
- method: "GET",
27023
- headers: { "Metadata-Flavor": "Google" },
27024
- timeout: TIMEOUT_MS,
27025
- ...signal === undefined ? {} : { signal },
27026
- ...lookup === undefined ? {} : { lookup }
27027
- }, (answer) => {
27028
- const chunks = [];
27029
- let read = 0;
27030
- answer.on("data", (chunk) => {
27031
- read += chunk.length;
27032
- if (read <= MAX_ANSWER_BYTES)
27033
- chunks.push(chunk);
27034
- });
27035
- answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
27036
- answer.on("error", reject);
27037
- });
27038
- call.on("timeout", () => call.destroy(Object.assign(new Error(`no answer within ${TIMEOUT_MS} ms`), { code: "ETIMEDOUT" })));
27039
- call.on("error", reject);
27040
- call.end();
27041
- return promise;
27057
+ class JWSInvalid extends JOSEError {
27058
+ static code = "ERR_JWS_INVALID";
27059
+ code = "ERR_JWS_INVALID";
27042
27060
  }
27043
- function metadataIdentity(audience, env = process.env, options = {}) {
27044
- return {
27045
- async read(signal) {
27046
- const url = tokenUrl(audience, env);
27047
- const named = `the metadata server ${serverNamed(env)}`;
27048
- let answer;
27049
- try {
27050
- answer = await get(url, signal, options.lookup);
27051
- } catch (error) {
27052
- throw new Error(`${named} could not be reached: ${errorClass(error)}`);
27053
- }
27054
- if (answer.status < 200 || answer.status > 299) {
27055
- throw new Error(`${named} answered HTTP ${answer.status}`);
27056
- }
27057
- const token = answer.body.trim();
27058
- if (token === "") {
27059
- throw new Error(`${named} answered an empty identity token`);
27060
- }
27061
- return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
27062
- },
27063
- describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
27064
- };
27061
+ class JWKInvalid extends JOSEError {
27062
+ static code = "ERR_JWK_INVALID";
27063
+ code = "ERR_JWK_INVALID";
27065
27064
  }
27066
27065
 
27067
- // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
27068
- var USER_AGENT;
27069
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
27070
- const NAME = "oauth4webapi";
27071
- const VERSION = "v3.8.8";
27072
- USER_AGENT = `${NAME}/${VERSION}`;
27073
- }
27074
- function looseInstanceOf(input, expected) {
27075
- if (input == null) {
27076
- return false;
27077
- }
27066
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
27067
+ var isCryptoKey = (key) => {
27068
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
27069
+ return true;
27078
27070
  try {
27079
- return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
27071
+ return key instanceof CryptoKey;
27080
27072
  } catch {
27081
27073
  return false;
27082
27074
  }
27083
- }
27084
- var ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
27085
- var ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
27086
- function CodedTypeError(message, code, cause) {
27087
- const err = new TypeError(message, { cause });
27088
- Object.assign(err, { code });
27089
- return err;
27090
- }
27091
- var allowInsecureRequests = Symbol();
27092
- var clockSkew = Symbol();
27093
- var clockTolerance = Symbol();
27094
- var customFetch = Symbol();
27095
- var modifyAssertion = Symbol();
27096
- var jweDecrypt = Symbol();
27097
- var jwksCache = Symbol();
27098
- var encoder2 = new TextEncoder;
27099
- var decoder = new TextDecoder;
27100
- function buf(input) {
27101
- if (typeof input === "string") {
27102
- return encoder2.encode(input);
27075
+ };
27076
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
27077
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
27078
+
27079
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
27080
+ function encodeBase64(input) {
27081
+ if (Uint8Array.prototype.toBase64) {
27082
+ return input.toBase64();
27103
27083
  }
27104
- return decoder.decode(input);
27105
- }
27106
- var encodeBase64Url;
27107
- if (Uint8Array.prototype.toBase64) {
27108
- encodeBase64Url = (input) => {
27109
- if (input instanceof ArrayBuffer) {
27110
- input = new Uint8Array(input);
27111
- }
27112
- return input.toBase64({ alphabet: "base64url", omitPadding: true });
27113
- };
27114
- } else {
27115
27084
  const CHUNK_SIZE = 32768;
27116
- encodeBase64Url = (input) => {
27117
- if (input instanceof ArrayBuffer) {
27118
- input = new Uint8Array(input);
27119
- }
27120
- const arr = [];
27121
- for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
27122
- arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
27123
- }
27124
- return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
27125
- };
27085
+ const arr = [];
27086
+ for (let i = 0;i < input.length; i += CHUNK_SIZE) {
27087
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
27088
+ }
27089
+ return btoa(arr.join(""));
27126
27090
  }
27127
- var decodeBase64Url;
27128
- if (Uint8Array.fromBase64) {
27129
- decodeBase64Url = (input) => {
27130
- try {
27131
- return Uint8Array.fromBase64(input, { alphabet: "base64url" });
27132
- } catch (cause) {
27133
- throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
27134
- }
27135
- };
27136
- } else {
27137
- decodeBase64Url = (input) => {
27091
+ function decodeBase64(encoded) {
27092
+ if (Uint8Array.fromBase64) {
27093
+ return Uint8Array.fromBase64(encoded);
27094
+ }
27095
+ const binary = atob(encoded);
27096
+ const bytes = new Uint8Array(binary.length);
27097
+ for (let i = 0;i < binary.length; i++) {
27098
+ bytes[i] = binary.charCodeAt(i);
27099
+ }
27100
+ return bytes;
27101
+ }
27102
+
27103
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
27104
+ var invalid = "The input to be decoded is not correctly encoded.";
27105
+ function decode3(input) {
27106
+ if (Uint8Array.fromBase64) {
27138
27107
  try {
27139
- const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
27140
- const bytes = new Uint8Array(binary.length);
27141
- for (let i = 0;i < binary.length; i++) {
27142
- bytes[i] = binary.charCodeAt(i);
27143
- }
27144
- return bytes;
27108
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
27109
+ alphabet: "base64url"
27110
+ });
27145
27111
  } catch (cause) {
27146
- throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
27112
+ throw new TypeError(invalid, { cause });
27147
27113
  }
27148
- };
27114
+ }
27115
+ let encoded = input;
27116
+ if (encoded instanceof Uint8Array) {
27117
+ encoded = decoder.decode(encoded);
27118
+ }
27119
+ if (encoded.includes("+") || encoded.includes("/")) {
27120
+ throw new TypeError(invalid);
27121
+ }
27122
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
27123
+ try {
27124
+ return decodeBase64(encoded);
27125
+ } catch {
27126
+ throw new TypeError(invalid);
27127
+ }
27149
27128
  }
27150
- function b64u(input) {
27151
- if (typeof input === "string") {
27152
- return decodeBase64Url(input);
27129
+ function encode5(input) {
27130
+ let unencoded = input;
27131
+ if (typeof unencoded === "string") {
27132
+ unencoded = encoder2.encode(unencoded);
27153
27133
  }
27154
- return encodeBase64Url(input);
27134
+ if (Uint8Array.prototype.toBase64) {
27135
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
27136
+ }
27137
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
27155
27138
  }
27156
27139
 
27157
- class UnsupportedOperationError extends Error {
27158
- code;
27159
- constructor(message, options) {
27160
- super(message, options);
27161
- this.name = this.constructor.name;
27162
- this.code = UNSUPPORTED_OPERATION;
27163
- Error.captureStackTrace?.(this, this.constructor);
27140
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
27141
+ function isObject3(input) {
27142
+ if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
27143
+ return false;
27144
+ }
27145
+ const prototype = Object.getPrototypeOf(input);
27146
+ if (prototype === null) {
27147
+ return true;
27148
+ }
27149
+ let proto = prototype;
27150
+ while (Object.getPrototypeOf(proto) !== null) {
27151
+ proto = Object.getPrototypeOf(proto);
27164
27152
  }
27153
+ return prototype === proto;
27165
27154
  }
27166
-
27167
- class OperationProcessingError extends Error {
27168
- code;
27169
- constructor(message, options) {
27170
- super(message, options);
27171
- this.name = this.constructor.name;
27155
+ function isDisjoint(...headers) {
27156
+ const parameters = new Set;
27157
+ for (const header of headers) {
27158
+ if (!header)
27159
+ continue;
27160
+ for (const parameter of Object.keys(header)) {
27161
+ if (parameters.has(parameter)) {
27162
+ return false;
27163
+ }
27164
+ parameters.add(parameter);
27165
+ }
27166
+ }
27167
+ return true;
27168
+ }
27169
+ var isJWK = (key) => isObject3(key) && typeof key.kty === "string";
27170
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
27171
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
27172
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
27173
+
27174
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/helpers.js
27175
+ var unprotected = Symbol();
27176
+ function assertNotSet(value, name) {
27177
+ if (value) {
27178
+ throw new TypeError(`${name} can only be called once`);
27179
+ }
27180
+ }
27181
+ async function digest(algorithm, data) {
27182
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
27183
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
27184
+ }
27185
+
27186
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwk_to_key.js
27187
+ async function jwkToKey(entry, jwk) {
27188
+ if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== undefined) {
27189
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
27190
+ }
27191
+ if (!entry.kty.includes(jwk.kty)) {
27192
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
27193
+ }
27194
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle;
27195
+ const isPrivate = !!(jwk.d || jwk.priv);
27196
+ const keyData = { ...jwk };
27197
+ if (keyData.kty !== "AKP") {
27198
+ delete keyData.alg;
27199
+ }
27200
+ delete keyData.use;
27201
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
27202
+ }
27203
+
27204
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key.js
27205
+ var tag = (key) => key[Symbol.toStringTag];
27206
+ var jwkMatchesOp = (entry, key, usage) => {
27207
+ const { alg } = entry;
27208
+ if (key.use !== undefined) {
27209
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
27210
+ if (key.use !== expected) {
27211
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
27212
+ }
27213
+ }
27214
+ if (key.alg !== undefined && key.alg !== alg) {
27215
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
27216
+ }
27217
+ if (Array.isArray(key.key_ops)) {
27218
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
27219
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
27220
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
27221
+ }
27222
+ }
27223
+ };
27224
+ function checkKeyType(entry, key, usage) {
27225
+ const { alg, secret } = entry;
27226
+ const privateKey = usage === "decrypt" || usage === "sign";
27227
+ if (secret && key instanceof Uint8Array)
27228
+ return [BYTES, key];
27229
+ if (isJWK(key)) {
27230
+ if (secret ? !isSecretJWK(key) : !(privateKey ? isPrivateJWK(key) : isPublicJWK(key))) {
27231
+ 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`);
27232
+ }
27233
+ jwkMatchesOp(entry, key, usage);
27234
+ return [JWK, key];
27235
+ }
27236
+ if (!isKeyLike(key)) {
27237
+ throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
27238
+ }
27239
+ if (secret) {
27240
+ if (key.type !== "secret") {
27241
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
27242
+ }
27243
+ } else {
27244
+ if (key.type === "secret") {
27245
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
27246
+ }
27247
+ const expectedType = privateKey ? "private" : "public";
27248
+ if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
27249
+ const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
27250
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
27251
+ }
27252
+ }
27253
+ return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
27254
+ }
27255
+ var BYTES = 0;
27256
+ var CRYPTO = 1;
27257
+ var KEYOBJECT = 2;
27258
+ var JWK = 3;
27259
+ var cache;
27260
+ var nist = {
27261
+ __proto__: null,
27262
+ prime256v1: "P-256",
27263
+ secp384r1: "P-384",
27264
+ secp521r1: "P-521"
27265
+ };
27266
+ function cached2(key, alg, value) {
27267
+ cache ||= new WeakMap;
27268
+ const entry = cache.get(key);
27269
+ if (value) {
27270
+ if (entry) {
27271
+ entry[alg] = value;
27272
+ } else {
27273
+ cache.set(key, { __proto__: null, [alg]: value });
27274
+ }
27275
+ }
27276
+ return value ?? entry?.[alg];
27277
+ }
27278
+ var handleJWK = async (key, jwk, entry) => cached2(key, entry.alg) ?? cached2(key, entry.alg, await jwkToKey(entry, { ...jwk, alg: entry.alg }));
27279
+ var handleKeyObject = (keyObject, entry) => {
27280
+ const hit = cached2(keyObject, entry.alg);
27281
+ if (hit)
27282
+ return hit;
27283
+ const isPublic = keyObject.type === "public";
27284
+ const usages = entry.usages[isPublic ? 0 : 1];
27285
+ const { asymmetricKeyType } = keyObject;
27286
+ const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
27287
+ const params = entry.resolve?.({ crv, asymmetricKeyType }) ?? entry.subtle;
27288
+ return cached2(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
27289
+ };
27290
+ async function prepareKey(entry, key, usage) {
27291
+ const tagged = checkKeyType(entry, key, usage);
27292
+ switch (tagged[0]) {
27293
+ case BYTES:
27294
+ case CRYPTO:
27295
+ return tagged[1];
27296
+ case JWK: {
27297
+ const key = tagged[1];
27298
+ if (key.k) {
27299
+ return decode3(key.k);
27300
+ }
27301
+ if (!Object.isFrozen(key)) {
27302
+ const { key_ops } = key;
27303
+ if (Array.isArray(key_ops))
27304
+ Object.freeze(key_ops);
27305
+ Object.freeze(key);
27306
+ }
27307
+ return handleJWK(key, key, entry);
27308
+ }
27309
+ case KEYOBJECT: {
27310
+ const keyObject = tagged[1];
27311
+ if (keyObject.type === "secret") {
27312
+ return keyObject.export();
27313
+ }
27314
+ if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
27315
+ return handleKeyObject(keyObject, entry);
27316
+ }
27317
+ return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
27318
+ }
27319
+ }
27320
+ }
27321
+
27322
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_descriptor.js
27323
+ function table(entries) {
27324
+ const out = { __proto__: null };
27325
+ for (const alg in entries) {
27326
+ out[alg] = { ...entries[alg], alg };
27327
+ }
27328
+ return out;
27329
+ }
27330
+
27331
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/options.js
27332
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
27333
+ function validateCritDuplicates(Err, protectedHeader) {
27334
+ const { crit } = protectedHeader ?? {};
27335
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length) {
27336
+ throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
27337
+ }
27338
+ }
27339
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
27340
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
27341
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
27342
+ }
27343
+ if (!protectedHeader || protectedHeader.crit === undefined) {
27344
+ return [];
27345
+ }
27346
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
27347
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
27348
+ }
27349
+ const recognized = recognizedOption === undefined ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
27350
+ for (const parameter of protectedHeader.crit) {
27351
+ if (!(parameter in recognized)) {
27352
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
27353
+ }
27354
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === undefined) {
27355
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
27356
+ }
27357
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === undefined)) {
27358
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
27359
+ }
27360
+ }
27361
+ return protectedHeader.crit;
27362
+ }
27363
+
27364
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/signing.js
27365
+ async function getSigKey(entry, key, usage) {
27366
+ if (key instanceof Uint8Array) {
27367
+ return crypto.subtle.importKey("raw", key, entry.subtle, false, [
27368
+ usage
27369
+ ]);
27370
+ }
27371
+ checkCryptoKey(key, entry.subtle, usage);
27372
+ if (entry.minRsaBits)
27373
+ checkModulusLength(entry.alg, key);
27374
+ return key;
27375
+ }
27376
+ async function sign(entry, key, data) {
27377
+ const cryptoKey = await getSigKey(entry, key, "sign");
27378
+ const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
27379
+ return new Uint8Array(signature);
27380
+ }
27381
+
27382
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_algorithms.js
27383
+ var sig = [["verify"], ["sign"]];
27384
+ function hmac(bits) {
27385
+ const subtle = { name: "HMAC", hash: `SHA-${bits}` };
27386
+ return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
27387
+ }
27388
+ function rsa(bits, saltLength) {
27389
+ const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
27390
+ const subtle = { name, hash: `SHA-${bits}` };
27391
+ return {
27392
+ kty: ["RSA"],
27393
+ subtle,
27394
+ signing: saltLength ? { ...subtle, saltLength } : subtle,
27395
+ usages: sig,
27396
+ minRsaBits: 2048
27397
+ };
27398
+ }
27399
+ function ecdsa(crv, bits) {
27400
+ return {
27401
+ kty: ["EC"],
27402
+ crv,
27403
+ subtle: { name: "ECDSA", namedCurve: crv },
27404
+ signing: { name: "ECDSA", hash: `SHA-${bits}` },
27405
+ usages: sig
27406
+ };
27407
+ }
27408
+ function eddsa() {
27409
+ const subtle = { name: "Ed25519" };
27410
+ return {
27411
+ kty: ["OKP"],
27412
+ crv: "Ed25519",
27413
+ subtle,
27414
+ signing: subtle,
27415
+ usages: sig
27416
+ };
27417
+ }
27418
+ function mldsa(bits) {
27419
+ const name = `ML-DSA-${bits}`;
27420
+ const subtle = { name };
27421
+ return {
27422
+ kty: ["AKP"],
27423
+ subtle,
27424
+ signing: subtle,
27425
+ usages: sig
27426
+ };
27427
+ }
27428
+ var JWS = table({
27429
+ HS256: hmac(256),
27430
+ HS384: hmac(384),
27431
+ HS512: hmac(512),
27432
+ RS256: rsa(256),
27433
+ RS384: rsa(384),
27434
+ RS512: rsa(512),
27435
+ PS256: rsa(256, 32),
27436
+ PS384: rsa(384, 48),
27437
+ PS512: rsa(512, 64),
27438
+ ES256: ecdsa("P-256", 256),
27439
+ ES384: ecdsa("P-384", 384),
27440
+ ES512: ecdsa("P-521", 512),
27441
+ EdDSA: eddsa(),
27442
+ Ed25519: eddsa(),
27443
+ "ML-DSA-44": mldsa(44),
27444
+ "ML-DSA-65": mldsa(65),
27445
+ "ML-DSA-87": mldsa(87)
27446
+ });
27447
+ function jwsAlgorithm(alg) {
27448
+ const entry = typeof alg === "string" ? JWS[alg] : undefined;
27449
+ if (!entry) {
27450
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
27451
+ }
27452
+ return entry;
27453
+ }
27454
+
27455
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_sign.js
27456
+ function unencodedPayload(protectedHeader) {
27457
+ return protectedHeader?.b64 === false && Array.isArray(protectedHeader.crit) && protectedHeader.crit.includes("b64");
27458
+ }
27459
+ async function createSignature(input, key) {
27460
+ const { protectedHeader, unprotectedHeader } = input;
27461
+ if (!protectedHeader && !unprotectedHeader) {
27462
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
27463
+ }
27464
+ if (!isDisjoint(protectedHeader, unprotectedHeader)) {
27465
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
27466
+ }
27467
+ const joseHeader = { ...protectedHeader, ...unprotectedHeader };
27468
+ validateCritDuplicates(JWSInvalid, protectedHeader);
27469
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, input.crit, protectedHeader, joseHeader);
27470
+ let b64 = true;
27471
+ if (extensions.includes("b64")) {
27472
+ b64 = protectedHeader.b64;
27473
+ if (typeof b64 !== "boolean") {
27474
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
27475
+ }
27476
+ }
27477
+ const { alg } = joseHeader;
27478
+ if (typeof alg !== "string" || !alg) {
27479
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
27480
+ }
27481
+ const entry = jwsAlgorithm(alg);
27482
+ let payloadS;
27483
+ let payloadB;
27484
+ if (b64) {
27485
+ const encoded = input.encoded ??= [];
27486
+ encoded[0] ??= encode5(input.payload);
27487
+ encoded[1] ??= encode4(encoded[0]);
27488
+ payloadS = encoded[0];
27489
+ payloadB = encoded[1];
27490
+ } else {
27491
+ payloadB = input.payload;
27492
+ payloadS = "";
27493
+ }
27494
+ let protectedHeaderString;
27495
+ let protectedHeaderBytes;
27496
+ if (protectedHeader) {
27497
+ protectedHeaderString = encode5(JSON.stringify(protectedHeader));
27498
+ protectedHeaderBytes = encode4(protectedHeaderString);
27499
+ } else {
27500
+ protectedHeaderString = "";
27501
+ protectedHeaderBytes = new Uint8Array;
27502
+ }
27503
+ const data = concat(protectedHeaderBytes, encode4("."), payloadB);
27504
+ const k = await prepareKey(entry, key, "sign");
27505
+ const signature = await sign(entry, k, data);
27506
+ const jws = {
27507
+ signature: encode5(signature),
27508
+ payload: payloadS
27509
+ };
27510
+ if (protectedHeader) {
27511
+ jws.protected = protectedHeaderString;
27512
+ }
27513
+ if (unprotectedHeader) {
27514
+ jws.header = unprotectedHeader;
27515
+ }
27516
+ return jws;
27517
+ }
27518
+
27519
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/flattened/sign.js
27520
+ class FlattenedSign {
27521
+ #payload;
27522
+ #protectedHeader;
27523
+ #unprotectedHeader;
27524
+ constructor(payload) {
27525
+ if (!(payload instanceof Uint8Array)) {
27526
+ throw new TypeError("payload must be an instance of Uint8Array");
27527
+ }
27528
+ this.#payload = payload;
27529
+ }
27530
+ setProtectedHeader(protectedHeader) {
27531
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
27532
+ this.#protectedHeader = protectedHeader;
27533
+ return this;
27534
+ }
27535
+ setUnprotectedHeader(unprotectedHeader) {
27536
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
27537
+ this.#unprotectedHeader = unprotectedHeader;
27538
+ return this;
27539
+ }
27540
+ async sign(key, options) {
27541
+ return createSignature({
27542
+ payload: this.#payload,
27543
+ protectedHeader: this.#protectedHeader,
27544
+ unprotectedHeader: this.#unprotectedHeader,
27545
+ crit: options?.crit
27546
+ }, key);
27547
+ }
27548
+ }
27549
+
27550
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/compact/sign.js
27551
+ class CompactSign {
27552
+ #flattened;
27553
+ #protectedHeader;
27554
+ constructor(payload) {
27555
+ this.#flattened = new FlattenedSign(payload);
27556
+ }
27557
+ setProtectedHeader(protectedHeader) {
27558
+ this.#flattened.setProtectedHeader(protectedHeader);
27559
+ this.#protectedHeader = protectedHeader;
27560
+ return this;
27561
+ }
27562
+ async sign(key, options) {
27563
+ if (unencodedPayload(this.#protectedHeader)) {
27564
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
27565
+ }
27566
+ const jws = await this.#flattened.sign(key, options);
27567
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
27568
+ }
27569
+ }
27570
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
27571
+ function omitUndefinedProperties(jwk) {
27572
+ return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
27573
+ }
27574
+ async function keyToJWK(key) {
27575
+ if (isKeyObject(key)) {
27576
+ if (key.type === "secret") {
27577
+ key = key.export();
27578
+ } else {
27579
+ return key.export({ format: "jwk" });
27580
+ }
27581
+ }
27582
+ if (key instanceof Uint8Array) {
27583
+ return {
27584
+ kty: "oct",
27585
+ k: encode5(key)
27586
+ };
27587
+ }
27588
+ if (!isCryptoKey(key)) {
27589
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
27590
+ }
27591
+ if (!key.extractable) {
27592
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
27593
+ }
27594
+ const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
27595
+ if (jwk.kty === "AKP") {
27596
+ jwk.alg = alg;
27597
+ }
27598
+ return jwk;
27599
+ }
27600
+ function exportJWK(key) {
27601
+ return keyToJWK(key);
27602
+ }
27603
+
27604
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jwk/thumbprint.js
27605
+ var check2 = (value, description) => {
27606
+ if (typeof value !== "string" || !value) {
27607
+ throw new JWKInvalid(`${description} missing or invalid`);
27608
+ }
27609
+ };
27610
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
27611
+ let jwk;
27612
+ if (isJWK(key)) {
27613
+ jwk = key;
27614
+ } else if (isKeyLike(key)) {
27615
+ jwk = await exportJWK(key);
27616
+ } else {
27617
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
27618
+ }
27619
+ digestAlgorithm ??= "sha256";
27620
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
27621
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
27622
+ }
27623
+ let components;
27624
+ switch (jwk.kty) {
27625
+ case "AKP":
27626
+ check2(jwk.alg, '"alg" (Algorithm) Parameter');
27627
+ check2(jwk.pub, '"pub" (Public key) Parameter');
27628
+ components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
27629
+ break;
27630
+ case "EC":
27631
+ check2(jwk.crv, '"crv" (Curve) Parameter');
27632
+ check2(jwk.x, '"x" (X Coordinate) Parameter');
27633
+ check2(jwk.y, '"y" (Y Coordinate) Parameter');
27634
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
27635
+ break;
27636
+ case "OKP":
27637
+ check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
27638
+ check2(jwk.x, '"x" (Public Key) Parameter');
27639
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
27640
+ break;
27641
+ case "RSA":
27642
+ check2(jwk.e, '"e" (Exponent) Parameter');
27643
+ check2(jwk.n, '"n" (Modulus) Parameter');
27644
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
27645
+ break;
27646
+ case "oct":
27647
+ check2(jwk.k, '"k" (Key Value) Parameter');
27648
+ components = { k: jwk.k, kty: jwk.kty };
27649
+ break;
27650
+ default:
27651
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
27652
+ }
27653
+ const data = encode4(JSON.stringify(components));
27654
+ return encode5(await digest(digestAlgorithm, data));
27655
+ }
27656
+ // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
27657
+ var USER_AGENT;
27658
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
27659
+ const NAME = "oauth4webapi";
27660
+ const VERSION = "v3.8.8";
27661
+ USER_AGENT = `${NAME}/${VERSION}`;
27662
+ }
27663
+ function looseInstanceOf(input, expected) {
27664
+ if (input == null) {
27665
+ return false;
27666
+ }
27667
+ try {
27668
+ return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
27669
+ } catch {
27670
+ return false;
27671
+ }
27672
+ }
27673
+ var ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
27674
+ var ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
27675
+ function CodedTypeError(message, code, cause) {
27676
+ const err = new TypeError(message, { cause });
27677
+ Object.assign(err, { code });
27678
+ return err;
27679
+ }
27680
+ var allowInsecureRequests = Symbol();
27681
+ var clockSkew = Symbol();
27682
+ var clockTolerance = Symbol();
27683
+ var customFetch = Symbol();
27684
+ var modifyAssertion = Symbol();
27685
+ var jweDecrypt = Symbol();
27686
+ var jwksCache = Symbol();
27687
+ var encoder3 = new TextEncoder;
27688
+ var decoder2 = new TextDecoder;
27689
+ function buf(input) {
27690
+ if (typeof input === "string") {
27691
+ return encoder3.encode(input);
27692
+ }
27693
+ return decoder2.decode(input);
27694
+ }
27695
+ var encodeBase64Url;
27696
+ if (Uint8Array.prototype.toBase64) {
27697
+ encodeBase64Url = (input) => {
27698
+ if (input instanceof ArrayBuffer) {
27699
+ input = new Uint8Array(input);
27700
+ }
27701
+ return input.toBase64({ alphabet: "base64url", omitPadding: true });
27702
+ };
27703
+ } else {
27704
+ const CHUNK_SIZE = 32768;
27705
+ encodeBase64Url = (input) => {
27706
+ if (input instanceof ArrayBuffer) {
27707
+ input = new Uint8Array(input);
27708
+ }
27709
+ const arr = [];
27710
+ for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
27711
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
27712
+ }
27713
+ return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
27714
+ };
27715
+ }
27716
+ var decodeBase64Url;
27717
+ if (Uint8Array.fromBase64) {
27718
+ decodeBase64Url = (input) => {
27719
+ try {
27720
+ return Uint8Array.fromBase64(input, { alphabet: "base64url" });
27721
+ } catch (cause) {
27722
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
27723
+ }
27724
+ };
27725
+ } else {
27726
+ decodeBase64Url = (input) => {
27727
+ try {
27728
+ const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
27729
+ const bytes = new Uint8Array(binary.length);
27730
+ for (let i = 0;i < binary.length; i++) {
27731
+ bytes[i] = binary.charCodeAt(i);
27732
+ }
27733
+ return bytes;
27734
+ } catch (cause) {
27735
+ throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
27736
+ }
27737
+ };
27738
+ }
27739
+ function b64u(input) {
27740
+ if (typeof input === "string") {
27741
+ return decodeBase64Url(input);
27742
+ }
27743
+ return encodeBase64Url(input);
27744
+ }
27745
+
27746
+ class UnsupportedOperationError extends Error {
27747
+ code;
27748
+ constructor(message, options) {
27749
+ super(message, options);
27750
+ this.name = this.constructor.name;
27751
+ this.code = UNSUPPORTED_OPERATION;
27752
+ Error.captureStackTrace?.(this, this.constructor);
27753
+ }
27754
+ }
27755
+
27756
+ class OperationProcessingError extends Error {
27757
+ code;
27758
+ constructor(message, options) {
27759
+ super(message, options);
27760
+ this.name = this.constructor.name;
27172
27761
  if (options?.code) {
27173
27762
  this.code = options?.code;
27174
27763
  }
@@ -27911,6 +28500,47 @@ function checkSigningAlgorithm(client, issuer, fallback, header) {
27911
28500
  }
27912
28501
  var skipStateCheck = Symbol();
27913
28502
  var expectNoState = Symbol();
28503
+ async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
28504
+ assertAs(as);
28505
+ assertClient(client);
28506
+ const url = resolveEndpoint(as, "device_authorization_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
28507
+ const body = new URLSearchParams(parameters);
28508
+ body.set("client_id", client.client_id);
28509
+ const headers = prepareHeaders(options?.headers);
28510
+ headers.set("accept", "application/json");
28511
+ return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
28512
+ }
28513
+ async function processDeviceAuthorizationResponse(as, client, response) {
28514
+ assertAs(as);
28515
+ assertClient(client);
28516
+ if (!looseInstanceOf(response, Response)) {
28517
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
28518
+ }
28519
+ await checkOAuthBodyError(response, 200, "Device Authorization Endpoint");
28520
+ assertReadableResponse(response);
28521
+ const json = await getResponseJsonBody(response);
28522
+ assertString(json.device_code, '"response" body "device_code" property', INVALID_RESPONSE, {
28523
+ body: json
28524
+ });
28525
+ assertString(json.user_code, '"response" body "user_code" property', INVALID_RESPONSE, {
28526
+ body: json
28527
+ });
28528
+ assertString(json.verification_uri, '"response" body "verification_uri" property', INVALID_RESPONSE, { body: json });
28529
+ let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
28530
+ assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
28531
+ body: json
28532
+ });
28533
+ json.expires_in = expiresIn;
28534
+ if (json.verification_uri_complete !== undefined) {
28535
+ assertString(json.verification_uri_complete, '"response" body "verification_uri_complete" property', INVALID_RESPONSE, { body: json });
28536
+ }
28537
+ if (json.interval !== undefined) {
28538
+ assertNumber(json.interval, false, '"response" body "interval" property', INVALID_RESPONSE, {
28539
+ body: json
28540
+ });
28541
+ }
28542
+ return json;
28543
+ }
27914
28544
  async function getResponseJsonBody(response, check = assertApplicationJson) {
27915
28545
  let json;
27916
28546
  try {
@@ -27984,7 +28614,7 @@ class ClientError extends Error {
27984
28614
  Error.captureStackTrace?.(this, this.constructor);
27985
28615
  }
27986
28616
  }
27987
- var decoder2 = new TextDecoder;
28617
+ var decoder3 = new TextDecoder;
27988
28618
  function e(msg, cause, code) {
27989
28619
  return new ClientError(msg, { cause, code });
27990
28620
  }
@@ -28213,6 +28843,16 @@ function getHelpers(response) {
28213
28843
  function addHelpers(response) {
28214
28844
  Object.defineProperties(response, getHelpers(response));
28215
28845
  }
28846
+ async function initiateDeviceAuthorization(config, parameters) {
28847
+ checkConfig(config);
28848
+ const { as, c, auth, fetch: fetch2, tlsOnly, timeout } = int2(config);
28849
+ return deviceAuthorizationRequest(as, c, auth, parameters, {
28850
+ [customFetch]: fetch2,
28851
+ [allowInsecureRequests]: !tlsOnly,
28852
+ headers: new Headers(headers),
28853
+ signal: signal2(timeout)
28854
+ }).then((response) => processDeviceAuthorizationResponse(as, c, response)).catch(errorHandler);
28855
+ }
28216
28856
  function allowInsecureRequests2(config) {
28217
28857
  int2(config).tlsOnly = false;
28218
28858
  }
@@ -28300,16 +28940,48 @@ async function genericGrantRequest(config, grantType, parameters, options) {
28300
28940
  return result;
28301
28941
  }
28302
28942
 
28303
- // ../cipher-client/src/token-client.ts
28304
- var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
28305
- var BROKER_URL_SETTING = "the broker URL";
28943
+ // ../cipher-client/src/device-login-file.ts
28944
+ import { createPrivateKey, randomUUID as randomUUID3 } from "crypto";
28945
+ import { constants as constants2 } from "fs";
28946
+ import {
28947
+ access,
28948
+ lstat as lstat2,
28949
+ mkdir,
28950
+ open as open2,
28951
+ readFile as readFile2,
28952
+ readlink,
28953
+ rename as rename2,
28954
+ rm as rm2,
28955
+ stat as stat2
28956
+ } from "fs/promises";
28957
+ import { userInfo } from "os";
28958
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join6 } from "path";
28959
+
28960
+ // ../cipher-client/src/device-login-lock.ts
28961
+ import { randomUUID as randomUUID2 } from "crypto";
28962
+ import { constants } from "fs";
28963
+ import {
28964
+ link,
28965
+ lstat,
28966
+ open,
28967
+ readdir as readdir2,
28968
+ rename,
28969
+ rm,
28970
+ stat,
28971
+ utimes
28972
+ } from "fs/promises";
28973
+ import { basename as basename2, dirname as dirname2, join as join5 } from "path";
28974
+
28975
+ // ../cipher-client/src/token-client.ts
28976
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
28977
+ var BROKER_URL_SETTING = "the broker URL";
28306
28978
  var RETRY_FIRST_WAIT_MS = 15000;
28307
28979
  var RETRY_MAX_WAIT_MS = 5 * 60000;
28308
28980
  var PENDING_FIRST_WAIT_MS = 2000;
28309
28981
  var PENDING_MAX_WAIT_MS = 30000;
28310
28982
  var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
28311
28983
  var TRADE_ATTEMPT_MS = 30000;
28312
- function sleep2(ms, signal) {
28984
+ function sleep2(ms, signal, holdsProcess = false) {
28313
28985
  const { promise, resolve } = Promise.withResolvers();
28314
28986
  if (signal?.aborted) {
28315
28987
  resolve();
@@ -28321,7 +28993,8 @@ function sleep2(ms, signal) {
28321
28993
  resolve();
28322
28994
  };
28323
28995
  const timer = setTimeout(done, ms);
28324
- timer.unref();
28996
+ if (!holdsProcess)
28997
+ timer.unref();
28325
28998
  signal?.addEventListener("abort", done, { once: true });
28326
28999
  return promise;
28327
29000
  }
@@ -28330,12 +29003,24 @@ function statusOf(error) {
28330
29003
  for (let depth = 0;depth < 4; depth += 1) {
28331
29004
  if (cause instanceof Response)
28332
29005
  return cause.status;
29006
+ if (cause instanceof ResponseBodyError || cause instanceof WWWAuthenticateChallengeError) {
29007
+ return cause.status;
29008
+ }
28333
29009
  if (typeof cause !== "object" || cause === null || !("cause" in cause))
28334
29010
  return 0;
28335
29011
  cause = cause.cause;
28336
29012
  }
28337
29013
  return 0;
28338
29014
  }
29015
+ function brokerRefusal(doing, refused, endpoint, error, context = {}) {
29016
+ if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
29017
+ const description = error.error_description;
29018
+ return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", refused, context);
29019
+ }
29020
+ const status = statusOf(error);
29021
+ const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
29022
+ return new BrokerTradeFailedError(`${doing} ${refused} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
29023
+ }
28339
29024
  function requestInit(options, signal, headers) {
28340
29025
  const signals = [options.signal, signal].filter((one) => one !== undefined);
28341
29026
  return {
@@ -28346,6 +29031,24 @@ function requestInit(options, signal, headers) {
28346
29031
  ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
28347
29032
  };
28348
29033
  }
29034
+ async function sendWithProof(proved, url, options, signal) {
29035
+ const send = async () => {
29036
+ const headers = new Headers(options.headers);
29037
+ headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
29038
+ return await proved.fetch(url, requestInit(options, signal, headers));
29039
+ };
29040
+ let answer = await send();
29041
+ const given = answer.headers.get("DPoP-Nonce") ?? "";
29042
+ if (given !== "")
29043
+ proved.nonce.value = given;
29044
+ if (answer.status === 400 && given !== "") {
29045
+ const body = await answer.clone().json().catch(() => null);
29046
+ const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
29047
+ if (asked)
29048
+ answer = await send();
29049
+ }
29050
+ return answer;
29051
+ }
28349
29052
 
28350
29053
  class BrokerTokenClient {
28351
29054
  #brokerUrl;
@@ -28362,7 +29065,7 @@ class BrokerTokenClient {
28362
29065
  #log;
28363
29066
  #fetch;
28364
29067
  #random;
28365
- #nonce = "";
29068
+ #nonce = { value: "" };
28366
29069
  #held = null;
28367
29070
  #loop = null;
28368
29071
  #waiters = new Set;
@@ -28586,6 +29289,12 @@ class BrokerTokenClient {
28586
29289
  }
28587
29290
  return { kind: "busy", said: error.message };
28588
29291
  }
29292
+ if (error instanceof LockHeldError) {
29293
+ return {
29294
+ kind: "unsent",
29295
+ said: `the trade of ${this.describe()} could not be made: ${scrub(error.message)}`
29296
+ };
29297
+ }
28589
29298
  if (timedOut) {
28590
29299
  return {
28591
29300
  kind: "unanswered",
@@ -28600,118 +29309,1141 @@ class BrokerTokenClient {
28600
29309
  };
28601
29310
  }
28602
29311
  async#trade(signal) {
28603
- const subject = await this.#subject.read(signal);
29312
+ const source = this.#subject;
29313
+ if (source.spend !== undefined) {
29314
+ return await source.spend((subject) => this.#exchange(subject, signal), signal);
29315
+ }
29316
+ return await this.#exchange(await source.read(signal), signal);
29317
+ }
29318
+ async#exchange(subject, signal) {
28604
29319
  holdSecret(subject.token, heldUntil(subject.token));
28605
29320
  const form = {
28606
29321
  subject_token: subject.token,
28607
29322
  subject_token_type: subject.tokenType
28608
29323
  };
28609
- if (this.#session !== "")
28610
- form[FORM_SESSION] = this.#session;
28611
- if (this.#projects.length > 0)
28612
- form[FORM_PROJECTS] = this.#projects.join(" ");
28613
- if (!this.#launcherCredential) {
28614
- form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
29324
+ if (this.#session !== "")
29325
+ form[FORM_SESSION] = this.#session;
29326
+ if (this.#projects.length > 0)
29327
+ form[FORM_PROJECTS] = this.#projects.join(" ");
29328
+ if (!this.#launcherCredential) {
29329
+ form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
29330
+ }
29331
+ if (this.#actor !== undefined) {
29332
+ let actor;
29333
+ try {
29334
+ actor = await this.#actor.read(signal);
29335
+ } catch (error) {
29336
+ throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
29337
+ cause: error
29338
+ });
29339
+ }
29340
+ form["actor_token"] = holdSecret(actor.token, heldUntil(actor.token));
29341
+ form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
29342
+ }
29343
+ const endpoint = this.#brokerUrl + TOKEN_PATH;
29344
+ const raw = { body: undefined };
29345
+ const config = new Configuration({ issuer: this.#brokerUrl, token_endpoint: endpoint }, EXCHANGE_CLIENT_ID, {}, None2());
29346
+ allowInsecureRequests2(config);
29347
+ config[customFetch2] = (url, options) => this.#send(url, options, signal, raw);
29348
+ let answered;
29349
+ try {
29350
+ answered = await genericGrantRequest(config, GRANT_TYPE_TOKEN_EXCHANGE, form);
29351
+ } catch (error) {
29352
+ throw brokerRefusal("trade", this.#subject.describe(), endpoint, error, {
29353
+ ...this.#subject.person === undefined ? {} : { person: this.#subject.person },
29354
+ ...this.#session === "" ? {} : { session: this.#session }
29355
+ });
29356
+ }
29357
+ return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
29358
+ }
29359
+ async#send(url, options, signal, raw) {
29360
+ const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
29361
+ raw.body = await answer.clone().json().catch(() => {
29362
+ return;
29363
+ });
29364
+ return answer;
29365
+ }
29366
+ #read(endpoint, answered, raw) {
29367
+ const written = typeof raw === "object" && raw !== null && "token_type" in raw ? raw.token_type : undefined;
29368
+ const tokenType = typeof written === "string" ? written : "";
29369
+ if (tokenType.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
29370
+ throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a token_type that is not DPoP, and this grant mints DPoP-bound tokens alone`);
29371
+ }
29372
+ if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
29373
+ throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a refresh token, which this grant never issues; a renewal trades a fresh identity token instead`);
29374
+ }
29375
+ const seconds = answered.expires_in ?? 0;
29376
+ if (!(seconds > 0)) {
29377
+ throw new BrokerTradeFailedError(`the broker at ${endpoint} answered no usable expires_in (a positive number of seconds)`);
29378
+ }
29379
+ const expiresAtText = typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "";
29380
+ let credentialExpiresAt = null;
29381
+ if (expiresAtText !== "") {
29382
+ credentialExpiresAt = new Date(expiresAtText);
29383
+ if (Number.isNaN(credentialExpiresAt.getTime())) {
29384
+ throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a credential_expires_at that is no RFC 3339 time`);
29385
+ }
29386
+ }
29387
+ return {
29388
+ accessToken: holdSecret(answered.access_token, Date.now() + seconds * 1000),
29389
+ tokenType,
29390
+ expiresAt: new Date(this.#now() + seconds * 1000),
29391
+ credentialId: typeof answered["credential_id"] === "string" ? answered["credential_id"] : "",
29392
+ credentialExpiresAt
29393
+ };
29394
+ }
29395
+ }
29396
+ function heldUntil(token) {
29397
+ const now = Date.now();
29398
+ const payload = token.split(".")[1];
29399
+ if (payload === undefined)
29400
+ return now;
29401
+ try {
29402
+ const { exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
29403
+ return typeof exp === "number" && Number.isFinite(exp) ? Math.max(exp * 1000, now) : now;
29404
+ } catch {
29405
+ return now;
29406
+ }
29407
+ }
29408
+
29409
+ // ../cipher-client/src/device-login-lock.ts
29410
+ var DEVICE_LOGIN_STALE_LOCK_MS = TRADE_ATTEMPT_MS / 2;
29411
+ var LOCK_HEARTBEAT_MS = DEVICE_LOGIN_STALE_LOCK_MS / 3;
29412
+ var DEVICE_LOGIN_MOST_BYTES = 64 * 1024;
29413
+ var LOCK_READ = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY | constants.O_NOFOLLOW;
29414
+ var LOCK_RETRY_MS = 100;
29415
+ var STEAL_STALE_MS = 5000;
29416
+ async function statOrNone(path, what) {
29417
+ try {
29418
+ return await lstat(path);
29419
+ } catch (error) {
29420
+ if (readErrorCode(error) === "ENOENT")
29421
+ return null;
29422
+ throw new Error(`read ${what}: ${readErrorCode(error)}`);
29423
+ }
29424
+ }
29425
+ async function createOwn(path, value, named) {
29426
+ let handle;
29427
+ try {
29428
+ handle = await open(path, "wx", 384);
29429
+ } catch (error) {
29430
+ if (readErrorCode(error) === "EEXIST")
29431
+ return false;
29432
+ throw new Error(`take the lock beside ${named}: ${readErrorCode(error)}`);
29433
+ }
29434
+ try {
29435
+ await handle.writeFile(value);
29436
+ } finally {
29437
+ await handle.close();
29438
+ }
29439
+ return true;
29440
+ }
29441
+ async function look(path, what) {
29442
+ let handle;
29443
+ try {
29444
+ handle = await open(path, LOCK_READ);
29445
+ } catch (error) {
29446
+ if (readErrorCode(error) === "ENOENT")
29447
+ return null;
29448
+ const stats = await statOrNone(path, what);
29449
+ return stats === null ? null : { stats, value: "" };
29450
+ }
29451
+ let seen;
29452
+ try {
29453
+ const stats = await handle.stat();
29454
+ const readable = stats.isFile() && stats.size <= DEVICE_LOGIN_MOST_BYTES;
29455
+ seen = { stats, value: readable ? await handle.readFile("utf8").catch(() => "") : "" };
29456
+ } catch (error) {
29457
+ await handle.close().catch(() => {});
29458
+ throw new Error(`read ${what}: ${readErrorCode(error)}`);
29459
+ }
29460
+ await handle.close().catch((error) => {
29461
+ throw new Error(`read ${what}: ${readErrorCode(error)}`);
29462
+ });
29463
+ return seen;
29464
+ }
29465
+ function sameFile(was) {
29466
+ return (seen) => seen.stats.dev === was.stats.dev && seen.stats.ino === was.stats.ino && seen.stats.mtimeMs === was.stats.mtimeMs && seen.value === was.value;
29467
+ }
29468
+ async function removeIfStill(path, isIt, what) {
29469
+ const moved = `${path}.stale-${randomUUID2()}`;
29470
+ try {
29471
+ await rename(path, moved);
29472
+ } catch (error) {
29473
+ if (readErrorCode(error) === "ENOENT")
29474
+ return true;
29475
+ throw new Error(`move ${what} aside: ${readErrorCode(error)}`);
29476
+ }
29477
+ const took = await look(moved, what);
29478
+ const same = took !== null && isIt(took);
29479
+ if (!same)
29480
+ await link(moved, path).catch(() => {});
29481
+ await rm(moved, { force: true }).catch((error) => {
29482
+ throw new Error(`remove ${what}, moved aside: ${readErrorCode(error)}`);
29483
+ });
29484
+ return same;
29485
+ }
29486
+ async function removeOwn(path, value, what) {
29487
+ const seen = await look(path, what);
29488
+ if (seen === null || seen.value !== value)
29489
+ return;
29490
+ await removeIfStill(path, (took) => took.value === value, what);
29491
+ }
29492
+ async function takeStale(lock, mine, named, options) {
29493
+ const locked = `the lock beside ${named}`;
29494
+ const found = await statOrNone(lock, locked);
29495
+ if (found === null)
29496
+ return true;
29497
+ if (Date.now() - found.mtimeMs <= DEVICE_LOGIN_STALE_LOCK_MS)
29498
+ return false;
29499
+ await options.at?.("lock-stale");
29500
+ const steal = `${lock}.steal`;
29501
+ const stealing = `the take-over lock beside ${named}`;
29502
+ if (!await createOwn(steal, mine, named)) {
29503
+ const taking = await look(steal, stealing);
29504
+ if (taking !== null && Date.now() - taking.stats.mtimeMs > STEAL_STALE_MS) {
29505
+ await options.at?.("steal-stale");
29506
+ await removeIfStill(steal, sameFile(taking), `the dead take-over lock beside ${named}`);
29507
+ }
29508
+ return false;
29509
+ }
29510
+ try {
29511
+ const again = await look(lock, locked);
29512
+ if (again === null)
29513
+ return true;
29514
+ if (Date.now() - again.stats.mtimeMs <= DEVICE_LOGIN_STALE_LOCK_MS)
29515
+ return false;
29516
+ await options.at?.("taking");
29517
+ return await removeIfStill(lock, sameFile(again), `the stale lock beside ${named}`);
29518
+ } finally {
29519
+ await removeOwn(steal, mine, stealing);
29520
+ }
29521
+ }
29522
+ function keepReleaseFailure(failed, released) {
29523
+ if (!(failed instanceof Error))
29524
+ return;
29525
+ Reflect.defineProperty(failed, failed.cause === undefined ? "cause" : "releaseFailure", {
29526
+ value: released,
29527
+ writable: true,
29528
+ enumerable: true,
29529
+ configurable: true
29530
+ });
29531
+ }
29532
+ async function withLoginLock(path, named, work, options = {}) {
29533
+ const lock = `${path}.lock`;
29534
+ const locked = `the lock beside ${named}`;
29535
+ const mine = `${process.pid} ${randomUUID2()}
29536
+ `;
29537
+ const wait = options.sleep ?? ((ms, signal) => sleep2(ms, signal, true));
29538
+ while (true) {
29539
+ if (options.signal?.aborted === true) {
29540
+ throw new LockHeldError(locked, { cause: options.signal.reason });
29541
+ }
29542
+ if (await createOwn(lock, mine, named))
29543
+ break;
29544
+ if (await takeStale(lock, mine, named, options))
29545
+ continue;
29546
+ await wait(LOCK_RETRY_MS, options.signal);
29547
+ }
29548
+ const beat = setInterval(async () => {
29549
+ const now = new Date;
29550
+ await utimes(lock, now, now).catch(() => {});
29551
+ }, LOCK_HEARTBEAT_MS);
29552
+ beat.unref();
29553
+ let answer;
29554
+ try {
29555
+ answer = await work(async () => (await look(lock, locked))?.value === mine);
29556
+ } catch (error) {
29557
+ clearInterval(beat);
29558
+ await removeOwn(lock, mine, locked).catch((released) => keepReleaseFailure(error, released));
29559
+ throw error;
29560
+ }
29561
+ clearInterval(beat);
29562
+ await removeOwn(lock, mine, locked);
29563
+ return answer;
29564
+ }
29565
+ function namedWithUuid(name, prefix) {
29566
+ return name.startsWith(prefix) && /^[0-9a-f-]{36}$/.test(name.slice(prefix.length));
29567
+ }
29568
+ async function removeUntouched(dir, left) {
29569
+ const names = await readdir2(dir).catch(() => []);
29570
+ for (const name of names.filter(left)) {
29571
+ const path = join5(dir, name);
29572
+ const info = await stat(path).catch(() => null);
29573
+ if (info !== null && Date.now() - info.mtimeMs > DEVICE_LOGIN_STALE_LOCK_MS) {
29574
+ await rm(path, { force: true }).catch(() => {});
29575
+ }
29576
+ }
29577
+ }
29578
+ async function removeLeftLocks(path) {
29579
+ const name = basename2(path);
29580
+ await removeUntouched(dirname2(path), (one) => namedWithUuid(one, `${name}.lock.stale-`) || namedWithUuid(one, `${name}.lock.steal.stale-`));
29581
+ }
29582
+
29583
+ // ../cipher-client/src/device-login-file.ts
29584
+ var DEVICE_LOGIN_FILE_VAR = "AGENT_SECRETS_DEVICE_LOGIN_FILE";
29585
+ var DEVICE_LOGIN_FILE_NAMED = `the device login ${DEVICE_LOGIN_FILE_VAR} names (default ~/.config/legion/device-login.json)`;
29586
+ function isTemporaryCopy(name) {
29587
+ return /^\.device-login-[0-9a-f-]{36}\.json\.tmp$/.test(name);
29588
+ }
29589
+ function deviceLoginFile(env) {
29590
+ const named = (env[DEVICE_LOGIN_FILE_VAR] ?? "").trim();
29591
+ if (named !== "")
29592
+ return named;
29593
+ const home = (env["HOME"] ?? "").trim();
29594
+ if (home === "") {
29595
+ 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`);
29596
+ }
29597
+ return join6(home, ".config", "legion", "device-login.json");
29598
+ }
29599
+ function member(json, name) {
29600
+ const value = json[name];
29601
+ return typeof value === "string" ? value : "";
29602
+ }
29603
+ function checkPrivate(info, what, forbidden, opens, notOwned) {
29604
+ const mode = info.mode & 511;
29605
+ if ((mode & forbidden) !== 0) {
29606
+ throw new Error(`${what} is mode ${mode.toString(8).padStart(4, "0")}, which ${opens}`);
29607
+ }
29608
+ const uid = process.getuid?.();
29609
+ if (uid !== undefined && info.uid !== uid) {
29610
+ throw new Error(`${what} is owned by uid ${info.uid}, not this user (uid ${uid}); ${notOwned}`);
29611
+ }
29612
+ }
29613
+ var STICKY = 512;
29614
+ var INITIAL_UID_MAP = "0 0 4294967295";
29615
+ var DEFAULT_OVERFLOW_UID = 65534;
29616
+ var systemFiles = new Map;
29617
+ async function systemFile(file) {
29618
+ let info;
29619
+ try {
29620
+ info = await stat2(file);
29621
+ } catch {
29622
+ return null;
29623
+ }
29624
+ const status = [info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs].join(":");
29625
+ const kept = systemFiles.get(file);
29626
+ if (kept?.status === status)
29627
+ return kept.text;
29628
+ const text = await readFile2(file, "utf8").catch(() => null);
29629
+ if (text === null)
29630
+ systemFiles.delete(file);
29631
+ else
29632
+ systemFiles.set(file, { status, text });
29633
+ return text;
29634
+ }
29635
+ async function safeOwner(uid, mine) {
29636
+ if (uid === mine || uid === 0)
29637
+ return true;
29638
+ const map = (await systemFile("/proc/self/uid_map") ?? "").trim().split(`
29639
+ `).map((line) => line.trim().split(/\s+/).join(" "));
29640
+ if (map[0] === "" || map.length === 1 && map[0] === INITIAL_UID_MAP)
29641
+ return false;
29642
+ const named = Number.parseInt(await systemFile("/proc/sys/kernel/overflowuid") ?? "", 10);
29643
+ return uid === (Number.isNaN(named) ? DEFAULT_OVERFLOW_UID : named);
29644
+ }
29645
+ async function records(file, fields, numbers) {
29646
+ const text = await systemFile(file);
29647
+ if (text === null)
29648
+ return null;
29649
+ const read = [];
29650
+ for (const line of text.split(`
29651
+ `)) {
29652
+ if (line.trim() === "" || line.startsWith("#"))
29653
+ continue;
29654
+ const record = line.split(":");
29655
+ if (record.length < fields || /^[+-]/.test(line))
29656
+ return null;
29657
+ if (numbers.some((at) => !/^\d+$/.test(record[at] ?? "")))
29658
+ return null;
29659
+ read.push(record);
29660
+ }
29661
+ return read;
29662
+ }
29663
+ async function privateGroup(gid, mine) {
29664
+ const [users, groups] = await Promise.all([
29665
+ records("/etc/passwd", 7, [2, 3]),
29666
+ records("/etc/group", 4, [2])
29667
+ ]);
29668
+ if (users === null || groups === null)
29669
+ return false;
29670
+ const named = groups.filter((group) => Number(group[2]) === gid);
29671
+ if (named.length === 0)
29672
+ return false;
29673
+ const myNames = new Set(users.filter((user) => Number(user[2]) === mine).map((user) => user[0]));
29674
+ let members = 0;
29675
+ for (const user of users) {
29676
+ if (Number(user[3]) !== gid)
29677
+ continue;
29678
+ if (Number(user[2]) !== mine)
29679
+ return false;
29680
+ members += 1;
29681
+ }
29682
+ for (const group of named) {
29683
+ for (const name of (group[3] ?? "").split(",")) {
29684
+ if (name.trim() === "")
29685
+ continue;
29686
+ if (!myNames.has(name.trim()))
29687
+ return false;
29688
+ members += 1;
29689
+ }
29690
+ }
29691
+ return members > 0;
29692
+ }
29693
+ async function checkOnTheWay(info, what) {
29694
+ const onTheWay = `a directory on the way to ${what}`;
29695
+ const mode = info.mode & 4095;
29696
+ const shown = mode.toString(8).padStart(4, "0");
29697
+ const uid = process.getuid?.();
29698
+ if ((mode & STICKY) === 0 && (mode & 2) !== 0) {
29699
+ 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`);
29700
+ }
29701
+ if ((mode & STICKY) === 0 && (mode & 16) !== 0 && (uid === undefined || !await privateGroup(info.gid, uid))) {
29702
+ 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`);
29703
+ }
29704
+ if (uid !== undefined && !await safeOwner(info.uid, uid)) {
29705
+ 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`);
29706
+ }
29707
+ }
29708
+ async function checkLinkOnTheWay(info, what) {
29709
+ const uid = process.getuid?.();
29710
+ if (uid !== undefined && !await safeOwner(info.uid, uid)) {
29711
+ 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`);
29712
+ }
29713
+ }
29714
+ async function lstatOnTheWay(path, what) {
29715
+ try {
29716
+ return await lstat2(path);
29717
+ } catch (error) {
29718
+ if (readErrorCode(error) === "ENOENT")
29719
+ return null;
29720
+ throw refusedBy(error, `read a directory on the way to ${what}`);
29721
+ }
29722
+ }
29723
+ async function walkTheWay(path, what, meet) {
29724
+ const names = (isAbsolute2(path) ? path : `${process.cwd()}/${path}`).split("/");
29725
+ let reached = "/";
29726
+ let info = await lstatOnTheWay(reached, what);
29727
+ let followed = 0;
29728
+ for (let name = names.shift();name !== undefined; name = names.shift()) {
29729
+ if (info === null)
29730
+ return null;
29731
+ if (name === "" || name === ".")
29732
+ continue;
29733
+ if (name === "..") {
29734
+ reached = dirname3(reached);
29735
+ info = await lstatOnTheWay(reached, what);
29736
+ continue;
29737
+ }
29738
+ await meet?.directory(reached, info);
29739
+ const next = reached === "/" ? `/${name}` : `${reached}/${name}`;
29740
+ const here = await lstatOnTheWay(next, what);
29741
+ if (here === null || !here.isSymbolicLink()) {
29742
+ reached = next;
29743
+ info = here;
29744
+ continue;
29745
+ }
29746
+ await meet?.link(reached, here);
29747
+ followed += 1;
29748
+ if (followed > LINKS_FOLLOWED_AT_MOST)
29749
+ throw notARegularFile("a loop of links");
29750
+ let target;
29751
+ try {
29752
+ target = await readlink(next);
29753
+ } catch (error) {
29754
+ const code = readErrorCode(error);
29755
+ if (code !== "EINVAL" && code !== "ENOENT") {
29756
+ throw refusedBy(error, `read a directory on the way to ${what}`);
29757
+ }
29758
+ names.unshift(name);
29759
+ continue;
29760
+ }
29761
+ names.unshift(...target.split("/"));
29762
+ if (isAbsolute2(target)) {
29763
+ reached = "/";
29764
+ info = await lstatOnTheWay(reached, what);
29765
+ }
29766
+ }
29767
+ return info === null ? null : reached;
29768
+ }
29769
+ async function homeReached() {
29770
+ const uid = process.getuid?.();
29771
+ const passwd = await records("/etc/passwd", 7, [2, 3]);
29772
+ let home = passwd?.find((user) => Number(user[2]) === uid)?.[5];
29773
+ if (home === undefined) {
29774
+ try {
29775
+ home = userInfo().homedir;
29776
+ } catch {
29777
+ return null;
29778
+ }
29779
+ }
29780
+ if (!isAbsolute2(home))
29781
+ return null;
29782
+ return await walkTheWay(home, "the home directory").catch(() => null);
29783
+ }
29784
+ async function checkDirectoriesOnTheWay(dir, what) {
29785
+ const home = await homeReached();
29786
+ const aboveHome = (at) => home !== null && home !== at && (at === "/" || home.startsWith(`${at}/`));
29787
+ await walkTheWay(dir, what, {
29788
+ directory: async (at, info) => {
29789
+ if (!aboveHome(at))
29790
+ await checkOnTheWay(info, what);
29791
+ },
29792
+ link: async (inside, info) => {
29793
+ if (!aboveHome(inside))
29794
+ await checkLinkOnTheWay(info, what);
29795
+ }
29796
+ });
29797
+ }
29798
+ async function checkLoginDirectory(dir, absent, what = `the directory of ${DEVICE_LOGIN_FILE_NAMED}`) {
29799
+ let info;
29800
+ try {
29801
+ info = await stat2(dir);
29802
+ } catch (error) {
29803
+ if (absent !== undefined && readErrorCode(error) === "ENOENT")
29804
+ throw absent();
29805
+ throw refusedBy(error, `read ${what}`);
29806
+ }
29807
+ 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");
29808
+ await checkDirectoriesOnTheWay(dir, what);
29809
+ }
29810
+ function notARegularFile(there) {
29811
+ 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";
29812
+ 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`);
29813
+ }
29814
+ function refusedBy(error, doing) {
29815
+ const code = readErrorCode(error);
29816
+ if (code === "ENXIO")
29817
+ return notARegularFile("a socket or a device");
29818
+ if (code === "ELOOP")
29819
+ return notARegularFile("a loop of links");
29820
+ if (code === "ENOTDIR") {
29821
+ 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`);
29822
+ }
29823
+ return new Error(`${doing}: ${code}`);
29824
+ }
29825
+ async function deviceLoginDirectory(path) {
29826
+ const dir = dirname3(path);
29827
+ try {
29828
+ await mkdir(dir, { recursive: true, mode: 448 });
29829
+ } catch (error) {
29830
+ throw refusedBy(error, `make the directory of ${DEVICE_LOGIN_FILE_NAMED}`);
29831
+ }
29832
+ await checkLoginDirectory(dir);
29833
+ }
29834
+ async function deviceLoginPlace(path) {
29835
+ await deviceLoginDirectory(path);
29836
+ const dir = dirname3(path);
29837
+ try {
29838
+ await access(dir, constants2.W_OK | constants2.X_OK);
29839
+ } catch (error) {
29840
+ const code = readErrorCode(error);
29841
+ 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" : ""}`);
29842
+ }
29843
+ let info;
29844
+ try {
29845
+ info = await stat2(path);
29846
+ } catch (error) {
29847
+ if (readErrorCode(error) === "ENOENT")
29848
+ return;
29849
+ throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
29850
+ }
29851
+ if (!info.isFile())
29852
+ throw notARegularFile(info);
29853
+ }
29854
+ var LOGIN_READ = constants2.O_RDONLY | constants2.O_NONBLOCK | constants2.O_NOCTTY;
29855
+ var LINKS_FOLLOWED_AT_MOST = 40;
29856
+ async function checkLinkDirectories(path, absent) {
29857
+ let checked = dirname3(path);
29858
+ let at = path;
29859
+ for (let followed = 0;; followed += 1) {
29860
+ if (dirname3(at) !== checked) {
29861
+ checked = dirname3(at);
29862
+ await checkLoginDirectory(checked, absent, `the directory of a file ${DEVICE_LOGIN_FILE_NAMED} links to`);
29863
+ }
29864
+ let info;
29865
+ try {
29866
+ info = await lstat2(at);
29867
+ } catch (error) {
29868
+ if (readErrorCode(error) === "ENOENT")
29869
+ return;
29870
+ throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
29871
+ }
29872
+ if (!info.isSymbolicLink())
29873
+ return;
29874
+ if (followed === LINKS_FOLLOWED_AT_MOST)
29875
+ throw notARegularFile("a loop of links");
29876
+ let target;
29877
+ try {
29878
+ target = await readlink(at);
29879
+ } catch (error) {
29880
+ const code = readErrorCode(error);
29881
+ if (code === "EINVAL" || code === "ENOENT")
29882
+ return;
29883
+ throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
29884
+ }
29885
+ at = isAbsolute2(target) ? target : `${dirname3(at)}/${target}`;
29886
+ }
29887
+ }
29888
+ async function readDeviceLogin(path) {
29889
+ 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}`);
29890
+ const failed = (error) => new Error(`read ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
29891
+ await checkLoginDirectory(dirname3(path), absent);
29892
+ await checkLinkDirectories(path, absent);
29893
+ let handle;
29894
+ try {
29895
+ handle = await open2(path, LOGIN_READ);
29896
+ } catch (error) {
29897
+ throw readErrorCode(error) === "ENOENT" ? absent() : refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
29898
+ }
29899
+ let data;
29900
+ try {
29901
+ const info = await handle.stat().catch((error) => {
29902
+ throw failed(error);
29903
+ });
29904
+ if (!info.isFile())
29905
+ throw notARegularFile(info);
29906
+ 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}`);
29907
+ if (info.size > DEVICE_LOGIN_MOST_BYTES) {
29908
+ 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}`);
29909
+ }
29910
+ data = await handle.readFile("utf8").catch((error) => {
29911
+ throw failed(error);
29912
+ });
29913
+ } catch (error) {
29914
+ await handle.close().catch(() => {});
29915
+ throw error;
29916
+ }
29917
+ await handle.close().catch((error) => {
29918
+ throw failed(error);
29919
+ });
29920
+ let json;
29921
+ try {
29922
+ const parsed = JSON.parse(data);
29923
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
29924
+ throw new Error;
29925
+ json = parsed;
29926
+ } catch {
29927
+ 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`);
29928
+ }
29929
+ const credentialId = member(json, "credential_id");
29930
+ const refreshToken = member(json, "refresh_token");
29931
+ const broker = member(json, "broker");
29932
+ const expiresAt = new Date(member(json, "expires_at"));
29933
+ if (credentialId === "" || refreshToken === "" || broker === "" || Number.isNaN(expiresAt.getTime())) {
29934
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: credential_id, refresh_token, broker and an RFC 3339 expires_at are all required`);
29935
+ }
29936
+ let key;
29937
+ try {
29938
+ key = createPrivateKey({
29939
+ key: Buffer.from(member(json, "key"), "base64"),
29940
+ format: "der",
29941
+ type: "pkcs8"
29942
+ });
29943
+ } catch {
29944
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a base64 PKCS#8 key`);
29945
+ }
29946
+ if (key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
29947
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a P-256 key`);
29948
+ }
29949
+ const accessToken = member(json, "access_token");
29950
+ const accessText = member(json, "access_expires_at");
29951
+ const accessExpiresAt = accessToken === "" || accessText === "" ? null : new Date(accessText);
29952
+ const accessUsable = accessExpiresAt !== null && !Number.isNaN(accessExpiresAt.getTime());
29953
+ return {
29954
+ key,
29955
+ credentialId,
29956
+ refreshToken: holdSecret(refreshToken, expiresAt),
29957
+ expiresAt,
29958
+ broker,
29959
+ accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
29960
+ accessExpiresAt: accessUsable ? accessExpiresAt : null
29961
+ };
29962
+ }
29963
+ function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
29964
+ 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}`);
29965
+ }
29966
+
29967
+ class KeptCopyError extends Error {
29968
+ suffix;
29969
+ constructor(suffix, failed) {
29970
+ 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`);
29971
+ this.suffix = suffix;
29972
+ }
29973
+ }
29974
+ async function keptCopy(temp, path, error) {
29975
+ const suffix = `.kept-${randomUUID3()}`;
29976
+ try {
29977
+ await rename2(temp, `${path}${suffix}`);
29978
+ } catch {
29979
+ return error;
29980
+ }
29981
+ return new KeptCopyError(suffix, error);
29982
+ }
29983
+ async function saveDeviceLogin(path, login, held, keep = false) {
29984
+ const dir = dirname3(path);
29985
+ const data = JSON.stringify({
29986
+ key: login.key.export({ format: "der", type: "pkcs8" }).toString("base64"),
29987
+ credential_id: login.credentialId,
29988
+ refresh_token: login.refreshToken,
29989
+ expires_at: login.expiresAt.toISOString(),
29990
+ broker: login.broker,
29991
+ ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
29992
+ access_token: login.accessToken,
29993
+ access_expires_at: login.accessExpiresAt.toISOString()
29994
+ }
29995
+ });
29996
+ await deviceLoginPlace(path);
29997
+ await removeUntouched(dir, isTemporaryCopy);
29998
+ await removeLeftLocks(path);
29999
+ const temp = join6(dir, `.device-login-${randomUUID3()}.json.tmp`);
30000
+ const saveFailed = (error) => new Error(`save ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
30001
+ let whole = false;
30002
+ try {
30003
+ try {
30004
+ const handle = await open2(temp, "wx", 384);
30005
+ try {
30006
+ await handle.writeFile(data);
30007
+ await handle.sync();
30008
+ } finally {
30009
+ await handle.close();
30010
+ }
30011
+ } catch (error) {
30012
+ throw saveFailed(error);
30013
+ }
30014
+ whole = true;
30015
+ if (!await held())
30016
+ throw keep ? lockLost("the new login was not kept in its place") : lockLost();
30017
+ await rename2(temp, path).catch((error) => {
30018
+ throw saveFailed(error);
30019
+ });
30020
+ } catch (error) {
30021
+ throw keep && whole ? await keptCopy(temp, path, error) : error;
30022
+ } finally {
30023
+ await rm2(temp, { force: true }).catch(() => {});
30024
+ }
30025
+ try {
30026
+ const handle = await open2(dir, "r");
30027
+ try {
30028
+ await handle.sync();
30029
+ } finally {
30030
+ await handle.close();
30031
+ }
30032
+ } catch {}
30033
+ }
30034
+
30035
+ // ../cipher-client/src/dpop.ts
30036
+ import {
30037
+ createHash,
30038
+ createPrivateKey as createPrivateKey2,
30039
+ createPublicKey,
30040
+ generateKeyPairSync,
30041
+ randomUUID as randomUUID4,
30042
+ sign as sign2
30043
+ } from "crypto";
30044
+ var ALGORITHM = "ES256";
30045
+ var CONNECTION_PROOF_METHOD = "CONNECT";
30046
+ var CONNECTION_PROOF_TARGET = "nats:connect";
30047
+ function targetUri(url) {
30048
+ const parsed = new URL(url);
30049
+ parsed.search = "";
30050
+ parsed.hash = "";
30051
+ return parsed.toString();
30052
+ }
30053
+ function dpopKey(privateKey, publicJwk) {
30054
+ const header = Buffer.from(JSON.stringify({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk })).toString("base64url");
30055
+ const signed = (htm, htu, nonce, accessToken) => {
30056
+ const claims = {
30057
+ jti: randomUUID4(),
30058
+ htm,
30059
+ htu,
30060
+ iat: Math.floor(Date.now() / 1000)
30061
+ };
30062
+ if (nonce !== undefined && nonce !== "")
30063
+ claims["nonce"] = nonce;
30064
+ if (accessToken !== undefined && accessToken !== "") {
30065
+ claims["ath"] = createHash("sha256").update(accessToken).digest("base64url");
28615
30066
  }
28616
- if (this.#actor !== undefined) {
28617
- let actor;
28618
- try {
28619
- actor = await this.#actor.read(signal);
28620
- } catch (error) {
28621
- throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
28622
- cause: error
28623
- });
28624
- }
28625
- form["actor_token"] = holdSecret(actor.token, heldUntil(actor.token));
28626
- form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
30067
+ const signingInput = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
30068
+ const signature = sign2("sha256", Buffer.from(signingInput), {
30069
+ key: privateKey,
30070
+ dsaEncoding: "ieee-p1363"
30071
+ });
30072
+ return `${signingInput}.${signature.toString("base64url")}`;
30073
+ };
30074
+ return {
30075
+ publicJwk,
30076
+ async proof(request) {
30077
+ return signed(request.method.toUpperCase(), targetUri(request.url), request.nonce, request.accessToken);
30078
+ },
30079
+ connectionProof({ accessToken, nonce }) {
30080
+ if (accessToken === "")
30081
+ throw new Error("no access token to prove a NATS connection for");
30082
+ if (nonce === "")
30083
+ throw new Error("the NATS server sent no nonce to sign");
30084
+ return signed(CONNECTION_PROOF_METHOD, CONNECTION_PROOF_TARGET, nonce, accessToken);
28627
30085
  }
28628
- const endpoint = this.#brokerUrl + TOKEN_PATH;
28629
- const raw = { body: undefined };
28630
- const config = new Configuration({ issuer: this.#brokerUrl, token_endpoint: endpoint }, EXCHANGE_CLIENT_ID, {}, None2());
30086
+ };
30087
+ }
30088
+ function publicJwkOf(privateKey, name) {
30089
+ const { kty, crv, x, y } = createPublicKey(privateKey).export({ format: "jwk" });
30090
+ if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
30091
+ throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
30092
+ }
30093
+ return { kty, crv, x, y };
30094
+ }
30095
+ async function newDpopKey() {
30096
+ const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
30097
+ return dpopKeyOf(privateKey, "this process's key");
30098
+ }
30099
+ function dpopKeyOf(privateKey, name) {
30100
+ return dpopKey(privateKey, publicJwkOf(privateKey, name));
30101
+ }
30102
+ async function importDpopKey(pkcs8Pem, name) {
30103
+ let privateKey;
30104
+ try {
30105
+ privateKey = createPrivateKey2(pkcs8Pem);
30106
+ } catch {
30107
+ throw new Error(`read ${name}: it does not parse as a PKCS#8 PEM private key`);
30108
+ }
30109
+ return dpopKey(privateKey, publicJwkOf(privateKey, name));
30110
+ }
30111
+
30112
+ // ../cipher-client/src/device-login.ts
30113
+ var BROKER_SETTING = "AGENT_SECRETS_URL";
30114
+ var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
30115
+ var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
30116
+ var DEFAULT_POLL_SECONDS = 5;
30117
+ var LEAST_POLL_SECONDS = 1;
30118
+ var MOST_POLL_SECONDS = 60;
30119
+ var MOST_LIFETIME_SECONDS = 3600;
30120
+ var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
30121
+ var UNPRINTABLE = /[\p{Cc}\p{Cf}]/u;
30122
+ function deviceLoginSessionName(thumbprint) {
30123
+ return `device-login-${thumbprint.slice(0, 12)}`;
30124
+ }
30125
+ function deviceLoginHost(name) {
30126
+ const labels = name.trim().toLowerCase().replace(/[^a-z0-9.-]+/g, "-").split(".").map((label) => label.replace(/^-+/, "").slice(0, 63).replace(/-+$/, "")).filter((label) => label !== "");
30127
+ const host = labels.join(".").slice(0, 253).replace(/[.-]+$/, "");
30128
+ return host === "" ? "device" : host;
30129
+ }
30130
+ function deviceLoginBroker(brokerUrl) {
30131
+ const trimmed = withoutTrailingSlashes(brokerUrl.trim());
30132
+ if (!isHttpUrl(trimmed))
30133
+ throw new Error(`${BROKER_SETTING} is not an http or https URL`);
30134
+ const { protocol, hostname } = new URL(trimmed);
30135
+ if (protocol === "http:" && !LOOPBACK_HOST.test(hostname)) {
30136
+ 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`);
30137
+ }
30138
+ return holdUrlUserinfo(trimmed);
30139
+ }
30140
+ function loginDpopKey(key) {
30141
+ return dpopKeyOf(key, "this machine's device login key");
30142
+ }
30143
+ function printable(value, what, endpoint) {
30144
+ if (UNPRINTABLE.test(value)) {
30145
+ 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`);
30146
+ }
30147
+ return value;
30148
+ }
30149
+ function page(uri, endpoint) {
30150
+ if (!isHttpUrl(uri)) {
30151
+ 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`);
30152
+ }
30153
+ return printable(uri, "page to type the code in", endpoint);
30154
+ }
30155
+ async function withDeviceLoginLock(path, work, options = {}) {
30156
+ await deviceLoginDirectory(path);
30157
+ return await withLoginLock(path, DEVICE_LOGIN_FILE_NAMED, work, options);
30158
+ }
30159
+ function brokerConfiguration(brokerUrl, fetchImpl, proved) {
30160
+ const config = new Configuration({
30161
+ issuer: brokerUrl,
30162
+ token_endpoint: brokerUrl + TOKEN_PATH,
30163
+ device_authorization_endpoint: brokerUrl + DEVICE_AUTHORIZATION_PATH
30164
+ }, MACHINE_LOGIN_CLIENT_ID, {}, None2());
30165
+ if (new URL(brokerUrl).protocol === "http:")
28631
30166
  allowInsecureRequests2(config);
28632
- config[customFetch2] = (url, options) => this.#send(url, options, signal, raw);
30167
+ config[customFetch2] = (url, options) => {
30168
+ const deadline = AbortSignal.timeout(BROKER_REQUEST_MS);
30169
+ return proved === undefined ? fetchImpl(url, requestInit(options, deadline, options.headers)) : sendWithProof({ key: proved.key, fetch: fetchImpl, nonce: proved.nonce }, url, options, deadline);
30170
+ };
30171
+ return config;
30172
+ }
30173
+ function loginOf(key, broker, answered, now) {
30174
+ const endpoint = broker + TOKEN_PATH;
30175
+ const credentialId = typeof answered["credential_id"] === "string" ? answered["credential_id"] : "";
30176
+ const expiresAt = new Date(typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "");
30177
+ const refreshToken = answered.refresh_token ?? "";
30178
+ const seconds = Math.min(answered.expires_in ?? 0, MOST_LIFETIME_SECONDS);
30179
+ if (credentialId === "" || Number.isNaN(expiresAt.getTime()) || refreshToken === "" || !(seconds > 0) || answered.token_type.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
30180
+ 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`);
30181
+ }
30182
+ const accessExpiresAt = new Date(now + seconds * 1000);
30183
+ return {
30184
+ key,
30185
+ credentialId: printable(credentialId, "credential_id", endpoint),
30186
+ refreshToken: holdSecret(refreshToken, expiresAt),
30187
+ expiresAt,
30188
+ broker,
30189
+ accessToken: holdSecret(answered.access_token, accessExpiresAt),
30190
+ accessExpiresAt
30191
+ };
30192
+ }
30193
+ async function startDeviceLogin(options) {
30194
+ const brokerUrl = deviceLoginBroker(options.brokerUrl);
30195
+ const endpoint = brokerUrl + DEVICE_AUTHORIZATION_PATH;
30196
+ const person = options.person.trim();
30197
+ const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
30198
+ const jwk = loginDpopKey(privateKey).publicJwk;
30199
+ const thumbprint = await calculateJwkThumbprint(jwk);
30200
+ const iat = Math.floor(Date.now() / 1000);
30201
+ const claims = {
30202
+ iss: thumbprint,
30203
+ aud: brokerUrl,
30204
+ jti: randomUUID5(),
30205
+ iat,
30206
+ exp: iat + REQUEST_OBJECT_LIFETIME_SECONDS,
30207
+ authorization_details: [{ type: LAUNCHER_CREDENTIAL_DETAIL, identifier: options.host }],
30208
+ login_hint: person
30209
+ };
30210
+ const request = await new CompactSign(new TextEncoder().encode(JSON.stringify(claims))).setProtectedHeader({ alg: "ES256", typ: REQUEST_OBJECT_TYPE, jwk }).sign(privateKey);
30211
+ const config = brokerConfiguration(brokerUrl, options.fetch ?? fetch);
30212
+ let answered;
30213
+ try {
30214
+ answered = await initiateDeviceAuthorization(config, {
30215
+ scope: MACHINE_LOGIN_SCOPE,
30216
+ dpop_jkt: thumbprint,
30217
+ request
30218
+ });
30219
+ } catch (error) {
30220
+ throw brokerRefusal("ask for a code for", "this machine's device login", endpoint, error);
30221
+ }
30222
+ const expiresAt = new Date(Date.now() + Math.min(answered.expires_in, MOST_LIFETIME_SECONDS) * 1000);
30223
+ return {
30224
+ brokerUrl,
30225
+ person,
30226
+ userCode: printable(answered.user_code, "user code", endpoint),
30227
+ verificationUri: page(answered.verification_uri, endpoint),
30228
+ verificationUriComplete: answered.verification_uri_complete === undefined ? undefined : page(answered.verification_uri_complete, endpoint),
30229
+ expiresAt,
30230
+ intervalSeconds: Math.min(Math.max(answered.interval ?? DEFAULT_POLL_SECONDS, LEAST_POLL_SECONDS), MOST_POLL_SECONDS),
30231
+ deviceCode: holdSecret(answered.device_code, expiresAt),
30232
+ key: privateKey
30233
+ };
30234
+ }
30235
+ async function finishDeviceLogin(started, options) {
30236
+ const wait = options.sleep ?? ((ms) => sleep2(ms, undefined, true));
30237
+ const config = brokerConfiguration(started.brokerUrl, options.fetch ?? fetch, {
30238
+ key: loginDpopKey(started.key),
30239
+ nonce: { value: "" }
30240
+ });
30241
+ const endpoint = started.brokerUrl + TOKEN_PATH;
30242
+ const expired = new Error(`the code ${started.userCode} expired before ${started.person} approved this machine; ask again with: ${DEVICE_LOGIN_COMMAND}`);
30243
+ let interval = started.intervalSeconds;
30244
+ while (true) {
30245
+ if (Date.now() >= started.expiresAt.getTime())
30246
+ throw expired;
30247
+ await wait(interval * 1000);
28633
30248
  let answered;
28634
30249
  try {
28635
- answered = await genericGrantRequest(config, GRANT_TYPE_TOKEN_EXCHANGE, form);
30250
+ answered = await genericGrantRequest(config, GRANT_TYPE_DEVICE_CODE, {
30251
+ device_code: started.deviceCode
30252
+ });
28636
30253
  } catch (error) {
28637
- throw this.#refusal(endpoint, error);
30254
+ const code = error instanceof ResponseBodyError ? error.error : "";
30255
+ if (code === "access_denied") {
30256
+ throw new Error(`this machine's device login was denied, not approved as ${started.person}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
30257
+ }
30258
+ if (code === "expired_token" || code === "invalid_grant")
30259
+ throw expired;
30260
+ if (code === "slow_down")
30261
+ interval += 5;
30262
+ const status = statusOf(error);
30263
+ const pollAgain = code === "authorization_pending" || code === "slow_down" || status === 0 || status === 429 || status >= 500;
30264
+ if (!pollAgain) {
30265
+ const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
30266
+ throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
30267
+ }
30268
+ continue;
28638
30269
  }
28639
- return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
28640
- }
28641
- #refusal(endpoint, error) {
28642
- if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
28643
- const description = error.error_description;
28644
- return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", this.#subject.describe(), {
28645
- ...this.#subject.person === undefined ? {} : { person: this.#subject.person },
28646
- ...this.#session === "" ? {} : { session: this.#session }
30270
+ const login = loginOf(started.key, started.brokerUrl, answered, Date.now());
30271
+ let replaced = "";
30272
+ let saved = false;
30273
+ try {
30274
+ await withDeviceLoginLock(options.path, async (held) => {
30275
+ replaced = await readDeviceLogin(options.path).then((kept) => kept.credentialId, () => "");
30276
+ await saveDeviceLogin(options.path, login, held, true);
30277
+ saved = true;
28647
30278
  });
30279
+ } catch (error) {
30280
+ if (saved) {
30281
+ 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`;
30282
+ return { ...login, replaced, lockLeft };
30283
+ }
30284
+ const revoke = `Machine logins on ${started.verificationUri}`;
30285
+ 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 });
28648
30286
  }
28649
- const status = statusOf(error);
28650
- const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
28651
- return new BrokerTradeFailedError(`trade ${this.#subject.describe()} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
30287
+ return { ...login, replaced, lockLeft: "" };
28652
30288
  }
28653
- async#send(url, options, signal, raw) {
28654
- const send = async () => {
28655
- const headers = new Headers(options.headers);
28656
- headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
28657
- return await this.#fetch(url, requestInit(options, signal, headers));
28658
- };
28659
- let answer = await send();
28660
- const given = answer.headers.get("DPoP-Nonce") ?? "";
28661
- if (given !== "")
28662
- this.#nonce = given;
28663
- if (answer.status === 400 && given !== "") {
28664
- const body = await answer.clone().json().catch(() => null);
28665
- const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
28666
- if (asked)
28667
- answer = await send();
28668
- }
28669
- raw.body = await answer.clone().json().catch(() => {
28670
- return;
28671
- });
28672
- return answer;
30289
+ }
30290
+
30291
+ class DeviceLoginIdentity {
30292
+ #path;
30293
+ #brokerUrl;
30294
+ #key;
30295
+ constructor(options) {
30296
+ this.#path = options.path;
30297
+ this.#brokerUrl = deviceLoginBroker(options.brokerUrl);
28673
30298
  }
28674
- #read(endpoint, answered, raw) {
28675
- const written = typeof raw === "object" && raw !== null && "token_type" in raw ? raw.token_type : undefined;
28676
- const tokenType = typeof written === "string" ? written : "";
28677
- if (tokenType.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
28678
- throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a token_type that is not DPoP, and this grant mints DPoP-bound tokens alone`);
28679
- }
28680
- if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
28681
- throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a refresh token, which this grant never issues; a renewal trades a fresh identity token instead`);
28682
- }
28683
- const seconds = answered.expires_in ?? 0;
28684
- if (!(seconds > 0)) {
28685
- throw new BrokerTradeFailedError(`the broker at ${endpoint} answered no usable expires_in (a positive number of seconds)`);
30299
+ describe() {
30300
+ return `this machine's device login (${DEVICE_LOGIN_FILE_NAMED})`;
30301
+ }
30302
+ async key() {
30303
+ return (await this.#loaded()).key;
30304
+ }
30305
+ async thumbprint() {
30306
+ return (await this.#loaded()).thumbprint;
30307
+ }
30308
+ #loaded() {
30309
+ if (this.#key === undefined) {
30310
+ const loading = readDeviceLogin(this.#path).then(async ({ key }) => {
30311
+ const dpop = loginDpopKey(key);
30312
+ return { key: dpop, thumbprint: await calculateJwkThumbprint(dpop.publicJwk) };
30313
+ });
30314
+ this.#key = loading;
30315
+ loading.catch(() => {
30316
+ if (this.#key === loading)
30317
+ this.#key = undefined;
30318
+ });
28686
30319
  }
28687
- const expiresAtText = typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "";
28688
- let credentialExpiresAt = null;
28689
- if (expiresAtText !== "") {
28690
- credentialExpiresAt = new Date(expiresAtText);
28691
- if (Number.isNaN(credentialExpiresAt.getTime())) {
28692
- throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a credential_expires_at that is no RFC 3339 time`);
30320
+ return this.#key;
30321
+ }
30322
+ async spend(trade, signal) {
30323
+ const { thumbprint } = await this.#loaded();
30324
+ return await withDeviceLoginLock(this.#path, async (held) => {
30325
+ let login = await readDeviceLogin(this.#path);
30326
+ if (withoutTrailingSlashes(login.broker) !== this.#brokerUrl) {
30327
+ 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}`);
30328
+ }
30329
+ if (await calculateJwkThumbprint(loginDpopKey(login.key).publicJwk) !== thumbprint) {
30330
+ 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`);
30331
+ }
30332
+ const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
30333
+ const expires = login.accessExpiresAt?.getTime() ?? 0;
30334
+ let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
30335
+ if (refreshed)
30336
+ login = await refresh();
30337
+ while (true) {
30338
+ try {
30339
+ return await trade({ token: login.accessToken, tokenType: SUBJECT_TYPE_ACCESS });
30340
+ } catch (error) {
30341
+ if (!(error instanceof BrokerRefusedError) || !error.subjectNotHonoured)
30342
+ throw error;
30343
+ if (!await held())
30344
+ throw lockLost();
30345
+ if (refreshed)
30346
+ throw error;
30347
+ login = await refresh();
30348
+ refreshed = true;
30349
+ }
28693
30350
  }
28694
- }
28695
- return {
28696
- accessToken: holdSecret(answered.access_token, Date.now() + seconds * 1000),
28697
- tokenType,
28698
- expiresAt: new Date(this.#now() + seconds * 1000),
28699
- credentialId: typeof answered["credential_id"] === "string" ? answered["credential_id"] : "",
28700
- credentialExpiresAt
28701
- };
30351
+ }, { signal });
30352
+ }
30353
+ async read(signal) {
30354
+ return await this.spend(async (subject) => subject, signal);
28702
30355
  }
28703
30356
  }
28704
- function heldUntil(token) {
28705
- const now = Date.now();
28706
- const payload = token.split(".")[1];
28707
- if (payload === undefined)
28708
- return now;
28709
- try {
28710
- const { exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
28711
- return typeof exp === "number" && Number.isFinite(exp) ? Math.max(exp * 1000, now) : now;
28712
- } catch {
28713
- return now;
30357
+ async function refreshDeviceLogin(path, login, options) {
30358
+ const config = brokerConfiguration(login.broker, fetch, {
30359
+ key: loginDpopKey(login.key),
30360
+ nonce: { value: "" }
30361
+ });
30362
+ const endpoint = login.broker + TOKEN_PATH;
30363
+ let answered;
30364
+ for (let sent = 0;answered === undefined; sent += 1) {
30365
+ if (!await options.held())
30366
+ throw lockLost();
30367
+ try {
30368
+ answered = await genericGrantRequest(config, GRANT_TYPE_REFRESH, {
30369
+ refresh_token: login.refreshToken
30370
+ });
30371
+ } catch (error) {
30372
+ if (error instanceof ResponseBodyError && error.error === "invalid_grant") {
30373
+ throw new DeviceLoginEndedError(options.describe);
30374
+ }
30375
+ if (sent === 0 && statusOf(error) === 0)
30376
+ continue;
30377
+ throw brokerRefusal("refresh", options.describe, endpoint, error);
30378
+ }
28714
30379
  }
30380
+ const next = loginOf(login.key, login.broker, answered, Date.now());
30381
+ await saveDeviceLogin(path, next, options.held);
30382
+ return next;
30383
+ }
30384
+
30385
+ // ../cipher-client/src/metadata-identity.ts
30386
+ import { Agent, request } from "http";
30387
+ var METADATA_HOST_VAR = "GCE_METADATA_HOST";
30388
+ var DEFAULT_METADATA_HOST = "metadata.google.internal";
30389
+ var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
30390
+ var TIMEOUT_MS = 1e4;
30391
+ var MAX_ANSWER_BYTES = 1 << 20;
30392
+ var agent = new Agent({ keepAlive: false });
30393
+ function tokenUrl(audience, env) {
30394
+ const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
30395
+ return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
30396
+ }
30397
+ function serverNamed(env) {
30398
+ return (env[METADATA_HOST_VAR] ?? "").trim() === "" ? `at ${DEFAULT_METADATA_HOST}` : `${METADATA_HOST_VAR} names`;
30399
+ }
30400
+ function get(url, signal, lookup) {
30401
+ const { promise, resolve, reject } = Promise.withResolvers();
30402
+ const call = request(url, {
30403
+ agent,
30404
+ method: "GET",
30405
+ headers: { "Metadata-Flavor": "Google" },
30406
+ timeout: TIMEOUT_MS,
30407
+ ...signal === undefined ? {} : { signal },
30408
+ ...lookup === undefined ? {} : { lookup }
30409
+ }, (answer) => {
30410
+ const chunks = [];
30411
+ let read = 0;
30412
+ answer.on("data", (chunk) => {
30413
+ read += chunk.length;
30414
+ if (read <= MAX_ANSWER_BYTES)
30415
+ chunks.push(chunk);
30416
+ });
30417
+ answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
30418
+ answer.on("error", reject);
30419
+ });
30420
+ call.on("timeout", () => call.destroy(Object.assign(new Error(`no answer within ${TIMEOUT_MS} ms`), { code: "ETIMEDOUT" })));
30421
+ call.on("error", reject);
30422
+ call.end();
30423
+ return promise;
30424
+ }
30425
+ function metadataIdentity(audience, env = process.env, options = {}) {
30426
+ return {
30427
+ async read(signal) {
30428
+ const url = tokenUrl(audience, env);
30429
+ const named = `the metadata server ${serverNamed(env)}`;
30430
+ let answer;
30431
+ try {
30432
+ answer = await get(url, signal, options.lookup);
30433
+ } catch (error) {
30434
+ throw new Error(`${named} could not be reached: ${errorClass(error)}`);
30435
+ }
30436
+ if (answer.status < 200 || answer.status > 299) {
30437
+ throw new Error(`${named} answered HTTP ${answer.status}`);
30438
+ }
30439
+ const token = answer.body.trim();
30440
+ if (token === "") {
30441
+ throw new Error(`${named} answered an empty identity token`);
30442
+ }
30443
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
30444
+ },
30445
+ describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
30446
+ };
28715
30447
  }
28716
30448
 
28717
30449
  // ../cipher-client/src/person-identity.ts
@@ -28928,14 +30660,14 @@ function poolIdentity(options) {
28928
30660
  }
28929
30661
 
28930
30662
  // ../cipher-client/src/projected-token.ts
28931
- import { readFile as readFile2 } from "fs/promises";
30663
+ import { readFile as readFile3 } from "fs/promises";
28932
30664
  function projectedToken(path, variable) {
28933
30665
  const named = `the projected service-account token ${variable} names`;
28934
30666
  return {
28935
30667
  async read(signal) {
28936
30668
  let contents;
28937
30669
  try {
28938
- contents = await readFile2(path, {
30670
+ contents = await readFile3(path, {
28939
30671
  encoding: "utf8",
28940
30672
  ...signal === undefined ? {} : { signal }
28941
30673
  });
@@ -28964,6 +30696,7 @@ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
28964
30696
  var IDENTITY_KUBERNETES = "kubernetes";
28965
30697
  var IDENTITY_METADATA = "metadata";
28966
30698
  var IDENTITY_POOL = "pool";
30699
+ var IDENTITY_DEVICE_LOGIN = "device-login";
28967
30700
  var BROKER_VARIABLES = [
28968
30701
  BROKER_URL_VAR,
28969
30702
  IDENTITY_VAR,
@@ -28973,6 +30706,7 @@ var BROKER_VARIABLES = [
28973
30706
  PROJECTS_VAR,
28974
30707
  POOL_AUDIENCE_VAR,
28975
30708
  POOL_ACCOUNT_VAR,
30709
+ DEVICE_LOGIN_FILE_VAR,
28976
30710
  SIGNIN_DIR_VAR,
28977
30711
  "XDG_STATE_HOME",
28978
30712
  "HOME",
@@ -29012,8 +30746,12 @@ function machineIdentity(env) {
29012
30746
  tokenAudience
29013
30747
  });
29014
30748
  }
30749
+ case IDENTITY_DEVICE_LOGIN: {
30750
+ const brokerUrl = required2(env, BROKER_URL_VAR, kind);
30751
+ return new DeviceLoginIdentity({ path: deviceLoginFile(env), brokerUrl });
30752
+ }
29015
30753
  default:
29016
- throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${IDENTITY_POOL}`);
30754
+ throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA}, ${IDENTITY_POOL} or ${IDENTITY_DEVICE_LOGIN}`);
29017
30755
  }
29018
30756
  }
29019
30757
  function tradeSession(env, own = "") {
@@ -29045,6 +30783,19 @@ async function brokerTokenClient(env, own = "") {
29045
30783
  return;
29046
30784
  if (!isHttpUrl(brokerUrl))
29047
30785
  throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
30786
+ if (machine instanceof DeviceLoginIdentity) {
30787
+ if (personTradeOff(env)) {
30788
+ 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`);
30789
+ }
30790
+ const client = new BrokerTokenClient({
30791
+ brokerUrl,
30792
+ key: await machine.key(),
30793
+ subject: machine,
30794
+ session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
30795
+ projects: tradeProjects(env)
30796
+ });
30797
+ return { client, signIn: undefined };
30798
+ }
29048
30799
  const record = await chooseSignIn(env);
29049
30800
  if (record === undefined) {
29050
30801
  const client = new BrokerTokenClient({
@@ -29849,7 +31600,7 @@ function natsCredential(env, section, namedNatsUrls, filePath, session) {
29849
31600
  throw new NoSessionNamedError(auth.source);
29850
31601
  return { kind: "broker", broker: brokerNatsCredential(env, session, auth.source) };
29851
31602
  }
29852
- var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
31603
+ var LOOPBACK_HOST2 = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
29853
31604
  function natsConflictText(source, natsSetting) {
29854
31605
  return `${source} is listener, and ${natsSetting} names NATS servers: set one of the two`;
29855
31606
  }
@@ -29874,7 +31625,7 @@ function listenerInbound(source, natsSetting, credential, session) {
29874
31625
  }
29875
31626
  function plainHttpOffMachine(url) {
29876
31627
  const host = URL.canParse(url) ? new URL(url) : undefined;
29877
- return host?.protocol === "http:" && !LOOPBACK_HOST.test(host.hostname) ? host.hostname : undefined;
31628
+ return host?.protocol === "http:" && !LOOPBACK_HOST2.test(host.hostname) ? host.hostname : undefined;
29878
31629
  }
29879
31630
  function envoySettings(env, config, options = {}) {
29880
31631
  if (config.kind === "failed")
@@ -30085,58 +31836,58 @@ function claudeProjectDirectory(environment, fallback) {
30085
31836
  // src/codex/codex-session-record.ts
30086
31837
  import { spawnSync } from "child_process";
30087
31838
  import { readFileSync as readFileSync5, readlinkSync as readlinkSync2, unwatchFile, watchFile } from "fs";
30088
- import { mkdir as mkdir2, readFile as readFile4, rename as rename2, utimes as utimes2, writeFile as writeFile2 } from "fs/promises";
31839
+ import { mkdir as mkdir3, readFile as readFile5, rename as rename4, utimes as utimes3, writeFile as writeFile2 } from "fs/promises";
30089
31840
  import { homedir as homedir3 } from "os";
30090
- import { basename as basename3, dirname as dirname3, join as join7 } from "path";
31841
+ import { basename as basename4, dirname as dirname5, join as join9 } from "path";
30091
31842
 
30092
31843
  // src/session-identity.ts
30093
- import { readFile as readFile3 } from "fs/promises";
30094
- import { basename as basename2, join as join6 } from "path";
31844
+ import { readFile as readFile4 } from "fs/promises";
31845
+ import { basename as basename3, join as join8 } from "path";
30095
31846
 
30096
31847
  // src/session-state.ts
30097
31848
  import { readFileSync as readFileSync4 } from "fs";
30098
- import { mkdir, readdir as readdir2, rename, rm, stat, utimes, writeFile } from "fs/promises";
30099
- import { dirname as dirname2, join as join5 } from "path";
31849
+ import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm3, stat as stat3, utimes as utimes2, writeFile } from "fs/promises";
31850
+ import { dirname as dirname4, join as join7 } from "path";
30100
31851
  async function writeAtomicStateFile(file, contents) {
30101
- await mkdir(dirname2(file), { recursive: true, mode: 448 });
31852
+ await mkdir2(dirname4(file), { recursive: true, mode: 448 });
30102
31853
  const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
30103
31854
  await writeFile(temporary, contents, { mode: 384 });
30104
- await rename(temporary, file);
31855
+ await rename3(temporary, file);
30105
31856
  }
30106
31857
  async function touchStateFile(file) {
30107
31858
  const now = new Date;
30108
- await utimes(file, now, now);
31859
+ await utimes2(file, now, now);
30109
31860
  }
30110
31861
  async function pruneStateDirectory(directory, isStale) {
30111
- const entries = await readdir2(directory).catch((error) => {
31862
+ const entries = await readdir3(directory).catch((error) => {
30112
31863
  if (hasErrnoCode(error, "ENOENT"))
30113
31864
  return [];
30114
31865
  throw error;
30115
31866
  });
30116
31867
  for (const entry of entries) {
30117
- const file = join5(directory, entry);
31868
+ const file = join7(directory, entry);
30118
31869
  if (!await isStale(file))
30119
31870
  continue;
30120
- await rm(file, { recursive: true, force: true });
31871
+ await rm3(file, { recursive: true, force: true });
30121
31872
  }
30122
31873
  }
30123
31874
  var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
30124
31875
  async function writtenLongAgo(file) {
30125
- const modified = await stat(file).then((stats) => stats.mtimeMs, () => {
31876
+ const modified = await stat3(file).then((stats) => stats.mtimeMs, () => {
30126
31877
  return;
30127
31878
  });
30128
31879
  return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
30129
31880
  }
30130
31881
  var TITLES_DIRECTORY = "titles";
30131
31882
  function sessionTitleFile(stateDirectory, sessionId) {
30132
- return join5(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
31883
+ return join7(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
30133
31884
  }
30134
31885
  async function writeChosenTitle(file, title) {
30135
31886
  await writeAtomicStateFile(file, `${title}
30136
31887
  `);
30137
31888
  }
30138
31889
  async function removeChosenTitle(file) {
30139
- await rm(file, { force: true });
31890
+ await rm3(file, { force: true });
30140
31891
  }
30141
31892
  function readChosenTitleSync(file) {
30142
31893
  try {
@@ -30157,7 +31908,7 @@ async function recordChosenTitle(sessionId, title) {
30157
31908
  await writeChosenTitle(file, chosen);
30158
31909
  }
30159
31910
  async function pruneStaleSessionTitles(stateDirectory) {
30160
- await pruneStateDirectory(join5(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
31911
+ await pruneStateDirectory(join7(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
30161
31912
  }
30162
31913
 
30163
31914
  // src/session-identity.ts
@@ -30182,14 +31933,14 @@ class SessionIdentity {
30182
31933
  }
30183
31934
  }
30184
31935
  function sessionHandoffDirectory(stateDirectory, claudePid) {
30185
- return join6(stateDirectory, "sessions", String(claudePid));
31936
+ return join8(stateDirectory, "sessions", String(claudePid));
30186
31937
  }
30187
31938
  function sessionHandoffFile(stateDirectory, claudePid) {
30188
- return join6(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
31939
+ return join8(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
30189
31940
  }
30190
31941
  var ROLES_DIRECTORY = "roles";
30191
31942
  function roleStateFile(stateDirectory, sessionId) {
30192
- return join6(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
31943
+ return join8(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
30193
31944
  }
30194
31945
 
30195
31946
  class UnparseableRoleRecordError extends Error {
@@ -30201,7 +31952,7 @@ class UnparseableRoleRecordError extends Error {
30201
31952
  async function readPersistedRole(roleFile) {
30202
31953
  let bytes;
30203
31954
  try {
30204
- bytes = await readFile3(roleFile, "utf8");
31955
+ bytes = await readFile4(roleFile, "utf8");
30205
31956
  } catch (error) {
30206
31957
  if (hasErrnoCode(error, "ENOENT"))
30207
31958
  return;
@@ -30223,7 +31974,7 @@ async function writeSessionHandoff(file, sessionId) {
30223
31974
  }
30224
31975
  async function readSessionHandoff(file) {
30225
31976
  try {
30226
- const id = (await readFile3(file, "utf8")).trim();
31977
+ const id = (await readFile4(file, "utf8")).trim();
30227
31978
  return id.length === 0 ? undefined : id;
30228
31979
  } catch (error) {
30229
31980
  if (hasErrnoCode(error, "ENOENT"))
@@ -30240,14 +31991,14 @@ function processExists(pid) {
30240
31991
  }
30241
31992
  }
30242
31993
  async function pruneStaleSessionHandoffs(stateDirectory) {
30243
- await pruneStateDirectory(join6(stateDirectory, "sessions"), (file) => {
30244
- const pid = basename2(file);
31994
+ await pruneStateDirectory(join8(stateDirectory, "sessions"), (file) => {
31995
+ const pid = basename3(file);
30245
31996
  return /^\d+$/.test(pid) && !processExists(Number(pid));
30246
31997
  });
30247
31998
  }
30248
31999
  async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
30249
32000
  const own = roleStateFile(stateDirectory, currentSessionId);
30250
- await pruneStateDirectory(join6(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
32001
+ await pruneStateDirectory(join8(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
30251
32002
  }
30252
32003
 
30253
32004
  // src/codex/codex-session-record.ts
@@ -30261,17 +32012,17 @@ var CodexSessionRecord = object({
30261
32012
  codex_started: string2().nullable().default(null)
30262
32013
  });
30263
32014
  function codexSessionRecordFile(stateDirectory, pid) {
30264
- return join7(stateDirectory, "codex-sessions", `${pid}.json`);
32015
+ return join9(stateDirectory, "codex-sessions", `${pid}.json`);
30265
32016
  }
30266
32017
  function codexEndedFile(stateDirectory, pid, sessionId) {
30267
- return join7(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
32018
+ return join9(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
30268
32019
  }
30269
32020
  async function markSessionEnded(stateDirectory, pid, sessionId) {
30270
32021
  const marker = codexEndedFile(stateDirectory, pid, sessionId);
30271
- await mkdir2(dirname3(marker), { mode: 448, recursive: true });
32022
+ await mkdir3(dirname5(marker), { mode: 448, recursive: true });
30272
32023
  await writeFile2(marker, "", { mode: 384 });
30273
32024
  const now = new Date;
30274
- await utimes2(codexSessionRecordFile(stateDirectory, pid), now, now);
32025
+ await utimes3(codexSessionRecordFile(stateDirectory, pid), now, now);
30275
32026
  }
30276
32027
  function watchRecord(file, pid, ended, changed, intervalMs) {
30277
32028
  const look = () => {
@@ -30287,21 +32038,21 @@ function watchRecord(file, pid, ended, changed, intervalMs) {
30287
32038
  }
30288
32039
  async function sessionEnded(file) {
30289
32040
  try {
30290
- await readFile4(file);
32041
+ await readFile5(file);
30291
32042
  return true;
30292
32043
  } catch {
30293
32044
  return false;
30294
32045
  }
30295
32046
  }
30296
32047
  async function writeCodexSessionRecord(file, value) {
30297
- await mkdir2(dirname3(file), { recursive: true, mode: 448 });
32048
+ await mkdir3(dirname5(file), { recursive: true, mode: 448 });
30298
32049
  const temporary = `${file}.${process.pid}.tmp`;
30299
32050
  await writeFile2(temporary, JSON.stringify(value), { mode: 384 });
30300
- await rename2(temporary, file);
32051
+ await rename4(temporary, file);
30301
32052
  }
30302
32053
  async function readCodexSessionRecord(file) {
30303
32054
  try {
30304
- const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile4(file, "utf8")));
32055
+ const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile5(file, "utf8")));
30305
32056
  return parsed.success ? parsed.data : undefined;
30306
32057
  } catch {
30307
32058
  return;
@@ -30309,17 +32060,17 @@ async function readCodexSessionRecord(file) {
30309
32060
  }
30310
32061
  function codexHome(env) {
30311
32062
  const set = env["CODEX_HOME"];
30312
- return set !== undefined && set !== "" ? set : join7(env["HOME"] || homedir3(), ".codex");
32063
+ return set !== undefined && set !== "" ? set : join9(env["HOME"] || homedir3(), ".codex");
30313
32064
  }
30314
32065
  function codexPluginDataDirectory(pluginRoot) {
30315
32066
  const version = pluginRoot;
30316
- const plugin = dirname3(version);
30317
- const marketplace = dirname3(plugin);
30318
- const cache = dirname3(marketplace);
30319
- const plugins = dirname3(cache);
30320
- if (basename3(cache) !== "cache" || basename3(plugins) !== "plugins")
32067
+ const plugin = dirname5(version);
32068
+ const marketplace = dirname5(plugin);
32069
+ const cache = dirname5(marketplace);
32070
+ const plugins = dirname5(cache);
32071
+ if (basename4(cache) !== "cache" || basename4(plugins) !== "plugins")
30321
32072
  return;
30322
- return join7(plugins, "data", `${basename3(plugin)}-${basename3(marketplace)}`);
32073
+ return join9(plugins, "data", `${basename4(plugin)}-${basename4(marketplace)}`);
30323
32074
  }
30324
32075
  var MAX_ANCESTORS = 16;
30325
32076
  function codexProcessId(readComm = procComm, readParent = procParent) {
@@ -30415,12 +32166,12 @@ function codexSubcommand(args) {
30415
32166
  }
30416
32167
  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.";
30417
32168
  async function pruneCodexSessionRecords(stateDirectory) {
30418
- await pruneStateDirectory(join7(stateDirectory, "codex-sessions"), (file) => {
30419
- const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename3(file));
32169
+ await pruneStateDirectory(join9(stateDirectory, "codex-sessions"), (file) => {
32170
+ const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename4(file));
30420
32171
  return match !== null && !processExists(Number(match[1]));
30421
32172
  });
30422
- await pruneStateDirectory(join7(stateDirectory, "codex-servers"), (file) => {
30423
- const name = basename3(file);
32173
+ await pruneStateDirectory(join9(stateDirectory, "codex-servers"), (file) => {
32174
+ const name = basename4(file);
30424
32175
  return /^\d+$/.test(name) && !processExists(Number(name));
30425
32176
  });
30426
32177
  }
@@ -30485,7 +32236,7 @@ async function sessionStart(raw) {
30485
32236
  process.stderr.write(`envoy: this session was not recorded, because the start of codex process ${pid} cannot be read; it gets no Envoy messages
30486
32237
  `);
30487
32238
  } else {
30488
- await rm2(codexEndedFile(pluginData, pid, input.session_id), { force: true });
32239
+ await rm4(codexEndedFile(pluginData, pid, input.session_id), { force: true });
30489
32240
  await writeCodexSessionRecord(codexSessionRecordFile(pluginData, pid), {
30490
32241
  codex_executable: codexExecutable(pid) ?? null,
30491
32242
  codex_home: codexHome(process.env),