@sjawhar/pi-envoy 17.26.0 → 17.27.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.
Files changed (3) hide show
  1. package/dist/dispatch.js +919 -80
  2. package/dist/envoy.js +951 -110
  3. package/package.json +1 -1
package/dist/dispatch.js CHANGED
@@ -15162,6 +15162,14 @@ var handoffValidation = {
15162
15162
  message: HANDOFF_RULE,
15163
15163
  refusal: (value) => handoffProblem(value) ?? HANDOFF_RULE
15164
15164
  };
15165
+ var REVIEW_REASON_RULE = "verdict changes_requested requires reason, a non-empty note saying what must change before the document can be approved.";
15166
+ var reviewValidation = {
15167
+ check: (value) => {
15168
+ const input = value;
15169
+ return input.verdict !== "changes_requested" || typeof input.reason === "string" && input.reason.trim() !== "";
15170
+ },
15171
+ message: REVIEW_REASON_RULE
15172
+ };
15165
15173
  var RESULT_REQUIRED_FIELDS = ["issue", "check", "role", "verdict", "commit"];
15166
15174
  var RESULT_RECORD_FIELDS = [
15167
15175
  ...RESULT_REQUIRED_FIELDS,
@@ -15545,6 +15553,20 @@ var dispatchToolSpecs = [
15545
15553
  version: z.number({ int: true, min: 1 }).describe("The plan version the review read and approved.")
15546
15554
  })
15547
15555
  },
