@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.
package/dist/dispatch.js CHANGED
@@ -15256,6 +15256,14 @@ var handoffValidation = {
15256
15256
  message: HANDOFF_RULE,
15257
15257
  refusal: (value) => handoffProblem(value) ?? HANDOFF_RULE
15258
15258
  };
15259
+ var REVIEW_REASON_RULE = "verdict changes_requested requires reason, a non-empty note saying what must change before the document can be approved.";
15260
+ var reviewValidation = {
15261
+ check: (value) => {
15262
+ const input = value;
15263
+ return input.verdict !== "changes_requested" || typeof input.reason === "string" && input.reason.trim() !== "";
15264
+ },
15265
+ message: REVIEW_REASON_RULE
15266
+ };
15259
15267
  var RESULT_REQUIRED_FIELDS = ["issue", "check", "role", "verdict", "commit"];
15260
15268
  var RESULT_RECORD_FIELDS = [
15261
15269
  ...RESULT_REQUIRED_FIELDS,
@@ -15639,6 +15647,20 @@ var dispatchToolSpecs = [
15639
15647
  version: z.number({ int: true, min: 1 }).describe("The plan version the review read and approved.")
15640
15648
  })
15641
15649
  },
15650
+ {
15651
+ name: "dispatch_review",
15652
+ example: { issue: "DSP-1", version: 2, verdict: "approved" },
15653
+ 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,
15654
+ arguments: (z) => ({
15655
+ issue: z.string().describe(ISSUE_REFERENCE),
15656
+ artifact: z.string().describe("Document artifact id, slug, or filename; the issue's spec by default.").optional(),
15657
+ 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."),
15658
+ verdict: z.enum(["approved", "changes_requested"]).describe("approved records an approval; changes_requested records a request for changes and requires reason."),
15659
+ reason: z.string().describe("What must change before the document can be approved. changes_requested requires it; an approval may carry one.").optional()
15660
+ }),
15661
+ validation: reviewValidation,
15662
+ strict: true
15663
+ },
15642
15664
  {
15643
15665
  name: "dispatch_result",
15644
15666
  example: {
@@ -18482,6 +18504,9 @@ class DispatchNoRouteError extends DispatchServiceError {
18482
18504
  super("NOT_FOUND", 404, NO_ROUTE_ROLLING_RELEASE_MESSAGE);
18483
18505
  }
18484
18506
  }
18507
+ function reviewNoRouteRefusal(baseUrl, route, version) {
18508
+ 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.");
18509
+ }
18485
18510
  var ISSUE_EVENTS_PAGE_MAX = 200;
18486
18511
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
18487
18512
  function requestSignal(signal) {
@@ -18615,6 +18640,15 @@ async function writeAnswer(response, key) {
18615
18640
  unjudged: !echoed && typeof shape.error === "string"
18616
18641
  };
18617
18642
  }
18643
+ var BROKER_TOKEN_NOT_ACTIVE = "BROKER_TOKEN_NOT_ACTIVE";
18644
+ async function tokenNotLive(response) {
18645
+ if (response.status !== 401 || !isJson(response))
18646
+ return false;
18647
+ const body = await response.clone().json().catch(() => {
18648
+ return;
18649
+ });
18650
+ return asErrorShape(body).code === BROKER_TOKEN_NOT_ACTIVE;
18651
+ }
18618
18652
  function whyNotAPage(answer) {
18619
18653
  if (typeof answer === "string") {
18620
18654
  return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
@@ -18937,6 +18971,18 @@ class DispatchClient {
18937
18971
  async planApprove(artifactID, input) {
18938
18972
  return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
18939
18973
  }
18974
+ async reviewArtifact(artifactID, version, input) {
18975
+ const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
18976
+ const body = { state: input.state, reason: input.reason };
18977
+ try {
18978
+ return await this.#json("POST", path, body);
18979
+ } catch (error) {
18980
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
18981
+ throw error;
18982
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
18983
+ throw reviewNoRouteRefusal(this.#baseUrl, route, version);
18984
+ }
18985
+ }
18940
18986
  async recordResult(issue, input) {
18941
18987
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
18942
18988
  }
@@ -19172,11 +19218,20 @@ class DispatchClient {
19172
19218
  });
19173
19219
  }
19174
19220
  async#send(method, url, body, accept = "application/json", signal, callerKey) {
19221
+ const key = method === "POST" || method === "PATCH" ? callerKey ?? crypto.randomUUID() : undefined;
19222
+ const send = async () => this.#sendPresenting(method, url, body, accept, signal, key);
19223
+ const answer = await send();
19224
+ if (this.#credential.stale === undefined || !await tokenNotLive(answer))
19225
+ return answer;
19226
+ this.#credential.stale();
19227
+ return await send();
19228
+ }
19229
+ async#sendPresenting(method, url, body, accept, signal, key) {
19175
19230
  const headers = { Accept: accept };
19176
19231
  let presented = await this.#credential.headers(method, url);
19177
19232
  if (body !== undefined)
19178
19233
  headers["Content-Type"] = body.type;
19179
- if (method !== "POST" && method !== "PATCH") {
19234
+ if (key === undefined) {
19180
19235
  return this.fetchImpl(url, {
19181
19236
  method,
19182
19237
  headers: { ...headers, ...presented },
@@ -19184,7 +19239,6 @@ class DispatchClient {
19184
19239
  ...body === undefined ? {} : { body: body.content }
19185
19240
  });
19186
19241
  }
19187
- const key = callerKey ?? crypto.randomUUID();
19188
19242
  headers[IDEMPOTENCY_KEY_HEADER] = key;
19189
19243
  const { pausesMs, withinMs, silenceMs, inFlightPauseMs, inFlightWithinMs } = this.writeRetry;
19190
19244
  const pause = this.writeRetry.pause ?? pauseFor;
@@ -25387,6 +25441,41 @@ async function readCommand(context) {
25387
25441
  };
25388
25442
  }
25389
25443
 
25444
+ // ../envoy-client/src/dispatch-commands/reviews.ts
25445
+ async function reviewCommand(context) {
25446
+ const { args, client, documentOwner, resolveDocument } = context;
25447
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
25448
+ const { artifact } = resolved;
25449
+ let review;
25450
+ try {
25451
+ review = await client.reviewArtifact(artifact.id, numberArg(args, "version"), {
25452
+ state: stringArg(args, "verdict"),
25453
+ ...defined("reason", optionalString(args, "reason"))
25454
+ });
25455
+ } catch (error) {
25456
+ throw refusalWithCode(error);
25457
+ }
25458
+ const issue = resolved.issue?.key;
25459
+ const answered = review.ask_id === null ? [] : [
25460
+ `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.`
25461
+ ];
25462
+ return {
25463
+ text: [
25464
+ `Recorded the review of ${artifact.name} (document id ${artifact.id}): ${review.state} at version ${review.version}, by ${actorText(review.actor)}.`,
25465
+ ...review.reason === null ? [] : [`Reason: ${JSON.stringify(review.reason)}`],
25466
+ ...answered
25467
+ ].join(`
25468
+ `),
25469
+ details: {
25470
+ issue,
25471
+ artifact: artifact.id,
25472
+ version: review.version,
25473
+ state: review.state,
25474
+ ...review.ask_id === null ? {} : { ask: review.ask_id }
25475
+ }
25476
+ };
25477
+ }
25478
+
25390
25479
  // ../envoy-client/src/session-answers.ts
25391
25480
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync2 } from "fs";
25392
25481
  import { join as join3 } from "path";
@@ -25946,6 +26035,7 @@ var dispatchCommands = {
25946
26035
  dispatch_doc_read: acting(docReadCommand),
25947
26036
  dispatch_request_approval: acting(requestApprovalCommand),
25948
26037
  dispatch_plan_approve: acting(planApproveCommand),
26038
+ dispatch_review: acting(reviewCommand),
25949
26039
  dispatch_result: acting(resultCommand),
25950
26040
  dispatch_results: acting(resultsCommand),
25951
26041
  dispatch_artifact: acting(artifactCommand),
@@ -26603,6 +26693,9 @@ function fileBearer(bearer, url, section, env, commands = "run") {
26603
26693
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
26604
26694
  }
26605
26695
 
26696
+ // ../broker-client/src/dpop.ts
26697
+ import { createPrivateKey, createPublicKey } from "crypto";
26698
+
26606
26699
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
26607
26700
  var encoder2 = new TextEncoder;
26608
26701
  var decoder = new TextDecoder;
@@ -27449,6 +27542,112 @@ function keyAlgorithm(alg, source) {
27449
27542
  return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : undefined) ?? unsupportedAlg(source);
27450
27543
  }
27451
27544
 
27545
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/asn1.js
27546
+ var bytesEqual = (a, b) => {
27547
+ if (a.byteLength !== b.length)
27548
+ return false;
27549
+ for (let i = 0;i < a.byteLength; i++) {
27550
+ if (a[i] !== b[i])
27551
+ return false;
27552
+ }
27553
+ return true;
27554
+ };
27555
+ var createASN1State = (data) => ({ data, pos: 0 });
27556
+ var readByte = (state) => {
27557
+ const byte = state.data[state.pos++];
27558
+ if (byte === undefined) {
27559
+ throw new Error("Unexpected end of ASN.1 input");
27560
+ }
27561
+ return byte;
27562
+ };
27563
+ var parseLength = (state) => {
27564
+ const first = readByte(state);
27565
+ if (first & 128) {
27566
+ const lengthOfLen = first & 127;
27567
+ let length = 0;
27568
+ for (let i = 0;i < lengthOfLen; i++) {
27569
+ length = length << 8 | readByte(state);
27570
+ }
27571
+ return length;
27572
+ }
27573
+ return first;
27574
+ };
27575
+ var expectTag = (state, expectedTag, errorMessage) => {
27576
+ if (readByte(state) !== expectedTag) {
27577
+ throw new Error(errorMessage);
27578
+ }
27579
+ };
27580
+ var getSubarray = (state, length) => {
27581
+ if (length < 0 || state.pos + length > state.data.length) {
27582
+ throw new Error("Unexpected end of ASN.1 input");
27583
+ }
27584
+ const result = state.data.subarray(state.pos, state.pos + length);
27585
+ state.pos += length;
27586
+ return result;
27587
+ };
27588
+ var parseAlgorithmOID = (state) => {
27589
+ expectTag(state, 6, "Expected algorithm OID");
27590
+ const oidLen = parseLength(state);
27591
+ return getSubarray(state, oidLen);
27592
+ };
27593
+ function parseKeyHeader(state, keyFormat) {
27594
+ expectTag(state, 48, `Invalid ${keyFormat === "spki" ? "SPKI" : "PKCS#8"} structure`);
27595
+ parseLength(state);
27596
+ if (keyFormat === "pkcs8") {
27597
+ expectTag(state, 2, "Expected version field");
27598
+ const length = parseLength(state);
27599
+ state.pos += length;
27600
+ }
27601
+ expectTag(state, 48, "Expected algorithm identifier");
27602
+ parseLength(state);
27603
+ }
27604
+ var parseECAlgorithmIdentifier = (state) => {
27605
+ const algOid = parseAlgorithmOID(state);
27606
+ if (bytesEqual(algOid, [43, 101, 110])) {
27607
+ return "X25519";
27608
+ }
27609
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
27610
+ throw new Error("Unsupported key algorithm");
27611
+ }
27612
+ expectTag(state, 6, "Expected curve OID");
27613
+ const curveOidLen = parseLength(state);
27614
+ const curveOid = getSubarray(state, curveOidLen);
27615
+ if (bytesEqual(curveOid, [42, 134, 72, 206, 61, 3, 1, 7]))
27616
+ return "P-256";
27617
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 34]))
27618
+ return "P-384";
27619
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 35]))
27620
+ return "P-521";
27621
+ throw new Error("Unsupported named curve");
27622
+ };
27623
+ var genericImport = async (keyFormat, keyData, alg, options) => {
27624
+ const entry = keyAlgorithm(alg, algArgument);
27625
+ if (entry.secret) {
27626
+ unsupportedAlg(algArgument);
27627
+ }
27628
+ const isPublic = keyFormat === "spki";
27629
+ let algorithm;
27630
+ if (entry.resolve) {
27631
+ try {
27632
+ const state = createASN1State(keyData);
27633
+ parseKeyHeader(state, keyFormat);
27634
+ algorithm = entry.resolve({ crv: parseECAlgorithmIdentifier(state) });
27635
+ } catch {
27636
+ throw new JOSENotSupported("Invalid or unsupported key format");
27637
+ }
27638
+ } else {
27639
+ algorithm = entry.subtle;
27640
+ }
27641
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
27642
+ };
27643
+ var processPEMData = (pem, pattern) => {
27644
+ return decodeBase64(pem.replace(pattern, ""));
27645
+ };
27646
+ var fromPKCS8 = (pem, alg, options) => {
27647
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
27648
+ return genericImport("pkcs8", keyData, alg, options);
27649
+ };
27650
+
27452
27651
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
27453
27652
  function omitUndefinedProperties(jwk) {
27454
27653
  return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
@@ -27482,6 +27681,13 @@ async function keyToJWK(key) {
27482
27681
  function exportJWK(key) {
27483
27682
  return keyToJWK(key);
27484
27683
  }
27684
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/import.js
27685
+ async function importPKCS8(pkcs8, alg, options) {
27686
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
27687
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
27688
+ }
27689
+ return fromPKCS8(pkcs8, alg, options);
27690
+ }
27485
27691
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/generate_key_pair.js
27486
27692
  function getModulusLengthOption(options) {
27487
27693
  const modulusLength = options?.modulusLength ?? 2048;
@@ -27525,6 +27731,11 @@ async function generateKeyPair(alg, options) {
27525
27731
  ...entry.usages[0]
27526
27732
  ]);
27527
27733
  }
