@sjawhar/claude-envoy 2.27.0 → 2.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36860,6 +36860,14 @@ var handoffValidation = {
36860
36860
  message: HANDOFF_RULE,
36861
36861
  refusal: (value) => handoffProblem(value) ?? HANDOFF_RULE
36862
36862
  };
36863
+ var REVIEW_REASON_RULE = "verdict changes_requested requires reason, a non-empty note saying what must change before the document can be approved.";
36864
+ var reviewValidation = {
36865
+ check: (value) => {
36866
+ const input = value;
36867
+ return input.verdict !== "changes_requested" || typeof input.reason === "string" && input.reason.trim() !== "";
36868
+ },
36869
+ message: REVIEW_REASON_RULE
36870
+ };
36863
36871
  var RESULT_REQUIRED_FIELDS = ["issue", "check", "role", "verdict", "commit"];
36864
36872
  var RESULT_RECORD_FIELDS = [
36865
36873
  ...RESULT_REQUIRED_FIELDS,
@@ -37243,6 +37251,20 @@ var dispatchToolSpecs = [
37243
37251
  version: z.number({ int: true, min: 1 }).describe("The plan version the review read and approved.")
37244
37252
  })
37245
37253
  },
37254
+ {
37255
+ name: "dispatch_review",
37256
+ example: { issue: "DSP-1", version: 2, verdict: "approved" },
37257
+ description: "Approve one version of an issue's document, or request changes on it, as the person your " + "token names: what the document header's Approve and Request changes record. A review " + "records an approval or a changes request in the person's name at that version, so it " + "works only with a token that names a person who holds approve; Dispatch refuses it to " + "any other token, with 403 OAUTH_SCOPE_REQUIRED or 403 SIGN_IN_REQUIRED. --version is the " + "version you read, sent in the review route's path, and it must be the version the review " + "would record: the document's latest settled version, or, while an approval request is " + "open on it, the version that request names for it. Any other is refused 409 " + "REVIEW_VERSION_MOVED, which names the version to read, and nothing is recorded. A " + "Dispatch build without the versioned review route answers no route and records nothing; " + "the command then says so and names /healthz, which names the commit of the build that " + "answers it when that build was stamped with one. With a request open the review answers " + "it, and records the same verdict on every document the " + "request names, each at the version the request names. A later version makes an approval " + "stale. A review is the one browser action this command takes for a person; every other " + "browser action is dispatch://INFRA-910's. " + ISSUE_REFERENCE,
37258
+ arguments: (z) => ({
37259
+ issue: z.string().describe(ISSUE_REFERENCE),
37260
+ artifact: z.string().describe("Document artifact id, slug, or filename; the issue's spec by default.").optional(),
37261
+ version: z.number({ int: true, min: 1 }).describe("The document version you read and review, sent as a segment of the review route's path: the version the review would record, or Dispatch refuses it 409 REVIEW_VERSION_MOVED naming the version to read."),
37262
+ verdict: z.enum(["approved", "changes_requested"]).describe("approved records an approval; changes_requested records a request for changes and requires reason."),
37263
+ reason: z.string().describe("What must change before the document can be approved. changes_requested requires it; an approval may carry one.").optional()
37264
+ }),
37265
+ validation: reviewValidation,
37266
+ strict: true
37267
+ },
37246
37268
  {
37247
37269
  name: "dispatch_result",
37248
37270
  example: {
@@ -39448,6 +39470,9 @@ function zodSchemaApi(zod) {
39448
39470
  }
39449
39471
  };
39450
39472
  }
39473
+ // ../broker-client/src/dpop.ts
39474
+ import { createPrivateKey, createPublicKey } from "crypto";
39475
+
39451
39476
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
39452
39477
  var encoder2 = new TextEncoder;
39453
39478
  var decoder = new TextDecoder;
@@ -40294,6 +40319,112 @@ function keyAlgorithm(alg, source) {
40294
40319
  return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : undefined) ?? unsupportedAlg(source);
40295
40320
  }
40296
40321
 
40322
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/asn1.js
40323
+ var bytesEqual = (a, b) => {
40324
+ if (a.byteLength !== b.length)
40325
+ return false;
40326
+ for (let i = 0;i < a.byteLength; i++) {
40327
+ if (a[i] !== b[i])
40328
+ return false;
40329
+ }
40330
+ return true;
40331
+ };
40332
+ var createASN1State = (data) => ({ data, pos: 0 });
40333
+ var readByte = (state) => {
40334
+ const byte = state.data[state.pos++];
40335
+ if (byte === undefined) {
40336
+ throw new Error("Unexpected end of ASN.1 input");
40337
+ }
40338
+ return byte;
40339
+ };
40340
+ var parseLength = (state) => {
40341
+ const first = readByte(state);
40342
+ if (first & 128) {
40343
+ const lengthOfLen = first & 127;
40344
+ let length = 0;
40345
+ for (let i = 0;i < lengthOfLen; i++) {
40346
+ length = length << 8 | readByte(state);
40347
+ }
40348
+ return length;
40349
+ }
40350
+ return first;
40351
+ };
40352
+ var expectTag = (state, expectedTag, errorMessage) => {
40353
+ if (readByte(state) !== expectedTag) {
40354
+ throw new Error(errorMessage);
40355
+ }
40356
+ };
40357
+ var getSubarray = (state, length) => {
40358
+ if (length < 0 || state.pos + length > state.data.length) {
40359
+ throw new Error("Unexpected end of ASN.1 input");
40360
+ }
40361
+ const result = state.data.subarray(state.pos, state.pos + length);
40362
+ state.pos += length;
40363
+ return result;
40364
+ };
40365
+ var parseAlgorithmOID = (state) => {
40366
+ expectTag(state, 6, "Expected algorithm OID");
40367
+ const oidLen = parseLength(state);
40368
+ return getSubarray(state, oidLen);
40369
+ };
40370
+ function parseKeyHeader(state, keyFormat) {
40371
+ expectTag(state, 48, `Invalid ${keyFormat === "spki" ? "SPKI" : "PKCS#8"} structure`);
40372
+ parseLength(state);
40373
+ if (keyFormat === "pkcs8") {
40374
+ expectTag(state, 2, "Expected version field");
40375
+ const length = parseLength(state);
40376
+ state.pos += length;
40377
+ }
40378
+ expectTag(state, 48, "Expected algorithm identifier");
40379
+ parseLength(state);
40380
+ }
40381
+ var parseECAlgorithmIdentifier = (state) => {
40382
+ const algOid = parseAlgorithmOID(state);
40383
+ if (bytesEqual(algOid, [43, 101, 110])) {
40384
+ return "X25519";
40385
+ }
40386
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
40387
+ throw new Error("Unsupported key algorithm");
40388
+ }
40389
+ expectTag(state, 6, "Expected curve OID");
40390
+ const curveOidLen = parseLength(state);
40391
+ const curveOid = getSubarray(state, curveOidLen);
40392
+ if (bytesEqual(curveOid, [42, 134, 72, 206, 61, 3, 1, 7]))
40393
+ return "P-256";
40394
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 34]))
40395
+ return "P-384";
40396
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 35]))
40397
+ return "P-521";
40398
+ throw new Error("Unsupported named curve");
40399
+ };
40400
+ var genericImport = async (keyFormat, keyData, alg, options) => {
40401
+ const entry = keyAlgorithm(alg, algArgument);
40402
+ if (entry.secret) {
40403
+ unsupportedAlg(algArgument);
40404
+ }
40405
+ const isPublic = keyFormat === "spki";
40406
+ let algorithm;
40407
+ if (entry.resolve) {
40408
+ try {
40409
+ const state = createASN1State(keyData);
40410
+ parseKeyHeader(state, keyFormat);
40411
+ algorithm = entry.resolve({ crv: parseECAlgorithmIdentifier(state) });
40412
+ } catch {
40413
+ throw new JOSENotSupported("Invalid or unsupported key format");
40414
+ }
40415
+ } else {
40416
+ algorithm = entry.subtle;
40417
+ }
40418
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
40419
+ };
40420
+ var processPEMData = (pem, pattern) => {
40421
+ return decodeBase64(pem.replace(pattern, ""));
40422
+ };
40423
+ var fromPKCS8 = (pem, alg, options) => {
40424
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
40425
+ return genericImport("pkcs8", keyData, alg, options);
40426
+ };
40427
+
40297
40428
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
40298
40429
  function omitUndefinedProperties(jwk) {
40299
40430
  return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
@@ -40327,6 +40458,13 @@ async function keyToJWK(key) {
40327
40458
  function exportJWK(key) {
40328
40459
  return keyToJWK(key);
40329
40460
  }
40461
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/import.js
40462
+ async function importPKCS8(pkcs8, alg, options) {
40463
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
40464
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
40465
+ }
40466
+ return fromPKCS8(pkcs8, alg, options);
40467
+ }
40330
40468
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/generate_key_pair.js
40331
40469
  function getModulusLengthOption(options) {
40332
40470
  const modulusLength = options?.modulusLength ?? 2048;
@@ -40370,6 +40508,11 @@ async function generateKeyPair(alg, options) {
40370
40508
  ...entry.usages[0]
40371
40509
  ]);
40372
40510
  }
40511
+ // ../broker-client/src/error-text.ts
40512
+ function messageOf(error) {
40513
+ return error instanceof Error ? error.message : String(error);
40514
+ }
40515
+
40373
40516
  // ../broker-client/src/dpop.ts
40374
40517
  var ALGORITHM = "ES256";