15556
+ {
15557
+ name: "dispatch_review",
15558
+ example: { issue: "DSP-1", version: 2, verdict: "approved" },
15559
+ 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,
15560
+ arguments: (z) => ({
15561
+ issue: z.string().describe(ISSUE_REFERENCE),
15562
+ artifact: z.string().describe("Document artifact id, slug, or filename; the issue's spec by default.").optional(),
15563
+ 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."),
15564
+ verdict: z.enum(["approved", "changes_requested"]).describe("approved records an approval; changes_requested records a request for changes and requires reason."),
15565
+ reason: z.string().describe("What must change before the document can be approved. changes_requested requires it; an approval may carry one.").optional()
15566
+ }),
15567
+ validation: reviewValidation,
15568
+ strict: true
15569
+ },
15548
15570
  {
15549
15571
  name: "dispatch_result",
15550
15572
  example: {
@@ -18349,6 +18371,9 @@ class DispatchNoRouteError extends DispatchServiceError {
18349
18371
  super("NOT_FOUND", 404, NO_ROUTE_ROLLING_RELEASE_MESSAGE);
18350
18372
  }
18351
18373
  }
18374
+ function reviewNoRouteRefusal(baseUrl, route, version) {
18375
+ 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.");
18376
+ }
18352
18377
  var ISSUE_EVENTS_PAGE_MAX = 200;
18353
18378
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
18354
18379
  function requestSignal(signal) {
@@ -18482,6 +18507,15 @@ async function writeAnswer(response, key) {
18482
18507
  unjudged: !echoed && typeof shape.error === "string"
18483
18508
  };
18484
18509
  }
18510
+ var BROKER_TOKEN_NOT_ACTIVE = "BROKER_TOKEN_NOT_ACTIVE";
18511
+ async function tokenNotLive(response) {
18512
+ if (response.status !== 401 || !isJson(response))
18513
+ return false;
18514
+ const body = await response.clone().json().catch(() => {
18515
+ return;
18516
+ });
18517
+ return asErrorShape(body).code === BROKER_TOKEN_NOT_ACTIVE;
18518
+ }
18485
18519
  function whyNotAPage(answer) {
18486
18520
  if (typeof answer === "string") {
18487
18521
  return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
@@ -18804,6 +18838,18 @@ class DispatchClient {
18804
18838
  async planApprove(artifactID, input) {
18805
18839
  return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
18806
18840
  }
18841
+ async reviewArtifact(artifactID, version, input) {
18842
+ const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
18843
+ const body = { state: input.state, reason: input.reason };
18844
+ try {
18845
+ return await this.#json("POST", path, body);
18846
+ } catch (error) {
18847
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
18848
+ throw error;
18849
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
18850
+ throw reviewNoRouteRefusal(this.#baseUrl, route, version);
18851
+ }
18852
+ }
18807
18853
  async recordResult(issue, input) {
18808
18854
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
18809
18855
  }
@@ -19039,11 +19085,20 @@ class DispatchClient {
19039
19085
  });
19040
19086
  }
19041
19087
  async#send(method, url, body, accept = "application/json", signal, callerKey) {
19088
+ const key = method === "POST" || method === "PATCH" ? callerKey ?? crypto.randomUUID() : undefined;
19089
+ const send = async () => this.#sendPresenting(method, url, body, accept, signal, key);
19090
+ const answer = await send();
19091
+ if (this.#credential.stale === undefined || !await tokenNotLive(answer))
19092
+ return answer;
19093
+ this.#credential.stale();
19094
+ return await send();
19095
+ }
19096
+ async#sendPresenting(method, url, body, accept, signal, key) {
19042
19097
  const headers = { Accept: accept };
19043
19098
  let presented = await this.#credential.headers(method, url);
19044
19099
  if (body !== undefined)
19045
19100
  headers["Content-Type"] = body.type;
19046
- if (method !== "POST" && method !== "PATCH") {
19101
+ if (key === undefined) {
19047
19102
  return this.fetchImpl(url, {
19048
19103
  method,
19049
19104
  headers: { ...headers, ...presented },
@@ -19051,7 +19106,6 @@ class DispatchClient {
19051
19106
  ...body === undefined ? {} : { body: body.content }
19052
19107
  });
19053
19108
  }
19054
- const key = callerKey ?? crypto.randomUUID();
19055
19109
  headers[IDEMPOTENCY_KEY_HEADER] = key;
19056
19110
  const { pausesMs, withinMs, silenceMs, inFlightPauseMs, inFlightWithinMs } = this.writeRetry;
19057
19111
  const pause = this.writeRetry.pause ?? pauseFor;
@@ -24018,6 +24072,41 @@ async function readCommand(context) {
24018
24072
  };
24019
24073
  }
24020
24074
 
24075
+ // ../envoy-client/src/dispatch-commands/reviews.ts
24076
+ async function reviewCommand(context) {
24077
+ const { args, client, documentOwner, resolveDocument } = context;
24078
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
24079
+ const { artifact } = resolved;
24080
+ let review;
24081
+ try {
24082
+ review = await client.reviewArtifact(artifact.id, numberArg(args, "version"), {
24083
+ state: stringArg(args, "verdict"),
24084
+ ...defined("reason", optionalString(args, "reason"))
24085
+ });
24086
+ } catch (error) {
24087
+ throw refusalWithCode(error);
24088
+ }
24089
+ const issue = resolved.issue?.key;
24090
+ const answered = review.ask_id === null ? [] : [
24091
+ `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.`
24092
+ ];
24093
+ return {
24094
+ text: [
24095
+ `Recorded the review of ${artifact.name} (document id ${artifact.id}): ${review.state} at version ${review.version}, by ${actorText(review.actor)}.`,
24096
+ ...review.reason === null ? [] : [`Reason: ${JSON.stringify(review.reason)}`],
24097
+ ...answered
24098
+ ].join(`
24099
+ `),
24100
+ details: {
24101
+ issue,
24102
+ artifact: artifact.id,
24103
+ version: review.version,
24104
+ state: review.state,
24105
+ ...review.ask_id === null ? {} : { ask: review.ask_id }
24106
+ }
24107
+ };
24108
+ }
24109
+
24021
24110
  // ../envoy-client/src/dispatch-session-directory.ts
24022
24111
  import { randomUUID } from "crypto";
24023
24112
  import { renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
@@ -24350,6 +24439,7 @@ var dispatchCommands = {
24350
24439
  dispatch_doc_read: acting(docReadCommand),
24351
24440
  dispatch_request_approval: acting(requestApprovalCommand),
24352
24441
  dispatch_plan_approve: acting(planApproveCommand),
24442
+ dispatch_review: acting(reviewCommand),
24353
24443
  dispatch_result: acting(resultCommand),
24354
24444
  dispatch_results: acting(resultsCommand),
24355
24445
  dispatch_artifact: acting(artifactCommand),
@@ -25003,6 +25093,9 @@ function fileBearer(bearer, url, section, env, commands = "run") {
25003
25093
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
25004
25094
  }
25005
25095
 
25096
+ // ../broker-client/src/dpop.ts
25097
+ import { createPrivateKey, createPublicKey } from "crypto";
25098
+
25006
25099
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
25007
25100
  var encoder2 = new TextEncoder;
25008
25101
  var decoder = new TextDecoder;
@@ -25849,6 +25942,112 @@ function keyAlgorithm(alg, source) {
25849
25942
  return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : undefined) ?? unsupportedAlg(source);
25850
25943
  }
25851
25944
 
25945
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/asn1.js
25946
+ var bytesEqual = (a, b) => {
25947
+ if (a.byteLength !== b.length)
25948
+ return false;
25949
+ for (let i = 0;i < a.byteLength; i++) {
25950
+ if (a[i] !== b[i])
25951
+ return false;
25952
+ }
25953
+ return true;
25954
+ };
25955
+ var createASN1State = (data) => ({ data, pos: 0 });
25956
+ var readByte = (state) => {
25957
+ const byte = state.data[state.pos++];
25958
+ if (byte === undefined) {
25959
+ throw new Error("Unexpected end of ASN.1 input");
25960
+ }
25961
+ return byte;
25962
+ };
25963
+ var parseLength = (state) => {
25964
+ const first = readByte(state);
25965
+ if (first & 128) {
25966
+ const lengthOfLen = first & 127;
25967
+ let length = 0;
25968
+ for (let i = 0;i < lengthOfLen; i++) {
25969
+ length = length << 8 | readByte(state);
25970
+ }
25971
+ return length;
25972
+ }
25973
+ return first;
25974
+ };
25975
+ var expectTag = (state, expectedTag, errorMessage) => {
25976
+ if (readByte(state) !== expectedTag) {
25977
+ throw new Error(errorMessage);
25978
+ }
25979
+ };
25980
+ var getSubarray = (state, length) => {
25981
+ if (length < 0 || state.pos + length > state.data.length) {
25982
+ throw new Error("Unexpected end of ASN.1 input");
25983
+ }
25984
+ const result = state.data.subarray(state.pos, state.pos + length);
25985
+ state.pos += length;
25986
+ return result;
25987
+ };
25988
+ var parseAlgorithmOID = (state) => {
25989
+ expectTag(state, 6, "Expected algorithm OID");
25990
+ const oidLen = parseLength(state);
25991
+ return getSubarray(state, oidLen);
25992
+ };
25993
+ function parseKeyHeader(state, keyFormat) {
25994
+ expectTag(state, 48, `Invalid ${keyFormat === "spki" ? "SPKI" : "PKCS#8"} structure`);
25995
+ parseLength(state);
25996
+ if (keyFormat === "pkcs8") {
25997
+ expectTag(state, 2, "Expected version field");
25998
+ const length = parseLength(state);
25999
+ state.pos += length;
26000
+ }
26001
+ expectTag(state, 48, "Expected algorithm identifier");
26002
+ parseLength(state);
26003
+ }
26004
+ var parseECAlgorithmIdentifier = (state) => {
26005
+ const algOid = parseAlgorithmOID(state);
26006
+ if (bytesEqual(algOid, [43, 101, 110])) {
26007
+ return "X25519";
26008
+ }
26009
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
26010
+ throw new Error("Unsupported key algorithm");
26011
+ }
26012
+ expectTag(state, 6, "Expected curve OID");
26013
+ const curveOidLen = parseLength(state);
26014
+ const curveOid = getSubarray(state, curveOidLen);
26015
+ if (bytesEqual(curveOid, [42, 134, 72, 206, 61, 3, 1, 7]))
26016
+ return "P-256";
26017
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 34]))
26018
+ return "P-384";
26019
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 35]))
26020
+ return "P-521";
26021
+ throw new Error("Unsupported named curve");
26022
+ };
26023
+ var genericImport = async (keyFormat, keyData, alg, options) => {
26024
+ const entry = keyAlgorithm(alg, algArgument);
26025
+ if (entry.secret) {
26026
+ unsupportedAlg(algArgument);
26027
+ }
26028
+ const isPublic = keyFormat === "spki";
26029
+ let algorithm;
26030
+ if (entry.resolve) {
26031
+ try {
26032
+ const state = createASN1State(keyData);
26033
+ parseKeyHeader(state, keyFormat);
26034
+ algorithm = entry.resolve({ crv: parseECAlgorithmIdentifier(state) });
26035
+ } catch {
26036
+ throw new JOSENotSupported("Invalid or unsupported key format");
26037
+ }
26038
+ } else {
26039
+ algorithm = entry.subtle;
26040
+ }
26041
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
26042
+ };
26043
+ var processPEMData = (pem, pattern) => {
26044
+ return decodeBase64(pem.replace(pattern, ""));
26045
+ };
26046
+ var fromPKCS8 = (pem, alg, options) => {
26047
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
26048
+ return genericImport("pkcs8", keyData, alg, options);
26049
+ };
26050
+
25852
26051
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
25853
26052
  function omitUndefinedProperties(jwk) {
25854
26053
  return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
@@ -25882,6 +26081,13 @@ async function keyToJWK(key) {
25882
26081
  function exportJWK(key) {
25883
26082
  return keyToJWK(key);
25884
26083
  }
26084
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/import.js
26085
+ async function importPKCS8(pkcs8, alg, options) {
26086
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
26087
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
26088
+ }
26089
+ return fromPKCS8(pkcs8, alg, options);
26090
+ }
25885
26091
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/generate_key_pair.js
25886
26092
  function getModulusLengthOption(options) {
25887
26093
  const modulusLength = options?.modulusLength ?? 2048;
@@ -25925,6 +26131,11 @@ async function generateKeyPair(alg, options) {
25925
26131
  ...entry.usages[0]
25926
26132
  ]);
25927
26133
  }
26134
+ // ../broker-client/src/error-text.ts
26135
+ function messageOf(error) {
26136
+ return error instanceof Error ? error.message : String(error);
26137
+ }
26138
+
25928
26139
  // ../broker-client/src/dpop.ts
25929
26140
  var ALGORITHM = "ES256";