27734
+ // ../broker-client/src/error-text.ts
27735
+ function messageOf(error) {
27736
+ return error instanceof Error ? error.message : String(error);
27737
+ }
27738
+
27528
27739
  // ../broker-client/src/dpop.ts
27529
27740
  var ALGORITHM = "ES256";
27530
27741
  function targetUri(url) {
@@ -27537,9 +27748,7 @@ async function accessTokenHash(accessToken) {
27537
27748
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
27538
27749
  return Buffer.from(digest).toString("base64url");
27539
27750
  }
27540
- async function newDpopKey() {
27541
- const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
27542
- const publicJwk = await exportJWK(publicKey);
27751
+ function dpopKey(privateKey, publicJwk) {
27543
27752
  return {
27544
27753
  publicJwk,
27545
27754
  async proof(request) {
@@ -27558,6 +27767,30 @@ async function newDpopKey() {
27558
27767
  }
27559
27768
  };
27560
27769
  }
27770
+ async function newDpopKey() {
27771
+ const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
27772
+ return dpopKey(privateKey, await exportJWK(publicKey));
27773
+ }
27774
+ async function importDpopKey(pkcs8Pem, name) {
27775
+ const unreadable = (error) => new Error(`read ${name}: ${messageOf(error)}`, { cause: error });
27776
+ let exported;
27777
+ try {
27778
+ exported = createPublicKey(createPrivateKey(pkcs8Pem)).export({ format: "jwk" });
27779
+ } catch (error) {
27780
+ throw unreadable(error);
27781
+ }
27782
+ const { kty, crv, x, y } = exported;
27783
+ if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
27784
+ throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
27785
+ }
27786
+ let privateKey;
27787
+ try {
27788
+ privateKey = await importPKCS8(pkcs8Pem, ALGORITHM, { extractable: false });
27789
+ } catch (error) {
27790
+ throw unreadable(error);
27791
+ }
27792
+ return dpopKey(privateKey, { kty, crv, x, y });
27793
+ }
27561
27794
 
27562
27795
  // ../broker-client/src/metadata-identity.ts
27563
27796
  import { Agent, request } from "http";
@@ -27571,6 +27804,7 @@ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
27571
27804
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
27572
27805
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
27573
27806
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
27807
+ var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
27574
27808
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
27575
27809
  var TOKEN_TYPE_DPOP = "DPoP";
27576
27810
 
@@ -27632,29 +27866,6 @@ function metadataIdentity(audience, env = process.env) {
27632
27866
  };
27633
27867
  }
27634
27868
 
27635
- // ../broker-client/src/projected-token.ts
27636
- import { readFile } from "fs/promises";
27637
- function projectedToken(path) {
27638
- return {
27639
- async read(signal) {
27640
- let contents;
27641
- try {
27642
- contents = await readFile(path, {
27643
- encoding: "utf8",
27644
- ...signal === undefined ? {} : { signal }
27645
- });
27646
- } catch (error) {
27647
- throw new Error(`read the projected service-account token ${path}: ${error.message}`);
27648
- }
27649
- const token = contents.trim();
27650
- if (token === "")
27651
- throw new Error(`the projected service-account token ${path} is empty`);
27652
- return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
27653
- },
27654
- describe: () => `the projected service-account token ${path}`
27655
- };
27656
- }
27657
-
27658
27869
  // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
27659
27870
  var USER_AGENT;
27660
27871
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
@@ -27800,6 +28011,56 @@ function signal(url, value) {
27800
28011
  }
27801
28012
  return;
27802
28013
  }