40375
40518
  function targetUri(url) {
@@ -40382,9 +40525,7 @@ async function accessTokenHash(accessToken) {
40382
40525
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
40383
40526
  return Buffer.from(digest).toString("base64url");
40384
40527
  }
40385
- async function newDpopKey() {
40386
- const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
40387
- const publicJwk = await exportJWK(publicKey);
40528
+ function dpopKey(privateKey, publicJwk) {
40388
40529
  return {
40389
40530
  publicJwk,
40390
40531
  async proof(request) {
@@ -40403,6 +40544,30 @@ async function newDpopKey() {
40403
40544
  }
40404
40545
  };
40405
40546
  }
40547
+ async function newDpopKey() {
40548
+ const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
40549
+ return dpopKey(privateKey, await exportJWK(publicKey));
40550
+ }
40551
+ async function importDpopKey(pkcs8Pem, name) {
40552
+ const unreadable = (error) => new Error(`read ${name}: ${messageOf(error)}`, { cause: error });
40553
+ let exported;
40554
+ try {
40555
+ exported = createPublicKey(createPrivateKey(pkcs8Pem)).export({ format: "jwk" });
40556
+ } catch (error) {
40557
+ throw unreadable(error);
40558
+ }
40559
+ const { kty, crv, x, y } = exported;
40560
+ if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
40561
+ throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
40562
+ }
40563
+ let privateKey;
40564
+ try {
40565
+ privateKey = await importPKCS8(pkcs8Pem, ALGORITHM, { extractable: false });
40566
+ } catch (error) {
40567
+ throw unreadable(error);
40568
+ }
40569
+ return dpopKey(privateKey, { kty, crv, x, y });
40570
+ }
40406
40571
 
40407
40572
  // ../broker-client/src/metadata-identity.ts
40408
40573
  import { Agent, request } from "http";
@@ -40416,6 +40581,7 @@ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
40416
40581
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
40417
40582
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
40418
40583
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
40584
+ var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
40419
40585
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
40420
40586
  var TOKEN_TYPE_DPOP = "DPoP";
40421
40587
 
@@ -40477,37 +40643,6 @@ function metadataIdentity(audience, env = process.env) {
40477
40643
  };
40478
40644
  }
40479
40645
 
40480
- // ../broker-client/src/projected-token.ts
40481
- import { readFile } from "fs/promises";
40482
- function projectedToken(path) {
40483
- return {
40484
- async read(signal) {
40485
- let contents;
40486
- try {
40487
- contents = await readFile(path, {
40488
- encoding: "utf8",
40489
- ...signal === undefined ? {} : { signal }
40490
- });
40491
- } catch (error) {
40492
- throw new Error(`read the projected service-account token ${path}: ${error.message}`);
40493
- }
40494
- const token = contents.trim();
40495
- if (token === "")
40496
- throw new Error(`the projected service-account token ${path} is empty`);
40497
- return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
40498
- },
40499
- describe: () => `the projected service-account token ${path}`
40500
- };
40501
- }
40502
-
40503
- // ../contracts/src/trailing-slash.ts
40504
- function withoutTrailingSlashes(url) {
40505
- let end = url.length;
40506
- while (end > 0 && url[end - 1] === "/")
40507
- end -= 1;
40508
- return url.slice(0, end);
40509
- }
40510
-
40511
40646
  // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
40512
40647
  var USER_AGENT;
40513
40648
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
@@ -40653,6 +40788,56 @@ function signal(url, value) {
40653
40788
  }
40654
40789
  return;
40655
40790
  }