25930
26141
  function targetUri(url) {
@@ -25937,9 +26148,7 @@ async function accessTokenHash(accessToken) {
25937
26148
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
25938
26149
  return Buffer.from(digest).toString("base64url");
25939
26150
  }
25940
- async function newDpopKey() {
25941
- const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
25942
- const publicJwk = await exportJWK(publicKey);
26151
+ function dpopKey(privateKey, publicJwk) {
25943
26152
  return {
25944
26153
  publicJwk,
25945
26154
  async proof(request) {
@@ -25958,6 +26167,30 @@ async function newDpopKey() {
25958
26167
  }
25959
26168
  };
25960
26169
  }
26170
+ async function newDpopKey() {
26171
+ const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
26172
+ return dpopKey(privateKey, await exportJWK(publicKey));
26173
+ }
26174
+ async function importDpopKey(pkcs8Pem, name) {
26175
+ const unreadable = (error) => new Error(`read ${name}: ${messageOf(error)}`, { cause: error });
26176
+ let exported;
26177
+ try {
26178
+ exported = createPublicKey(createPrivateKey(pkcs8Pem)).export({ format: "jwk" });
26179
+ } catch (error) {
26180
+ throw unreadable(error);
26181
+ }
26182
+ const { kty, crv, x, y } = exported;
26183
+ if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
26184
+ throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
26185
+ }
26186
+ let privateKey;
26187
+ try {
26188
+ privateKey = await importPKCS8(pkcs8Pem, ALGORITHM, { extractable: false });
26189
+ } catch (error) {
26190
+ throw unreadable(error);
26191
+ }
26192
+ return dpopKey(privateKey, { kty, crv, x, y });
26193
+ }
25961
26194
 
25962
26195
  // ../broker-client/src/metadata-identity.ts
25963
26196
  import { Agent, request } from "http";
@@ -25971,6 +26204,7 @@ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
25971
26204
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
25972
26205
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
25973
26206
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
26207
+ var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
25974
26208
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
25975
26209
  var TOKEN_TYPE_DPOP = "DPoP";
25976
26210
 
@@ -26032,29 +26266,6 @@ function metadataIdentity(audience, env = process.env) {
26032
26266
  };
26033
26267
  }
26034
26268
 
26035
- // ../broker-client/src/projected-token.ts
26036
- import { readFile } from "fs/promises";
26037
- function projectedToken(path) {
26038
- return {
26039
- async read(signal) {
26040
- let contents;
26041
- try {
26042
- contents = await readFile(path, {
26043
- encoding: "utf8",
26044
- ...signal === undefined ? {} : { signal }
26045
- });
26046
- } catch (error) {
26047
- throw new Error(`read the projected service-account token ${path}: ${error.message}`);
26048
- }
26049
- const token = contents.trim();
26050
- if (token === "")
26051
- throw new Error(`the projected service-account token ${path} is empty`);
26052
- return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
26053
- },
26054
- describe: () => `the projected service-account token ${path}`
26055
- };
26056
- }
26057
-
26058
26269
  // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
26059
26270
  var USER_AGENT;
26060
26271
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
@@ -26200,6 +26411,56 @@ function signal(url, value) {
26200
26411
  }
26201
26412
  return;
26202
26413
  }