28014
+ function replaceDoubleSlash(pathname) {
28015
+ if (pathname.includes("//")) {
28016
+ return pathname.replace("//", "/");
28017
+ }
28018
+ return pathname;
28019
+ }
28020
+ function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
28021
+ if (url.pathname === "/") {
28022
+ url.pathname = wellKnown;
28023
+ } else {
28024
+ url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
28025
+ }
28026
+ return url;
28027
+ }
28028
+ function appendWellKnown(url, wellKnown) {
28029
+ url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
28030
+ return url;
28031
+ }
28032
+ async function performDiscovery(input, urlName, transform, options) {
28033
+ if (!(input instanceof URL)) {
28034
+ throw CodedTypeError(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE);
28035
+ }
28036
+ checkProtocol(input, options?.[allowInsecureRequests] !== true);
28037
+ const url = transform(new URL(input.href));
28038
+ const headers = prepareHeaders(options?.headers);
28039
+ headers.set("accept", "application/json");
28040
+ return (options?.[customFetch] || fetch)(url.href, {
28041
+ body: undefined,
28042
+ headers: Object.fromEntries(headers.entries()),
28043
+ method: "GET",
28044
+ redirect: "manual",
28045
+ signal: signal(url, options?.signal)
28046
+ });
28047
+ }
28048
+ async function discoveryRequest(issuerIdentifier, options) {
28049
+ return performDiscovery(issuerIdentifier, "issuerIdentifier", (url) => {
28050
+ switch (options?.algorithm) {
28051
+ case undefined:
28052
+ case "oidc":
28053
+ appendWellKnown(url, ".well-known/openid-configuration");
28054
+ break;
28055
+ case "oauth2":
28056
+ prependWellKnown(url, ".well-known/oauth-authorization-server");
28057
+ break;
28058
+ default:
28059
+ throw CodedTypeError('"options.algorithm" must be "oidc" (default), or "oauth2"', ERR_INVALID_ARG_VALUE);
28060
+ }
28061
+ return url;
28062
+ }, options);
28063
+ }
27803
28064
  function assertNumber(input, allow0, it, code, cause) {
27804
28065
  try {
27805
28066
  if (typeof input !== "number" || !Number.isFinite(input)) {
@@ -27836,6 +28097,25 @@ function assertString(input, it, code, cause) {
27836
28097
  throw err;
27837
28098
  }
27838
28099
  }
28100
+ async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
28101
+ const expected = expectedIssuerIdentifier;
28102
+ if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
28103
+ throw CodedTypeError('"expectedIssuerIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE);
28104
+ }
28105
+ if (!looseInstanceOf(response, Response)) {
28106
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
28107
+ }
28108
+ if (response.status !== 200) {
28109
+ throw OPE('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
28110
+ }
28111
+ assertReadableResponse(response);
28112
+ const json = await getResponseJsonBody(response);
28113
+ assertString(json.issuer, '"response" body "issuer" property', INVALID_RESPONSE, { body: json });
28114
+ if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {
28115
+ throw OPE('"response" body "issuer" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: "issuer" });
28116
+ }
28117
+ return json;
28118
+ }
27839
28119
  function assertApplicationJson(response) {
27840
28120
  assertContentType(response, "application/json");
27841
28121
  }
@@ -28115,6 +28395,14 @@ async function tokenEndpointRequest(as, client, clientAuthentication, grantType,
28115
28395
  options?.DPoP?.cacheNonce(response, url);
28116
28396
  return response;
28117
28397
  }
28398
+ async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
28399
+ assertAs(as);
28400
+ assertClient(client);
28401
+ assertString(refreshToken, '"refreshToken"');
28402
+ const parameters = new URLSearchParams(options?.additionalParameters);
28403
+ parameters.set("refresh_token", refreshToken);
28404
+ return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
28405
+ }
28118
28406
  var idTokenClaims = new WeakMap;
28119
28407
  var jwtRefs = new WeakMap;
28120
28408
  function getValidatedIdTokenClaims(ref) {
@@ -28192,6 +28480,9 @@ function checkAuthenticationChallenges(response) {
28192
28480
  throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", { cause: challenges, response });
28193
28481
  }
28194
28482
  }
28483
+ async function processRefreshTokenResponse(as, client, response, options) {
28484
+ return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
28485
+ }
28195
28486
  function validateAudience(expected, result) {
28196
28487
  if (Array.isArray(result.claims.aud)) {
28197
28488
  if (!result.claims.aud.includes(expected)) {
@@ -28544,6 +28835,73 @@ function errorHandler(err) {
28544
28835
  }
28545
28836
  throw new ClientError("something went wrong", { cause: err });
28546
28837
  }
28838
+ function handleEntraId(server, as, options) {
28839
+ if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
28840
+ as[kEntraId] = true;
28841
+ return true;
28842
+ }
28843
+ return false;
28844
+ }
28845
+ function handleB2Clogin(server, options) {
28846
+ if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) {
28847
+ return true;
28848
+ }
28849
+ return false;
28850
+ }
28851
+ async function discovery(server, clientId, metadata, clientAuthentication, options) {
28852
+ const as = await performDiscovery2(server, options);
28853
+ const instance = new Configuration(as, clientId, metadata, clientAuthentication);
28854
+ let internals = int2(instance);
28855
+ if (options?.[customFetch2]) {
28856
+ internals.fetch = options[customFetch2];
28857
+ }
28858
+ if (options?.timeout) {
28859
+ internals.timeout = options.timeout;
28860
+ }
28861
+ if (options?.execute) {
28862
+ for (const extension of options.execute) {
28863
+ extension(instance);
28864
+ }
28865
+ }
28866
+ return instance;
28867
+ }
28868
+ async function performDiscovery2(server, options) {
28869
+ if (!(server instanceof URL)) {
28870
+ throw CodedTypeError2('"server" must be an instance of URL', ERR_INVALID_ARG_TYPE2);
28871
+ }
28872
+ const resolve = !server.href.includes("/.well-known/");
28873
+ const timeout = options?.timeout ?? 30;
28874
+ const signal = AbortSignal.timeout(timeout * 1000);
28875
+ const as = await (resolve ? discoveryRequest(server, {
28876
+ algorithm: options?.algorithm,
28877
+ [customFetch]: options?.[customFetch2],
28878
+ [allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests2),
28879
+ signal,
28880
+ headers: new Headers(headers)
28881
+ }) : (options?.[customFetch2] || fetch)((() => {
28882
+ checkProtocol(server, options?.execute?.includes(allowInsecureRequests2) ? false : true);
28883
+ return server.href;
28884
+ })(), {
28885
+ headers: Object.fromEntries(new Headers({ accept: "application/json", ...headers }).entries()),
28886
+ body: undefined,
28887
+ method: "GET",
28888
+ redirect: "manual",
28889
+ signal
28890
+ })).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
28891
+ if (resolve && new URL(as.issuer).href !== server.href) {
28892
+ handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
28893
+ throw new ClientError("discovered metadata issuer does not match the expected issuer", {
28894
+ code: JSON_ATTRIBUTE_COMPARISON,
28895
+ cause: {
28896
+ expected: server.href,
28897
+ body: as,
28898
+ attribute: "issuer"
28899
+ }
28900
+ });
28901
+ })();
28902
+ }
28903
+ return as;
28904
+ }
28547
28905
  function getServerHelpers(metadata) {
28548
28906
  return {
28549
28907
  supportsPKCE: {
@@ -28660,6 +29018,37 @@ function addHelpers(response) {
28660
29018
  function allowInsecureRequests2(config) {
28661
29019
  int2(config).tlsOnly = false;
28662
29020
  }
29021
+ async function refreshTokenGrant(config, refreshToken, parameters, options) {
29022
+ checkConfig(config);
29023
+ parameters = new URLSearchParams(parameters);
29024
+ const { as, c, auth, fetch: fetch2, tlsOnly, nonRepudiation, timeout, decrypt } = int2(config);
29025
+ const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
29026
+ [customFetch]: fetch2,
29027
+ [allowInsecureRequests]: !tlsOnly,
29028
+ additionalParameters: parameters,
29029
+ DPoP: options?.DPoP,
29030
+ headers: new Headers(headers),
29031
+ signal: signal2(timeout)
29032
+ }).catch(errorHandler);
29033
+ const p = processRefreshTokenResponse(as, c, response, {
29034
+ [jweDecrypt]: decrypt
29035
+ });
29036
+ let result;
29037
+ try {
29038
+ result = await p;
29039
+ } catch (err) {
29040
+ if (retryable(err, options)) {
29041
+ return refreshTokenGrant(config, refreshToken, parameters, {
29042
+ ...options,
29043
+ flag: retry
29044
+ });
29045
+ }
29046
+ errorHandler(err);
29047
+ }
29048
+ result.id_token && await nonRepudiation?.(response);
29049
+ addHelpers(result);
29050
+ return result;
29051
+ }
28663
29052
  function checkConfig(input) {
28664
29053
  if (!(input instanceof Configuration)) {
28665
29054
  throw CodedTypeError2('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE2);
@@ -28713,6 +29102,136 @@ async function genericGrantRequest(config, grantType, parameters, options) {
28713
29102
  return result;
28714
29103
  }
28715
29104
 
29105
+ // ../broker-client/src/signins.ts
29106
+ import { readdir, readFile } from "fs/promises";
29107
+ import { join as join6 } from "path";
29108
+ var SIGNIN_DIR_VAR = "AGENT_SECRETS_SIGNIN_DIR";
29109
+ var PERSON_VAR = "AGENT_SECRETS_PERSON";
29110
+ var PERSON_TRADE_VAR = "PERSON_SIGNIN_TRADE";
29111
+ var SIGNIN_ISSUER_VAR = "AGENT_SECRETS_SIGNIN_ISSUER";
29112
+ var SIGNIN_CLIENT_ID_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_ID";
29113
+ var SIGNIN_CLIENT_SECRET_FILE_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_SECRET_FILE";
29114
+ var DEFAULT_SIGNIN_ISSUER = "https://accounts.google.com";
29115
+ var SIGNIN_COMMAND = "agent-secrets login";
29116
+ var SIGNINS_DIR = "signins";
29117
+ var RECORD_MEMBERS = [
29118
+ "person",
29119
+ "issuer",
29120
+ "client_id",
29121
+ "refresh_token",
29122
+ "box_key",
29123
+ "thumbprint",
29124
+ "enrollment_id",
29125
+ "signed_in_at"
29126
+ ];
29127
+ function signInDirectory(env) {
29128
+ const named = env[SIGNIN_DIR_VAR] ?? "";
29129
+ if (named !== "")
29130
+ return named;
29131
+ const state = env.XDG_STATE_HOME ?? "";
29132
+ const base = state !== "" ? state : join6(env.HOME ?? "", ".local", "state");
29133
+ return join6(base, "agent-secrets", SIGNINS_DIR);
29134
+ }
29135
+ async function readSignIn(path) {
29136
+ let text;
29137
+ try {
29138
+ text = await readFile(path, "utf8");
29139
+ } catch (error) {
29140
+ throw new Error(`read the sign-in at ${path}: ${messageOf(error)}`, { cause: error });
29141
+ }
29142
+ let parsed;
29143
+ try {
29144
+ parsed = JSON.parse(text);
29145
+ } catch {
29146
+ throw new Error(`read the sign-in at ${path}: it is not JSON; run: ${SIGNIN_COMMAND}`);
29147
+ }
29148
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
29149
+ throw new Error(`read the sign-in at ${path}: it holds no JSON object; run: ${SIGNIN_COMMAND}`);
29150
+ }
29151
+ const fields = parsed;
29152
+ const record = {};
29153
+ for (const member of RECORD_MEMBERS) {
29154
+ const given = fields[member] ?? "";
29155
+ if (typeof given !== "string") {
29156
+ throw new Error(`read the sign-in at ${path}: its ${member} is not a string; run: ${SIGNIN_COMMAND}`);
29157
+ }
29158
+ record[member] = given;
29159
+ }
29160
+ const read = record;
29161
+ if (read.person === "" || read.refresh_token === "" || read.box_key === "") {
29162
+ throw new Error(`the sign-in at ${path} names no person, no refresh token or no box key; run: ${SIGNIN_COMMAND}`);
29163
+ }
29164
+ return read;
29165
+ }
29166
+ async function listSignIns(dir) {
29167
+ let entries;
29168
+ try {
29169
+ entries = await readdir(dir, { withFileTypes: true });
29170
+ } catch (error) {
29171
+ if (error.code === "ENOENT")
29172
+ return [];
29173
+ throw new Error(`read this machine's sign-ins: ${messageOf(error)}`, { cause: error });
29174
+ }
29175
+ const names = entries.filter((entry) => !entry.isDirectory() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
29176
+ const records = [];
29177
+ for (const name of names)
29178
+ records.push(await readSignIn(join6(dir, name)));
29179
+ return records.sort((a, b) => a.person < b.person ? -1 : a.person > b.person ? 1 : 0);
29180
+ }
29181
+ function namesOf(records) {
29182
+ return records.map((record) => record.person).join(", ");
29183
+ }
29184
+ function personTradeOff(env) {
29185
+ const written = (env[PERSON_TRADE_VAR] ?? "").trim();
29186
+ if (written === "")
29187
+ return false;
29188
+ if (written === "off")
29189
+ return true;
29190
+ 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`);
29191
+ }
29192
+ async function chooseSignIn(env) {
29193
+ if (personTradeOff(env))
29194
+ return;
29195
+ const records = await listSignIns(signInDirectory(env));
29196
+ const person = (env[PERSON_VAR] ?? "").trim().toLowerCase();
29197
+ if (records.length === 0)
29198
+ return;
29199
+ if (person !== "") {
29200
+ const named = records.find((record) => record.person.toLowerCase() === person);
29201
+ if (named !== undefined)
29202
+ return named;
29203
+ throw new Error(`${PERSON_VAR} names ${person}, who is not signed in on this machine; signed in here: ${namesOf(records)}; run: ${SIGNIN_COMMAND}`);
29204
+ }
29205
+ if (records.length === 1)
29206
+ return records[0];
29207
+ 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`);
29208
+ }
29209
+ function signInSessionName(record) {
29210
+ const name = `signin-${record.person}`;
29211
+ return record.thumbprint === "" ? name : `${name}-${record.thumbprint.slice(0, 12)}`;
29212
+ }
29213
+ async function signInFlow(env) {
29214
+ const clientId = (env[SIGNIN_CLIENT_ID_VAR] ?? "").trim();
29215
+ const secretFile = (env[SIGNIN_CLIENT_SECRET_FILE_VAR] ?? "").trim();
29216
+ if (clientId === "" && secretFile === "")
29217
+ return;
29218
+ if (clientId === "" || secretFile === "") {
29219
+ 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`);
29220
+ }
29221
+ let secret;
29222
+ try {
29223
+ secret = await readFile(secretFile, "utf8");
29224
+ } catch (error) {
29225
+ throw new Error(`read the sign-in client's secret (${SIGNIN_CLIENT_SECRET_FILE_VAR}): ${messageOf(error)}`, { cause: error });
29226
+ }
29227
+ const issuer = (env[SIGNIN_ISSUER_VAR] ?? "").trim();
29228
+ return {
29229
+ issuer: withoutTrailingSlashes(issuer === "" ? DEFAULT_SIGNIN_ISSUER : issuer),
29230
+ clientId,
29231
+ clientSecret: secret.trim()
29232
+ };
29233
+ }
29234
+
28716
29235
  // ../broker-client/src/token-client.ts
28717
29236
  var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
28718
29237
  var TOO_MANY_REQUESTS = 429;
@@ -28723,8 +29242,8 @@ class BrokerRefusedError extends Error {
28723
29242
  status;
28724
29243
  code;
28725
29244
  description;
28726
- constructor(status, code, description) {
28727
- 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}`);
29245
+ constructor(status, code, description, refused) {
29246
+ super(description === "" ? `the secrets broker refused ${refused}: HTTP ${status} ${code}` : `the secrets broker refused ${refused}: HTTP ${status} ${code}: ${description}`);
28728
29247
  this.status = status;
28729
29248
  this.code = code;
28730
29249
  this.description = description;
@@ -28734,6 +29253,20 @@ class BrokerRefusedError extends Error {
28734
29253
  return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE;
28735
29254
  }
28736
29255
  }
29256
+
29257
+ class SignInEndedError extends Error {
29258
+ issuer;
29259
+ person;
29260
+ constructor(issuer, person, options) {
29261
+ super(`${issuer} no longer honours ${person}'s sign-in on this machine; run: ${SIGNIN_COMMAND}`, options);
29262
+ this.issuer = issuer;
29263
+ this.person = person;
29264
+ this.name = "SignInEndedError";
29265
+ }
29266
+ }
29267
+ function isFinalRefusal(error) {
29268
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
29269
+ }
28737
29270
  function statusOf(error) {
28738
29271
  let cause = error;
28739
29272
  for (let depth = 0;depth < 4; depth += 1) {
@@ -28745,6 +29278,16 @@ function statusOf(error) {
28745
29278
  }
28746
29279
  return 0;
28747
29280
  }
29281
+ function requestInit(options, signal, headers) {
29282
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
29283
+ return {
29284
+ method: options.method,
29285
+ headers,
29286
+ body: options.body,
29287
+ redirect: options.redirect,
29288
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
29289
+ };
29290
+ }
28748
29291
 
28749
29292
  class BrokerTokenClient {
28750
29293
  #brokerUrl;
@@ -28793,6 +29336,9 @@ class BrokerTokenClient {
28793
29336
  this.#trading = null;
28794
29337
  }
28795
29338
  }
29339
+ drop() {
29340
+ this.#held = null;
29341
+ }
28796
29342
  async#renew(signal) {
28797
29343
  try {
28798
29344
  const token = await this.#trade(signal);
@@ -28800,7 +29346,7 @@ class BrokerTokenClient {
28800
29346
  return token;
28801
29347
  } catch (error) {
28802
29348
  const held = this.#held;
28803
- if (!(error instanceof BrokerRefusedError && error.permanent) && held !== null && this.#now() < held.expiresAt.getTime()) {
29349
+ if (!isFinalRefusal(error) && held !== null && this.#now() < held.expiresAt.getTime()) {
28804
29350
  return held;
28805
29351
  }
28806
29352
  this.#held = null;
@@ -28823,8 +29369,9 @@ class BrokerTokenClient {
28823
29369
  try {
28824
29370
  actor = await this.#actor.read(signal);
28825
29371
  } catch (error) {
28826
- const said = error instanceof Error ? error.message : String(error);
28827
- throw new Error(`read the machine this person signed in on: ${said}`, { cause: error });
29372
+ throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
29373
+ cause: error
29374
+ });
28828
29375
  }
28829
29376
  form["actor_token"] = actor.token;
28830
29377
  form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
@@ -28844,10 +29391,10 @@ class BrokerTokenClient {
28844
29391
  }
28845
29392
  #refusal(endpoint, error) {
28846
29393
  if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
28847
- return new BrokerRefusedError(error.status, error.error, error.error_description ?? "");
29394
+ return new BrokerRefusedError(error.status, error.error, error.error_description ?? "", this.#subject.describe());
28848
29395
  }
28849
29396
  const status = statusOf(error);
28850
- const message = error instanceof Error ? error.message : String(error);
29397
+ const message = messageOf(error);
28851
29398
  const said = status === 0 ? message : `HTTP ${status}: ${message}`;
28852
29399
  return new Error(`trade ${this.#subject.describe()} at ${endpoint}: ${said}`, {
28853
29400
  cause: error
@@ -28857,15 +29404,7 @@ class BrokerTokenClient {
28857
29404
  const send = async () => {
28858
29405
  const headers = new Headers(options.headers);
28859
29406
  headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
28860
- const signals = [options.signal, signal].filter((one) => one !== undefined);
28861
- const body = options.body;
28862
- return await this.#fetch(url, {
28863
- method: options.method,
28864
- headers,
28865
- body,
28866
- redirect: options.redirect,
28867
- ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
28868
- });
29407
+ return await this.#fetch(url, requestInit(options, signal, headers));
28869
29408
  };
28870
29409
  let answer = await send();
28871
29410
  const given = answer.headers.get("DPoP-Nonce") ?? "";
@@ -28913,15 +29452,241 @@ class BrokerTokenClient {
28913
29452
  }
28914
29453
  }
28915
29454
 
29455
+ // ../broker-client/src/person-identity.ts
29456
+ var ISSUER_TIMEOUT_SECONDS = 30;
29457
+ var INVALID_GRANT = "invalid_grant";
29458
+ function issuerSaid(error) {
29459
+ if (error instanceof ResponseBodyError) {
29460
+ const description = error.error_description ?? "";
29461
+ return `HTTP ${error.status} ${error.error}${description === "" ? "" : `: ${description}`}`;
29462
+ }
29463
+ let message = messageOf(error);
29464
+ const cause = error instanceof Error ? error.cause : undefined;
29465
+ if (cause instanceof Error && cause.message !== message)
29466
+ message += `: ${cause.message}`;
29467
+ const status = statusOf(error);
29468
+ return status === 0 ? message : `HTTP ${status}: ${message}`;
29469
+ }
29470
+ function personIdentity(record, flow, options = {}) {
29471
+ const { person, refresh_token: refreshToken, client_id: clientId } = record;
29472
+ if (clientId !== "" && clientId !== flow.clientId) {
29473
+ 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}`);
29474
+ }
29475
+ const send = options.fetch ?? fetch;
29476
+ const insecure = flow.issuer.startsWith("http:");
29477
+ let discovered = null;
29478
+ const through = (signal) => (url, init) => send(url, requestInit(init, signal, init.headers));
29479
+ const discover = async (signal) => {
29480
+ try {
29481
+ const config = await discovery(new URL(flow.issuer), flow.clientId, undefined, undefined, {
29482
+ [customFetch2]: through(signal),
29483
+ timeout: ISSUER_TIMEOUT_SECONDS,
29484
+ ...insecure ? { execute: [allowInsecureRequests2] } : {}
29485
+ });
29486
+ return config.serverMetadata();
29487
+ } catch (error) {
29488
+ throw new Error(`read the sign-in issuer ${flow.issuer}: ${issuerSaid(error)}`, {
29489
+ cause: error
29490
+ });
29491
+ }
29492
+ };
29493
+ return {
29494
+ async read(signal) {
29495
+ discovered ??= discover(signal);
29496
+ const discovering = discovered;
29497
+ let metadata;
29498
+ try {
29499
+ metadata = await discovering;
29500
+ } catch (error) {
29501
+ if (discovered === discovering)
29502
+ discovered = null;
29503
+ throw error;
29504
+ }
29505
+ let answered;
29506
+ try {
29507
+ const config = new Configuration(metadata, flow.clientId, undefined, ClientSecretPost2(flow.clientSecret));
29508
+ if (insecure)
29509
+ allowInsecureRequests2(config);
29510
+ config.timeout = ISSUER_TIMEOUT_SECONDS;
29511
+ config[customFetch2] = through(signal);
29512
+ answered = await refreshTokenGrant(config, refreshToken);
29513
+ } catch (error) {
29514
+ if (error instanceof ResponseBodyError && error.error === INVALID_GRANT) {
29515
+ throw new SignInEndedError(flow.issuer, person, { cause: error });
29516
+ }
29517
+ throw new Error(`renew ${person}'s sign-in at ${flow.issuer}: ${issuerSaid(error)}`);
29518
+ }
29519
+ const idToken = answered.id_token ?? "";
29520
+ if (idToken === "") {
29521
+ throw new Error(`${flow.issuer} answered no id_token: the sign-in asked for the "openid" scope and must be answered one`);
29522
+ }
29523
+ return { token: idToken, tokenType: SUBJECT_TOKEN_TYPE_PERSON };
29524
+ },
29525
+ describe: () => `${person}'s sign-in on this machine`
29526
+ };
29527
+ }
29528
+
29529
+ // ../broker-client/src/pool-identity.ts
29530
+ var DEFAULT_SECURITY_TOKEN_SERVICE_URL = "https://sts.googleapis.com/v1/token";
29531
+ var DEFAULT_IAM_CREDENTIALS_URL = "https://iamcredentials.googleapis.com";
29532
+ var REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
29533
+ var SCOPE = "https://www.googleapis.com/auth/cloud-platform";
29534
+ var SUBJECT_TOKEN_TYPE_JWT = "urn:ietf:params:oauth:token-type:jwt";
29535
+ var POOL_TIMEOUT_MS = 20000;
29536
+ var MAX_ANSWER_BYTES2 = 1 << 20;
29537
+ function poolSubjectTokenType(brokerType) {
29538
+ return brokerType === SUBJECT_TOKEN_TYPE_KUBERNETES ? SUBJECT_TOKEN_TYPE_JWT : brokerType;
29539
+ }
29540
+ function pathEscape(segment) {
29541
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(?:24|26|2B|3A|3D|40)/g, decodeURIComponent);
29542
+ }
29543
+ async function answerText(answer) {
29544
+ const reader = answer.body?.getReader();
29545
+ if (reader === undefined)
29546
+ return "";
29547
+ const chunks = [];
29548
+ let read = 0;
29549
+ while (read < MAX_ANSWER_BYTES2) {
29550
+ const { done, value } = await reader.read();
29551
+ if (done)
29552
+ break;
29553
+ const kept = value.subarray(0, MAX_ANSWER_BYTES2 - read);
29554
+ chunks.push(kept);
29555
+ read += kept.length;
29556
+ }
29557
+ await reader.cancel().catch(() => {
29558
+ return;
29559
+ });
29560
+ return Buffer.concat(chunks).toString("utf8");
29561
+ }
29562
+ function poolIdentity(options) {
29563
+ const securityTokenService = options.securityTokenServiceUrl ?? DEFAULT_SECURITY_TOKEN_SERVICE_URL;
29564
+ const iamCredentials = (options.iamCredentialsUrl ?? DEFAULT_IAM_CREDENTIALS_URL).replace(/\/$/, "");
29565
+ const account = pathEscape(options.serviceAccount);
29566
+ const mintEndpoint = `${iamCredentials}/v1/projects/-/serviceAccounts/${account}:generateIdToken`;
29567
+ const call = async (endpoint, bearer, body, member, signal) => {
29568
+ const signals = [AbortSignal.timeout(POOL_TIMEOUT_MS), signal].filter((one) => one !== undefined);
29569
+ const answer = await fetch(endpoint, {
29570
+ method: "POST",
29571
+ headers: {
29572
+ "Content-Type": "application/json",
29573
+ ...bearer === "" ? {} : { Authorization: `Bearer ${bearer}` }
29574
+ },
29575
+ body: JSON.stringify(body),
29576
+ signal: AbortSignal.any(signals)
29577
+ });
29578
+ const text = await answerText(answer);
29579
+ if (answer.status < 200 || answer.status > 299) {
29580
+ throw new Error(`HTTP ${answer.status}: ${text.trim()}`);
29581
+ }
29582
+ let parsed;
29583
+ try {
29584
+ parsed = JSON.parse(text);
29585
+ } catch {
29586
+ throw new Error(`HTTP ${answer.status}: the answer is not JSON`);
29587
+ }
29588
+ const value = typeof parsed === "object" && parsed !== null ? parsed[member] : undefined;
29589
+ return typeof value === "string" ? value : "";
29590
+ };
29591
+ const federate = async (subject, signal) => {
29592
+ let federated;
29593
+ try {
29594
+ federated = await call(securityTokenService, "", {
29595
+ audience: options.audience,
29596
+ grantType: GRANT_TYPE_TOKEN_EXCHANGE,
29597
+ requestedTokenType: REQUESTED_TOKEN_TYPE,
29598
+ scope: SCOPE,
29599
+ subjectTokenType: poolSubjectTokenType(subject.tokenType),
29600
+ subjectToken: subject.token
29601
+ }, "access_token", signal);
29602
+ } catch (error) {
29603
+ throw new Error(`trade this machine's credential at the security token service ${securityTokenService}: ${messageOf(error)}`, { cause: error });
29604
+ }
29605
+ if (federated === "") {
29606
+ throw new Error(`the security token service ${securityTokenService} answered no access_token`);
29607
+ }
29608
+ return federated;
29609
+ };
29610
+ const generateIdToken = async (federated, signal) => {
29611
+ let token;
29612
+ try {
29613
+ token = await call(mintEndpoint, federated, { audience: options.tokenAudience, includeEmail: true }, "token", signal);
29614
+ } catch (error) {
29615
+ throw new Error(`mint this machine's identity token at ${mintEndpoint}: ${messageOf(error)}`, { cause: error });
29616
+ }
29617
+ if (token === "")
29618
+ throw new Error(`generateIdToken at ${mintEndpoint} answered no token`);
29619
+ return token;
29620
+ };
29621
+ return {
29622
+ async read(signal) {
29623
+ let subject;
29624
+ try {
29625
+ subject = await options.subject.read(signal);
29626
+ } catch (error) {
29627
+ throw new Error(`read the credential the workload identity pool federates: ${messageOf(error)}`, { cause: error });
29628
+ }
29629
+ const federated = await federate(subject, signal);
29630
+ return {
29631
+ token: await generateIdToken(federated, signal),
29632
+ tokenType: SUBJECT_TOKEN_TYPE_GOOGLE
29633
+ };
29634
+ },
29635
+ describe: () => `a Google identity token for ${options.tokenAudience} minted through the workload identity pool ${options.audience} as ${options.serviceAccount}`
29636
+ };
29637
+ }
29638
+
29639
+ // ../broker-client/src/projected-token.ts
29640
+ import { readFile as readFile2 } from "fs/promises";
29641
+ function projectedToken(path) {
29642
+ return {
29643
+ async read(signal) {
29644
+ let contents;
29645
+ try {
29646
+ contents = await readFile2(path, {
29647
+ encoding: "utf8",
29648
+ ...signal === undefined ? {} : { signal }
29649
+ });
29650
+ } catch (error) {
29651
+ throw new Error(`read the projected service-account token ${path}: ${error.message}`);
29652
+ }
29653
+ const token = contents.trim();
29654
+ if (token === "")
29655
+ throw new Error(`the projected service-account token ${path} is empty`);
29656
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
29657
+ },
29658
+ describe: () => `the projected service-account token ${path}`
29659
+ };
29660
+ }
29661
+
28916
29662
  // ../broker-client/src/environment.ts
28917
29663
  var BROKER_URL_VAR = "AGENT_SECRETS_URL";
28918
29664
  var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
28919
29665
  var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
28920
29666
  var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
28921
29667
  var SESSION_VAR = "AGENT_SECRETS_SESSION";
29668
+ var POOL_AUDIENCE_VAR = "AGENT_SECRETS_POOL_AUDIENCE";
29669
+ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
28922
29670
  var IDENTITY_KUBERNETES = "kubernetes";
28923
29671
  var IDENTITY_METADATA = "metadata";
28924
29672
  var IDENTITY_POOL = "pool";
29673
+ var BROKER_VARIABLES = [
29674
+ BROKER_URL_VAR,
29675
+ IDENTITY_VAR,
29676
+ MACHINE_TOKEN_FILE_VAR,
29677
+ MACHINE_AUDIENCE_VAR,
29678
+ SESSION_VAR,
29679
+ POOL_AUDIENCE_VAR,
29680
+ POOL_ACCOUNT_VAR,
29681
+ SIGNIN_DIR_VAR,
29682
+ "XDG_STATE_HOME",
29683
+ "HOME",
29684
+ PERSON_VAR,
29685
+ PERSON_TRADE_VAR,
29686
+ SIGNIN_ISSUER_VAR,
29687
+ SIGNIN_CLIENT_ID_VAR,
29688
+ SIGNIN_CLIENT_SECRET_FILE_VAR
29689
+ ];
28925
29690
  function value(env, name) {
28926
29691
  return (env[name] ?? "").trim();
28927
29692
  }
@@ -28940,10 +29705,20 @@ function machineIdentity(env) {
28940
29705
  return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind));
28941
29706
  case IDENTITY_METADATA:
28942
29707
  return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
28943
- case IDENTITY_POOL:
28944
- 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}`);
29708
+ case IDENTITY_POOL: {
29709
+ const subject = required2(env, MACHINE_TOKEN_FILE_VAR, kind);
29710
+ const tokenAudience = required2(env, MACHINE_AUDIENCE_VAR, kind);
29711
+ const audience = required2(env, POOL_AUDIENCE_VAR, kind);
29712
+ const serviceAccount = required2(env, POOL_ACCOUNT_VAR, kind);
29713
+ return poolIdentity({
29714
+ subject: projectedToken(subject),
29715
+ audience,
29716
+ serviceAccount,
29717
+ tokenAudience
29718
+ });
29719
+ }
28945
29720
  default:
28946
- throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
29721
+ throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${IDENTITY_POOL}`);
28947
29722
  }