40791
+ function replaceDoubleSlash(pathname) {
40792
+ if (pathname.includes("//")) {
40793
+ return pathname.replace("//", "/");
40794
+ }
40795
+ return pathname;
40796
+ }
40797
+ function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
40798
+ if (url.pathname === "/") {
40799
+ url.pathname = wellKnown;
40800
+ } else {
40801
+ url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
40802
+ }
40803
+ return url;
40804
+ }
40805
+ function appendWellKnown(url, wellKnown) {
40806
+ url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
40807
+ return url;
40808
+ }
40809
+ async function performDiscovery(input, urlName, transform, options) {
40810
+ if (!(input instanceof URL)) {
40811
+ throw CodedTypeError(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE);
40812
+ }
40813
+ checkProtocol(input, options?.[allowInsecureRequests] !== true);
40814
+ const url = transform(new URL(input.href));
40815
+ const headers = prepareHeaders(options?.headers);
40816
+ headers.set("accept", "application/json");
40817
+ return (options?.[customFetch] || fetch)(url.href, {
40818
+ body: undefined,
40819
+ headers: Object.fromEntries(headers.entries()),
40820
+ method: "GET",
40821
+ redirect: "manual",
40822
+ signal: signal(url, options?.signal)
40823
+ });
40824
+ }
40825
+ async function discoveryRequest(issuerIdentifier, options) {
40826
+ return performDiscovery(issuerIdentifier, "issuerIdentifier", (url) => {
40827
+ switch (options?.algorithm) {
40828
+ case undefined:
40829
+ case "oidc":
40830
+ appendWellKnown(url, ".well-known/openid-configuration");
40831
+ break;
40832
+ case "oauth2":
40833
+ prependWellKnown(url, ".well-known/oauth-authorization-server");
40834
+ break;
40835
+ default:
40836
+ throw CodedTypeError('"options.algorithm" must be "oidc" (default), or "oauth2"', ERR_INVALID_ARG_VALUE);
40837
+ }
40838
+ return url;
40839
+ }, options);
40840
+ }
40656
40841
  function assertNumber(input, allow0, it, code, cause) {
40657
40842
  try {
40658
40843
  if (typeof input !== "number" || !Number.isFinite(input)) {
@@ -40689,6 +40874,25 @@ function assertString(input, it, code, cause) {
40689
40874
  throw err;
40690
40875
  }
40691
40876
  }
40877
+ async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
40878
+ const expected = expectedIssuerIdentifier;
40879
+ if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
40880
+ throw CodedTypeError('"expectedIssuerIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE);
40881
+ }
40882
+ if (!looseInstanceOf(response, Response)) {
40883
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
40884
+ }
40885
+ if (response.status !== 200) {
40886
+ throw OPE('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
40887
+ }
40888
+ assertReadableResponse(response);
40889
+ const json = await getResponseJsonBody(response);
40890
+ assertString(json.issuer, '"response" body "issuer" property', INVALID_RESPONSE, { body: json });
40891
+ if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {
40892
+ throw OPE('"response" body "issuer" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: "issuer" });
40893
+ }
40894
+ return json;
40895
+ }
40692
40896
  function assertApplicationJson(response) {
40693
40897
  assertContentType(response, "application/json");
40694
40898
  }
@@ -40968,6 +41172,14 @@ async function tokenEndpointRequest(as, client, clientAuthentication, grantType,
40968
41172
  options?.DPoP?.cacheNonce(response, url);
40969
41173
  return response;
40970
41174
  }
41175
+ async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
41176
+ assertAs(as);
41177
+ assertClient(client);
41178
+ assertString(refreshToken, '"refreshToken"');
41179
+ const parameters = new URLSearchParams(options?.additionalParameters);
41180
+ parameters.set("refresh_token", refreshToken);
41181
+ return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
41182
+ }
40971
41183
  var idTokenClaims = new WeakMap;
40972
41184
  var jwtRefs = new WeakMap;
40973
41185
  function getValidatedIdTokenClaims(ref) {
@@ -41045,6 +41257,9 @@ function checkAuthenticationChallenges(response) {
41045
41257
  throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", { cause: challenges, response });
41046
41258
  }
41047
41259
  }
41260
+ async function processRefreshTokenResponse(as, client, response, options) {
41261
+ return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
41262
+ }
41048
41263
  function validateAudience(expected, result) {
41049
41264
  if (Array.isArray(result.claims.aud)) {
41050
41265
  if (!result.claims.aud.includes(expected)) {
@@ -41397,6 +41612,73 @@ function errorHandler(err) {
41397
41612
  }
41398
41613
  throw new ClientError("something went wrong", { cause: err });
41399
41614
  }
41615
+ function handleEntraId(server, as, options) {
41616
+ if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
41617
+ as[kEntraId] = true;
41618
+ return true;
41619
+ }
41620
+ return false;
41621
+ }
41622
+ function handleB2Clogin(server, options) {
41623
+ if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) {
41624
+ return true;
41625
+ }
41626
+ return false;
41627
+ }
41628
+ async function discovery(server, clientId, metadata, clientAuthentication, options) {
41629
+ const as = await performDiscovery2(server, options);
41630
+ const instance = new Configuration(as, clientId, metadata, clientAuthentication);
41631
+ let internals = int2(instance);
41632
+ if (options?.[customFetch2]) {
41633
+ internals.fetch = options[customFetch2];
41634
+ }
41635
+ if (options?.timeout) {
41636
+ internals.timeout = options.timeout;
41637
+ }
41638
+ if (options?.execute) {
41639
+ for (const extension of options.execute) {
41640
+ extension(instance);
41641
+ }
41642
+ }
41643
+ return instance;
41644
+ }
41645
+ async function performDiscovery2(server, options) {
41646
+ if (!(server instanceof URL)) {
41647
+ throw CodedTypeError2('"server" must be an instance of URL', ERR_INVALID_ARG_TYPE2);
41648
+ }
41649
+ const resolve = !server.href.includes("/.well-known/");
41650
+ const timeout = options?.timeout ?? 30;
41651
+ const signal = AbortSignal.timeout(timeout * 1000);
41652
+ const as = await (resolve ? discoveryRequest(server, {
41653
+ algorithm: options?.algorithm,
41654
+ [customFetch]: options?.[customFetch2],
41655
+ [allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests2),
41656
+ signal,
41657
+ headers: new Headers(headers)
41658
+ }) : (options?.[customFetch2] || fetch)((() => {
41659
+ checkProtocol(server, options?.execute?.includes(allowInsecureRequests2) ? false : true);
41660
+ return server.href;
41661
+ })(), {
41662
+ headers: Object.fromEntries(new Headers({ accept: "application/json", ...headers }).entries()),
41663
+ body: undefined,
41664
+ method: "GET",
41665
+ redirect: "manual",
41666
+ signal
41667
+ })).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
41668
+ if (resolve && new URL(as.issuer).href !== server.href) {
41669
+ handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
41670
+ throw new ClientError("discovered metadata issuer does not match the expected issuer", {
41671
+ code: JSON_ATTRIBUTE_COMPARISON,
41672
+ cause: {
41673
+ expected: server.href,
41674
+ body: as,
41675
+ attribute: "issuer"
41676
+ }
41677
+ });
41678
+ })();
41679
+ }
41680
+ return as;
41681
+ }
41400
41682
  function getServerHelpers(metadata) {
41401
41683
  return {
41402
41684
  supportsPKCE: {
@@ -41513,6 +41795,37 @@ function addHelpers(response) {
41513
41795
  function allowInsecureRequests2(config) {
41514
41796
  int2(config).tlsOnly = false;
41515
41797
  }
41798
+ async function refreshTokenGrant(config, refreshToken, parameters, options) {
41799
+ checkConfig(config);
41800
+ parameters = new URLSearchParams(parameters);
41801
+ const { as, c, auth, fetch: fetch2, tlsOnly, nonRepudiation, timeout, decrypt } = int2(config);
41802
+ const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
41803
+ [customFetch]: fetch2,
41804
+ [allowInsecureRequests]: !tlsOnly,
41805
+ additionalParameters: parameters,
41806
+ DPoP: options?.DPoP,
41807
+ headers: new Headers(headers),
41808
+ signal: signal2(timeout)
41809
+ }).catch(errorHandler);
41810
+ const p = processRefreshTokenResponse(as, c, response, {
41811
+ [jweDecrypt]: decrypt
41812
+ });
41813
+ let result;
41814
+ try {
41815
+ result = await p;
41816
+ } catch (err) {
41817
+ if (retryable(err, options)) {
41818
+ return refreshTokenGrant(config, refreshToken, parameters, {
41819
+ ...options,
41820
+ flag: retry
41821
+ });
41822
+ }
41823
+ errorHandler(err);
41824
+ }
41825
+ result.id_token && await nonRepudiation?.(response);
41826
+ addHelpers(result);
41827
+ return result;
41828
+ }
41516
41829
  function checkConfig(input) {
41517
41830
  if (!(input instanceof Configuration)) {
41518
41831
  throw CodedTypeError2('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE2);
@@ -41566,6 +41879,146 @@ async function genericGrantRequest(config, grantType, parameters, options) {
41566
41879
  return result;
41567
41880
  }
41568
41881
 
41882
+ // ../broker-client/src/signins.ts
41883
+ import { readdir, readFile } from "fs/promises";
41884
+ import { join } from "path";
41885
+
41886
+ // ../contracts/src/trailing-slash.ts
41887
+ function withoutTrailingSlashes(url) {
41888
+ let end = url.length;
41889
+ while (end > 0 && url[end - 1] === "/")
41890
+ end -= 1;
41891
+ return url.slice(0, end);
41892
+ }
41893
+
41894
+ // ../broker-client/src/signins.ts
41895
+ var SIGNIN_DIR_VAR = "AGENT_SECRETS_SIGNIN_DIR";
41896
+ var PERSON_VAR = "AGENT_SECRETS_PERSON";
41897
+ var PERSON_TRADE_VAR = "PERSON_SIGNIN_TRADE";
41898
+ var SIGNIN_ISSUER_VAR = "AGENT_SECRETS_SIGNIN_ISSUER";
41899
+ var SIGNIN_CLIENT_ID_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_ID";
41900
+ var SIGNIN_CLIENT_SECRET_FILE_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_SECRET_FILE";
41901
+ var DEFAULT_SIGNIN_ISSUER = "https://accounts.google.com";
41902
+ var SIGNIN_COMMAND = "agent-secrets login";
41903
+ var SIGNINS_DIR = "signins";
41904
+ var RECORD_MEMBERS = [
41905
+ "person",
41906
+ "issuer",
41907
+ "client_id",
41908
+ "refresh_token",
41909
+ "box_key",
41910
+ "thumbprint",
41911
+ "enrollment_id",
41912
+ "signed_in_at"
41913
+ ];
41914
+ function signInDirectory(env) {
41915
+ const named = env[SIGNIN_DIR_VAR] ?? "";
41916
+ if (named !== "")
41917
+ return named;
41918
+ const state = env.XDG_STATE_HOME ?? "";
41919
+ const base = state !== "" ? state : join(env.HOME ?? "", ".local", "state");
41920
+ return join(base, "agent-secrets", SIGNINS_DIR);
41921
+ }
41922
+ async function readSignIn(path) {
41923
+ let text;
41924
+ try {
41925
+ text = await readFile(path, "utf8");
41926
+ } catch (error) {
41927
+ throw new Error(`read the sign-in at ${path}: ${messageOf(error)}`, { cause: error });
41928
+ }
41929
+ let parsed;
41930
+ try {
41931
+ parsed = JSON.parse(text);
41932
+ } catch {
41933
+ throw new Error(`read the sign-in at ${path}: it is not JSON; run: ${SIGNIN_COMMAND}`);
41934
+ }
41935
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
41936
+ throw new Error(`read the sign-in at ${path}: it holds no JSON object; run: ${SIGNIN_COMMAND}`);
41937
+ }
41938
+ const fields = parsed;
41939
+ const record = {};
41940
+ for (const member of RECORD_MEMBERS) {
41941
+ const given = fields[member] ?? "";
41942
+ if (typeof given !== "string") {
41943
+ throw new Error(`read the sign-in at ${path}: its ${member} is not a string; run: ${SIGNIN_COMMAND}`);
41944
+ }
41945
+ record[member] = given;
41946
+ }
41947
+ const read = record;
41948
+ if (read.person === "" || read.refresh_token === "" || read.box_key === "") {
41949
+ throw new Error(`the sign-in at ${path} names no person, no refresh token or no box key; run: ${SIGNIN_COMMAND}`);
41950
+ }
41951
+ return read;
41952
+ }
41953
+ async function listSignIns(dir) {
41954
+ let entries;
41955
+ try {
41956
+ entries = await readdir(dir, { withFileTypes: true });
41957
+ } catch (error) {
41958
+ if (error.code === "ENOENT")
41959
+ return [];
41960
+ throw new Error(`read this machine's sign-ins: ${messageOf(error)}`, { cause: error });
41961
+ }
41962
+ const names = entries.filter((entry) => !entry.isDirectory() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
41963
+ const records = [];
41964
+ for (const name of names)
41965
+ records.push(await readSignIn(join(dir, name)));
41966
+ return records.sort((a, b) => a.person < b.person ? -1 : a.person > b.person ? 1 : 0);
41967
+ }
41968
+ function namesOf(records) {
41969
+ return records.map((record) => record.person).join(", ");
41970
+ }
41971
+ function personTradeOff(env) {
41972
+ const written = (env[PERSON_TRADE_VAR] ?? "").trim();
41973
+ if (written === "")
41974
+ return false;
41975
+ if (written === "off")
41976
+ return true;
41977
+ throw new Error(`${PERSON_TRADE_VAR} is "${written}" and takes off or nothing: set it to off where this process's own credentials trade this machine and never a person signed in on it, and leave it unset where they trade the person signed in here`);
41978
+ }
41979
+ async function chooseSignIn(env) {
41980
+ if (personTradeOff(env))
41981
+ return;
41982
+ const records = await listSignIns(signInDirectory(env));
41983
+ const person = (env[PERSON_VAR] ?? "").trim().toLowerCase();
41984
+ if (records.length === 0)
41985
+ return;
41986
+ if (person !== "") {
41987
+ const named = records.find((record) => record.person.toLowerCase() === person);
41988
+ if (named !== undefined)
41989
+ return named;
41990
+ throw new Error(`${PERSON_VAR} names ${person}, who is not signed in on this machine; signed in here: ${namesOf(records)}; run: ${SIGNIN_COMMAND}`);
41991
+ }
41992
+ if (records.length === 1)
41993
+ return records[0];
41994
+ throw new Error(`${records.length} people are signed in on this machine (${namesOf(records)}), so this session must say which one it acts for: set ${PERSON_VAR} to one of them`);
41995
+ }
41996
+ function signInSessionName(record) {
41997
+ const name = `signin-${record.person}`;
41998
+ return record.thumbprint === "" ? name : `${name}-${record.thumbprint.slice(0, 12)}`;
41999
+ }
42000
+ async function signInFlow(env) {
42001
+ const clientId = (env[SIGNIN_CLIENT_ID_VAR] ?? "").trim();
42002
+ const secretFile = (env[SIGNIN_CLIENT_SECRET_FILE_VAR] ?? "").trim();
42003
+ if (clientId === "" && secretFile === "")
42004
+ return;
42005
+ if (clientId === "" || secretFile === "") {
42006
+ throw new Error(`a person's sign-in needs both ${SIGNIN_CLIENT_ID_VAR} and ${SIGNIN_CLIENT_SECRET_FILE_VAR}; this machine has one of them`);
42007
+ }
42008
+ let secret;
42009
+ try {
42010
+ secret = await readFile(secretFile, "utf8");
42011
+ } catch (error) {
42012
+ throw new Error(`read the sign-in client's secret (${SIGNIN_CLIENT_SECRET_FILE_VAR}): ${messageOf(error)}`, { cause: error });
42013
+ }
42014
+ const issuer = (env[SIGNIN_ISSUER_VAR] ?? "").trim();
42015
+ return {
42016
+ issuer: withoutTrailingSlashes(issuer === "" ? DEFAULT_SIGNIN_ISSUER : issuer),
42017
+ clientId,
42018
+ clientSecret: secret.trim()
42019
+ };
42020
+ }
42021
+
41569
42022
  // ../broker-client/src/token-client.ts
41570
42023
  var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
41571
42024
  var TOO_MANY_REQUESTS = 429;
@@ -41576,8 +42029,8 @@ class BrokerRefusedError extends Error {
41576
42029
  status;
41577
42030
  code;
41578
42031
  description;
41579
- constructor(status, code, description) {
41580
- super(description === "" ? `the secrets broker refused this machine's identity: HTTP ${status} ${code}` : `the secrets broker refused this machine's identity: HTTP ${status} ${code}: ${description}`);
42032
+ constructor(status, code, description, refused) {
42033
+ super(description === "" ? `the secrets broker refused ${refused}: HTTP ${status} ${code}` : `the secrets broker refused ${refused}: HTTP ${status} ${code}: ${description}`);
41581
42034
  this.status = status;
41582
42035
  this.code = code;
41583
42036
  this.description = description;
@@ -41587,6 +42040,20 @@ class BrokerRefusedError extends Error {
41587
42040
  return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE;
41588
42041
  }
41589
42042
  }
42043
+
42044
+ class SignInEndedError extends Error {
42045
+ issuer;
42046
+ person;
42047
+ constructor(issuer, person, options) {
42048
+ super(`${issuer} no longer honours ${person}'s sign-in on this machine; run: ${SIGNIN_COMMAND}`, options);
42049
+ this.issuer = issuer;
42050
+ this.person = person;
42051
+ this.name = "SignInEndedError";
42052
+ }
42053
+ }
42054
+ function isFinalRefusal(error) {
42055
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
42056
+ }
41590
42057
  function statusOf(error) {
41591
42058
  let cause = error;
41592
42059
  for (let depth = 0;depth < 4; depth += 1) {
@@ -41598,6 +42065,16 @@ function statusOf(error) {
41598
42065
  }
41599
42066
  return 0;
41600
42067
  }
42068
+ function requestInit(options, signal, headers) {
42069
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
42070
+ return {
42071
+ method: options.method,
42072
+ headers,
42073
+ body: options.body,
42074
+ redirect: options.redirect,
42075
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
42076
+ };
42077
+ }
41601
42078
 
41602
42079
  class BrokerTokenClient {
41603
42080
  #brokerUrl;
@@ -41646,6 +42123,9 @@ class BrokerTokenClient {
41646
42123
  this.#trading = null;
41647
42124
  }
41648
42125
  }
42126
+ drop() {
42127
+ this.#held = null;
42128
+ }
41649
42129
  async#renew(signal) {
41650
42130
  try {
41651
42131
  const token = await this.#trade(signal);
@@ -41653,7 +42133,7 @@ class BrokerTokenClient {
41653
42133
  return token;
41654
42134
  } catch (error) {
41655
42135
  const held = this.#held;
41656
- if (!(error instanceof BrokerRefusedError && error.permanent) && held !== null && this.#now() < held.expiresAt.getTime()) {
42136
+ if (!isFinalRefusal(error) && held !== null && this.#now() < held.expiresAt.getTime()) {
41657
42137
  return held;
41658
42138
  }
41659
42139
  this.#held = null;
@@ -41676,8 +42156,9 @@ class BrokerTokenClient {
41676
42156
  try {
41677
42157
  actor = await this.#actor.read(signal);
41678
42158
  } catch (error) {
41679
- const said = error instanceof Error ? error.message : String(error);
41680
- throw new Error(`read the machine this person signed in on: ${said}`, { cause: error });
42159
+ throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
42160
+ cause: error
42161
+ });
41681
42162
  }
41682
42163
  form["actor_token"] = actor.token;
41683
42164
  form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
@@ -41697,10 +42178,10 @@ class BrokerTokenClient {
41697
42178
  }
41698
42179
  #refusal(endpoint, error) {
41699
42180
  if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
41700
- return new BrokerRefusedError(error.status, error.error, error.error_description ?? "");
42181
+ return new BrokerRefusedError(error.status, error.error, error.error_description ?? "", this.#subject.describe());
41701
42182
  }
41702
42183
  const status = statusOf(error);
41703
- const message = error instanceof Error ? error.message : String(error);
42184
+ const message = messageOf(error);
41704
42185
  const said = status === 0 ? message : `HTTP ${status}: ${message}`;
41705
42186
  return new Error(`trade ${this.#subject.describe()} at ${endpoint}: ${said}`, {
41706
42187
  cause: error
@@ -41710,15 +42191,7 @@ class BrokerTokenClient {
41710
42191
  const send = async () => {
41711
42192
  const headers = new Headers(options.headers);
41712
42193
  headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
41713
- const signals = [options.signal, signal].filter((one) => one !== undefined);
41714
- const body = options.body;
41715
- return await this.#fetch(url, {
41716
- method: options.method,
41717
- headers,
41718
- body,
41719
- redirect: options.redirect,
41720
- ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
41721
- });
42194
+ return await this.#fetch(url, requestInit(options, signal, headers));
41722
42195
  };
41723
42196
  let answer = await send();
41724
42197
  const given = answer.headers.get("DPoP-Nonce") ?? "";
@@ -41766,15 +42239,241 @@ class BrokerTokenClient {
41766
42239
  }
41767
42240
  }
41768
42241
 
42242
+ // ../broker-client/src/person-identity.ts
42243
+ var ISSUER_TIMEOUT_SECONDS = 30;
42244
+ var INVALID_GRANT = "invalid_grant";
42245
+ function issuerSaid(error) {
42246
+ if (error instanceof ResponseBodyError) {
42247
+ const description = error.error_description ?? "";
42248
+ return `HTTP ${error.status} ${error.error}${description === "" ? "" : `: ${description}`}`;
42249
+ }
42250
+ let message = messageOf(error);
42251
+ const cause = error instanceof Error ? error.cause : undefined;
42252
+ if (cause instanceof Error && cause.message !== message)
42253
+ message += `: ${cause.message}`;
42254
+ const status = statusOf(error);
42255
+ return status === 0 ? message : `HTTP ${status}: ${message}`;
42256
+ }
42257
+ function personIdentity(record, flow, options = {}) {
42258
+ const { person, refresh_token: refreshToken, client_id: clientId } = record;
42259
+ if (clientId !== "" && clientId !== flow.clientId) {
42260
+ throw new Error(`${person} signed in with another client than this machine now has (${clientId}), so their sign-in cannot be renewed; run: ${SIGNIN_COMMAND}`);
42261
+ }
42262
+ const send = options.fetch ?? fetch;
42263
+ const insecure = flow.issuer.startsWith("http:");
42264
+ let discovered = null;
42265
+ const through = (signal) => (url, init) => send(url, requestInit(init, signal, init.headers));
42266
+ const discover = async (signal) => {
42267
+ try {
42268
+ const config = await discovery(new URL(flow.issuer), flow.clientId, undefined, undefined, {
42269
+ [customFetch2]: through(signal),
42270
+ timeout: ISSUER_TIMEOUT_SECONDS,
42271
+ ...insecure ? { execute: [allowInsecureRequests2] } : {}
42272
+ });
42273
+ return config.serverMetadata();
42274
+ } catch (error) {
42275
+ throw new Error(`read the sign-in issuer ${flow.issuer}: ${issuerSaid(error)}`, {
42276
+ cause: error
42277
+ });
42278
+ }
42279
+ };
42280
+ return {
42281
+ async read(signal) {
42282
+ discovered ??= discover(signal);
42283
+ const discovering = discovered;
42284
+ let metadata;
42285
+ try {
42286
+ metadata = await discovering;
42287
+ } catch (error) {
42288
+ if (discovered === discovering)
42289
+ discovered = null;
42290
+ throw error;
42291
+ }
42292
+ let answered;
42293
+ try {
42294
+ const config = new Configuration(metadata, flow.clientId, undefined, ClientSecretPost2(flow.clientSecret));
42295
+ if (insecure)
42296
+ allowInsecureRequests2(config);
42297
+ config.timeout = ISSUER_TIMEOUT_SECONDS;
42298
+ config[customFetch2] = through(signal);
42299
+ answered = await refreshTokenGrant(config, refreshToken);
42300
+ } catch (error) {
42301
+ if (error instanceof ResponseBodyError && error.error === INVALID_GRANT) {
42302
+ throw new SignInEndedError(flow.issuer, person, { cause: error });
42303
+ }
42304
+ throw new Error(`renew ${person}'s sign-in at ${flow.issuer}: ${issuerSaid(error)}`);
42305
+ }
42306
+ const idToken = answered.id_token ?? "";
42307
+ if (idToken === "") {
42308
+ throw new Error(`${flow.issuer} answered no id_token: the sign-in asked for the "openid" scope and must be answered one`);
42309
+ }
42310
+ return { token: idToken, tokenType: SUBJECT_TOKEN_TYPE_PERSON };
42311
+ },
42312
+ describe: () => `${person}'s sign-in on this machine`
42313
+ };
42314
+ }
42315
+
42316
+ // ../broker-client/src/pool-identity.ts
42317
+ var DEFAULT_SECURITY_TOKEN_SERVICE_URL = "https://sts.googleapis.com/v1/token";
42318
+ var DEFAULT_IAM_CREDENTIALS_URL = "https://iamcredentials.googleapis.com";
42319
+ var REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
42320
+ var SCOPE = "https://www.googleapis.com/auth/cloud-platform";
42321
+ var SUBJECT_TOKEN_TYPE_JWT = "urn:ietf:params:oauth:token-type:jwt";
42322
+ var POOL_TIMEOUT_MS = 20000;
42323
+ var MAX_ANSWER_BYTES2 = 1 << 20;
42324
+ function poolSubjectTokenType(brokerType) {
42325
+ return brokerType === SUBJECT_TOKEN_TYPE_KUBERNETES ? SUBJECT_TOKEN_TYPE_JWT : brokerType;
42326
+ }
42327
+ function pathEscape(segment) {
42328
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(?:24|26|2B|3A|3D|40)/g, decodeURIComponent);
42329
+ }
42330
+ async function answerText(answer) {
42331
+ const reader = answer.body?.getReader();
42332
+ if (reader === undefined)
42333
+ return "";
42334
+ const chunks = [];
42335
+ let read = 0;
42336
+ while (read < MAX_ANSWER_BYTES2) {
42337
+ const { done, value } = await reader.read();
42338
+ if (done)
42339
+ break;
42340
+ const kept = value.subarray(0, MAX_ANSWER_BYTES2 - read);
42341
+ chunks.push(kept);
42342
+ read += kept.length;
42343
+ }
42344
+ await reader.cancel().catch(() => {
42345
+ return;
42346
+ });
42347
+ return Buffer.concat(chunks).toString("utf8");
42348
+ }
42349
+ function poolIdentity(options) {
42350
+ const securityTokenService = options.securityTokenServiceUrl ?? DEFAULT_SECURITY_TOKEN_SERVICE_URL;
42351
+ const iamCredentials = (options.iamCredentialsUrl ?? DEFAULT_IAM_CREDENTIALS_URL).replace(/\/$/, "");
42352
+ const account = pathEscape(options.serviceAccount);
42353
+ const mintEndpoint = `${iamCredentials}/v1/projects/-/serviceAccounts/${account}:generateIdToken`;
42354
+ const call = async (endpoint, bearer, body, member, signal) => {
42355
+ const signals = [AbortSignal.timeout(POOL_TIMEOUT_MS), signal].filter((one) => one !== undefined);
42356
+ const answer = await fetch(endpoint, {
42357
+ method: "POST",
42358
+ headers: {
42359
+ "Content-Type": "application/json",
42360
+ ...bearer === "" ? {} : { Authorization: `Bearer ${bearer}` }
42361
+ },
42362
+ body: JSON.stringify(body),
42363
+ signal: AbortSignal.any(signals)
42364
+ });
42365
+ const text = await answerText(answer);
42366
+ if (answer.status < 200 || answer.status > 299) {
42367
+ throw new Error(`HTTP ${answer.status}: ${text.trim()}`);
42368
+ }
42369
+ let parsed;
42370
+ try {
42371
+ parsed = JSON.parse(text);
42372
+ } catch {
42373
+ throw new Error(`HTTP ${answer.status}: the answer is not JSON`);
42374
+ }
42375
+ const value = typeof parsed === "object" && parsed !== null ? parsed[member] : undefined;
42376
+ return typeof value === "string" ? value : "";
42377
+ };
42378
+ const federate = async (subject, signal) => {
42379
+ let federated;
42380
+ try {
42381
+ federated = await call(securityTokenService, "", {
42382
+ audience: options.audience,
42383
+ grantType: GRANT_TYPE_TOKEN_EXCHANGE,
42384
+ requestedTokenType: REQUESTED_TOKEN_TYPE,
42385
+ scope: SCOPE,
42386
+ subjectTokenType: poolSubjectTokenType(subject.tokenType),
42387
+ subjectToken: subject.token
42388
+ }, "access_token", signal);
42389
+ } catch (error) {
42390
+ throw new Error(`trade this machine's credential at the security token service ${securityTokenService}: ${messageOf(error)}`, { cause: error });
42391
+ }
42392
+ if (federated === "") {
42393
+ throw new Error(`the security token service ${securityTokenService} answered no access_token`);
42394
+ }
42395
+ return federated;
42396
+ };
42397
+ const generateIdToken = async (federated, signal) => {
42398
+ let token;
42399
+ try {
42400
+ token = await call(mintEndpoint, federated, { audience: options.tokenAudience, includeEmail: true }, "token", signal);
42401
+ } catch (error) {
42402
+ throw new Error(`mint this machine's identity token at ${mintEndpoint}: ${messageOf(error)}`, { cause: error });
42403
+ }
42404
+ if (token === "")
42405
+ throw new Error(`generateIdToken at ${mintEndpoint} answered no token`);
42406
+ return token;
42407
+ };
42408
+ return {
42409
+ async read(signal) {
42410
+ let subject;
42411
+ try {
42412
+ subject = await options.subject.read(signal);
42413
+ } catch (error) {
42414
+ throw new Error(`read the credential the workload identity pool federates: ${messageOf(error)}`, { cause: error });
42415
+ }
42416
+ const federated = await federate(subject, signal);
42417
+ return {
42418
+ token: await generateIdToken(federated, signal),
42419
+ tokenType: SUBJECT_TOKEN_TYPE_GOOGLE
42420
+ };
42421
+ },
42422
+ describe: () => `a Google identity token for ${options.tokenAudience} minted through the workload identity pool ${options.audience} as ${options.serviceAccount}`
42423
+ };
42424
+ }
42425
+
42426
+ // ../broker-client/src/projected-token.ts
42427
+ import { readFile as readFile2 } from "fs/promises";
42428
+ function projectedToken(path) {
42429
+ return {
42430
+ async read(signal) {
42431
+ let contents;
42432
+ try {
42433
+ contents = await readFile2(path, {
42434
+ encoding: "utf8",
42435
+ ...signal === undefined ? {} : { signal }
42436
+ });
42437
+ } catch (error) {
42438
+ throw new Error(`read the projected service-account token ${path}: ${error.message}`);
42439
+ }
42440
+ const token = contents.trim();
42441
+ if (token === "")
42442
+ throw new Error(`the projected service-account token ${path} is empty`);
42443
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
42444
+ },
42445
+ describe: () => `the projected service-account token ${path}`
42446
+ };
42447
+ }
42448
+
41769
42449
  // ../broker-client/src/environment.ts
41770
42450
  var BROKER_URL_VAR = "AGENT_SECRETS_URL";
41771
42451
  var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
41772
42452
  var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
41773
42453
  var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
41774
42454
  var SESSION_VAR = "AGENT_SECRETS_SESSION";
42455
+ var POOL_AUDIENCE_VAR = "AGENT_SECRETS_POOL_AUDIENCE";
42456
+ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
41775
42457
  var IDENTITY_KUBERNETES = "kubernetes";
41776
42458
  var IDENTITY_METADATA = "metadata";
41777
42459
  var IDENTITY_POOL = "pool";
42460
+ var BROKER_VARIABLES = [
42461
+ BROKER_URL_VAR,
42462
+ IDENTITY_VAR,
42463
+ MACHINE_TOKEN_FILE_VAR,
42464
+ MACHINE_AUDIENCE_VAR,
42465
+ SESSION_VAR,
42466
+ POOL_AUDIENCE_VAR,
42467
+ POOL_ACCOUNT_VAR,
42468
+ SIGNIN_DIR_VAR,
42469
+ "XDG_STATE_HOME",
42470
+ "HOME",
42471
+ PERSON_VAR,
42472
+ PERSON_TRADE_VAR,
42473
+ SIGNIN_ISSUER_VAR,
42474
+ SIGNIN_CLIENT_ID_VAR,
42475
+ SIGNIN_CLIENT_SECRET_FILE_VAR
42476
+ ];
41778
42477
  function value(env, name) {
41779
42478
  return (env[name] ?? "").trim();
41780
42479
  }
@@ -41793,10 +42492,20 @@ function machineIdentity(env) {
41793
42492
  return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind));
41794
42493
  case IDENTITY_METADATA:
41795
42494
  return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
41796
- case IDENTITY_POOL:
41797
- throw new Error(`${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), which federates at the workload identity pool; this process can prove ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
42495
+ case IDENTITY_POOL: {
42496
+ const subject = required2(env, MACHINE_TOKEN_FILE_VAR, kind);
42497
+ const tokenAudience = required2(env, MACHINE_AUDIENCE_VAR, kind);
42498
+ const audience = required2(env, POOL_AUDIENCE_VAR, kind);
42499
+ const serviceAccount = required2(env, POOL_ACCOUNT_VAR, kind);
42500
+ return poolIdentity({
42501
+ subject: projectedToken(subject),
42502
+ audience,
42503
+ serviceAccount,
42504
+ tokenAudience
42505
+ });
42506
+ }
41798
42507
  default:
41799
- throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
42508
+ throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${IDENTITY_POOL}`);
41800
42509
  }
41801
42510
  }
41802
42511
  function tradeSession(env, own = "") {
@@ -41805,16 +42514,32 @@ function tradeSession(env, own = "") {
41805
42514
  }
41806
42515
  async function brokerTokenClient(env, own = "") {
41807
42516
  const brokerUrl = value(env, BROKER_URL_VAR);
41808
- const subject = machineIdentity(env);
41809
- if (brokerUrl === "" || subject === undefined)
42517
+ const machine = machineIdentity(env);
42518
+ if (brokerUrl === "" || machine === undefined)
41810
42519
  return;
41811
- return new BrokerTokenClient({
42520
+ const record = await chooseSignIn(env);
42521
+ if (record === undefined) {
42522
+ const client = new BrokerTokenClient({
42523
+ brokerUrl,
42524
+ key: await newDpopKey(),
42525
+ subject: machine,
42526
+ session: tradeSession(env, own),
42527
+ launcherCredential: false
42528
+ });
42529
+ return { client, signIn: undefined };
42530
+ }
42531
+ const flow = await signInFlow(env);
42532
+ if (flow === undefined) {
42533
+ throw new Error(`${record.person} is signed in on this machine, and this machine configures no sign-in client to renew that sign-in with: set ${SIGNIN_CLIENT_ID_VAR} and ${SIGNIN_CLIENT_SECRET_FILE_VAR}`);
42534
+ }
42535
+ const client = new BrokerTokenClient({
41812
42536
  brokerUrl,
41813
- key: await newDpopKey(),
41814
- subject,
41815
- session: tradeSession(env, own),
41816
- launcherCredential: false
42537
+ key: await importDpopKey(record.box_key, `${record.person}'s box key`),
42538
+ subject: personIdentity(record, flow),
42539
+ actor: machine,
42540
+ session: own.trim() || signInSessionName(record)
41817
42541
  });
42542
+ return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
41818
42543
  }
41819
42544
 
41820
42545
  // ../envoy-client/src/broker-credential.ts
@@ -41827,12 +42552,6 @@ function brokerRouteConfigured(env) {
41827
42552
  if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
41828
42553
  return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
41829
42554
  }
41830
- if ((env[IDENTITY_VAR] ?? "").trim() === IDENTITY_POOL) {
41831
- return {
41832
- traded: false,
41833
- gap: `${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), never by this process`
41834
- };
41835
- }
41836
42555
  if (machineIdentity(env) === undefined) {
41837
42556
  return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
41838
42557
  }
@@ -41842,37 +42561,91 @@ var CLIENTS = new Map;
41842
42561
  function forgetBrokerSession(session) {
41843
42562
  CLIENTS.delete(session.trim());
41844
42563
  }
41845
- function clientFor(env, own) {
41846
- const session = tradeSession(env, own);
41847
- const key = JSON.stringify([
41848
- env.AGENT_SECRETS_URL,
41849
- env.AGENT_SECRETS_MACHINE_IDENTITY,
41850
- env.AGENT_SECRETS_MACHINE_TOKEN_FILE,
41851
- env.AGENT_SECRETS_MACHINE_AUDIENCE
41852
- ]);
41853
- const held = CLIENTS.get(session) ?? new Map;
41854
- CLIENTS.set(session, held);
41855
- const made = held.get(key) ?? brokerTokenClient(env, session);
41856
- held.set(key, made);
41857
- return made;
42564
+ function signInName(record) {
42565
+ return `${record.person}\x00${record.thumbprint}`;
42566
+ }
42567
+ function keyOf(env, own) {
42568
+ return {
42569
+ session: own.trim(),
42570
+ variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
42571
+ };
42572
+ }
42573
+ function entryFor(key) {
42574
+ let sessions = CLIENTS.get(key.session);
42575
+ if (sessions === undefined) {
42576
+ sessions = new Map;
42577
+ CLIENTS.set(key.session, sessions);
42578
+ }
42579
+ let entry = sessions.get(key.variables);
42580
+ if (entry === undefined) {
42581
+ entry = { making: undefined, made: undefined, refused: new Map };
42582
+ sessions.set(key.variables, entry);
42583
+ }
42584
+ return entry;
42585
+ }
42586
+ async function make(env, own) {
42587
+ const made = await brokerTokenClient(env, own);
42588
+ const signIn = made?.signIn;
42589
+ return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
42590
+ }
42591
+ async function clientFor(env, own) {
42592
+ const key = keyOf(env, own);
42593
+ const entry = entryFor(key);
42594
+ if (entry.refused.size > 0) {
42595
+ const record = await chooseSignIn(env);
42596
+ const chosen = record === undefined ? "" : signInName(record);
42597
+ if (entry.refused.has(chosen))
42598
+ throw entry.refused.get(chosen);
42599
+ if (entry.made !== undefined && entry.made.signIn !== chosen) {
42600
+ entry.making = undefined;
42601
+ entry.made = undefined;
42602
+ }
42603
+ }
42604
+ let making = entry.making;
42605
+ if (making === undefined) {
42606
+ const started = make(env, key.session);
42607
+ making = started;
42608
+ entry.making = started;
42609
+ started.then((made) => {
42610
+ if (entry.making === started)
42611
+ entry.made = made;
42612
+ }, () => {
42613
+ if (entry.making === started)
42614
+ entry.making = undefined;
42615
+ });
42616
+ }
42617
+ return { entry, made: await making };
41858
42618
  }
41859
42619
  function brokerCredential(env, session) {
41860
- let held = "";
42620
+ let presented = "";
42621
+ const own = (acting) => (acting ?? "").trim() || sessionName(session);
41861
42622
  return {
41862
42623
  scheme: "DPoP",
41863
42624
  async headers(method, url, acting) {
41864
- const client = await clientFor(env, (acting ?? "").trim() || sessionName(session));
42625
+ const { entry, made } = await clientFor(env, own(acting));
42626
+ const { client } = made;
41865
42627
  if (client === undefined) {
41866
42628
  throw new Error("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
41867
42629
  }
41868
- const token = await client.token();
41869
- held = token.accessToken;
42630
+ let token;
42631
+ try {
42632
+ token = await client.token();
42633
+ } catch (error) {
42634
+ if (made.signIn !== "" && isFinalRefusal(error))
42635
+ entry.refused.set(made.signIn, error);
42636
+ throw error;
42637
+ }
42638
+ presented = token.accessToken;
41870
42639
  return {
41871
42640
  Authorization: `DPoP ${token.accessToken}`,
41872
42641
  DPoP: await client.key.proof({ method, url, accessToken: token.accessToken })
41873
42642
  };
41874
42643
  },
41875
- secret: () => held
42644
+ stale(acting) {
42645
+ const key = keyOf(env, own(acting));
42646
+ CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop();
42647
+ },
42648
+ secret: () => presented
41876
42649
  };
41877
42650
  }
41878
42651
 
@@ -43046,6 +43819,9 @@ class DispatchNoRouteError extends DispatchServiceError {
43046
43819
  super("NOT_FOUND", 404, NO_ROUTE_ROLLING_RELEASE_MESSAGE);
43047
43820
  }
43048
43821
  }
43822
+ function reviewNoRouteRefusal(baseUrl, route, version) {
43823
+ return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${baseUrl} answered no route for ${route} each time the review was sent, and an ` + "answer of no route records no review. This build is older than that route. No other review " + "route was asked: the review route an older build serves takes no version, and it " + `would record the review at a version that build chooses, which may not be version ${version}. ` + `The no-route answer does not name the build; GET ${baseUrl}/healthz names the commit of the ` + "build that answers it, when that build was stamped with one.");
43824
+ }
43049
43825
  var ISSUE_EVENTS_PAGE_MAX = 200;
43050
43826
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
43051
43827
  function requestSignal(signal) {
@@ -43179,6 +43955,15 @@ async function writeAnswer(response, key) {
43179
43955
  unjudged: !echoed && typeof shape.error === "string"
43180
43956
  };
43181
43957
  }
43958
+ var BROKER_TOKEN_NOT_ACTIVE = "BROKER_TOKEN_NOT_ACTIVE";
43959
+ async function tokenNotLive(response) {
43960
+ if (response.status !== 401 || !isJson(response))
43961
+ return false;
43962
+ const body = await response.clone().json().catch(() => {
43963
+ return;
43964
+ });
43965
+ return asErrorShape(body).code === BROKER_TOKEN_NOT_ACTIVE;
43966
+ }
43182
43967
  function whyNotAPage(answer) {
43183
43968
  if (typeof answer === "string") {
43184
43969
  return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
@@ -43501,6 +44286,18 @@ class DispatchClient {
43501
44286
  async planApprove(artifactID, input) {
43502
44287
  return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
43503
44288
  }
44289
+ async reviewArtifact(artifactID, version, input) {
44290
+ const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
44291
+ const body = { state: input.state, reason: input.reason };
44292
+ try {
44293
+ return await this.#json("POST", path, body);
44294
+ } catch (error) {
44295
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
44296
+ throw error;
44297
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
44298
+ throw reviewNoRouteRefusal(this.#baseUrl, route, version);
44299
+ }
44300
+ }
43504
44301
  async recordResult(issue, input) {
43505
44302
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
43506
44303
  }
@@ -43736,11 +44533,20 @@ class DispatchClient {
43736
44533
  });
43737
44534
  }
43738
44535
  async#send(method, url, body, accept = "application/json", signal, callerKey) {
44536
+ const key = method === "POST" || method === "PATCH" ? callerKey ?? crypto.randomUUID() : undefined;
44537
+ const send = async () => this.#sendPresenting(method, url, body, accept, signal, key);
44538
+ const answer = await send();
44539
+ if (this.#credential.stale === undefined || !await tokenNotLive(answer))
44540
+ return answer;
44541
+ this.#credential.stale();
44542
+ return await send();
44543
+ }
44544
+ async#sendPresenting(method, url, body, accept, signal, key) {
43739
44545
  const headers = { Accept: accept };
43740
44546
  let presented = await this.#credential.headers(method, url);
43741
44547
  if (body !== undefined)
43742
44548
  headers["Content-Type"] = body.type;
43743
- if (method !== "POST" && method !== "PATCH") {
44549
+ if (key === undefined) {
43744
44550
  return this.fetchImpl(url, {
43745
44551
  method,
43746
44552
  headers: { ...headers, ...presented },
@@ -43748,7 +44554,6 @@ class DispatchClient {
43748
44554
  ...body === undefined ? {} : { body: body.content }
43749
44555
  });
43750
44556
  }
43751
- const key = callerKey ?? crypto.randomUUID();
43752
44557
  headers[IDEMPOTENCY_KEY_HEADER] = key;
43753
44558
  const { pausesMs, withinMs, silenceMs, inFlightPauseMs, inFlightWithinMs } = this.writeRetry;
43754
44559
  const pause = this.writeRetry.pause ?? pauseFor;
@@ -46817,7 +47622,7 @@ function brokerRouteForced(env) {
46817
47622
  return false;
46818
47623
  if (written === "1")
46819
47624
  return true;
46820
- return offWithError(`DISPATCH_TOKEN_BROKER is "${written}" and takes 1: set it to 1 where this session's Dispatch credential is this machine's own identity traded at the secrets broker, and leave it unset where a bearer is read as usual`);
47625
+ return offWithError(`DISPATCH_TOKEN_BROKER is "${written}" and takes 1: set it to 1 where this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and leave it unset where a bearer is read as usual`);
46821
47626
  }
46822
47627
  function dispatchTarget(env, config) {
46823
47628
  if (config.kind === "failed")
@@ -46868,7 +47673,7 @@ function dispatchTarget(env, config) {
46868
47673
  return { enabled: true, url: brokered, source: { kind: "broker" } };
46869
47674
  }
46870
47675
  if (forced) {
46871
- return offWithError(`DISPATCH_TOKEN_BROKER is set, so this session's Dispatch credential is this machine's own identity traded at the secrets broker, and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
47676
+ return offWithError(`DISPATCH_TOKEN_BROKER is set, so this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
46872
47677
  }
46873
47678
  return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
46874
47679
  }
@@ -46887,20 +47692,20 @@ function activeDispatchSettings(resolution) {
46887
47692
  import { randomUUID } from "crypto";
46888
47693
  import { renameSync, rmSync as rmSync2, writeFileSync } from "fs";
46889
47694
  import { homedir as homedir2 } from "os";
46890
- import { join as join2 } from "path";
47695
+ import { join as join3 } from "path";
46891
47696
  var SESSION_ID_PATH_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/;
46892
47697
  var PRIVATE_FILE = 384;
46893
47698
  function sessionStateRoot(env) {
46894
47699
  const stateDir = env["DISPATCH_STATE_DIR"];
46895
47700
  if (stateDir)
46896
47701
  return stateDir;
46897
- return join2(env["XDG_STATE_HOME"] || join2(homedir2(), ".local", "state"), "dispatch");
47702
+ return join3(env["XDG_STATE_HOME"] || join3(homedir2(), ".local", "state"), "dispatch");
46898
47703
  }
46899
47704
  function sessionDirectory(env, sessionId) {
46900
47705
  if (!SESSION_ID_PATH_SEGMENT.test(sessionId) || sessionId === "." || sessionId === "..") {
46901
47706
  throw new Error(`dispatch: the session id ${JSON.stringify(sessionId)} is not 1-128 letters, digits, ".", "_" or "-"`);
46902
47707
  }
46903
- return join2(sessionStateRoot(env), "sessions", sessionId);
47708
+ return join3(sessionStateRoot(env), "sessions", sessionId);
46904
47709
  }
46905
47710
  function writeAtomically(path, text) {
46906
47711
  const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
@@ -46928,7 +47733,7 @@ import {
46928
47733
  statSync as statSync3,
46929
47734
  writeFileSync as writeFileSync3
46930
47735
  } from "fs";
46931
- import { join as join5 } from "path";
47736
+ import { join as join6 } from "path";
46932
47737
 
46933
47738
  // ../envoy-client/src/askgate-marker.ts
46934
47739
  import { createHash, randomBytes } from "crypto";
@@ -46947,7 +47752,7 @@ import {
46947
47752
  utimesSync,
46948
47753
  writeFileSync as writeFileSync2
46949
47754
  } from "fs";
46950
- import { isAbsolute as isAbsolute2, join as join3, resolve as resolve2 } from "path";
47755
+ import { isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "path";
46951
47756
  var ASKGATE_RECORD = "askgate";
46952
47757
  var MARKER_MAX_AGE_MS = 2 * 60 * 60000;
46953
47758
  var STORE_BEAT_MS = 10 * 60000;
@@ -47069,7 +47874,7 @@ var STORE_NAME = /^([1-9][0-9]*)(?:-([0-9]+)(?:-([0-9]+))?)?$/;
47069
47874
  function storeTouched(store) {
47070
47875
  const own = statSync2(store).mtimeMs;
47071
47876
  try {
47072
- return Math.max(own, statSync2(join3(store, MARKERS)).mtimeMs);
47877
+ return Math.max(own, statSync2(join4(store, MARKERS)).mtimeMs);
47073
47878
  } catch (error) {
47074
47879
  if (hasErrnoCode(error, "ENOENT"))
47075
47880
  return own;
@@ -47078,7 +47883,7 @@ function storeTouched(store) {
47078
47883
  }
47079
47884
  var UNNAMESPACED_STORE_MAX_AGE_MS = 14 * 86400000;
47080
47885
  function sweepStores(root, now) {
47081
- const parent = join3(root, "askgate");
47886
+ const parent = join4(root, "askgate");
47082
47887
  let names;
47083
47888
  try {
47084
47889
  names = readdirSync(parent);
@@ -47089,7 +47894,7 @@ function sweepStores(root, now) {
47089
47894
  const match = STORE_NAME.exec(name);
47090
47895
  if (match === null)
47091
47896
  continue;
47092
- const store = join3(parent, name);
47897
+ const store = join4(parent, name);
47093
47898
  try {
47094
47899
  const owner = { pid: Number(match[1]), start: match[2] ?? null, ns: match[3] ?? null, store };
47095
47900
  if (ownerLive(owner, now))
@@ -47103,7 +47908,7 @@ function sweepStores(root, now) {
47103
47908
  }
47104
47909
  }
47105
47910
  function recordNamesStore(dir) {
47106
- const record = join3(dir, ASKGATE_RECORD);
47911
+ const record = join4(dir, ASKGATE_RECORD);
47107
47912
  let names;
47108
47913
  try {
47109
47914
  names = readdirSync(record);
@@ -47114,7 +47919,7 @@ function recordNamesStore(dir) {
47114
47919
  if (!name.endsWith(OWNER_FILE))
47115
47920
  continue;
47116
47921
  try {
47117
- const parsed = parseOwner(readFileSync3(join3(record, name), "utf-8"));
47922
+ const parsed = parseOwner(readFileSync3(join4(record, name), "utf-8"));
47118
47923
  if (parsed === undefined)
47119
47924
  return true;
47120
47925
  statSync2(parsed.owner.store);
@@ -47127,7 +47932,7 @@ function recordNamesStore(dir) {
47127
47932
  return false;
47128
47933
  }
47129
47934
  function askgateState(dir, now = Date.now()) {
47130
- const record = join3(dir, ASKGATE_RECORD);
47935
+ const record = join4(dir, ASKGATE_RECORD);
47131
47936
  let names;
47132
47937
  try {
47133
47938
  names = readdirSync(record);
@@ -47140,7 +47945,7 @@ function askgateState(dir, now = Date.now()) {
47140
47945
  for (const name of names) {
47141
47946
  if (!name.endsWith(OWNER_FILE))
47142
47947
  continue;
47143
- const file = join3(record, name);
47948
+ const file = join4(record, name);
47144
47949
  let text;
47145
47950
  try {
47146
47951
  text = readFileSync3(file, "utf-8");
@@ -47160,7 +47965,7 @@ function askgateState(dir, now = Date.now()) {
47160
47965
  return { kind: "off" };
47161
47966
  for (const { file, store } of live) {
47162
47967
  try {
47163
- if (!statSync2(join3(store, MARKERS)).isDirectory())
47968
+ if (!statSync2(join4(store, MARKERS)).isDirectory())
47164
47969
  throw new Error("not a directory");
47165
47970
  } catch (error) {
47166
47971
  return {
@@ -47212,11 +48017,11 @@ function consumeMarker(stores, argv, args, files, now) {
47212
48017
  let expired = false;
47213
48018
  const usable = [];
47214
48019
  for (const store of stores) {
47215
- const dir = join3(store, MARKERS);
48020
+ const dir = join4(store, MARKERS);
47216
48021
  for (const name of readdirSync(dir)) {
47217
48022
  if (!name.startsWith(`${key}.`))
47218
48023
  continue;
47219
- const file = join3(dir, name);
48024
+ const file = join4(dir, name);
47220
48025
  const marker = readMarker(file);
47221
48026
  if (marker === undefined || marker.argv !== key)
47222
48027
  continue;
@@ -51700,9 +52505,44 @@ async function readCommand(context) {
51700
52505
  };
51701
52506
  }
51702
52507
 
52508
+ // ../envoy-client/src/dispatch-commands/reviews.ts
52509
+ async function reviewCommand(context) {
52510
+ const { args, client, documentOwner, resolveDocument } = context;
52511
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
52512
+ const { artifact } = resolved;
52513
+ let review;
52514
+ try {
52515
+ review = await client.reviewArtifact(artifact.id, numberArg(args, "version"), {
52516
+ state: stringArg(args, "verdict"),
52517
+ ...defined("reason", optionalString(args, "reason"))
52518
+ });
52519
+ } catch (error) {
52520
+ throw refusalWithCode(error);
52521
+ }
52522
+ const issue = resolved.issue?.key;
52523
+ const answered = review.ask_id === null ? [] : [
52524
+ `It also answered the open approval request (ask ${review.ask_id}), so Dispatch recorded the same verdict on every document that request named, each at the version the request named for it. Dispatch answered with the review of ${artifact.name} alone, so no other document's review is shown here; ${commandLine("dispatch_doc_read", { issue })} --artifact <document> prints the approval each of them now reads.`
52525
+ ];
52526
+ return {
52527
+ text: [
52528
+ `Recorded the review of ${artifact.name} (document id ${artifact.id}): ${review.state} at version ${review.version}, by ${actorText(review.actor)}.`,
52529
+ ...review.reason === null ? [] : [`Reason: ${JSON.stringify(review.reason)}`],
52530
+ ...answered
52531
+ ].join(`
52532
+ `),
52533
+ details: {
52534
+ issue,
52535
+ artifact: artifact.id,
52536
+ version: review.version,
52537
+ state: review.state,
52538
+ ...review.ask_id === null ? {} : { ask: review.ask_id }
52539
+ }
52540
+ };
52541
+ }
52542
+
51703
52543
  // ../envoy-client/src/session-answers.ts
51704
52544
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "fs";
51705
- import { join as join4 } from "path";
52545
+ import { join as join5 } from "path";
51706
52546
  var SESSION_ANSWERS_WINDOW_MS = 72 * 3600000;
51707
52547
  var SESSION_ANSWERS_MAX_CHARS = 8000;
51708
52548
  var SESSION_ANSWERS_DEADLINE_MS = 800;
@@ -51830,7 +52670,7 @@ processGlobal2[STATE_KEY] = state;
51830
52670
  var CACHE_FILE = "answers.json";
51831
52671
  function readCacheFile(directory, url) {
51832
52672
  try {
51833
- const value = JSON.parse(readFileSync4(join4(directory, CACHE_FILE), "utf-8"));
52673
+ const value = JSON.parse(readFileSync4(join5(directory, CACHE_FILE), "utf-8"));
51834
52674
  if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
51835
52675
  return {
51836
52676
  dispatch_url: value.dispatch_url,
@@ -51948,7 +52788,7 @@ async function readSessionAnswers(options) {
51948
52788
  if (directory !== undefined) {
51949
52789
  try {
51950
52790
  mkdirSync2(directory, { recursive: true, mode: 448 });
51951
- writeAtomically(join4(directory, CACHE_FILE), JSON.stringify(cache));
52791
+ writeAtomically(join5(directory, CACHE_FILE), JSON.stringify(cache));
51952
52792
  } catch {}
51953
52793
  }
51954
52794
  return { cache };
@@ -52227,6 +53067,7 @@ var dispatchCommands = {
52227
53067
  dispatch_doc_read: acting(docReadCommand),
52228
53068
  dispatch_request_approval: acting(requestApprovalCommand),
52229
53069
  dispatch_plan_approve: acting(planApproveCommand),
53070
+ dispatch_review: acting(reviewCommand),
52230
53071
  dispatch_result: acting(resultCommand),
52231
53072
  dispatch_results: acting(resultsCommand),
52232
53073
  dispatch_artifact: acting(artifactCommand),
@@ -52281,7 +53122,7 @@ function stringList(value) {
52281
53122
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
52282
53123
  }
52283
53124
  function loadSessionMemory(dir, sessionId) {
52284
- const path = join5(dir, "state.json");
53125
+ const path = join6(dir, "state.json");
52285
53126
  const text = readIfPresent(path);
52286
53127
  if (text === undefined)
52287
53128
  return new Set;
@@ -52307,7 +53148,7 @@ function writeMemory(dir, sessionId, follows) {
52307
53148
  follows: [...follows],
52308
53149
  keyedLayer: keyedLayerMemory()
52309
53150
  };
52310
- writeAtomically(join5(dir, "state.json"), `${JSON.stringify(state)}
53151
+ writeAtomically(join6(dir, "state.json"), `${JSON.stringify(state)}
52311
53152
  `);
52312
53153
  }
52313
53154
  function appendResult(dir, entry) {
@@ -52316,7 +53157,7 @@ function appendResult(dir, entry) {
52316
53157
  }
52317
53158
  function writeResult(dir, entry) {
52318
53159
  const line = { at: new Date().toISOString(), ...entry };
52319
- appendFileSync(join5(dir, "results.jsonl"), `${JSON.stringify(line)}
53160
+ appendFileSync(join6(dir, "results.jsonl"), `${JSON.stringify(line)}
52320
53161
  `, { mode: PRIVATE_FILE2 });
52321
53162
  }
52322
53163
  function recordOutcome(dir, sessionId, follows, entry) {
@@ -52327,8 +53168,8 @@ function recordOutcome(dir, sessionId, follows, entry) {
52327
53168
  function writePicture(dir, image) {
52328
53169
  const bytes = Buffer.from(image.data, "base64");
52329
53170
  const name = createHash2("sha256").update(bytes).digest("hex").slice(0, 16);
52330
- const pictures = join5(dir, "pictures");
52331
- const path = join5(pictures, `${name}.${PICTURE_EXTENSIONS[image.mimeType]}`);
53171
+ const pictures = join6(dir, "pictures");
53172
+ const path = join6(pictures, `${name}.${PICTURE_EXTENSIONS[image.mimeType]}`);
52332
53173
  ensureDirectory(pictures);
52333
53174
  try {
52334
53175
  writeFileSync3(path, bytes, { mode: PRIVATE_FILE2, flag: "wx" });
@@ -52339,21 +53180,21 @@ function writePicture(dir, image) {
52339
53180
  return { path, bytes: bytes.length };
52340
53181
  }
52341
53182
  function writeLongOutput(dir, text) {
52342
- const out = join5(dir, "out");
53183
+ const out = join6(dir, "out");
52343
53184
  ensureDirectory(out);
52344
- const path = join5(out, `${new Date().toISOString().replaceAll(":", "-")}-${process.pid}.md`);
53185
+ const path = join6(out, `${new Date().toISOString().replaceAll(":", "-")}-${process.pid}.md`);
52345
53186
  writeFileSync3(path, text, { mode: PRIVATE_FILE2 });
52346
53187
  return path;
52347
53188
  }
52348
53189
  function writeSessionTitle(dir, title) {
52349
53190
  ensureDirectory(dir);
52350
- writeAtomically(join5(dir, "title"), title);
53191
+ writeAtomically(join6(dir, "title"), title);
52351
53192
  }
52352
53193
  function readSessionTitle(dir) {
52353
- return readIfPresent(join5(dir, "title")) || undefined;
53194
+ return readIfPresent(join6(dir, "title")) || undefined;
52354
53195
  }
52355
53196
  function pruneSessions(root, now) {
52356
- const stamp = join5(root, PRUNED_STAMP);
53197
+ const stamp = join6(root, PRUNED_STAMP);
52357
53198
  try {
52358
53199
  if (now - statSync3(stamp).mtimeMs < PRUNE_INTERVAL_MS)
52359
53200
  return;
@@ -52361,7 +53202,7 @@ function pruneSessions(root, now) {
52361
53202
  if (!hasErrnoCode(error, "ENOENT"))
52362
53203
  throw error;
52363
53204
  }
52364
- const sessions = join5(root, "sessions");
53205
+ const sessions = join6(root, "sessions");
52365
53206
  let entries = [];
52366
53207
  try {
52367
53208
  entries = readdirSync2(sessions, { withFileTypes: true });
@@ -52372,7 +53213,7 @@ function pruneSessions(root, now) {
52372
53213
  for (const entry of entries) {
52373
53214
  if (!entry.isDirectory())
52374
53215
  continue;
52375
- const dir = join5(sessions, entry.name);
53216
+ const dir = join6(sessions, entry.name);
52376
53217
  try {
52377
53218
  const idle = now - statSync3(dir).mtimeMs > IDLE_SESSION_MS;
52378
53219
  if (idle && askgateState(dir, now).kind === "off" && !recordNamesStore(dir)) {
@@ -56561,7 +57402,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
56561
57402
 
56562
57403
  // package.json
56563
57404
  var name = "@sjawhar/claude-envoy";
56564
- var version2 = "2.27.0";
57405
+ var version2 = "2.28.0";
56565
57406
  var legion = {
56566
57407
  daemonApiVersion: 141
56567
57408
  };
@@ -57517,13 +58358,13 @@ function claudeProjectDirectory(environment, fallback) {
57517
58358
  }
57518
58359
 
57519
58360
  // src/session-identity.ts
57520
- import { readFile as readFile2 } from "fs/promises";
57521
- import { basename as basename2, join as join7 } from "path";
58361
+ import { readFile as readFile3 } from "fs/promises";
58362
+ import { basename as basename2, join as join8 } from "path";
57522
58363
 
57523
58364
  // src/session-state.ts
57524
58365
  import { readFileSync as readFileSync6 } from "fs";
57525
- import { mkdir, readdir, rename, rm, stat, utimes, writeFile } from "fs/promises";
57526
- import { dirname as dirname2, join as join6 } from "path";
58366
+ import { mkdir, readdir as readdir2, rename, rm, stat, utimes, writeFile } from "fs/promises";
58367
+ import { dirname as dirname2, join as join7 } from "path";
57527
58368
  async function writeAtomicStateFile(file, contents) {
57528
58369
  await mkdir(dirname2(file), { recursive: true, mode: 448 });
57529
58370
  const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
@@ -57535,13 +58376,13 @@ async function touchStateFile(file) {
57535
58376
  await utimes(file, now, now);
57536
58377
  }
57537
58378
  async function pruneStateDirectory(directory, isStale) {
57538
- const entries = await readdir(directory).catch((error) => {
58379
+ const entries = await readdir2(directory).catch((error) => {
57539
58380
  if (hasErrnoCode(error, "ENOENT"))
57540
58381
  return [];
57541
58382
  throw error;
57542
58383
  });
57543
58384
  for (const entry of entries) {
57544
- const file = join6(directory, entry);
58385
+ const file = join7(directory, entry);
57545
58386
  if (!await isStale(file))
57546
58387
  continue;
57547
58388
  await rm(file, { recursive: true, force: true });
@@ -57556,7 +58397,7 @@ async function writtenLongAgo(file) {
57556
58397
  }
57557
58398
  var TITLES_DIRECTORY = "titles";
57558
58399
  function sessionTitleFile(stateDirectory, sessionId) {
57559
- return join6(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
58400
+ return join7(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
57560
58401
  }
57561
58402
  async function writeChosenTitle(file, title) {
57562
58403
  await writeAtomicStateFile(file, `${title}
@@ -57584,7 +58425,7 @@ async function recordChosenTitle(sessionId, title) {
57584
58425
  await writeChosenTitle(file, chosen);
57585
58426
  }
57586
58427
  async function pruneStaleSessionTitles(stateDirectory) {
57587
- await pruneStateDirectory(join6(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
58428
+ await pruneStateDirectory(join7(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
57588
58429
  }
57589
58430
 
57590
58431
  // src/session-identity.ts
@@ -57609,14 +58450,14 @@ class SessionIdentity {
57609
58450
  }
57610
58451
  }
57611
58452
  function sessionHandoffDirectory(stateDirectory, claudePid) {
57612
- return join7(stateDirectory, "sessions", String(claudePid));
58453
+ return join8(stateDirectory, "sessions", String(claudePid));
57613
58454
  }
57614
58455
  function sessionHandoffFile(stateDirectory, claudePid) {
57615
- return join7(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
58456
+ return join8(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
57616
58457
  }
57617
58458
  var ROLES_DIRECTORY = "roles";
57618
58459
  function roleStateFile(stateDirectory, sessionId) {
57619
- return join7(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
58460
+ return join8(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
57620
58461
  }
57621
58462
 
57622
58463
  class UnparseableRoleRecordError extends Error {
@@ -57628,7 +58469,7 @@ class UnparseableRoleRecordError extends Error {
57628
58469
  async function readPersistedRole(roleFile) {
57629
58470
  let bytes;
57630
58471
  try {
57631
- bytes = await readFile2(roleFile, "utf8");
58472
+ bytes = await readFile3(roleFile, "utf8");
57632
58473
  } catch (error) {
57633
58474
  if (hasErrnoCode(error, "ENOENT"))
57634
58475
  return;
@@ -57650,7 +58491,7 @@ async function writeSessionHandoff(file, sessionId) {
57650
58491
  }
57651
58492
  async function readSessionHandoff(file) {
57652
58493
  try {
57653
- const id = (await readFile2(file, "utf8")).trim();
58494
+ const id = (await readFile3(file, "utf8")).trim();
57654
58495
  return id.length === 0 ? undefined : id;
57655
58496
  } catch (error) {
57656
58497
  if (hasErrnoCode(error, "ENOENT"))
@@ -57667,14 +58508,14 @@ function processExists(pid) {
57667
58508
  }
57668
58509
  }
57669
58510
  async function pruneStaleSessionHandoffs(stateDirectory) {
57670
- await pruneStateDirectory(join7(stateDirectory, "sessions"), (file) => {
58511
+ await pruneStateDirectory(join8(stateDirectory, "sessions"), (file) => {
57671
58512
  const pid = basename2(file);
57672
58513
  return /^\d+$/.test(pid) && !processExists(Number(pid));
57673
58514
  });
57674
58515
  }
57675
58516
  async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
57676
58517
  const own = roleStateFile(stateDirectory, currentSessionId);
57677
- await pruneStateDirectory(join7(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
58518
+ await pruneStateDirectory(join8(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
57678
58519
  }
57679
58520
 
57680
58521
  // src/envoy-off.ts
@@ -57746,8 +58587,8 @@ function installedPluginVersion(bundlePath) {
57746
58587
  }
57747
58588
 
57748
58589
  // src/legion-claim.ts
57749
- import { readdir as readdir2, stat as stat2 } from "fs/promises";
57750
- import { join as join9 } from "path";
58590
+ import { readdir as readdir3, stat as stat2 } from "fs/promises";
58591
+ import { join as join10 } from "path";
57751
58592
  import { setTimeout as delay } from "timers/promises";
57752
58593
 
57753
58594
  // ../pi-shared/src/stall-limits.ts
@@ -57894,7 +58735,7 @@ function claimRoleAtFirstTurn(host, role, firstTurn) {
57894
58735
  // src/legion-phase-hook.ts
57895
58736
  import { randomUUID as randomUUID3 } from "crypto";
57896
58737
  import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
57897
- import { dirname as dirname3, join as join8 } from "path";
58738
+ import { dirname as dirname3, join as join9 } from "path";
57898
58739
 
57899
58740
  // ../pi-shared/src/phase-reminder.ts
57900
58741
  import { randomUUID as randomUUID2 } from "crypto";
@@ -58347,7 +59188,7 @@ function phaseHookToolDefinition() {
58347
59188
  };
58348
59189
  }
58349
59190
  function phaseStallFile(configDir, sessionID) {
58350
- return join8(configDir, `legion-phase-stall-${sessionID}.json`);
59191
+ return join9(configDir, `legion-phase-stall-${sessionID}.json`);
58351
59192
  }
58352
59193
  function paneReminderLog(write) {
58353
59194
  const line = (level, message, context) => {
@@ -58400,7 +59241,7 @@ function readPhaseStallRecord(file, log) {
58400
59241
  };
58401
59242
  }
58402
59243
  function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
58403
- const temporary = join8(dirname3(file), `.legion-phase-stall-${randomUUID3()}`);
59244
+ const temporary = join9(dirname3(file), `.legion-phase-stall-${randomUUID3()}`);
58404
59245
  try {
58405
59246
  writeFileSync4(temporary, JSON.stringify({ ...entry, ...recreatedNoticeSent ? { recreatedNoticeSent } : {} }), { mode: 384 });
58406
59247
  renameSync3(temporary, file);
@@ -58605,12 +59446,12 @@ function stopPane(why) {
58605
59446
  endPane();
58606
59447
  }
58607
59448
  async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
58608
- const projects = join9(configDir, "projects");
59449
+ const projects = join10(configDir, "projects");
58609
59450
  const name = `${sessionID}.jsonl`;
58610
59451
  for (;; ) {
58611
59452
  signal.throwIfAborted();
58612
- for (const directory of await readdir2(projects).catch(() => [])) {
58613
- const file = join9(projects, directory, name);
59453
+ for (const directory of await readdir3(projects).catch(() => [])) {
59454
+ const file = join10(projects, directory, name);
58614
59455
  if (await isFile(file))
58615
59456
  return file;
58616
59457
  }
@@ -59710,14 +60551,14 @@ function modSession(options) {
59710
60551
  }
59711
60552
 
59712
60553
  // src/replay-state.ts
59713
- import { join as join10 } from "path";
60554
+ import { join as join11 } from "path";
59714
60555
 
59715
60556
  // src/state-file.ts
59716
- import { readFile as readFile3 } from "fs/promises";
60557
+ import { readFile as readFile4 } from "fs/promises";
59717
60558
  async function readStateFile(file, schema, empty, refusal) {
59718
60559
  let text;
59719
60560
  try {
59720
- text = await readFile3(file, "utf8");
60561
+ text = await readFile4(file, "utf8");
59721
60562
  } catch (error) {
59722
60563
  if (hasErrnoCode(error, "ENOENT"))
59723
60564
  return empty;
@@ -59740,7 +60581,7 @@ var ReplayStateFileSchema = LedgerSnapshotSchema.extend({
59740
60581
  consumer: ConsumerDeliverySnapshotSchema.optional()
59741
60582
  });
59742
60583
  function replayStateFile(stateDirectory, sessionId) {
59743
- return join10(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
60584
+ return join11(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
59744
60585
  }
59745
60586
  async function readReplayState(file) {
59746
60587
  return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no delivery state");
@@ -60235,7 +61076,7 @@ function createUserTurnRouter(options) {
60235
61076
  }
60236
61077
 
60237
61078
  // src/user-turn-state.ts
60238
- import { join as join11 } from "path";
61079
+ import { join as join12 } from "path";
60239
61080
  var TURNS_DIRECTORY = "turns";
60240
61081
  var HANDLED_ATTEMPTS_MAX = 1000;
60241
61082
  var DELIVERED_ROWS_MAX = 1000;
@@ -60245,7 +61086,7 @@ var UserTurnStateSchema = object({
60245
61086
  rows: array(DeliveredRowSchema).default([])
60246
61087
  });
60247
61088
  function userTurnStateFile(stateDirectory, sessionId) {
60248
- return join11(stateDirectory, TURNS_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
61089
+ return join12(stateDirectory, TURNS_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
60249
61090
  }
60250
61091
  async function readUserTurnState(file) {
60251
61092
  return await readStateFile(file, UserTurnStateSchema, { handled: [], rows: [] }, "holds no record of this session's turns");
@@ -60283,7 +61124,7 @@ function userTurnState(file, restored) {
60283
61124
  };
60284
61125
  }
60285
61126
  async function pruneStaleSessionTurns(stateDirectory) {
60286
- await pruneStateDirectory(join11(stateDirectory, TURNS_DIRECTORY), writtenLongAgo);
61127
+ await pruneStateDirectory(join12(stateDirectory, TURNS_DIRECTORY), writtenLongAgo);
60287
61128
  }
60288
61129
 
60289
61130
  // src/envoy-channel-server.ts