26414
+ function replaceDoubleSlash(pathname) {
26415
+ if (pathname.includes("//")) {
26416
+ return pathname.replace("//", "/");
26417
+ }
26418
+ return pathname;
26419
+ }
26420
+ function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
26421
+ if (url.pathname === "/") {
26422
+ url.pathname = wellKnown;
26423
+ } else {
26424
+ url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
26425
+ }
26426
+ return url;
26427
+ }
26428
+ function appendWellKnown(url, wellKnown) {
26429
+ url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
26430
+ return url;
26431
+ }
26432
+ async function performDiscovery(input, urlName, transform, options) {
26433
+ if (!(input instanceof URL)) {
26434
+ throw CodedTypeError(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE);
26435
+ }
26436
+ checkProtocol(input, options?.[allowInsecureRequests] !== true);
26437
+ const url = transform(new URL(input.href));
26438
+ const headers = prepareHeaders(options?.headers);
26439
+ headers.set("accept", "application/json");
26440
+ return (options?.[customFetch] || fetch)(url.href, {
26441
+ body: undefined,
26442
+ headers: Object.fromEntries(headers.entries()),
26443
+ method: "GET",
26444
+ redirect: "manual",
26445
+ signal: signal(url, options?.signal)
26446
+ });
26447
+ }
26448
+ async function discoveryRequest(issuerIdentifier, options) {
26449
+ return performDiscovery(issuerIdentifier, "issuerIdentifier", (url) => {
26450
+ switch (options?.algorithm) {
26451
+ case undefined:
26452
+ case "oidc":
26453
+ appendWellKnown(url, ".well-known/openid-configuration");
26454
+ break;
26455
+ case "oauth2":
26456
+ prependWellKnown(url, ".well-known/oauth-authorization-server");
26457
+ break;
26458
+ default:
26459
+ throw CodedTypeError('"options.algorithm" must be "oidc" (default), or "oauth2"', ERR_INVALID_ARG_VALUE);
26460
+ }
26461
+ return url;
26462
+ }, options);
26463
+ }
26203
26464
  function assertNumber(input, allow0, it, code, cause) {
26204
26465
  try {
26205
26466
  if (typeof input !== "number" || !Number.isFinite(input)) {
@@ -26236,6 +26497,25 @@ function assertString(input, it, code, cause) {
26236
26497
  throw err;
26237
26498
  }
26238
26499
  }
26500
+ async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
26501
+ const expected = expectedIssuerIdentifier;
26502
+ if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
26503
+ throw CodedTypeError('"expectedIssuerIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE);
26504
+ }
26505
+ if (!looseInstanceOf(response, Response)) {
26506
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
26507
+ }
26508
+ if (response.status !== 200) {
26509
+ throw OPE('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
26510
+ }
26511
+ assertReadableResponse(response);
26512
+ const json = await getResponseJsonBody(response);
26513
+ assertString(json.issuer, '"response" body "issuer" property', INVALID_RESPONSE, { body: json });
26514
+ if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {
26515
+ throw OPE('"response" body "issuer" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: "issuer" });
26516
+ }
26517
+ return json;
26518
+ }
26239
26519
  function assertApplicationJson(response) {
26240
26520
  assertContentType(response, "application/json");
26241
26521
  }
@@ -26515,6 +26795,14 @@ async function tokenEndpointRequest(as, client, clientAuthentication, grantType,
26515
26795
  options?.DPoP?.cacheNonce(response, url);
26516
26796
  return response;
26517
26797
  }
26798
+ async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
26799
+ assertAs(as);
26800
+ assertClient(client);
26801
+ assertString(refreshToken, '"refreshToken"');
26802
+ const parameters = new URLSearchParams(options?.additionalParameters);
26803
+ parameters.set("refresh_token", refreshToken);
26804
+ return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
26805
+ }
26518
26806
  var idTokenClaims = new WeakMap;
26519
26807
  var jwtRefs = new WeakMap;
26520
26808
  function getValidatedIdTokenClaims(ref) {
@@ -26592,6 +26880,9 @@ function checkAuthenticationChallenges(response) {
26592
26880
  throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", { cause: challenges, response });
26593
26881
  }
26594
26882
  }
26883
+ async function processRefreshTokenResponse(as, client, response, options) {
26884
+ return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
26885
+ }
26595
26886
  function validateAudience(expected, result) {
26596
26887
  if (Array.isArray(result.claims.aud)) {
26597
26888
  if (!result.claims.aud.includes(expected)) {
@@ -26944,6 +27235,73 @@ function errorHandler(err) {
26944
27235
  }
26945
27236
  throw new ClientError("something went wrong", { cause: err });
26946
27237
  }
27238
+ function handleEntraId(server, as, options) {
27239
+ if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
27240
+ as[kEntraId] = true;
27241
+ return true;
27242
+ }
27243
+ return false;
27244
+ }
27245
+ function handleB2Clogin(server, options) {
27246
+ if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) {
27247
+ return true;
27248
+ }
27249
+ return false;
27250
+ }
27251
+ async function discovery(server, clientId, metadata, clientAuthentication, options) {
27252
+ const as = await performDiscovery2(server, options);
27253
+ const instance = new Configuration(as, clientId, metadata, clientAuthentication);
27254
+ let internals = int2(instance);
27255
+ if (options?.[customFetch2]) {
27256
+ internals.fetch = options[customFetch2];
27257
+ }
27258
+ if (options?.timeout) {
27259
+ internals.timeout = options.timeout;
27260
+ }
27261
+ if (options?.execute) {
27262
+ for (const extension of options.execute) {
27263
+ extension(instance);
27264
+ }
27265
+ }
27266
+ return instance;
27267
+ }
27268
+ async function performDiscovery2(server, options) {
27269
+ if (!(server instanceof URL)) {
27270
+ throw CodedTypeError2('"server" must be an instance of URL', ERR_INVALID_ARG_TYPE2);
27271
+ }
27272
+ const resolve = !server.href.includes("/.well-known/");
27273
+ const timeout = options?.timeout ?? 30;
27274
+ const signal = AbortSignal.timeout(timeout * 1000);
27275
+ const as = await (resolve ? discoveryRequest(server, {
27276
+ algorithm: options?.algorithm,
27277
+ [customFetch]: options?.[customFetch2],
27278
+ [allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests2),
27279
+ signal,
27280
+ headers: new Headers(headers)
27281
+ }) : (options?.[customFetch2] || fetch)((() => {
27282
+ checkProtocol(server, options?.execute?.includes(allowInsecureRequests2) ? false : true);
27283
+ return server.href;
27284
+ })(), {
27285
+ headers: Object.fromEntries(new Headers({ accept: "application/json", ...headers }).entries()),
27286
+ body: undefined,
27287
+ method: "GET",
27288
+ redirect: "manual",
27289
+ signal
27290
+ })).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
27291
+ if (resolve && new URL(as.issuer).href !== server.href) {
27292
+ handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
27293
+ throw new ClientError("discovered metadata issuer does not match the expected issuer", {
27294
+ code: JSON_ATTRIBUTE_COMPARISON,
27295
+ cause: {
27296
+ expected: server.href,
27297
+ body: as,
27298
+ attribute: "issuer"
27299
+ }
27300
+ });
27301
+ })();
27302
+ }
27303
+ return as;
27304
+ }
26947
27305
  function getServerHelpers(metadata) {
26948
27306
  return {
26949
27307
  supportsPKCE: {
@@ -27060,6 +27418,37 @@ function addHelpers(response) {
27060
27418
  function allowInsecureRequests2(config) {
27061
27419
  int2(config).tlsOnly = false;
27062
27420
  }
27421
+ async function refreshTokenGrant(config, refreshToken, parameters, options) {
27422
+ checkConfig(config);
27423
+ parameters = new URLSearchParams(parameters);
27424
+ const { as, c, auth, fetch: fetch2, tlsOnly, nonRepudiation, timeout, decrypt } = int2(config);
27425
+ const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
27426
+ [customFetch]: fetch2,
27427
+ [allowInsecureRequests]: !tlsOnly,
27428
+ additionalParameters: parameters,
27429
+ DPoP: options?.DPoP,
27430
+ headers: new Headers(headers),
27431
+ signal: signal2(timeout)
27432
+ }).catch(errorHandler);
27433
+ const p = processRefreshTokenResponse(as, c, response, {
27434
+ [jweDecrypt]: decrypt
27435
+ });
27436
+ let result;
27437
+ try {
27438
+ result = await p;
27439
+ } catch (err) {
27440
+ if (retryable(err, options)) {
27441
+ return refreshTokenGrant(config, refreshToken, parameters, {
27442
+ ...options,
27443
+ flag: retry
27444
+ });
27445
+ }
27446
+ errorHandler(err);
27447
+ }
27448
+ result.id_token && await nonRepudiation?.(response);
27449
+ addHelpers(result);
27450
+ return result;
27451
+ }
27063
27452
  function checkConfig(input) {
27064
27453
  if (!(input instanceof Configuration)) {
27065
27454
  throw CodedTypeError2('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE2);
@@ -27113,6 +27502,136 @@ async function genericGrantRequest(config, grantType, parameters, options) {
27113
27502
  return result;
27114
27503
  }
27115
27504
 
27505
+ // ../broker-client/src/signins.ts
27506
+ import { readdir, readFile } from "fs/promises";
27507
+ import { join as join5 } from "path";
27508
+ var SIGNIN_DIR_VAR = "AGENT_SECRETS_SIGNIN_DIR";
27509
+ var PERSON_VAR = "AGENT_SECRETS_PERSON";
27510
+ var PERSON_TRADE_VAR = "PERSON_SIGNIN_TRADE";
27511
+ var SIGNIN_ISSUER_VAR = "AGENT_SECRETS_SIGNIN_ISSUER";
27512
+ var SIGNIN_CLIENT_ID_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_ID";
27513
+ var SIGNIN_CLIENT_SECRET_FILE_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_SECRET_FILE";
27514
+ var DEFAULT_SIGNIN_ISSUER = "https://accounts.google.com";
27515
+ var SIGNIN_COMMAND = "agent-secrets login";
27516
+ var SIGNINS_DIR = "signins";
27517
+ var RECORD_MEMBERS = [
27518
+ "person",
27519
+ "issuer",
27520
+ "client_id",
27521
+ "refresh_token",
27522
+ "box_key",
27523
+ "thumbprint",
27524
+ "enrollment_id",
27525
+ "signed_in_at"
27526
+ ];
27527
+ function signInDirectory(env) {
27528
+ const named = env[SIGNIN_DIR_VAR] ?? "";
27529
+ if (named !== "")
27530
+ return named;
27531
+ const state = env.XDG_STATE_HOME ?? "";
27532
+ const base = state !== "" ? state : join5(env.HOME ?? "", ".local", "state");
27533
+ return join5(base, "agent-secrets", SIGNINS_DIR);
27534
+ }
27535
+ async function readSignIn(path) {
27536
+ let text;
27537
+ try {
27538
+ text = await readFile(path, "utf8");
27539
+ } catch (error) {
27540
+ throw new Error(`read the sign-in at ${path}: ${messageOf(error)}`, { cause: error });
27541
+ }
27542
+ let parsed;
27543
+ try {
27544
+ parsed = JSON.parse(text);
27545
+ } catch {
27546
+ throw new Error(`read the sign-in at ${path}: it is not JSON; run: ${SIGNIN_COMMAND}`);
27547
+ }
27548
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
27549
+ throw new Error(`read the sign-in at ${path}: it holds no JSON object; run: ${SIGNIN_COMMAND}`);
27550
+ }
27551
+ const fields = parsed;
27552
+ const record = {};
27553
+ for (const member of RECORD_MEMBERS) {
27554
+ const given = fields[member] ?? "";
27555
+ if (typeof given !== "string") {
27556
+ throw new Error(`read the sign-in at ${path}: its ${member} is not a string; run: ${SIGNIN_COMMAND}`);
27557
+ }
27558
+ record[member] = given;
27559
+ }
27560
+ const read = record;
27561
+ if (read.person === "" || read.refresh_token === "" || read.box_key === "") {
27562
+ throw new Error(`the sign-in at ${path} names no person, no refresh token or no box key; run: ${SIGNIN_COMMAND}`);
27563
+ }
27564
+ return read;
27565
+ }
27566
+ async function listSignIns(dir) {
27567
+ let entries;
27568
+ try {
27569
+ entries = await readdir(dir, { withFileTypes: true });
27570
+ } catch (error) {
27571
+ if (error.code === "ENOENT")
27572
+ return [];
27573
+ throw new Error(`read this machine's sign-ins: ${messageOf(error)}`, { cause: error });
27574
+ }
27575
+ const names = entries.filter((entry) => !entry.isDirectory() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
27576
+ const records = [];
27577
+ for (const name of names)
27578
+ records.push(await readSignIn(join5(dir, name)));
27579
+ return records.sort((a, b) => a.person < b.person ? -1 : a.person > b.person ? 1 : 0);
27580
+ }
27581
+ function namesOf(records) {
27582
+ return records.map((record) => record.person).join(", ");
27583
+ }
27584
+ function personTradeOff(env) {
27585
+ const written = (env[PERSON_TRADE_VAR] ?? "").trim();
27586
+ if (written === "")
27587
+ return false;
27588
+ if (written === "off")
27589
+ return true;
27590
+ 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`);
27591
+ }
27592
+ async function chooseSignIn(env) {
27593
+ if (personTradeOff(env))
27594
+ return;
27595
+ const records = await listSignIns(signInDirectory(env));
27596
+ const person = (env[PERSON_VAR] ?? "").trim().toLowerCase();
27597
+ if (records.length === 0)
27598
+ return;
27599
+ if (person !== "") {
27600
+ const named = records.find((record) => record.person.toLowerCase() === person);
27601
+ if (named !== undefined)
27602
+ return named;
27603
+ throw new Error(`${PERSON_VAR} names ${person}, who is not signed in on this machine; signed in here: ${namesOf(records)}; run: ${SIGNIN_COMMAND}`);
27604
+ }
27605
+ if (records.length === 1)
27606
+ return records[0];
27607
+ 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`);
27608
+ }
27609
+ function signInSessionName(record) {
27610
+ const name = `signin-${record.person}`;
27611
+ return record.thumbprint === "" ? name : `${name}-${record.thumbprint.slice(0, 12)}`;
27612
+ }
27613
+ async function signInFlow(env) {
27614
+ const clientId = (env[SIGNIN_CLIENT_ID_VAR] ?? "").trim();
27615
+ const secretFile = (env[SIGNIN_CLIENT_SECRET_FILE_VAR] ?? "").trim();
27616
+ if (clientId === "" && secretFile === "")
27617
+ return;
27618
+ if (clientId === "" || secretFile === "") {
27619
+ 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`);
27620
+ }
27621
+ let secret;
27622
+ try {
27623
+ secret = await readFile(secretFile, "utf8");
27624
+ } catch (error) {
27625
+ throw new Error(`read the sign-in client's secret (${SIGNIN_CLIENT_SECRET_FILE_VAR}): ${messageOf(error)}`, { cause: error });
27626
+ }
27627
+ const issuer = (env[SIGNIN_ISSUER_VAR] ?? "").trim();
27628
+ return {
27629
+ issuer: withoutTrailingSlashes(issuer === "" ? DEFAULT_SIGNIN_ISSUER : issuer),
27630
+ clientId,
27631
+ clientSecret: secret.trim()
27632
+ };
27633
+ }
27634
+
27116
27635
  // ../broker-client/src/token-client.ts
27117
27636
  var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
27118
27637
  var TOO_MANY_REQUESTS = 429;
@@ -27123,8 +27642,8 @@ class BrokerRefusedError extends Error {
27123
27642
  status;
27124
27643
  code;
27125
27644
  description;
27126
- constructor(status, code, description) {
27127
- 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}`);
27645
+ constructor(status, code, description, refused) {
27646
+ super(description === "" ? `the secrets broker refused ${refused}: HTTP ${status} ${code}` : `the secrets broker refused ${refused}: HTTP ${status} ${code}: ${description}`);
27128
27647
  this.status = status;
27129
27648
  this.code = code;
27130
27649
  this.description = description;
@@ -27134,6 +27653,20 @@ class BrokerRefusedError extends Error {
27134
27653
  return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE;
27135
27654
  }
27136
27655
  }
27656
+
27657
+ class SignInEndedError extends Error {
27658
+ issuer;
27659
+ person;
27660
+ constructor(issuer, person, options) {
27661
+ super(`${issuer} no longer honours ${person}'s sign-in on this machine; run: ${SIGNIN_COMMAND}`, options);
27662
+ this.issuer = issuer;
27663
+ this.person = person;
27664
+ this.name = "SignInEndedError";
27665
+ }
27666
+ }
27667
+ function isFinalRefusal(error) {
27668
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
27669
+ }
27137
27670
  function statusOf(error) {
27138
27671
  let cause = error;
27139
27672
  for (let depth = 0;depth < 4; depth += 1) {
@@ -27145,6 +27678,16 @@ function statusOf(error) {
27145
27678
  }
27146
27679
  return 0;
27147
27680
  }
27681
+ function requestInit(options, signal, headers) {
27682
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
27683
+ return {
27684
+ method: options.method,
27685
+ headers,
27686
+ body: options.body,
27687
+ redirect: options.redirect,
27688
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
27689
+ };
27690
+ }
27148
27691
 
27149
27692
  class BrokerTokenClient {
27150
27693
  #brokerUrl;
@@ -27193,6 +27736,9 @@ class BrokerTokenClient {
27193
27736
  this.#trading = null;
27194
27737
  }
27195
27738
  }
27739
+ drop() {
27740
+ this.#held = null;
27741
+ }
27196
27742
  async#renew(signal) {
27197
27743
  try {
27198
27744
  const token = await this.#trade(signal);
@@ -27200,7 +27746,7 @@ class BrokerTokenClient {
27200
27746
  return token;
27201
27747
  } catch (error) {
27202
27748
  const held = this.#held;
27203
- if (!(error instanceof BrokerRefusedError && error.permanent) && held !== null && this.#now() < held.expiresAt.getTime()) {
27749
+ if (!isFinalRefusal(error) && held !== null && this.#now() < held.expiresAt.getTime()) {
27204
27750
  return held;
27205
27751
  }
27206
27752
  this.#held = null;
@@ -27223,8 +27769,9 @@ class BrokerTokenClient {
27223
27769
  try {
27224
27770
  actor = await this.#actor.read(signal);
27225
27771
  } catch (error) {
27226
- const said = error instanceof Error ? error.message : String(error);
27227
- throw new Error(`read the machine this person signed in on: ${said}`, { cause: error });
27772
+ throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
27773
+ cause: error
27774
+ });
27228
27775
  }
27229
27776
  form["actor_token"] = actor.token;
27230
27777
  form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
@@ -27244,10 +27791,10 @@ class BrokerTokenClient {
27244
27791
  }
27245
27792
  #refusal(endpoint, error) {
27246
27793
  if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
27247
- return new BrokerRefusedError(error.status, error.error, error.error_description ?? "");
27794
+ return new BrokerRefusedError(error.status, error.error, error.error_description ?? "", this.#subject.describe());
27248
27795
  }
27249
27796
  const status = statusOf(error);
27250
- const message = error instanceof Error ? error.message : String(error);
27797
+ const message = messageOf(error);
27251
27798
  const said = status === 0 ? message : `HTTP ${status}: ${message}`;
27252
27799
  return new Error(`trade ${this.#subject.describe()} at ${endpoint}: ${said}`, {
27253
27800
  cause: error
@@ -27257,15 +27804,7 @@ class BrokerTokenClient {
27257
27804
  const send = async () => {
27258
27805
  const headers = new Headers(options.headers);
27259
27806
  headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
27260
- const signals = [options.signal, signal].filter((one) => one !== undefined);
27261
- const body = options.body;
27262
- return await this.#fetch(url, {
27263
- method: options.method,
27264
- headers,
27265
- body,
27266
- redirect: options.redirect,
27267
- ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
27268
- });
27807
+ return await this.#fetch(url, requestInit(options, signal, headers));
27269
27808
  };
27270
27809
  let answer = await send();
27271
27810
  const given = answer.headers.get("DPoP-Nonce") ?? "";
@@ -27313,15 +27852,241 @@ class BrokerTokenClient {
27313
27852
  }
27314
27853
  }
27315
27854
 
27855
+ // ../broker-client/src/person-identity.ts
27856
+ var ISSUER_TIMEOUT_SECONDS = 30;
27857
+ var INVALID_GRANT = "invalid_grant";
27858
+ function issuerSaid(error) {
27859
+ if (error instanceof ResponseBodyError) {
27860
+ const description = error.error_description ?? "";
27861
+ return `HTTP ${error.status} ${error.error}${description === "" ? "" : `: ${description}`}`;
27862
+ }
27863
+ let message = messageOf(error);
27864
+ const cause = error instanceof Error ? error.cause : undefined;
27865
+ if (cause instanceof Error && cause.message !== message)
27866
+ message += `: ${cause.message}`;
27867
+ const status = statusOf(error);
27868
+ return status === 0 ? message : `HTTP ${status}: ${message}`;
27869
+ }
27870
+ function personIdentity(record, flow, options = {}) {
27871
+ const { person, refresh_token: refreshToken, client_id: clientId } = record;
27872
+ if (clientId !== "" && clientId !== flow.clientId) {
27873
+ 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}`);
27874
+ }
27875
+ const send = options.fetch ?? fetch;
27876
+ const insecure = flow.issuer.startsWith("http:");
27877
+ let discovered = null;
27878
+ const through = (signal) => (url, init) => send(url, requestInit(init, signal, init.headers));
27879
+ const discover = async (signal) => {
27880
+ try {
27881
+ const config = await discovery(new URL(flow.issuer), flow.clientId, undefined, undefined, {
27882
+ [customFetch2]: through(signal),
27883
+ timeout: ISSUER_TIMEOUT_SECONDS,
27884
+ ...insecure ? { execute: [allowInsecureRequests2] } : {}
27885
+ });
27886
+ return config.serverMetadata();
27887
+ } catch (error) {
27888
+ throw new Error(`read the sign-in issuer ${flow.issuer}: ${issuerSaid(error)}`, {
27889
+ cause: error
27890
+ });
27891
+ }
27892
+ };
27893
+ return {
27894
+ async read(signal) {
27895
+ discovered ??= discover(signal);
27896
+ const discovering = discovered;
27897
+ let metadata;
27898
+ try {
27899
+ metadata = await discovering;
27900
+ } catch (error) {
27901
+ if (discovered === discovering)
27902
+ discovered = null;
27903
+ throw error;
27904
+ }
27905
+ let answered;
27906
+ try {
27907
+ const config = new Configuration(metadata, flow.clientId, undefined, ClientSecretPost2(flow.clientSecret));
27908
+ if (insecure)
27909
+ allowInsecureRequests2(config);
27910
+ config.timeout = ISSUER_TIMEOUT_SECONDS;
27911
+ config[customFetch2] = through(signal);
27912
+ answered = await refreshTokenGrant(config, refreshToken);
27913
+ } catch (error) {
27914
+ if (error instanceof ResponseBodyError && error.error === INVALID_GRANT) {
27915
+ throw new SignInEndedError(flow.issuer, person, { cause: error });
27916
+ }
27917
+ throw new Error(`renew ${person}'s sign-in at ${flow.issuer}: ${issuerSaid(error)}`);
27918
+ }
27919
+ const idToken = answered.id_token ?? "";
27920
+ if (idToken === "") {
27921
+ throw new Error(`${flow.issuer} answered no id_token: the sign-in asked for the "openid" scope and must be answered one`);
27922
+ }
27923
+ return { token: idToken, tokenType: SUBJECT_TOKEN_TYPE_PERSON };
27924
+ },
27925
+ describe: () => `${person}'s sign-in on this machine`
27926
+ };
27927
+ }
27928
+
27929
+ // ../broker-client/src/pool-identity.ts
27930
+ var DEFAULT_SECURITY_TOKEN_SERVICE_URL = "https://sts.googleapis.com/v1/token";
27931
+ var DEFAULT_IAM_CREDENTIALS_URL = "https://iamcredentials.googleapis.com";
27932
+ var REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
27933
+ var SCOPE = "https://www.googleapis.com/auth/cloud-platform";
27934
+ var SUBJECT_TOKEN_TYPE_JWT = "urn:ietf:params:oauth:token-type:jwt";
27935
+ var POOL_TIMEOUT_MS = 20000;
27936
+ var MAX_ANSWER_BYTES2 = 1 << 20;
27937
+ function poolSubjectTokenType(brokerType) {
27938
+ return brokerType === SUBJECT_TOKEN_TYPE_KUBERNETES ? SUBJECT_TOKEN_TYPE_JWT : brokerType;
27939
+ }
27940
+ function pathEscape(segment) {
27941
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(?:24|26|2B|3A|3D|40)/g, decodeURIComponent);
27942
+ }
27943
+ async function answerText(answer) {
27944
+ const reader = answer.body?.getReader();
27945
+ if (reader === undefined)
27946
+ return "";
27947
+ const chunks = [];
27948
+ let read = 0;
27949
+ while (read < MAX_ANSWER_BYTES2) {
27950
+ const { done, value } = await reader.read();
27951
+ if (done)
27952
+ break;
27953
+ const kept = value.subarray(0, MAX_ANSWER_BYTES2 - read);
27954
+ chunks.push(kept);
27955
+ read += kept.length;
27956
+ }
27957
+ await reader.cancel().catch(() => {
27958
+ return;
27959
+ });
27960
+ return Buffer.concat(chunks).toString("utf8");
27961
+ }
27962
+ function poolIdentity(options) {
27963
+ const securityTokenService = options.securityTokenServiceUrl ?? DEFAULT_SECURITY_TOKEN_SERVICE_URL;
27964
+ const iamCredentials = (options.iamCredentialsUrl ?? DEFAULT_IAM_CREDENTIALS_URL).replace(/\/$/, "");
27965
+ const account = pathEscape(options.serviceAccount);
27966
+ const mintEndpoint = `${iamCredentials}/v1/projects/-/serviceAccounts/${account}:generateIdToken`;
27967
+ const call = async (endpoint, bearer, body, member, signal) => {
27968
+ const signals = [AbortSignal.timeout(POOL_TIMEOUT_MS), signal].filter((one) => one !== undefined);
27969
+ const answer = await fetch(endpoint, {
27970
+ method: "POST",
27971
+ headers: {
27972
+ "Content-Type": "application/json",
27973
+ ...bearer === "" ? {} : { Authorization: `Bearer ${bearer}` }
27974
+ },
27975
+ body: JSON.stringify(body),
27976
+ signal: AbortSignal.any(signals)
27977
+ });
27978
+ const text = await answerText(answer);
27979
+ if (answer.status < 200 || answer.status > 299) {
27980
+ throw new Error(`HTTP ${answer.status}: ${text.trim()}`);
27981
+ }
27982
+ let parsed;
27983
+ try {
27984
+ parsed = JSON.parse(text);
27985
+ } catch {
27986
+ throw new Error(`HTTP ${answer.status}: the answer is not JSON`);
27987
+ }
27988
+ const value = typeof parsed === "object" && parsed !== null ? parsed[member] : undefined;
27989
+ return typeof value === "string" ? value : "";
27990
+ };
27991
+ const federate = async (subject, signal) => {
27992
+ let federated;
27993
+ try {
27994
+ federated = await call(securityTokenService, "", {
27995
+ audience: options.audience,
27996
+ grantType: GRANT_TYPE_TOKEN_EXCHANGE,
27997
+ requestedTokenType: REQUESTED_TOKEN_TYPE,
27998
+ scope: SCOPE,
27999
+ subjectTokenType: poolSubjectTokenType(subject.tokenType),
28000
+ subjectToken: subject.token
28001
+ }, "access_token", signal);
28002
+ } catch (error) {
28003
+ throw new Error(`trade this machine's credential at the security token service ${securityTokenService}: ${messageOf(error)}`, { cause: error });
28004
+ }
28005
+ if (federated === "") {
28006
+ throw new Error(`the security token service ${securityTokenService} answered no access_token`);
28007
+ }
28008
+ return federated;
28009
+ };
28010
+ const generateIdToken = async (federated, signal) => {
28011
+ let token;
28012
+ try {
28013
+ token = await call(mintEndpoint, federated, { audience: options.tokenAudience, includeEmail: true }, "token", signal);
28014
+ } catch (error) {
28015
+ throw new Error(`mint this machine's identity token at ${mintEndpoint}: ${messageOf(error)}`, { cause: error });
28016
+ }
28017
+ if (token === "")
28018
+ throw new Error(`generateIdToken at ${mintEndpoint} answered no token`);
28019
+ return token;
28020
+ };
28021
+ return {
28022
+ async read(signal) {
28023
+ let subject;
28024
+ try {
28025
+ subject = await options.subject.read(signal);
28026
+ } catch (error) {
28027
+ throw new Error(`read the credential the workload identity pool federates: ${messageOf(error)}`, { cause: error });
28028
+ }
28029
+ const federated = await federate(subject, signal);
28030
+ return {
28031
+ token: await generateIdToken(federated, signal),
28032
+ tokenType: SUBJECT_TOKEN_TYPE_GOOGLE
28033
+ };
28034
+ },
28035
+ describe: () => `a Google identity token for ${options.tokenAudience} minted through the workload identity pool ${options.audience} as ${options.serviceAccount}`
28036
+ };
28037
+ }
28038
+
28039
+ // ../broker-client/src/projected-token.ts
28040
+ import { readFile as readFile2 } from "fs/promises";
28041
+ function projectedToken(path) {
28042
+ return {
28043
+ async read(signal) {
28044
+ let contents;
28045
+ try {
28046
+ contents = await readFile2(path, {
28047
+ encoding: "utf8",
28048
+ ...signal === undefined ? {} : { signal }
28049
+ });
28050
+ } catch (error) {
28051
+ throw new Error(`read the projected service-account token ${path}: ${error.message}`);
28052
+ }
28053
+ const token = contents.trim();
28054
+ if (token === "")
28055
+ throw new Error(`the projected service-account token ${path} is empty`);
28056
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
28057
+ },
28058
+ describe: () => `the projected service-account token ${path}`
28059
+ };
28060
+ }
28061
+
27316
28062
  // ../broker-client/src/environment.ts
27317
28063
  var BROKER_URL_VAR = "AGENT_SECRETS_URL";
27318
28064
  var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
27319
28065
  var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
27320
28066
  var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
27321
28067
  var SESSION_VAR = "AGENT_SECRETS_SESSION";
28068
+ var POOL_AUDIENCE_VAR = "AGENT_SECRETS_POOL_AUDIENCE";
28069
+ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
27322
28070
  var IDENTITY_KUBERNETES = "kubernetes";
27323
28071
  var IDENTITY_METADATA = "metadata";
27324
28072
  var IDENTITY_POOL = "pool";
28073
+ var BROKER_VARIABLES = [
28074
+ BROKER_URL_VAR,
28075
+ IDENTITY_VAR,
28076
+ MACHINE_TOKEN_FILE_VAR,
28077
+ MACHINE_AUDIENCE_VAR,
28078
+ SESSION_VAR,
28079
+ POOL_AUDIENCE_VAR,
28080
+ POOL_ACCOUNT_VAR,
28081
+ SIGNIN_DIR_VAR,
28082
+ "XDG_STATE_HOME",
28083
+ "HOME",
28084
+ PERSON_VAR,
28085
+ PERSON_TRADE_VAR,
28086
+ SIGNIN_ISSUER_VAR,
28087
+ SIGNIN_CLIENT_ID_VAR,
28088
+ SIGNIN_CLIENT_SECRET_FILE_VAR
28089
+ ];
27325
28090
  function value(env, name) {
27326
28091
  return (env[name] ?? "").trim();
27327
28092
  }
@@ -27340,10 +28105,20 @@ function machineIdentity(env) {
27340
28105
  return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind));
27341
28106
  case IDENTITY_METADATA:
27342
28107
  return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
27343
- case IDENTITY_POOL:
27344
- 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}`);
28108
+ case IDENTITY_POOL: {
28109
+ const subject = required2(env, MACHINE_TOKEN_FILE_VAR, kind);
28110
+ const tokenAudience = required2(env, MACHINE_AUDIENCE_VAR, kind);
28111
+ const audience = required2(env, POOL_AUDIENCE_VAR, kind);
28112
+ const serviceAccount = required2(env, POOL_ACCOUNT_VAR, kind);
28113
+ return poolIdentity({
28114
+ subject: projectedToken(subject),
28115
+ audience,
28116
+ serviceAccount,
28117
+ tokenAudience
28118
+ });
28119
+ }
27345
28120
  default:
27346
- throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
28121
+ throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${IDENTITY_POOL}`);
27347
28122
  }