28948
29723
  }
28949
29724
  function tradeSession(env, own = "") {
@@ -28952,16 +29727,32 @@ function tradeSession(env, own = "") {
28952
29727
  }
28953
29728
  async function brokerTokenClient(env, own = "") {
28954
29729
  const brokerUrl = value(env, BROKER_URL_VAR);
28955
- const subject = machineIdentity(env);
28956
- if (brokerUrl === "" || subject === undefined)
29730
+ const machine = machineIdentity(env);
29731
+ if (brokerUrl === "" || machine === undefined)
28957
29732
  return;
28958
- return new BrokerTokenClient({
29733
+ const record = await chooseSignIn(env);
29734
+ if (record === undefined) {
29735
+ const client = new BrokerTokenClient({
29736
+ brokerUrl,
29737
+ key: await newDpopKey(),
29738
+ subject: machine,
29739
+ session: tradeSession(env, own),
29740
+ launcherCredential: false
29741
+ });
29742
+ return { client, signIn: undefined };
29743
+ }
29744
+ const flow = await signInFlow(env);
29745
+ if (flow === undefined) {
29746
+ 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}`);
29747
+ }
29748
+ const client = new BrokerTokenClient({
28959
29749
  brokerUrl,
28960
- key: await newDpopKey(),
28961
- subject,
28962
- session: tradeSession(env, own),
28963
- launcherCredential: false
29750
+ key: await importDpopKey(record.box_key, `${record.person}'s box key`),
29751
+ subject: personIdentity(record, flow),
29752
+ actor: machine,
29753
+ session: own.trim() || signInSessionName(record)
28964
29754
  });
29755
+ return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
28965
29756
  }
28966
29757
 
28967
29758
  // ../envoy-client/src/broker-credential.ts
@@ -28974,12 +29765,6 @@ function brokerRouteConfigured(env) {
28974
29765
  if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
28975
29766
  return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
28976
29767
  }
28977
- if ((env[IDENTITY_VAR] ?? "").trim() === IDENTITY_POOL) {
28978
- return {
28979
- traded: false,
28980
- gap: `${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), never by this process`
28981
- };
28982
- }
28983
29768
  if (machineIdentity(env) === undefined) {
28984
29769
  return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
28985
29770
  }
@@ -28989,37 +29774,91 @@ var CLIENTS = new Map;
28989
29774
  function forgetBrokerSession(session) {
28990
29775
  CLIENTS.delete(session.trim());
28991
29776
  }
28992
- function clientFor(env, own) {
28993
- const session = tradeSession(env, own);
28994
- const key = JSON.stringify([
28995
- env.AGENT_SECRETS_URL,
28996
- env.AGENT_SECRETS_MACHINE_IDENTITY,
28997
- env.AGENT_SECRETS_MACHINE_TOKEN_FILE,
28998
- env.AGENT_SECRETS_MACHINE_AUDIENCE
28999
- ]);
29000
- const held = CLIENTS.get(session) ?? new Map;
29001
- CLIENTS.set(session, held);
29002
- const made = held.get(key) ?? brokerTokenClient(env, session);
29003
- held.set(key, made);
29004
- return made;
29777
+ function signInName(record) {
29778
+ return `${record.person}\x00${record.thumbprint}`;
29779
+ }
29780
+ function keyOf(env, own) {
29781
+ return {
29782
+ session: own.trim(),
29783
+ variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
29784
+ };
29785
+ }
29786
+ function entryFor(key) {
29787
+ let sessions = CLIENTS.get(key.session);
29788
+ if (sessions === undefined) {
29789
+ sessions = new Map;
29790
+ CLIENTS.set(key.session, sessions);
29791
+ }
29792
+ let entry = sessions.get(key.variables);
29793
+ if (entry === undefined) {
29794
+ entry = { making: undefined, made: undefined, refused: new Map };
29795
+ sessions.set(key.variables, entry);
29796
+ }
29797
+ return entry;
29798
+ }
29799
+ async function make(env, own) {
29800
+ const made = await brokerTokenClient(env, own);
29801
+ const signIn = made?.signIn;
29802
+ return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
29803
+ }
29804
+ async function clientFor(env, own) {
29805
+ const key = keyOf(env, own);
29806
+ const entry = entryFor(key);
29807
+ if (entry.refused.size > 0) {
29808
+ const record = await chooseSignIn(env);
29809
+ const chosen = record === undefined ? "" : signInName(record);
29810
+ if (entry.refused.has(chosen))
29811
+ throw entry.refused.get(chosen);
29812
+ if (entry.made !== undefined && entry.made.signIn !== chosen) {
29813
+ entry.making = undefined;
29814
+ entry.made = undefined;
29815
+ }
29816
+ }
29817
+ let making = entry.making;
29818
+ if (making === undefined) {
29819
+ const started = make(env, key.session);
29820
+ making = started;
29821
+ entry.making = started;
29822
+ started.then((made) => {
29823
+ if (entry.making === started)
29824
+ entry.made = made;
29825
+ }, () => {
29826
+ if (entry.making === started)
29827
+ entry.making = undefined;
29828
+ });
29829
+ }
29830
+ return { entry, made: await making };
29005
29831
  }
29006
29832
  function brokerCredential(env, session) {
29007
- let held = "";
29833
+ let presented = "";
29834
+ const own = (acting) => (acting ?? "").trim() || sessionName(session);
29008
29835
  return {
29009
29836
  scheme: "DPoP",
29010
29837
  async headers(method, url, acting) {
29011
- const client = await clientFor(env, (acting ?? "").trim() || sessionName(session));
29838
+ const { entry, made } = await clientFor(env, own(acting));
29839
+ const { client } = made;
29012
29840
  if (client === undefined) {
29013
29841
  throw new Error("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
29014
29842
  }
29015
- const token = await client.token();
29016
- held = token.accessToken;
29843
+ let token;
29844
+ try {
29845
+ token = await client.token();
29846
+ } catch (error) {
29847
+ if (made.signIn !== "" && isFinalRefusal(error))
29848
+ entry.refused.set(made.signIn, error);
29849
+ throw error;
29850
+ }
29851
+ presented = token.accessToken;
29017
29852
  return {
29018
29853
  Authorization: `DPoP ${token.accessToken}`,
29019
29854
  DPoP: await client.key.proof({ method, url, accessToken: token.accessToken })
29020
29855
  };
29021
29856
  },
29022
- secret: () => held
29857
+ stale(acting) {
29858
+ const key = keyOf(env, own(acting));
29859
+ CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop();
29860
+ },
29861
+ secret: () => presented
29023
29862
  };
29024
29863
  }
29025
29864
 
@@ -29099,7 +29938,7 @@ function brokerRouteForced(env) {
29099
29938
  return false;
29100
29939
  if (written === "1")
29101
29940
  return true;
29102
- 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`);
29941
+ 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`);
29103
29942
  }
29104
29943
  function dispatchTarget(env, config) {
29105
29944
  if (config.kind === "failed")
@@ -29150,7 +29989,7 @@ function dispatchTarget(env, config) {
29150
29989
  return { enabled: true, url: brokered, source: { kind: "broker" } };
29151
29990
  }
29152
29991
  if (forced) {
29153
- 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`);
29992
+ 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`);
29154
29993
  }
29155
29994
  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}`);
29156
29995
  }