27348
28123
  }
27349
28124
  function tradeSession(env, own = "") {
@@ -27352,16 +28127,32 @@ function tradeSession(env, own = "") {
27352
28127
  }
27353
28128
  async function brokerTokenClient(env, own = "") {
27354
28129
  const brokerUrl = value(env, BROKER_URL_VAR);
27355
- const subject = machineIdentity(env);
27356
- if (brokerUrl === "" || subject === undefined)
28130
+ const machine = machineIdentity(env);
28131
+ if (brokerUrl === "" || machine === undefined)
27357
28132
  return;
27358
- return new BrokerTokenClient({
28133
+ const record = await chooseSignIn(env);
28134
+ if (record === undefined) {
28135
+ const client = new BrokerTokenClient({
28136
+ brokerUrl,
28137
+ key: await newDpopKey(),
28138
+ subject: machine,
28139
+ session: tradeSession(env, own),
28140
+ launcherCredential: false
28141
+ });
28142
+ return { client, signIn: undefined };
28143
+ }
28144
+ const flow = await signInFlow(env);
28145
+ if (flow === undefined) {
28146
+ 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}`);
28147
+ }
28148
+ const client = new BrokerTokenClient({
27359
28149
  brokerUrl,
27360
- key: await newDpopKey(),
27361
- subject,
27362
- session: tradeSession(env, own),
27363
- launcherCredential: false
28150
+ key: await importDpopKey(record.box_key, `${record.person}'s box key`),
28151
+ subject: personIdentity(record, flow),
28152
+ actor: machine,
28153
+ session: own.trim() || signInSessionName(record)
27364
28154
  });
28155
+ return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
27365
28156
  }
27366
28157
 
27367
28158
  // ../envoy-client/src/broker-credential.ts
@@ -27374,49 +28165,97 @@ function brokerRouteConfigured(env) {
27374
28165
  if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
27375
28166
  return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
27376
28167
  }
27377
- if ((env[IDENTITY_VAR] ?? "").trim() === IDENTITY_POOL) {
27378
- return {
27379
- traded: false,
27380
- gap: `${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), never by this process`
27381
- };
27382
- }
27383
28168
  if (machineIdentity(env) === undefined) {
27384
28169
  return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
27385
28170
  }
27386
28171
  return { traded: true };
27387
28172
  }
27388
28173
  var CLIENTS = new Map;
27389
- function clientFor(env, own) {
27390
- const session = tradeSession(env, own);
27391
- const key = JSON.stringify([
27392
- env.AGENT_SECRETS_URL,
27393
- env.AGENT_SECRETS_MACHINE_IDENTITY,
27394
- env.AGENT_SECRETS_MACHINE_TOKEN_FILE,
27395
- env.AGENT_SECRETS_MACHINE_AUDIENCE
27396
- ]);
27397
- const held = CLIENTS.get(session) ?? new Map;
27398
- CLIENTS.set(session, held);
27399
- const made = held.get(key) ?? brokerTokenClient(env, session);
27400
- held.set(key, made);
27401
- return made;
28174
+ function signInName(record) {
28175
+ return `${record.person}\x00${record.thumbprint}`;
28176
+ }
28177
+ function keyOf(env, own) {
28178
+ return {
28179
+ session: own.trim(),
28180
+ variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
28181
+ };
28182
+ }
28183
+ function entryFor(key) {
28184
+ let sessions = CLIENTS.get(key.session);
28185
+ if (sessions === undefined) {
28186
+ sessions = new Map;
28187
+ CLIENTS.set(key.session, sessions);
28188
+ }
28189
+ let entry = sessions.get(key.variables);
28190
+ if (entry === undefined) {
28191
+ entry = { making: undefined, made: undefined, refused: new Map };
28192
+ sessions.set(key.variables, entry);
28193
+ }
28194
+ return entry;
28195
+ }
28196
+ async function make(env, own) {
28197
+ const made = await brokerTokenClient(env, own);
28198
+ const signIn = made?.signIn;
28199
+ return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
28200
+ }
28201
+ async function clientFor(env, own) {
28202
+ const key = keyOf(env, own);
28203
+ const entry = entryFor(key);
28204
+ if (entry.refused.size > 0) {
28205
+ const record = await chooseSignIn(env);
28206
+ const chosen = record === undefined ? "" : signInName(record);
28207
+ if (entry.refused.has(chosen))
28208
+ throw entry.refused.get(chosen);
28209
+ if (entry.made !== undefined && entry.made.signIn !== chosen) {
28210
+ entry.making = undefined;
28211
+ entry.made = undefined;
28212
+ }
28213
+ }
28214
+ let making = entry.making;
28215
+ if (making === undefined) {
28216
+ const started = make(env, key.session);
28217
+ making = started;
28218
+ entry.making = started;
28219
+ started.then((made) => {
28220
+ if (entry.making === started)
28221
+ entry.made = made;
28222
+ }, () => {
28223
+ if (entry.making === started)
28224
+ entry.making = undefined;
28225
+ });
28226
+ }
28227
+ return { entry, made: await making };
27402
28228
  }
27403
28229
  function brokerCredential(env, session) {
27404
- let held = "";
28230
+ let presented = "";
28231
+ const own = (acting) => (acting ?? "").trim() || sessionName(session);
27405
28232
  return {
27406
28233
  scheme: "DPoP",
27407
28234
  async headers(method, url, acting) {
27408
- const client = await clientFor(env, (acting ?? "").trim() || sessionName(session));
28235
+ const { entry, made } = await clientFor(env, own(acting));
28236
+ const { client } = made;
27409
28237
  if (client === undefined) {
27410
28238
  throw new Error("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
27411
28239
  }
27412
- const token = await client.token();
27413
- held = token.accessToken;
28240
+ let token;
28241
+ try {
28242
+ token = await client.token();
28243
+ } catch (error) {
28244
+ if (made.signIn !== "" && isFinalRefusal(error))
28245
+ entry.refused.set(made.signIn, error);
28246
+ throw error;
28247
+ }
28248
+ presented = token.accessToken;
27414
28249
  return {
27415
28250
  Authorization: `DPoP ${token.accessToken}`,
27416
28251
  DPoP: await client.key.proof({ method, url, accessToken: token.accessToken })
27417
28252
  };
27418
28253
  },
27419
- secret: () => held
28254
+ stale(acting) {
28255
+ const key = keyOf(env, own(acting));
28256
+ CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop();
28257
+ },
28258
+ secret: () => presented
27420
28259
  };
27421
28260
  }
27422
28261
 
@@ -27492,7 +28331,7 @@ function brokerRouteForced(env) {
27492
28331
  return false;
27493
28332
  if (written === "1")
27494
28333
  return true;
27495
- 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`);
28334
+ 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`);
27496
28335
  }
27497
28336
  function dispatchTarget(env, config) {
27498
28337
  if (config.kind === "failed")
@@ -27543,7 +28382,7 @@ function dispatchTarget(env, config) {
27543
28382
  return { enabled: true, url: brokered, source: { kind: "broker" } };
27544
28383
  }
27545
28384
  if (forced) {
27546
- 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`);
28385
+ 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`);
27547
28386
  }
27548
28387
  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}`);
27549
28388
  }