@sjawhar/claude-envoy 5.24.0 → 5.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dispatch.js CHANGED
@@ -980,10 +980,10 @@ __export(exports_coerce, {
980
980
  });
981
981
 
982
982
  // ../envoy-client/bin/dispatch.ts
983
- import { readFileSync as readFileSync8 } from "fs";
983
+ import { readFileSync as readFileSync7 } from "fs";
984
984
 
985
985
  // ../envoy-client/src/dispatch-cli.ts
986
- import { closeSync as closeSync5, constants as constants4, fstatSync as fstatSync3, openSync as openSync5, readFileSync as readFileSync7 } from "fs";
986
+ import { closeSync as closeSync4, constants as constants4, fstatSync as fstatSync3, openSync as openSync4, readFileSync as readFileSync6 } from "fs";
987
987
 
988
988
  // ../envoy-client/src/askgate-marker.ts
989
989
  import { createHash, randomBytes } from "crypto";
@@ -19230,6 +19230,10 @@ var FORM_SESSION = "session";
19230
19230
  var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
19231
19231
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
19232
19232
  var FORM_PROJECTS = "projects";
19233
+ var FORM_SCOPE = "scope";
19234
+ var SCOPE_READ = "read";
19235
+ var FORM_AS_OF = "as_of";
19236
+ var HEADER_DPOP_HOLDER = "DPoP-Holder";
19233
19237
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
19234
19238
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
19235
19239
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
@@ -19342,6 +19346,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
19342
19346
  "The machine login the subject token belongs to has ended\\.",
19343
19347
  "The machine login has ended\\.",
19344
19348
  "Another live machine login holds the key this proof was signed with\\. A (?:machine makes a key of its own|sign-in makes a box key of its own)\\.",
19349
+ "A live read token is bound to the key this proof was signed with\\. Make a new key\\.",
19345
19350
  `${PERSON_SLOT} is a restricted member, whose token names its projects: set AGENT_SECRETS_PROJECTS to the projects this session works on\\.`,
19346
19351
  `The token names a project its person cannot see: ${PROJECT_SLOT}\\.`,
19347
19352
  `The subject token was refused: its entry names the project ${PROJECT_SLOT}, which its person ${PERSON_SLOT} cannot see\\.`,
@@ -19354,6 +19359,19 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
19354
19359
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
19355
19360
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
19356
19361
  `${PERSON_SLOT}'s credentials are held by Dispatch; they work again when \\k<person> signs in to Dispatch, or when Dispatch can confirm \\k<person> with Google again`,
19362
+ "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
19363
+ "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
19364
+ "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
19365
+ "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
19366
+ "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
19367
+ `${PERSON_SLOT}'s sign-in on this machine holds no launcher credential yet, and a read trade makes none\\. Sign in with \`agent-secrets login\` first\\.`,
19368
+ `${PERSON_SLOT}'s sign-in on this machine holds a launcher credential that has lapsed, and a read trade renews none\\. One ordinary trade of the sign-in renews it, as \`agent-secrets\` makes; then trade for read again\\.`,
19369
+ "A person's read trade sends a DPoP-Holder proof: the box key proves the sign-in and is bound to no read token, so the token is bound to a key made for its holder\\.",
19370
+ "The DPoP-Holder header binds a read token to its holder's key, and this trade does not ask for the scope read\\. Ask for it, or send no DPoP-Holder header\\.",
19371
+ "The DPoP-Holder proof was refused: a trade sends one, a DPoP proof of this request signed with the key it embeds, spent nowhere before\\.",
19372
+ "The DPoP-Holder proof is signed with the key the DPoP proof is signed with, and the holder's key is a key of its own\\.",
19373
+ "The key this read token would be bound to signs launcher proofs: a live launcher credential is bound to it, and no read token is bound to such a key\\. Send a DPoP-Holder proof by a key made for the token's holder, and the token is bound to that key\\.",
19374
+ "The key this proof was signed with signs launcher proofs: a live launcher credential is bound to it, and no read token is bound to such a key\\. Ask for the scope read with a DPoP-Holder proof by a key made for the token's holder, or trade with a key that holds no launcher credential\\.",
19357
19375
  ...POLICY_REFUSAL_PATTERNS
19358
19376
  ].map((source) => new RegExp(`^${source}$`));
19359
19377
  var LIBRARY_DESCRIPTIONS = [
@@ -19671,17 +19689,16 @@ function isFinalRefusal(error) {
19671
19689
 
19672
19690
  // ../envoy-client/src/envoy-config.ts
19673
19691
  import {
19674
- chmodSync,
19675
- closeSync as closeSync2,
19676
- existsSync,
19677
- lstatSync,
19678
- mkdtempSync,
19679
- openSync as openSync2,
19680
- readFileSync as readFileSync3,
19681
- readlinkSync as readlinkSync2,
19682
- rmSync as rmSync2,
19683
- statSync as statSync2
19684
- } from "fs";
19692
+ access,
19693
+ chmod,
19694
+ lstat,
19695
+ mkdtemp,
19696
+ open,
19697
+ readFile as readFile3,
19698
+ readlink,
19699
+ rm,
19700
+ stat
19701
+ } from "fs/promises";
19685
19702
  import { homedir, tmpdir } from "os";
19686
19703
  import * as path from "path";
19687
19704
 
@@ -19771,15 +19788,44 @@ function jsonErrorPosition(text) {
19771
19788
  }
19772
19789
  }
19773
19790
 
19791
+ // ../envoy-client/src/process-group.ts
19792
+ function killGroup(pid) {
19793
+ try {
19794
+ process.kill(-pid, "SIGKILL");
19795
+ } catch {}
19796
+ }
19797
+ var WATCH = 'exec 3<&0; (while read -r line <&3; do :; done; kill -s KILL -- -$$) </dev/null >/dev/null 2>&1 & exec "$0" "$@" </dev/null 3<&-';
19798
+ function groupWatchedBy(argv) {
19799
+ return ["/bin/sh", "-c", WATCH, ...argv];
19800
+ }
19801
+ function spawnWatched(argv, options) {
19802
+ const child = Bun.spawn(groupWatchedBy(argv), {
19803
+ ...options,
19804
+ stdin: "pipe",
19805
+ detached: true
19806
+ });
19807
+ let closed = false;
19808
+ return {
19809
+ child,
19810
+ endGroup: () => {
19811
+ killGroup(child.pid);
19812
+ if (closed)
19813
+ return;
19814
+ closed = true;
19815
+ child.stdin.end();
19816
+ }
19817
+ };
19818
+ }
19819
+
19774
19820
  // ../envoy-client/src/secret-file.ts
19775
- import { readFileSync as readFileSync2 } from "fs";
19821
+ import { readFile as readFile2 } from "fs/promises";
19776
19822
  function sendable(value) {
19777
19823
  return !/[\s\p{Cc}]/u.test(value);
19778
19824
  }
19779
- function readSecretFile(variable, filePath) {
19825
+ async function readSecretFile(variable, filePath) {
19780
19826
  let contents;
19781
19827
  try {
19782
- contents = readFileSync2(filePath, "utf8");
19828
+ contents = await readFile2(filePath, "utf8");
19783
19829
  } catch (error) {
19784
19830
  throw new Error(`${variable} names a file that could not be read (${readErrorCode(error)})`);
19785
19831
  }
@@ -19914,20 +19960,28 @@ function describeSchemaIssue(filePath, error) {
19914
19960
  }
19915
19961
  return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
19916
19962
  }
19917
- function danglingLink(filePath) {
19963
+ async function danglingLink(filePath) {
19918
19964
  try {
19919
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync2(filePath) : null;
19965
+ return (await lstat(filePath)).isSymbolicLink() ? await readlink(filePath) : null;
19920
19966
  } catch {
19921
19967
  return null;
19922
19968
  }
19923
19969
  }
19924
- function parseFile(filePath, schema, checkout) {
19970
+ async function exists(file) {
19971
+ try {
19972
+ await access(file);
19973
+ return true;
19974
+ } catch {
19975
+ return false;
19976
+ }
19977
+ }
19978
+ async function parseFile(filePath, schema, checkout) {
19925
19979
  let raw;
19926
19980
  try {
19927
- raw = readFileSync3(filePath, "utf-8");
19981
+ raw = await readFile3(filePath, "utf-8");
19928
19982
  } catch (error) {
19929
19983
  if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
19930
- return { kind: "absent", link: danglingLink(filePath) };
19984
+ return { kind: "absent", link: checkout ? null : await danglingLink(filePath) };
19931
19985
  }
19932
19986
  return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
19933
19987
  }
@@ -19955,53 +20009,77 @@ function parseFile(filePath, schema, checkout) {
19955
20009
  }
19956
20010
  var FAILURE_KEPT_MS = 60000;
19957
20011
  var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
20012
+ var COMMAND_RUNS = Symbol.for("legion.envoy-config.command-runs.v1");
19958
20013
  var processGlobal = globalThis;
19959
20014
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
19960
20015
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
19961
- function runCommand(command, env, cwd) {
20016
+ var commandRuns = processGlobal[COMMAND_RUNS] ?? new Map;
20017
+ processGlobal[COMMAND_RUNS] = commandRuns;
20018
+ async function unnamedFile() {
20019
+ const directory = await mkdtemp(path.join(tmpdir(), "envoy-command-"));
20020
+ try {
20021
+ await chmod(directory, 448);
20022
+ return await open(path.join(directory, "stdout"), "wx+", 384);
20023
+ } finally {
20024
+ await rm(directory, { recursive: true, force: true });
20025
+ }
20026
+ }
20027
+ async function readOutput(file) {
20028
+ const output = Buffer.alloc((await file.stat()).size);
20029
+ let read = 0;
20030
+ while (read < output.length) {
20031
+ const { bytesRead } = await file.read(output, read, output.length - read, read);
20032
+ if (bytesRead === 0)
20033
+ break;
20034
+ read += bytesRead;
20035
+ }
20036
+ return output.toString("utf-8", 0, read);
20037
+ }
20038
+ async function runCommand(command, env, cwd) {
19962
20039
  const timeoutMs = commandTimeoutMs(env);
19963
20040
  const childEnv = {};
19964
20041
  for (const [name, variable] of Object.entries(env)) {
19965
20042
  if (variable !== undefined)
19966
20043
  childEnv[name] = variable;
19967
20044
  }
19968
- const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
20045
+ const file = await unnamedFile();
19969
20046
  try {
19970
- chmodSync(directory, 448);
19971
- const output = path.join(directory, "stdout");
19972
- const fd = openSync2(output, "wx", 384);
19973
- let result;
20047
+ let watched;
19974
20048
  try {
19975
- result = Bun.spawnSync(["/bin/sh", "-c", command], {
20049
+ watched = spawnWatched(["/bin/sh", "-c", command], {
19976
20050
  cwd,
19977
20051
  env: childEnv,
19978
- stdin: "ignore",
19979
- stdout: fd,
19980
- stderr: "ignore",
19981
- timeout: timeoutMs,
19982
- detached: true
20052
+ stdout: file.fd,
20053
+ stderr: "ignore"
19983
20054
  });
19984
20055
  } catch (error) {
19985
20056
  return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
19986
- } finally {
19987
- closeSync2(fd);
19988
20057
  }
20058
+ const { child, endGroup } = watched;
20059
+ let timedOut = false;
20060
+ const timer = setTimeout(() => {
20061
+ timedOut = true;
20062
+ endGroup();
20063
+ }, timeoutMs);
19989
20064
  try {
19990
- process.kill(-result.pid, "SIGKILL");
19991
- } catch {}
19992
- if (result.exitedDueToTimeout) {
20065
+ await child.exited;
20066
+ } finally {
20067
+ clearTimeout(timer);
20068
+ }
20069
+ endGroup();
20070
+ if (timedOut) {
19993
20071
  return {
19994
20072
  failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
19995
20073
  timedOut: true
19996
20074
  };
19997
20075
  }
19998
- if (!result.success) {
20076
+ if (child.exitCode !== 0) {
19999
20077
  return {
20000
- failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
20078
+ failure: `exited with ${child.signalCode ?? `status ${child.exitCode}`}`,
20001
20079
  timedOut: false
20002
20080
  };
20003
20081
  }
20004
- const value = readFileSync3(output, "utf-8").trim();
20082
+ const value = (await readOutput(file)).trim();
20005
20083
  if (value.length === 0)
20006
20084
  return { failure: "printed nothing", timedOut: false };
20007
20085
  if (!sendable(value)) {
@@ -20012,10 +20090,10 @@ function runCommand(command, env, cwd) {
20012
20090
  }
20013
20091
  return { value };
20014
20092
  } finally {
20015
- rmSync2(directory, { recursive: true, force: true });
20093
+ await file.close();
20016
20094
  }
20017
20095
  }
20018
- function fileValue(value, field, filePath, env, commands = "run") {
20096
+ async function fileValue(value, field, filePath, env, commands = "run") {
20019
20097
  if (!value.startsWith("!")) {
20020
20098
  if (!sendable(value)) {
20021
20099
  throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
@@ -20031,42 +20109,50 @@ function fileValue(value, field, filePath, env, commands = "run") {
20031
20109
  throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
20032
20110
  }
20033
20111
  } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
20034
- outcome = { ...runCommand(command, env, cwd), at: Date.now() };
20035
- commandOutcomes.set(key, outcome);
20112
+ let run = commandRuns.get(key);
20113
+ if (run === undefined) {
20114
+ run = runCommand(command, env, cwd).then((ran) => {
20115
+ const kept = { ...ran, at: Date.now() };
20116
+ commandOutcomes.set(key, kept);
20117
+ return kept;
20118
+ }).finally(() => commandRuns.delete(key));
20119
+ commandRuns.set(key, run);
20120
+ }
20121
+ outcome = await run;
20036
20122
  }
20037
20123
  if ("failure" in outcome)
20038
20124
  throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
20039
20125
  return outcome.value;
20040
20126
  }
20041
- function statDevice(directory) {
20127
+ async function statDevice(directory) {
20042
20128
  try {
20043
- return statSync2(directory).dev;
20129
+ return (await stat(directory)).dev;
20044
20130
  } catch {
20045
20131
  return;
20046
20132
  }
20047
20133
  }
20048
- function moveNotice(oldFile, newFile, move, deviceOf) {
20049
- const oldDevice = deviceOf(path.dirname(oldFile));
20134
+ async function moveNotice(oldFile, newFile, move, deviceOf) {
20135
+ const oldDevice = await deviceOf(path.dirname(oldFile));
20050
20136
  let ancestor = path.dirname(newFile);
20051
- let newDevice = deviceOf(ancestor);
20137
+ let newDevice = await deviceOf(ancestor);
20052
20138
  while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
20053
20139
  ancestor = path.dirname(ancestor);
20054
- newDevice = deviceOf(ancestor);
20140
+ newDevice = await deviceOf(ancestor);
20055
20141
  }
20056
20142
  if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
20057
20143
  return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
20058
20144
  }
20059
20145
  return `${oldFile} is not read: ${move}`;
20060
20146
  }
20061
- function oldUserFileNotice(filePath, env, deviceOf) {
20147
+ async function oldUserFileNotice(filePath, env, deviceOf) {
20062
20148
  const home = nonEmpty(env.HOME) ?? homedir();
20063
20149
  const old = path.join(home, ".config", "opencode", "envoy.json");
20064
- if (!existsSync(old))
20150
+ if (!await exists(old))
20065
20151
  return;
20066
20152
  const selected = path.resolve(filePath);
20067
20153
  const userFile = path.resolve(home, ".config", "legion", "envoy.json");
20068
20154
  if (selected === userFile) {
20069
- return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
20155
+ return await moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
20070
20156
  }
20071
20157
  const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
20072
20158
  if (profileFile) {
@@ -20084,14 +20170,18 @@ function missingConfigNotice(filePath, missing, off) {
20084
20170
  const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
20085
20171
  return `no envoy.json at ${filePath}${link}: ${off}${old}`;
20086
20172
  }
20087
- function readEnvoyConfig(filePath, env, options) {
20173
+ async function readEnvoyConfig(filePath, env, options) {
20088
20174
  const deviceOf = options.deviceOf ?? statDevice;
20089
- const chosen = parseFile(filePath, EnvoyFileSchema, false);
20090
- if (chosen.kind === "invalid")
20091
- return { kind: "failed", path: filePath, error: chosen.reason };
20092
20175
  const resolvedChosen = path.resolve(filePath);
20093
20176
  const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
20094
- const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
20177
+ const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
20178
+ const [chosen, checkoutFile, oldCheckoutThere] = await Promise.all([
20179
+ parseFile(filePath, EnvoyFileSchema, false),
20180
+ checkoutPath === resolvedChosen ? Promise.resolve({ kind: "absent", link: null }) : parseFile(checkoutPath, CheckoutFileSchema, true),
20181
+ oldCheckout === resolvedChosen ? Promise.resolve(false) : exists(oldCheckout)
20182
+ ]);
20183
+ if (chosen.kind === "invalid")
20184
+ return { kind: "failed", path: filePath, error: chosen.reason };
20095
20185
  const own = chosen.kind === "valid" ? chosen.settings : {};
20096
20186
  let checkout = null;
20097
20187
  if (checkoutFile.kind === "invalid") {
@@ -20105,11 +20195,11 @@ function readEnvoyConfig(filePath, env, options) {
20105
20195
  askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
20106
20196
  };
20107
20197
  }
20108
- const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
20109
- const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
20110
- moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
20198
+ const checkoutMissing = checkoutPath === resolvedChosen ? chosen.kind === "absent" : checkoutFile.kind === "absent" || checkoutFile.kind === "invalid" && !await exists(checkoutPath);
20199
+ const warnings = oldCheckout !== resolvedChosen && checkoutMissing && oldCheckoutThere ? [
20200
+ await moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
20111
20201
  ] : [];
20112
- const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
20202
+ const unreadOldUserFile = chosen.kind === "absent" ? await oldUserFileNotice(filePath, env, deviceOf) : undefined;
20113
20203
  return {
20114
20204
  kind: "read",
20115
20205
  path: filePath,
@@ -20137,10 +20227,10 @@ function bearerCredential(token) {
20137
20227
  secret: () => token
20138
20228
  };
20139
20229
  }
20140
- function bearerSource(env, section, written) {
20230
+ async function bearerSource(env, section, written) {
20141
20231
  const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
20142
20232
  if (pointer !== undefined) {
20143
- return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
20233
+ return { kind: "variable", token: await readSecretFile(`${section}_TOKEN_FILE`, pointer) };
20144
20234
  }
20145
20235
  const plain = nonEmpty(env[`${section}_TOKEN`]);
20146
20236
  if (plain !== undefined) {
@@ -20152,7 +20242,7 @@ function bearerSource(env, section, written) {
20152
20242
  const bearer = written();
20153
20243
  return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
20154
20244
  }
20155
- function fileBearer(bearer, url, section, env, commands = "run") {
20245
+ async function fileBearer(bearer, url, section, env, commands = "run") {
20156
20246
  const named = httpUrl2(url)?.origin;
20157
20247
  const paired = httpUrl2(bearer.server)?.origin;
20158
20248
  if (named !== paired) {
@@ -29645,64 +29735,8 @@ async function genericGrantRequest(config, grantType, parameters, options) {
29645
29735
  return result;
29646
29736
  }
29647
29737
 
29648
- // ../cipher-client/src/device-login-file.ts
29649
- import { createPrivateKey, randomUUID as randomUUID2 } from "crypto";
29650
- import { constants as constants3 } from "fs";
29651
- import {
29652
- access,
29653
- lstat as lstat2,
29654
- mkdir,
29655
- open as open2,
29656
- readFile as readFile2,
29657
- readlink,
29658
- rename as rename2,
29659
- rm as rm2,
29660
- stat as stat2
29661
- } from "fs/promises";
29662
- import { userInfo } from "os";
29663
- import { dirname as dirname3, isAbsolute as isAbsolute3, join as join5 } from "path";
29664
-
29665
- // ../cipher-client/src/device-login-lock.ts
29666
- import { randomUUID } from "crypto";
29667
- import { closeSync as closeSync3, constants as constants2, fstatSync, openSync as openSync3, readSync } from "fs";
29668
- import {
29669
- link,
29670
- lstat,
29671
- open,
29672
- readdir as readdir2,
29673
- rename,
29674
- rm,
29675
- stat,
29676
- utimes
29677
- } from "fs/promises";
29678
- import { basename as basename2, dirname as dirname2, join as join4 } from "path";
29679
-
29680
- // ../cipher-client/src/token-client.ts
29681
- var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
29738
+ // ../cipher-client/src/broker-request.ts
29682
29739
  var BROKER_URL_SETTING = "the broker URL";
29683
- var RETRY_FIRST_WAIT_MS = 15000;
29684
- var RETRY_MAX_WAIT_MS = 5 * 60000;
29685
- var PENDING_FIRST_WAIT_MS = 2000;
29686
- var PENDING_MAX_WAIT_MS = 30000;
29687
- var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
29688
- var TRADE_ATTEMPT_MS = 30000;
29689
- function sleep2(ms, signal, holdsProcess = false) {
29690
- const { promise, resolve } = Promise.withResolvers();
29691
- if (signal?.aborted) {
29692
- resolve();
29693
- return promise;
29694
- }
29695
- const done = () => {
29696
- clearTimeout(timer);
29697
- signal?.removeEventListener("abort", done);
29698
- resolve();
29699
- };
29700
- const timer = setTimeout(done, ms);
29701
- if (!holdsProcess)
29702
- timer.unref();
29703
- signal?.addEventListener("abort", done, { once: true });
29704
- return promise;
29705
- }
29706
29740
  function statusOf(error) {
29707
29741
  let cause = error;
29708
29742
  for (let depth = 0;depth < 4; depth += 1) {
@@ -29739,7 +29773,11 @@ function requestInit(options, signal, headers) {
29739
29773
  async function sendWithProof(proved, url, options, signal) {
29740
29774
  const send = async () => {
29741
29775
  const headers = new Headers(options.headers);
29742
- headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
29776
+ const request = { method: options.method, url, nonce: proved.nonce.value };
29777
+ headers.set("DPoP", await proved.key.proof(request));
29778
+ if (proved.holderKey !== undefined) {
29779
+ headers.set(HEADER_DPOP_HOLDER, await proved.holderKey.proof(request));
29780
+ }
29743
29781
  return await proved.fetch(url, requestInit(options, signal, headers));
29744
29782
  };
29745
29783
  let answer = await send();
@@ -29755,14 +29793,82 @@ async function sendWithProof(proved, url, options, signal) {
29755
29793
  return answer;
29756
29794
  }
29757
29795
 
29796
+ // ../cipher-client/src/device-login-file.ts
29797
+ import { createPrivateKey, randomUUID as randomUUID2 } from "crypto";
29798
+ import { constants as constants3 } from "fs";
29799
+ import {
29800
+ access as access2,
29801
+ lstat as lstat3,
29802
+ mkdir,
29803
+ open as open3,
29804
+ readFile as readFile4,
29805
+ readlink as readlink2,
29806
+ rename as rename2,
29807
+ rm as rm3,
29808
+ stat as stat3
29809
+ } from "fs/promises";
29810
+ import { userInfo } from "os";
29811
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join5 } from "path";
29812
+
29813
+ // ../cipher-client/src/device-login-lock.ts
29814
+ import { randomUUID } from "crypto";
29815
+ import { closeSync as closeSync2, constants as constants2, fstatSync, openSync as openSync2, readSync } from "fs";
29816
+ import {
29817
+ link,
29818
+ lstat as lstat2,
29819
+ open as open2,
29820
+ readdir as readdir2,
29821
+ rename,
29822
+ rm as rm2,
29823
+ stat as stat2,
29824
+ utimes
29825
+ } from "fs/promises";
29826
+ import { basename as basename2, dirname as dirname2, join as join4 } from "path";
29827
+
29828
+ // ../cipher-client/src/token-client.ts
29829
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
29830
+ function renewalAt(expiresAt, now, renewBeforeMs) {
29831
+ const left = expiresAt - now;
29832
+ if (left <= 0)
29833
+ return now;
29834
+ return Math.max(expiresAt - renewBeforeMs, now + left / 2);
29835
+ }
29836
+ var EXPIRES_IN_STEP_MS = 1000;
29837
+ var RETRY_FIRST_WAIT_MS = 15000;
29838
+ var RETRY_MAX_WAIT_MS = 5 * 60000;
29839
+ var PENDING_FIRST_WAIT_MS = 2000;
29840
+ var PENDING_MAX_WAIT_MS = 30000;
29841
+ var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
29842
+ var TRADE_ATTEMPT_MS = 30000;
29843
+ function sleep2(ms, signal, holdsProcess = false) {
29844
+ const { promise, resolve } = Promise.withResolvers();
29845
+ if (signal?.aborted) {
29846
+ resolve();
29847
+ return promise;
29848
+ }
29849
+ const done = () => {
29850
+ clearTimeout(timer);
29851
+ signal?.removeEventListener("abort", done);
29852
+ resolve();
29853
+ };
29854
+ const timer = setTimeout(done, ms);
29855
+ if (!holdsProcess)
29856
+ timer.unref();
29857
+ signal?.addEventListener("abort", done, { once: true });
29858
+ return promise;
29859
+ }
29860
+
29758
29861
  class BrokerTokenClient {
29759
29862
  #brokerUrl;
29760
29863
  #key;
29864
+ #holderKey;
29761
29865
  #subject;
29762
29866
  #actor;
29763
29867
  #session;
29764
29868
  #projects;
29765
29869
  #launcherCredential;
29870
+ #scope;
29871
+ #asOf;
29766
29872
  #renewBeforeMs;
29767
29873
  #now;
29768
29874
  #attemptMs;
@@ -29791,11 +29897,14 @@ class BrokerTokenClient {
29791
29897
  throw new Error("broker client: the broker URL is not an http or https URL");
29792
29898
  this.#brokerUrl = holdUrlUserinfo(brokerUrl);
29793
29899
  this.#key = options.key;
29900
+ this.#holderKey = options.holderKey;
29794
29901
  this.#subject = options.subject;
29795
29902
  this.#actor = options.actor;
29796
29903
  this.#session = options.session ?? "";
29797
29904
  this.#projects = [...options.projects ?? []];
29798
29905
  this.#launcherCredential = options.launcherCredential ?? true;
29906
+ this.#scope = options.scope ?? "";
29907
+ this.#asOf = options.asOf ?? "";
29799
29908
  this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
29800
29909
  this.#now = options.now ?? Date.now;
29801
29910
  this.#attemptMs = options.attemptMs ?? TRADE_ATTEMPT_MS;
@@ -29805,7 +29914,7 @@ class BrokerTokenClient {
29805
29914
  this.#random = options.random ?? Math.random;
29806
29915
  }
29807
29916
  get key() {
29808
- return this.#key;
29917
+ return this.#holderKey ?? this.#key;
29809
29918
  }
29810
29919
  describe() {
29811
29920
  return this.#subject.describe();
@@ -29814,10 +29923,11 @@ class BrokerTokenClient {
29814
29923
  const waitForReady = options.waitForReady === true;
29815
29924
  const now = this.#now();
29816
29925
  const held = this.#held;
29817
- if (held !== null && now < held.expiresAt.getTime() - this.#renewBeforeMs)
29818
- return held;
29819
- if (held !== null && now < held.expiresAt.getTime() && this.#last !== null)
29820
- return held;
29926
+ if (held !== null && now < held.renewsAt)
29927
+ return held.token;
29928
+ if (held !== null && now < held.token.expiresAt.getTime() && this.#last !== null) {
29929
+ return held.token;
29930
+ }
29821
29931
  const closed = this.#closed.signal;
29822
29932
  if (closed.aborted)
29823
29933
  throw closed.reason;
@@ -29851,8 +29961,8 @@ class BrokerTokenClient {
29851
29961
  const stop = () => {
29852
29962
  this.#waiters.delete(waiter);
29853
29963
  const held = this.#held;
29854
- if (held !== null && this.#now() < held.expiresAt.getTime())
29855
- resolve(held);
29964
+ if (held !== null && this.#now() < held.token.expiresAt.getTime())
29965
+ resolve(held.token);
29856
29966
  else
29857
29967
  reject(this.#stopped(signal?.reason));
29858
29968
  };
@@ -29892,7 +30002,7 @@ class BrokerTokenClient {
29892
30002
  });
29893
30003
  }
29894
30004
  drop(accessToken) {
29895
- if (accessToken !== undefined && this.#held?.accessToken !== accessToken)
30005
+ if (accessToken !== undefined && this.#held?.token.accessToken !== accessToken)
29896
30006
  return;
29897
30007
  this.#held = null;
29898
30008
  }
@@ -29923,7 +30033,10 @@ class BrokerTokenClient {
29923
30033
  if (this.#pendingSaid !== null && this.#since !== null) {
29924
30034
  this.#log(`the secrets broker answered this pod's session ${this.#session} once it was registered, ${Math.round((this.#now() - this.#since) / 1000)} s and ${this.#failed} failed trades after the first`);
29925
30035
  }
29926
- this.#held = token;
30036
+ this.#held = {
30037
+ token,
30038
+ renewsAt: renewalAt(token.expiresAt.getTime(), this.#now(), this.#renewBeforeMs)
30039
+ };
29927
30040
  this.#last = null;
29928
30041
  this.#since = null;
29929
30042
  this.#failed = 0;
@@ -29963,8 +30076,8 @@ class BrokerTokenClient {
29963
30076
  this.#since ??= now;
29964
30077
  this.#failed += 1;
29965
30078
  const held = this.#held;
29966
- if (held !== null && now < held.expiresAt.getTime()) {
29967
- this.#tell((waiter) => waiter.resolve(held));
30079
+ if (held !== null && now < held.token.expiresAt.getTime()) {
30080
+ this.#tell((waiter) => waiter.resolve(held.token));
29968
30081
  } else {
29969
30082
  this.#held = null;
29970
30083
  if (failure.kind !== "pending") {
@@ -30016,7 +30129,8 @@ class BrokerTokenClient {
30016
30129
  async#trade(signal) {
30017
30130
  const source = this.#subject;
30018
30131
  if (source.spend !== undefined) {
30019
- return await source.spend((subject) => this.#exchange(subject, signal), signal);
30132
+ const leastLifeMs = this.#scope === SCOPE_READ ? this.#renewBeforeMs + EXPIRES_IN_STEP_MS : undefined;
30133
+ return await source.spend((subject) => this.#exchange(subject, signal), signal, leastLifeMs);
30020
30134
  }
30021
30135
  return await this.#exchange(await source.read(signal), signal);
30022
30136
  }
@@ -30030,6 +30144,10 @@ class BrokerTokenClient {
30030
30144
  form[FORM_SESSION] = this.#session;
30031
30145
  if (this.#projects.length > 0)
30032
30146
  form[FORM_PROJECTS] = this.#projects.join(" ");
30147
+ if (this.#scope !== "")
30148
+ form[FORM_SCOPE] = this.#scope;
30149
+ if (this.#asOf !== "")
30150
+ form[FORM_AS_OF] = this.#asOf;
30033
30151
  if (!this.#launcherCredential) {
30034
30152
  form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
30035
30153
  }
@@ -30062,7 +30180,7 @@ class BrokerTokenClient {
30062
30180
  return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
30063
30181
  }
30064
30182
  async#send(url, options, signal, raw) {
30065
- const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
30183
+ const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
30066
30184
  raw.body = await answer.clone().json().catch(() => {
30067
30185
  return;
30068
30186
  });
@@ -30120,7 +30238,7 @@ var LOCK_RETRY_MS = 100;
30120
30238
  var STEAL_STALE_MS = 5000;
30121
30239
  async function statOrNone(path, what) {
30122
30240
  try {
30123
- return await lstat(path);
30241
+ return await lstat2(path);
30124
30242
  } catch (error) {
30125
30243
  if (readErrorCode(error) === "ENOENT")
30126
30244
  return null;
@@ -30130,7 +30248,7 @@ async function statOrNone(path, what) {
30130
30248
  async function createOwn(path, value, named) {
30131
30249
  let handle;
30132
30250
  try {
30133
- handle = await open(path, "wx", 384);
30251
+ handle = await open2(path, "wx", 384);
30134
30252
  } catch (error) {
30135
30253
  if (readErrorCode(error) === "EEXIST")
30136
30254
  return false;
@@ -30146,7 +30264,7 @@ async function createOwn(path, value, named) {
30146
30264
  async function look(path, what) {
30147
30265
  let handle;
30148
30266
  try {
30149
- handle = await open(path, LOCK_READ);
30267
+ handle = await open2(path, LOCK_READ);
30150
30268
  } catch (error) {
30151
30269
  if (readErrorCode(error) === "ENOENT")
30152
30270
  return null;
@@ -30183,7 +30301,7 @@ async function removeIfStill(path, isIt, what) {
30183
30301
  const same = took !== null && isIt(took);
30184
30302
  if (!same)
30185
30303
  await link(moved, path).catch(() => {});
30186
- await rm(moved, { force: true }).catch((error) => {
30304
+ await rm2(moved, { force: true }).catch((error) => {
30187
30305
  throw new Error(`remove ${what}, moved aside: ${readErrorCode(error)}`);
30188
30306
  });
30189
30307
  return same;
@@ -30270,7 +30388,7 @@ async function withLoginLock(path, named, work, options = {}) {
30270
30388
  function loginLockHeldBy(path, pid) {
30271
30389
  let fd;
30272
30390
  try {
30273
- fd = openSync3(`${path}.lock`, LOCK_READ);
30391
+ fd = openSync2(`${path}.lock`, LOCK_READ);
30274
30392
  } catch {
30275
30393
  return false;
30276
30394
  }
@@ -30284,7 +30402,7 @@ function loginLockHeldBy(path, pid) {
30284
30402
  return false;
30285
30403
  } finally {
30286
30404
  try {
30287
- closeSync3(fd);
30405
+ closeSync2(fd);
30288
30406
  } catch {}
30289
30407
  }
30290
30408
  }
@@ -30295,9 +30413,9 @@ async function removeUntouched(dir, left) {
30295
30413
  const names = await readdir2(dir).catch(() => []);
30296
30414
  for (const name of names.filter(left)) {
30297
30415
  const path = join4(dir, name);
30298
- const info = await stat(path).catch(() => null);
30416
+ const info = await stat2(path).catch(() => null);
30299
30417
  if (info !== null && Date.now() - info.mtimeMs > DEVICE_LOGIN_STALE_LOCK_MS) {
30300
- await rm(path, { force: true }).catch(() => {});
30418
+ await rm2(path, { force: true }).catch(() => {});
30301
30419
  }
30302
30420
  }
30303
30421
  }
@@ -30325,6 +30443,10 @@ function member(json, name) {
30325
30443
  const value = json[name];
30326
30444
  return typeof value === "string" ? value : "";
30327
30445
  }
30446
+ function wholeMember(json, name) {
30447
+ const value = json[name];
30448
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
30449
+ }
30328
30450
  function checkPrivate(info, what, forbidden, opens, notOwned) {
30329
30451
  const mode = info.mode & 511;
30330
30452
  if ((mode & forbidden) !== 0) {
@@ -30342,7 +30464,7 @@ var systemFiles = new Map;
30342
30464
  async function systemFile(file) {
30343
30465
  let info;
30344
30466
  try {
30345
- info = await stat2(file);
30467
+ info = await stat3(file);
30346
30468
  } catch {
30347
30469
  return null;
30348
30470
  }
@@ -30350,7 +30472,7 @@ async function systemFile(file) {
30350
30472
  const kept = systemFiles.get(file);
30351
30473
  if (kept?.status === status)
30352
30474
  return kept.text;
30353
- const text = await readFile2(file, "utf8").catch(() => null);
30475
+ const text = await readFile4(file, "utf8").catch(() => null);
30354
30476
  if (text === null)
30355
30477
  systemFiles.delete(file);
30356
30478
  else
@@ -30438,7 +30560,7 @@ async function checkLinkOnTheWay(info, what) {
30438
30560
  }
30439
30561
  async function lstatOnTheWay(path, what) {
30440
30562
  try {
30441
- return await lstat2(path);
30563
+ return await lstat3(path);
30442
30564
  } catch (error) {
30443
30565
  if (readErrorCode(error) === "ENOENT")
30444
30566
  return null;
@@ -30474,7 +30596,7 @@ async function walkTheWay(path, what, meet) {
30474
30596
  throw notARegularFile("a loop of links");
30475
30597
  let target;
30476
30598
  try {
30477
- target = await readlink(next);
30599
+ target = await readlink2(next);
30478
30600
  } catch (error) {
30479
30601
  const code = readErrorCode(error);
30480
30602
  if (code !== "EINVAL" && code !== "ENOENT") {
@@ -30523,7 +30645,7 @@ async function checkDirectoriesOnTheWay(dir, what) {
30523
30645
  async function checkLoginDirectory(dir, absent, what = `the directory of ${DEVICE_LOGIN_FILE_NAMED}`) {
30524
30646
  let info;
30525
30647
  try {
30526
- info = await stat2(dir);
30648
+ info = await stat3(dir);
30527
30649
  } catch (error) {
30528
30650
  if (absent !== undefined && readErrorCode(error) === "ENOENT")
30529
30651
  throw absent();
@@ -30560,14 +30682,14 @@ async function deviceLoginPlace(path) {
30560
30682
  await deviceLoginDirectory(path);
30561
30683
  const dir = dirname3(path);
30562
30684
  try {
30563
- await access(dir, constants3.W_OK | constants3.X_OK);
30685
+ await access2(dir, constants3.W_OK | constants3.X_OK);
30564
30686
  } catch (error) {
30565
30687
  const code = readErrorCode(error);
30566
30688
  throw new Error(`this user cannot enter and write to the directory of ${DEVICE_LOGIN_FILE_NAMED}: ${code}${code === "EACCES" ? "; run chmod 700 on it" : ""}`);
30567
30689
  }
30568
30690
  let info;
30569
30691
  try {
30570
- info = await stat2(path);
30692
+ info = await stat3(path);
30571
30693
  } catch (error) {
30572
30694
  if (readErrorCode(error) === "ENOENT")
30573
30695
  return;
@@ -30588,7 +30710,7 @@ async function checkLinkDirectories(path, absent) {
30588
30710
  }
30589
30711
  let info;
30590
30712
  try {
30591
- info = await lstat2(at);
30713
+ info = await lstat3(at);
30592
30714
  } catch (error) {
30593
30715
  if (readErrorCode(error) === "ENOENT")
30594
30716
  return;
@@ -30600,7 +30722,7 @@ async function checkLinkDirectories(path, absent) {
30600
30722
  throw notARegularFile("a loop of links");
30601
30723
  let target;
30602
30724
  try {
30603
- target = await readlink(at);
30725
+ target = await readlink2(at);
30604
30726
  } catch (error) {
30605
30727
  const code = readErrorCode(error);
30606
30728
  if (code === "EINVAL" || code === "ENOENT")
@@ -30617,7 +30739,7 @@ async function readDeviceLogin(path) {
30617
30739
  await checkLinkDirectories(path, absent);
30618
30740
  let handle;
30619
30741
  try {
30620
- handle = await open2(path, LOGIN_READ);
30742
+ handle = await open3(path, LOGIN_READ);
30621
30743
  } catch (error) {
30622
30744
  throw readErrorCode(error) === "ENOENT" ? absent() : refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
30623
30745
  }
@@ -30682,7 +30804,8 @@ async function readDeviceLogin(path) {
30682
30804
  expiresAt,
30683
30805
  broker,
30684
30806
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
30685
- accessExpiresAt: accessUsable ? accessExpiresAt : null
30807
+ accessExpiresAt: accessUsable ? accessExpiresAt : null,
30808
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
30686
30809
  };
30687
30810
  }
30688
30811
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -30715,7 +30838,8 @@ async function saveDeviceLogin(path, login, held, keep = false) {
30715
30838
  broker: login.broker,
30716
30839
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
30717
30840
  access_token: login.accessToken,
30718
- access_expires_at: login.accessExpiresAt.toISOString()
30841
+ access_expires_at: login.accessExpiresAt.toISOString(),
30842
+ ...login.accessLifeSeconds === null ? {} : { access_life_seconds: login.accessLifeSeconds }
30719
30843
  }
30720
30844
  });
30721
30845
  await deviceLoginPlace(path);
@@ -30726,7 +30850,7 @@ async function saveDeviceLogin(path, login, held, keep = false) {
30726
30850
  let whole = false;
30727
30851
  try {
30728
30852
  try {
30729
- const handle = await open2(temp, "wx", 384);
30853
+ const handle = await open3(temp, "wx", 384);
30730
30854
  try {
30731
30855
  await handle.writeFile(data);
30732
30856
  await handle.sync();
@@ -30745,10 +30869,10 @@ async function saveDeviceLogin(path, login, held, keep = false) {
30745
30869
  } catch (error) {
30746
30870
  throw keep && whole ? await keptCopy(temp, path, error) : error;
30747
30871
  } finally {
30748
- await rm2(temp, { force: true }).catch(() => {});
30872
+ await rm3(temp, { force: true }).catch(() => {});
30749
30873
  }
30750
30874
  try {
30751
- const handle = await open2(dir, "r");
30875
+ const handle = await open3(dir, "r");
30752
30876
  try {
30753
30877
  await handle.sync();
30754
30878
  } finally {
@@ -30837,6 +30961,11 @@ async function importDpopKey(pkcs8Pem, name) {
30837
30961
  // ../cipher-client/src/device-login.ts
30838
30962
  var BROKER_SETTING = "AGENT_SECRETS_URL";
30839
30963
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
30964
+ function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
30965
+ if (leastLifeMs === undefined || lifeSeconds === null)
30966
+ return ACCESS_MARGIN_MS;
30967
+ return Math.max(ACCESS_MARGIN_MS, Math.min(leastLifeMs, lifeSeconds * 1000 / 2));
30968
+ }
30840
30969
  var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
30841
30970
  var DEFAULT_POLL_SECONDS = 5;
30842
30971
  var LEAST_POLL_SECONDS = 1;
@@ -30912,7 +31041,8 @@ function loginOf(key, broker, answered, now) {
30912
31041
  expiresAt,
30913
31042
  broker,
30914
31043
  accessToken: holdSecret(answered.access_token, accessExpiresAt),
30915
- accessExpiresAt
31044
+ accessExpiresAt,
31045
+ accessLifeSeconds: seconds
30916
31046
  };
30917
31047
  }
30918
31048
  async function startDeviceLogin(options) {
@@ -31044,7 +31174,7 @@ class DeviceLoginIdentity {
31044
31174
  }
31045
31175
  return this.#key;
31046
31176
  }
31047
- async spend(trade, signal) {
31177
+ async spend(trade, signal, leastLifeMs) {
31048
31178
  const { thumbprint } = await this.#loaded();
31049
31179
  return await withDeviceLoginLock(this.#path, async (held) => {
31050
31180
  let login = await readDeviceLogin(this.#path);
@@ -31056,7 +31186,8 @@ class DeviceLoginIdentity {
31056
31186
  }
31057
31187
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
31058
31188
  const expires = login.accessExpiresAt?.getTime() ?? 0;
31059
- let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
31189
+ const least = leastAccessLifeMs(leastLifeMs, login.accessLifeSeconds);
31190
+ let refreshed = login.accessToken === "" || expires - Date.now() < least;
31060
31191
  if (refreshed)
31061
31192
  login = await refresh();
31062
31193
  while (true) {
@@ -31388,14 +31519,14 @@ function poolIdentity(options) {
31388
31519
  }
31389
31520
 
31390
31521
  // ../cipher-client/src/projected-token.ts
31391
- import { readFile as readFile3 } from "fs/promises";
31522
+ import { readFile as readFile5 } from "fs/promises";
31392
31523
  function projectedToken(path, variable) {
31393
31524
  const named = `the projected service-account token ${variable} names`;
31394
31525
  return {
31395
31526
  async read(signal) {
31396
31527
  let contents;
31397
31528
  try {
31398
- contents = await readFile3(path, {
31529
+ contents = await readFile5(path, {
31399
31530
  encoding: "utf8",
31400
31531
  ...signal === undefined ? {} : { signal }
31401
31532
  });
@@ -31504,13 +31635,15 @@ function tradeProjects(env) {
31504
31635
  }
31505
31636
  return sorted;
31506
31637
  }
31507
- async function brokerTokenClient(env, own = "") {
31638
+ async function brokerTokenClient(env, own = "", read) {
31508
31639
  const brokerUrl = value(env, BROKER_URL_VAR);
31509
31640
  const machine = machineIdentity(env);
31510
31641
  if (brokerUrl === "" || machine === undefined)
31511
31642
  return;
31512
31643
  if (!isHttpUrl(brokerUrl))
31513
31644
  throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
31645
+ const narrowed = read === undefined ? {} : { scope: SCOPE_READ, asOf: read.asOf };
31646
+ const heldApart = async () => read === undefined ? {} : { ...narrowed, holderKey: await newDpopKey() };
31514
31647
  if (machine instanceof DeviceLoginIdentity) {
31515
31648
  if (personTradeOff(env)) {
31516
31649
  throw new Error(`${PERSON_TRADE_VAR}=off turns off every trade made as a person, and ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} trades this machine's device login as the person who approved it; unset one of them`);
@@ -31520,7 +31653,8 @@ async function brokerTokenClient(env, own = "") {
31520
31653
  key: await machine.key(),
31521
31654
  subject: machine,
31522
31655
  session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
31523
- projects: tradeProjects(env)
31656
+ projects: tradeProjects(env),
31657
+ ...await heldApart()
31524
31658
  });
31525
31659
  return { client, signIn: undefined };
31526
31660
  }
@@ -31531,7 +31665,8 @@ async function brokerTokenClient(env, own = "") {
31531
31665
  key: await newDpopKey(),
31532
31666
  subject: machine,
31533
31667
  session: tradeSession(env, own),
31534
- launcherCredential: false
31668
+ launcherCredential: false,
31669
+ ...narrowed
31535
31670
  });
31536
31671
  return { client, signIn: undefined };
31537
31672
  }
@@ -31545,11 +31680,481 @@ async function brokerTokenClient(env, own = "") {
31545
31680
  subject: personIdentity(record, flow),
31546
31681
  actor: machine,
31547
31682
  session: own.trim() || signInSessionName(record),
31548
- projects: tradeProjects(env)
31683
+ projects: tradeProjects(env),
31684
+ ...await heldApart()
31549
31685
  });
31550
31686
  return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
31551
31687
  }
31552
31688
 
31689
+ // ../envoy-client/src/broker-credential.ts
31690
+ function sessionName(naming) {
31691
+ if (naming === undefined)
31692
+ return "";
31693
+ return (typeof naming === "string" ? naming : naming()).trim();
31694
+ }
31695
+ function brokerRouteConfigured(env) {
31696
+ if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
31697
+ return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
31698
+ }
31699
+ if (machineIdentity(env) === undefined) {
31700
+ return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
31701
+ }
31702
+ return { traded: true };
31703
+ }
31704
+ var CLIENTS = new Map;
31705
+ function closeAll(entries) {
31706
+ for (const held of entries?.values() ?? [])
31707
+ held.made?.client?.close();
31708
+ }
31709
+ function forgetBrokerSession(session) {
31710
+ const key = session.trim();
31711
+ closeAll(CLIENTS.get(key));
31712
+ CLIENTS.delete(key);
31713
+ }
31714
+ function signInName(record) {
31715
+ return `${record.person}\x00${record.thumbprint}`;
31716
+ }
31717
+ function keyOf(env, own, read) {
31718
+ const values = BROKER_VARIABLES.map((name) => env[name]);
31719
+ if (read !== undefined)
31720
+ values.push({ read: true, asOf: read.asOf ?? "" });
31721
+ return { session: own.trim(), variables: JSON.stringify(values) };
31722
+ }
31723
+ function entryFor(key) {
31724
+ let sessions = CLIENTS.get(key.session);
31725
+ if (sessions === undefined) {
31726
+ sessions = new Map;
31727
+ CLIENTS.set(key.session, sessions);
31728
+ }
31729
+ let entry = sessions.get(key.variables);
31730
+ if (entry === undefined) {
31731
+ entry = { making: undefined, made: undefined, refused: new Map };
31732
+ sessions.set(key.variables, entry);
31733
+ }
31734
+ return entry;
31735
+ }
31736
+ async function make(env, own, read) {
31737
+ const made = await brokerTokenClient(env, own, read);
31738
+ const signIn = made?.signIn;
31739
+ return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
31740
+ }
31741
+ async function clientFor(env, own, read) {
31742
+ const key = keyOf(env, own, read);
31743
+ const entry = entryFor(key);
31744
+ if (entry.refused.size > 0) {
31745
+ const record = await chooseSignIn(env);
31746
+ const chosen = record === undefined ? "" : signInName(record);
31747
+ if (entry.refused.has(chosen))
31748
+ throw entry.refused.get(chosen);
31749
+ if (entry.made !== undefined && entry.made.signIn !== chosen) {
31750
+ entry.made.client?.close();
31751
+ entry.making = undefined;
31752
+ entry.made = undefined;
31753
+ }
31754
+ }
31755
+ let making = entry.making;
31756
+ if (making === undefined) {
31757
+ const started = make(env, key.session, read);
31758
+ making = started;
31759
+ entry.making = started;
31760
+ started.then((made) => {
31761
+ if (entry.making === started)
31762
+ entry.made = made;
31763
+ }, () => {
31764
+ if (entry.making === started)
31765
+ entry.making = undefined;
31766
+ });
31767
+ }
31768
+ return { entry, made: await making };
31769
+ }
31770
+ function untilAborted(promise, signal) {
31771
+ if (signal === undefined)
31772
+ return promise;
31773
+ if (signal.aborted)
31774
+ return Promise.reject(signal.reason);
31775
+ return new Promise((resolve, reject) => {
31776
+ const stop = () => reject(signal.reason);
31777
+ signal.addEventListener("abort", stop, { once: true });
31778
+ promise.then((value) => {
31779
+ signal.removeEventListener("abort", stop);
31780
+ resolve(value);
31781
+ }, (error) => {
31782
+ signal.removeEventListener("abort", stop);
31783
+ reject(error);
31784
+ });
31785
+ });
31786
+ }
31787
+ async function tradedToken(env, own, { signal, waitForReady = false, read }) {
31788
+ const { entry, made } = await untilAborted(clientFor(env, own, read), signal);
31789
+ const { client } = made;
31790
+ if (client === undefined) {
31791
+ throw new LoggableError("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
31792
+ }
31793
+ const { session, variables } = keyOf(env, own, read);
31794
+ try {
31795
+ return {
31796
+ token: await client.token(signal, { waitForReady }),
31797
+ key: client.key,
31798
+ session: own,
31799
+ identity: JSON.stringify([session, variables, made.signIn])
31800
+ };
31801
+ } catch (error) {
31802
+ if (made.signIn !== "" && isFinalRefusal(error))
31803
+ entry.refused.set(made.signIn, error);
31804
+ throw error;
31805
+ }
31806
+ }
31807
+ function brokerTokenFor(env, session) {
31808
+ return (signal, waitForReady) => tradedToken(env, sessionName(session), { signal, waitForReady });
31809
+ }
31810
+ function dropHeld(key, token) {
31811
+ CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop(token);
31812
+ }
31813
+ function dropTradedToken(env, traded) {
31814
+ dropHeld(keyOf(env, traded.session), traded.token.accessToken);
31815
+ }
31816
+ function brokerCredential(env, session, read) {
31817
+ let presented = "";
31818
+ const presentedAs = new WeakMap;
31819
+ const own = (acting) => (acting ?? "").trim() || sessionName(session);
31820
+ return {
31821
+ scheme: "DPoP",
31822
+ async headers(method, url, acting, signal) {
31823
+ const traded = await tradedToken(env, own(acting), { signal, read });
31824
+ const { token, key, identity } = traded;
31825
+ presented = token.accessToken;
31826
+ const headers = {
31827
+ Authorization: `DPoP ${token.accessToken}`,
31828
+ DPoP: await key.proof({ method, url, accessToken: token.accessToken })
31829
+ };
31830
+ presentedAs.set(headers, {
31831
+ identity,
31832
+ key: keyOf(env, traded.session, read),
31833
+ token: token.accessToken
31834
+ });
31835
+ return headers;
31836
+ },
31837
+ identity: (headers) => presentedAs.get(headers)?.identity,
31838
+ stale(acting, headers) {
31839
+ const told = headers === undefined ? undefined : presentedAs.get(headers);
31840
+ dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
31841
+ },
31842
+ secret: () => presented
31843
+ };
31844
+ }
31845
+
31846
+ // ../envoy-client/src/file-token-credential.ts
31847
+ import { readFileSync as readFileSync2 } from "fs";
31848
+ var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
31849
+ var DPOP_KEY_FILE_VAR = "DISPATCH_BROKER_DPOP_KEY_FILE";
31850
+ var PKCS8_LABEL = "PRIVATE KEY";
31851
+ var PKCS8_PEM = new RegExp(`^-----BEGIN ${PKCS8_LABEL}-----\\r?\\n(?:[A-Za-z0-9+/=]+\\r?\\n)+-----END ${PKCS8_LABEL}-----$`);
31852
+ function readNamed(variable, filePath) {
31853
+ try {
31854
+ return readFileSync2(filePath, "utf8");
31855
+ } catch (error) {
31856
+ throw new Error(`${variable} names ${filePath}, which could not be read (${readErrorCode(error)})`);
31857
+ }
31858
+ }
31859
+ function tokenIn(filePath) {
31860
+ const token = readNamed(TOKEN_FILE_VAR, filePath).trim();
31861
+ if (token === "") {
31862
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds no token: it is empty or blank`);
31863
+ }
31864
+ if (!sendable(token)) {
31865
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds whitespace or a control character inside its token`);
31866
+ }
31867
+ return holdSecret(token);
31868
+ }
31869
+ async function keyIn(filePath) {
31870
+ const pem = readNamed(DPOP_KEY_FILE_VAR, filePath).trim();
31871
+ if (!PKCS8_PEM.test(pem)) {
31872
+ throw new Error(`${DPOP_KEY_FILE_VAR} names ${filePath}, which does not hold one P-256 private key in PKCS#8 PEM`);
31873
+ }
31874
+ return await importDpopKey(pem, `${DPOP_KEY_FILE_VAR}'s key ${filePath}`);
31875
+ }
31876
+ function fileTokenCredential(files, dispatchUrl) {
31877
+ const origin = httpUrl2(dispatchUrl)?.origin;
31878
+ let presented = "";
31879
+ return {
31880
+ scheme: "DPoP",
31881
+ async headers(method, url) {
31882
+ const target = httpUrl2(url)?.origin;
31883
+ if (origin === undefined || target !== origin) {
31884
+ throw new Error(`the token ${TOKEN_FILE_VAR} names goes to DISPATCH_URL's origin (${origin}) alone, and this request is for ${target ?? "a URL that is not http or https"}`);
31885
+ }
31886
+ const token = tokenIn(files.tokenFile);
31887
+ const key = await keyIn(files.keyFile);
31888
+ presented = token;
31889
+ return {
31890
+ Authorization: `DPoP ${token}`,
31891
+ DPoP: await key.proof({ method, url, accessToken: token })
31892
+ };
31893
+ },
31894
+ stale() {},
31895
+ secret: () => presented
31896
+ };
31897
+ }
31898
+
31899
+ // ../envoy-client/src/dispatch-config.ts
31900
+ var DEFAULT_SERVER_URL = "http://localhost:8766";
31901
+ function checkoutPair(checkout, serverUrl) {
31902
+ const { token } = checkout.dispatch;
31903
+ if (token === undefined) {
31904
+ throw new Error(`${checkout.path}: dispatch.serverUrl requires dispatch.token in the same file`);
31905
+ }
31906
+ return {
31907
+ kind: "file",
31908
+ token,
31909
+ field: "dispatch.token",
31910
+ path: checkout.path,
31911
+ server: serverUrl,
31912
+ checkout: true
31913
+ };
31914
+ }
31915
+ function writtenToken(config, checkout) {
31916
+ if (checkout?.dispatch.token !== undefined) {
31917
+ throw new Error(`${checkout.path}: dispatch.token requires dispatch.serverUrl in the same file`);
31918
+ }
31919
+ const own = config.dispatch;
31920
+ if (own.token === undefined)
31921
+ return;
31922
+ const server = own.serverUrl ?? DEFAULT_SERVER_URL;
31923
+ return {
31924
+ token: own.token,
31925
+ field: "dispatch.token",
31926
+ path: config.path,
31927
+ server,
31928
+ checkout: false
31929
+ };
31930
+ }
31931
+ function lostDispatchUrlNotice(env, config) {
31932
+ if (nonEmpty(env.DISPATCH_TOKEN_FILE) === undefined)
31933
+ return;
31934
+ const link = config.missing?.link ?? null;
31935
+ const old = config.missing?.oldUserFileNotice;
31936
+ return [
31937
+ "DISPATCH_TOKEN_FILE is set and DISPATCH_URL is not, so Dispatch is off: this shell lost the DISPATCH_URL it started with. Export DISPATCH_URL again, set to the Dispatch server that token is for",
31938
+ ...link === null ? [] : [`${config.path} is a link to ${link}, which does not exist`],
31939
+ ...old === undefined ? [] : [old]
31940
+ ].join("; ");
31941
+ }
31942
+ async function dispatchSettings(env, config, options = {}) {
31943
+ const target = await dispatchTarget(env, config, options.tokenFiles === true);
31944
+ if (!target.enabled)
31945
+ return target;
31946
+ const { url, urlSetting, source } = target;
31947
+ let credential;
31948
+ try {
31949
+ if (source.kind === "broker")
31950
+ credential = brokerCredential(env, options.session, source.read);
31951
+ else if (source.kind === "files")
31952
+ credential = fileTokenCredential(source, url);
31953
+ else {
31954
+ credential = bearerCredential(source.kind === "variable" ? source.token : await fileBearer(source, url, "DISPATCH", env, options.commands));
31955
+ }
31956
+ } catch (error) {
31957
+ return offWithError(messageFor(error));
31958
+ }
31959
+ const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
31960
+ const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
31961
+ if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
31962
+ return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
31963
+ }
31964
+ const base = publicUrl === undefined ? url : withoutTrailingSlashes(publicUrl);
31965
+ const linkNotice = linkNoticeFor(base, publicUrl === undefined ? urlSetting : "DISPATCH_PUBLIC_URL");
31966
+ return {
31967
+ enabled: true,
31968
+ url,
31969
+ credential,
31970
+ ...publicUrl === undefined ? {} : { publicUrl: withoutTrailingSlashes(publicUrl) },
31971
+ ...linkNotice === undefined ? {} : { linkNotice }
31972
+ };
31973
+ }
31974
+ async function dispatchUrl(env, config) {
31975
+ const target = await dispatchTarget(env, config);
31976
+ return target.enabled ? target.url : undefined;
31977
+ }
31978
+ var BESIDE_TOKEN_FILES = [
31979
+ "DISPATCH_TOKEN_BROKER",
31980
+ "DISPATCH_TOKEN_BROKER_READ",
31981
+ "DISPATCH_TOKEN_BROKER_AS_OF",
31982
+ "DISPATCH_TOKEN",
31983
+ "DISPATCH_TOKEN_FILE",
31984
+ BROKER_URL_VAR,
31985
+ IDENTITY_VAR
31986
+ ];
31987
+ function tokenFilesSet(env) {
31988
+ const set = [
31989
+ ...nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE) === undefined ? [] : [TOKEN_FILE_VAR],
31990
+ ...nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE) === undefined ? [] : [DPOP_KEY_FILE_VAR]
31991
+ ];
31992
+ if (set.length === 0)
31993
+ return;
31994
+ return `${set.join(" and ")} ${set.length === 1 ? "is" : "are"} set`;
31995
+ }
31996
+ function settingsBesideTokenFiles(env) {
31997
+ return BESIDE_TOKEN_FILES.filter((name) => nonEmpty(env[name]) !== undefined).map((name) => `${name} is set`);
31998
+ }
31999
+ function tokenFilesTarget(env, config, taken) {
32000
+ const set = tokenFilesSet(env);
32001
+ if (set === undefined)
32002
+ return;
32003
+ if (!taken) {
32004
+ return offWithError(`${set}, and only the dispatch command reads the token files: Dispatch is off here rather than written with another credential beside them`);
32005
+ }
32006
+ const tokenFile = nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE);
32007
+ const keyFile = nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE);
32008
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
32009
+ const { checkout } = config;
32010
+ const problems = [
32011
+ ...tokenFile === undefined ? [`${TOKEN_FILE_VAR} is not set`] : [],
32012
+ ...keyFile === undefined ? [`${DPOP_KEY_FILE_VAR} is not set`] : [],
32013
+ ...explicitUrl === undefined ? ["DISPATCH_URL is not set"] : [],
32014
+ ...settingsBesideTokenFiles(env),
32015
+ ...config.dispatch.token === undefined ? [] : [`dispatch.token is set in ${config.path}`],
32016
+ ...checkout?.kind === "valid" && checkout.dispatch.token !== undefined ? [`dispatch.token is set in ${checkout.path}`] : [],
32017
+ ...checkout?.kind === "invalid" ? [`${checkout.error}, so whether it sets dispatch.token cannot be told`] : []
32018
+ ];
32019
+ if (problems.length > 0 || tokenFile === undefined || keyFile === undefined || explicitUrl === undefined) {
32020
+ return offWithError(`${TOKEN_FILE_VAR} and ${DPOP_KEY_FILE_VAR} go together, with DISPATCH_URL, as the dispatch command's only Dispatch credential: ${problems.join("; ")}`);
32021
+ }
32022
+ if (config.dispatch.enabled === false) {
32023
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
32024
+ }
32025
+ if (httpUrl2(explicitUrl) === undefined) {
32026
+ return offWithError("DISPATCH_URL must be an http or https URL");
32027
+ }
32028
+ return {
32029
+ enabled: true,
32030
+ url: withoutTrailingSlashes(explicitUrl),
32031
+ urlSetting: "DISPATCH_URL",
32032
+ source: { kind: "files", tokenFile, keyFile }
32033
+ };
32034
+ }
32035
+ function brokerRouteForced(env) {
32036
+ const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
32037
+ if (written === "")
32038
+ return false;
32039
+ if (written === "1")
32040
+ return true;
32041
+ return offWithError("DISPATCH_TOKEN_BROKER 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");
32042
+ }
32043
+ var CUT_FORM = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
32044
+ var ZERO_TIME = Date.parse("0001-01-01T00:00:00.000Z");
32045
+ function isCut(text) {
32046
+ const parts = CUT_FORM.exec(text);
32047
+ if (parts === null)
32048
+ return false;
32049
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = parts.slice(1, 7).map((part) => Number(part ?? "0"));
32050
+ const [zoneHour = 0, zoneMinute = 0] = parts.slice(9, 11).map((part) => Number(part ?? "0"));
32051
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
32052
+ const exists = month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth && hour <= 23 && minute <= 59 && second <= 59 && zoneHour <= 23 && zoneMinute <= 59;
32053
+ if (!exists)
32054
+ return false;
32055
+ const offset = (parts[8] === "-" ? -1 : 1) * (zoneHour * 60 + zoneMinute);
32056
+ const instant = new Date(0);
32057
+ instant.setUTCFullYear(year, month - 1, day);
32058
+ instant.setUTCHours(hour, minute - offset, second, 0);
32059
+ return Number(parts[7] ?? "0") !== 0 || instant.getTime() !== ZERO_TIME;
32060
+ }
32061
+ function readTradeSetting(env) {
32062
+ const read = (env.DISPATCH_TOKEN_BROKER_READ ?? "").trim();
32063
+ const cut = (env.DISPATCH_TOKEN_BROKER_AS_OF ?? "").trim();
32064
+ if (read !== "" && read !== "1") {
32065
+ return offWithError("DISPATCH_TOKEN_BROKER_READ takes 1: set it to 1 where this session's Dispatch credential is a broker token that only reads, and leave it unset where it writes");
32066
+ }
32067
+ if (read === "") {
32068
+ if (cut === "")
32069
+ return;
32070
+ return offWithError("DISPATCH_TOKEN_BROKER_AS_OF names the cut a read-only token reads at, and goes only beside DISPATCH_TOKEN_BROKER_READ=1: set DISPATCH_TOKEN_BROKER_READ to 1 beside it, or unset DISPATCH_TOKEN_BROKER_AS_OF");
32071
+ }
32072
+ if (cut === "")
32073
+ return {};
32074
+ if (!isCut(cut)) {
32075
+ return offWithError("DISPATCH_TOKEN_BROKER_AS_OF is not an RFC 3339 time with at most six fractional digits and Z or a numeric offset, such as 1999-12-31T23:59:59Z");
32076
+ }
32077
+ return { asOf: cut };
32078
+ }
32079
+ async function dispatchTarget(env, config, tokenFiles = false) {
32080
+ if (config.kind === "failed")
32081
+ return offWithError(config.error);
32082
+ const files = tokenFilesTarget(env, config, tokenFiles);
32083
+ if (files !== undefined)
32084
+ return files;
32085
+ const brokerOnly = brokerRouteForced(env);
32086
+ if (typeof brokerOnly !== "boolean")
32087
+ return brokerOnly;
32088
+ const read = readTradeSetting(env);
32089
+ if (read !== undefined && "enabled" in read)
32090
+ return read;
32091
+ const forced = brokerOnly || read !== undefined;
32092
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
32093
+ const checkoutFile = explicitUrl === undefined ? config.checkout : null;
32094
+ if (checkoutFile?.kind === "invalid")
32095
+ return offWithError(checkoutFile.error);
32096
+ const checkout = checkoutFile?.kind === "valid" ? checkoutFile : null;
32097
+ const own = config.dispatch;
32098
+ if (own.enabled === false) {
32099
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
32100
+ }
32101
+ if (checkout?.dispatch.enabled === false) {
32102
+ return offWithNotice(`${checkout.path} sets dispatch.enabled to false: Dispatch is off`);
32103
+ }
32104
+ const checkoutServer = checkout?.dispatch.serverUrl;
32105
+ const addressed = explicitUrl !== undefined || checkoutServer !== undefined || own.serverUrl !== undefined || own.enabled === true;
32106
+ if (!addressed) {
32107
+ const lost = lostDispatchUrlNotice(env, config);
32108
+ if (lost !== undefined)
32109
+ return offWithNotice(lost);
32110
+ return offWithNotice(config.missing === null ? `${config.path} names no Dispatch server, and DISPATCH_URL is not set: Dispatch is off` : missingConfigNotice(config.path, config.missing, "Dispatch is off"));
32111
+ }
32112
+ if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
32113
+ return offWithError("DISPATCH_URL must be an http or https URL");
32114
+ }
32115
+ let source = { kind: "none" };
32116
+ if (!forced) {
32117
+ try {
32118
+ source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : await bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
32119
+ } catch (error) {
32120
+ return offWithError(messageFor(error));
32121
+ }
32122
+ }
32123
+ if (source.kind === "none") {
32124
+ let route;
32125
+ try {
32126
+ route = brokerRouteConfigured(env);
32127
+ } catch (error) {
32128
+ return offWithError(messageFor(error));
32129
+ }
32130
+ if (route.traded) {
32131
+ const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
32132
+ const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
32133
+ return { enabled: true, url: brokered, urlSetting, source: { kind: "broker", read } };
32134
+ }
32135
+ if (forced) {
32136
+ return offWithError(`${read === undefined ? "DISPATCH_TOKEN_BROKER" : "DISPATCH_TOKEN_BROKER_READ"} 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`);
32137
+ }
32138
+ 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}`);
32139
+ }
32140
+ const url = withoutTrailingSlashes(explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL));
32141
+ const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : source.kind === "file" ? `dispatch.serverUrl in ${source.path}` : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
32142
+ return { enabled: true, url, urlSetting, source };
32143
+ }
32144
+ var DEFAULT_URL_SETTING = "Dispatch's default URL";
32145
+ function linkNoticeFor(linkBase, setting) {
32146
+ if (isCleanUrl(linkBase))
32147
+ return;
32148
+ return `${setting} is not a plain http(s) URL (it carries user info, a query, a fragment, '%' or '\\'), so the links Dispatch commands print are dispatch:// references; set DISPATCH_PUBLIC_URL to a plain https URL for dashboard links`;
32149
+ }
32150
+ function activeDispatchSettings(resolution) {
32151
+ if (resolution.enabled)
32152
+ return resolution;
32153
+ if (resolution.error !== null)
32154
+ throw new Error(`dispatch config: ${resolution.error}`);
32155
+ return null;
32156
+ }
32157
+
31553
32158
  // ../envoy-client/src/dispatch-commands/login.ts
31554
32159
  var OK = 0;
31555
32160
  var REFUSED = 1;
@@ -31604,6 +32209,11 @@ async function loginCommand(argv, env, io) {
31604
32209
  io.print(LOGIN_HELP);
31605
32210
  return OK;
31606
32211
  }
32212
+ const tokenFiles = tokenFilesSet(env);
32213
+ if (tokenFiles !== undefined) {
32214
+ const beside = settingsBesideTokenFiles(env);
32215
+ return refuse(`${tokenFiles}, and the token files are the dispatch command's only Dispatch credential, which trades nothing at the secrets broker; a device login asks the broker and keeps a login in a file, so it does not run beside them${beside.length === 0 ? "" : `: ${beside.join("; ")}`}. Run dispatch login in a shell that sets neither token file.`, USAGE);
32216
+ }
31607
32217
  if (parsed.kind === "refused")
31608
32218
  return refuse(`${parsed.problem}. Run dispatch login --help.`, USAGE);
31609
32219
  if (!parsed.device) {
@@ -33795,12 +34405,12 @@ async function reviewCommand(context) {
33795
34405
  }
33796
34406
 
33797
34407
  // ../envoy-client/src/session-answers.ts
33798
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "fs";
34408
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3 } from "fs";
33799
34409
  import { join as join7 } from "path";
33800
34410
 
33801
34411
  // ../envoy-client/src/dispatch-session-directory.ts
33802
34412
  import { randomUUID as randomUUID5 } from "crypto";
33803
- import { renameSync as renameSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
34413
+ import { renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
33804
34414
  import { homedir as homedir2 } from "os";
33805
34415
  import { join as join6 } from "path";
33806
34416
  var SESSION_ID_PATH_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/;
@@ -33823,7 +34433,7 @@ function writeAtomically(path, text) {
33823
34433
  writeFileSync2(temporary, text, { mode: PRIVATE_FILE });
33824
34434
  renameSync2(temporary, path);
33825
34435
  } catch (error) {
33826
- rmSync3(temporary, { force: true });
34436
+ rmSync2(temporary, { force: true });
33827
34437
  throw error;
33828
34438
  }
33829
34439
  }
@@ -33966,7 +34576,7 @@ processGlobal2[STATE_KEY] = state;
33966
34576
  var CACHE_FILE = "answers.json";
33967
34577
  function readCacheFile(directory, url) {
33968
34578
  try {
33969
- const value = JSON.parse(readFileSync4(join7(directory, CACHE_FILE), "utf-8"));
34579
+ const value = JSON.parse(readFileSync3(join7(directory, CACHE_FILE), "utf-8"));
33970
34580
  if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
33971
34581
  return {
33972
34582
  dispatch_url: value.dispatch_url,
@@ -34167,13 +34777,29 @@ async function whoamiCommand(context) {
34167
34777
  const service = identity.kind === "agent" ? identity.service ?? null : null;
34168
34778
  const proved = identity.kind === "agent" ? identity.session ?? null : null;
34169
34779
  const project = identity.kind === "agent" ? identity.project ?? null : null;
34780
+ const readOnly = identity.scopes?.includes("read") === true;
34781
+ const cut = identity.kind === "agent" ? identity.cut ?? null : null;
34170
34782
  const session = proved ?? sessionId;
34171
34783
  const unowned = "no owner, so an issue you create without an assignee takes its parent's assignee when the parent is in the same project, else the project's default assignee, which every project names, so the issue always has one.";
34172
34784
  const answered = identity.kind === "agent" ? identity.sign_in_required : undefined;
34173
34785
  const signInNeeded = answered ?? (owner === null && service !== null && proved !== null);
34174
- const acting = owner !== null ? `Session ${session} acts for ${owner}: issues you create without an assignee are assigned to ${owner}.` : service !== null ? signInNeeded ? `Session ${session} runs as service ${serviceSubjectLabel(service)} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.` : `Session ${session} runs as service ${serviceSubjectLabel(service)}: ${unowned}` : `Session ${session} runs under the shared token: ${unowned}`;
34175
- const elsewhere = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId}): Dispatch records every write you make as ${proved}.` : "";
34176
- const writable = project !== null ? ` It may write project ${project} and no other.` : "";
34786
+ const who = owner !== null ? `acts for ${owner}` : service !== null ? `runs as service ${serviceSubjectLabel(service)}` : "runs";
34787
+ const named = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId})` : "";
34788
+ let acting;
34789
+ let elsewhere = named === "" ? "" : `${named}: Dispatch records every write you make as ${proved}.`;
34790
+ if (readOnly) {
34791
+ acting = `Session ${session} ${who} with a read-only credential: it may read, and Dispatch refuses every write it makes.${cut === null ? "" : ` Its cut is ${cut}, the past time it reads Dispatch at.`}`;
34792
+ elsewhere = named === "" ? "" : `${named}.`;
34793
+ } else if (owner !== null) {
34794
+ acting = `Session ${session} ${who}: issues you create without an assignee are assigned to ${owner}.`;
34795
+ } else if (signInNeeded) {
34796
+ acting = `Session ${session} ${who} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.`;
34797
+ } else if (service !== null) {
34798
+ acting = `Session ${session} ${who}: ${unowned}`;
34799
+ } else {
34800
+ acting = `Session ${session} runs under the shared token: ${unowned}`;
34801
+ }
34802
+ const writable = project !== null && !readOnly ? ` It may write project ${project} and no other.` : "";
34177
34803
  return {
34178
34804
  text: acting + elsewhere + writable,
34179
34805
  details: { session, owner, service, project }
@@ -34446,15 +35072,15 @@ async function executeDispatchTool(input) {
34446
35072
  import { createHash as createHash3 } from "crypto";
34447
35073
  import {
34448
35074
  appendFileSync as appendFileSync2,
34449
- closeSync as closeSync4,
35075
+ closeSync as closeSync3,
34450
35076
  fstatSync as fstatSync2,
34451
35077
  mkdirSync as mkdirSync3,
34452
- openSync as openSync4,
35078
+ openSync as openSync3,
34453
35079
  readdirSync as readdirSync2,
34454
- readFileSync as readFileSync5,
35080
+ readFileSync as readFileSync4,
34455
35081
  readSync as readSync2,
34456
- rmSync as rmSync4,
34457
- statSync as statSync3,
35082
+ rmSync as rmSync3,
35083
+ statSync as statSync2,
34458
35084
  writeFileSync as writeFileSync3
34459
35085
  } from "fs";
34460
35086
  import { join as join8 } from "path";
@@ -34474,7 +35100,7 @@ function ensureDirectory(dir) {
34474
35100
  }
34475
35101
  function readIfPresent(path) {
34476
35102
  try {
34477
- return readFileSync5(path, "utf-8");
35103
+ return readFileSync4(path, "utf-8");
34478
35104
  } catch (error) {
34479
35105
  if (hasErrnoCode(error, "ENOENT"))
34480
35106
  return;
@@ -34557,7 +35183,7 @@ function readSessionTitle(dir) {
34557
35183
  function pruneSessions(root, now) {
34558
35184
  const stamp = join8(root, PRUNED_STAMP);
34559
35185
  try {
34560
- if (now - statSync3(stamp).mtimeMs < PRUNE_INTERVAL_MS)
35186
+ if (now - statSync2(stamp).mtimeMs < PRUNE_INTERVAL_MS)
34561
35187
  return;
34562
35188
  } catch (error) {
34563
35189
  if (!hasErrnoCode(error, "ENOENT"))
@@ -34576,9 +35202,9 @@ function pruneSessions(root, now) {
34576
35202
  continue;
34577
35203
  const dir = join8(sessions, entry.name);
34578
35204
  try {
34579
- const idle = now - statSync3(dir).mtimeMs > IDLE_SESSION_MS;
35205
+ const idle = now - statSync2(dir).mtimeMs > IDLE_SESSION_MS;
34580
35206
  if (idle && askgateState(dir, now).kind === "off" && !recordNamesStore(dir)) {
34581
- rmSync4(dir, { recursive: true, force: true });
35207
+ rmSync3(dir, { recursive: true, force: true });
34582
35208
  }
34583
35209
  } catch (error) {
34584
35210
  if (!hasErrnoCode(error, "ENOENT"))
@@ -34592,12 +35218,12 @@ function pruneSessions(root, now) {
34592
35218
 
34593
35219
  // ../envoy-client/src/process-ancestry.ts
34594
35220
  import { execFileSync } from "child_process";
34595
- import { readFileSync as readFileSync6 } from "fs";
35221
+ import { readFileSync as readFileSync5 } from "fs";
34596
35222
  var MAX_ANCESTORS = 64;
34597
35223
  var PARENT_LOOKUP_MS = 1000;
34598
35224
  function procParentPid(pid) {
34599
35225
  try {
34600
- const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
35226
+ const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34601
35227
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
34602
35228
  return Number.isInteger(parent) ? parent : undefined;
34603
35229
  } catch {
@@ -34639,7 +35265,7 @@ function isAncestor(candidate, pid = process.pid) {
34639
35265
  }
34640
35266
  function procCommand(pid) {
34641
35267
  try {
34642
- return readFileSync6(`/proc/${pid}/comm`, "utf8").trim();
35268
+ return readFileSync5(`/proc/${pid}/comm`, "utf8").trim();
34643
35269
  } catch {
34644
35270
  return;
34645
35271
  }
@@ -34658,316 +35284,6 @@ function nearestAncestorNamed(names, pid = process.pid, reader = PROC_READER) {
34658
35284
  return;
34659
35285
  }
34660
35286
 
34661
- // ../envoy-client/src/broker-credential.ts
34662
- function sessionName(naming) {
34663
- if (naming === undefined)
34664
- return "";
34665
- return (typeof naming === "string" ? naming : naming()).trim();
34666
- }
34667
- function brokerRouteConfigured(env) {
34668
- if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
34669
- return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
34670
- }
34671
- if (machineIdentity(env) === undefined) {
34672
- return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
34673
- }
34674
- return { traded: true };
34675
- }
34676
- var CLIENTS = new Map;
34677
- function closeAll(entries) {
34678
- for (const held of entries?.values() ?? [])
34679
- held.made?.client?.close();
34680
- }
34681
- function forgetBrokerSession(session) {
34682
- const key = session.trim();
34683
- closeAll(CLIENTS.get(key));
34684
- CLIENTS.delete(key);
34685
- }
34686
- function signInName(record) {
34687
- return `${record.person}\x00${record.thumbprint}`;
34688
- }
34689
- function keyOf(env, own) {
34690
- return {
34691
- session: own.trim(),
34692
- variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
34693
- };
34694
- }
34695
- function entryFor(key) {
34696
- let sessions = CLIENTS.get(key.session);
34697
- if (sessions === undefined) {
34698
- sessions = new Map;
34699
- CLIENTS.set(key.session, sessions);
34700
- }
34701
- let entry = sessions.get(key.variables);
34702
- if (entry === undefined) {
34703
- entry = { making: undefined, made: undefined, refused: new Map };
34704
- sessions.set(key.variables, entry);
34705
- }
34706
- return entry;
34707
- }
34708
- async function make(env, own) {
34709
- const made = await brokerTokenClient(env, own);
34710
- const signIn = made?.signIn;
34711
- return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
34712
- }
34713
- async function clientFor(env, own) {
34714
- const key = keyOf(env, own);
34715
- const entry = entryFor(key);
34716
- if (entry.refused.size > 0) {
34717
- const record = await chooseSignIn(env);
34718
- const chosen = record === undefined ? "" : signInName(record);
34719
- if (entry.refused.has(chosen))
34720
- throw entry.refused.get(chosen);
34721
- if (entry.made !== undefined && entry.made.signIn !== chosen) {
34722
- entry.made.client?.close();
34723
- entry.making = undefined;
34724
- entry.made = undefined;
34725
- }
34726
- }
34727
- let making = entry.making;
34728
- if (making === undefined) {
34729
- const started = make(env, key.session);
34730
- making = started;
34731
- entry.making = started;
34732
- started.then((made) => {
34733
- if (entry.making === started)
34734
- entry.made = made;
34735
- }, () => {
34736
- if (entry.making === started)
34737
- entry.making = undefined;
34738
- });
34739
- }
34740
- return { entry, made: await making };
34741
- }
34742
- function untilAborted(promise, signal) {
34743
- if (signal === undefined)
34744
- return promise;
34745
- if (signal.aborted)
34746
- return Promise.reject(signal.reason);
34747
- return new Promise((resolve, reject) => {
34748
- const stop = () => reject(signal.reason);
34749
- signal.addEventListener("abort", stop, { once: true });
34750
- promise.then((value) => {
34751
- signal.removeEventListener("abort", stop);
34752
- resolve(value);
34753
- }, (error) => {
34754
- signal.removeEventListener("abort", stop);
34755
- reject(error);
34756
- });
34757
- });
34758
- }
34759
- async function tradedToken(env, own, signal, waitForReady = false) {
34760
- const { entry, made } = await untilAborted(clientFor(env, own), signal);
34761
- const { client } = made;
34762
- if (client === undefined) {
34763
- throw new LoggableError("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
34764
- }
34765
- const { session, variables } = keyOf(env, own);
34766
- try {
34767
- return {
34768
- token: await client.token(signal, { waitForReady }),
34769
- key: client.key,
34770
- session: own,
34771
- identity: JSON.stringify([session, variables, made.signIn])
34772
- };
34773
- } catch (error) {
34774
- if (made.signIn !== "" && isFinalRefusal(error))
34775
- entry.refused.set(made.signIn, error);
34776
- throw error;
34777
- }
34778
- }
34779
- function brokerTokenFor(env, session) {
34780
- return (signal, waitForReady) => tradedToken(env, sessionName(session), signal, waitForReady);
34781
- }
34782
- function dropHeld(key, token) {
34783
- CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop(token);
34784
- }
34785
- function dropTradedToken(env, traded) {
34786
- dropHeld(keyOf(env, traded.session), traded.token.accessToken);
34787
- }
34788
- function brokerCredential(env, session) {
34789
- let presented = "";
34790
- const presentedAs = new WeakMap;
34791
- const own = (acting) => (acting ?? "").trim() || sessionName(session);
34792
- return {
34793
- scheme: "DPoP",
34794
- async headers(method, url, acting, signal) {
34795
- const traded = await tradedToken(env, own(acting), signal);
34796
- const { token, key, identity } = traded;
34797
- presented = token.accessToken;
34798
- const headers = {
34799
- Authorization: `DPoP ${token.accessToken}`,
34800
- DPoP: await key.proof({ method, url, accessToken: token.accessToken })
34801
- };
34802
- presentedAs.set(headers, {
34803
- identity,
34804
- key: keyOf(env, traded.session),
34805
- token: token.accessToken
34806
- });
34807
- return headers;
34808
- },
34809
- identity: (headers) => presentedAs.get(headers)?.identity,
34810
- stale(acting, headers) {
34811
- const told = headers === undefined ? undefined : presentedAs.get(headers);
34812
- dropHeld(told?.key ?? keyOf(env, own(acting)), told?.token);
34813
- },
34814
- secret: () => presented
34815
- };
34816
- }
34817
-
34818
- // ../envoy-client/src/dispatch-config.ts
34819
- var DEFAULT_SERVER_URL = "http://localhost:8766";
34820
- function checkoutPair(checkout, serverUrl) {
34821
- const { token } = checkout.dispatch;
34822
- if (token === undefined) {
34823
- throw new Error(`${checkout.path}: dispatch.serverUrl requires dispatch.token in the same file`);
34824
- }
34825
- return {
34826
- kind: "file",
34827
- token,
34828
- field: "dispatch.token",
34829
- path: checkout.path,
34830
- server: serverUrl,
34831
- checkout: true
34832
- };
34833
- }
34834
- function writtenToken(config, checkout) {
34835
- if (checkout?.dispatch.token !== undefined) {
34836
- throw new Error(`${checkout.path}: dispatch.token requires dispatch.serverUrl in the same file`);
34837
- }
34838
- const own = config.dispatch;
34839
- if (own.token === undefined)
34840
- return;
34841
- const server = own.serverUrl ?? DEFAULT_SERVER_URL;
34842
- return {
34843
- token: own.token,
34844
- field: "dispatch.token",
34845
- path: config.path,
34846
- server,
34847
- checkout: false
34848
- };
34849
- }
34850
- function lostDispatchUrlNotice(env, config) {
34851
- if (nonEmpty(env.DISPATCH_TOKEN_FILE) === undefined)
34852
- return;
34853
- const link = config.missing?.link ?? null;
34854
- const old = config.missing?.oldUserFileNotice;
34855
- return [
34856
- "DISPATCH_TOKEN_FILE is set and DISPATCH_URL is not, so Dispatch is off: this shell lost the DISPATCH_URL it started with. Export DISPATCH_URL again, set to the Dispatch server that token is for",
34857
- ...link === null ? [] : [`${config.path} is a link to ${link}, which does not exist`],
34858
- ...old === undefined ? [] : [old]
34859
- ].join("; ");
34860
- }
34861
- function dispatchSettings(env, config, options = {}) {
34862
- const target = dispatchTarget(env, config);
34863
- if (!target.enabled)
34864
- return target;
34865
- const { url, urlSetting, source } = target;
34866
- let credential;
34867
- try {
34868
- credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
34869
- } catch (error) {
34870
- return offWithError(messageFor(error));
34871
- }
34872
- const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
34873
- const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
34874
- if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
34875
- return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
34876
- }
34877
- const base = publicUrl === undefined ? url : withoutTrailingSlashes(publicUrl);
34878
- const linkNotice = linkNoticeFor(base, publicUrl === undefined ? urlSetting : "DISPATCH_PUBLIC_URL");
34879
- return {
34880
- enabled: true,
34881
- url,
34882
- credential,
34883
- ...publicUrl === undefined ? {} : { publicUrl: withoutTrailingSlashes(publicUrl) },
34884
- ...linkNotice === undefined ? {} : { linkNotice }
34885
- };
34886
- }
34887
- function dispatchUrl(env, config) {
34888
- const target = dispatchTarget(env, config);
34889
- return target.enabled ? target.url : undefined;
34890
- }
34891
- function brokerRouteForced(env) {
34892
- const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
34893
- if (written === "")
34894
- return false;
34895
- if (written === "1")
34896
- return true;
34897
- return offWithError("DISPATCH_TOKEN_BROKER 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");
34898
- }
34899
- function dispatchTarget(env, config) {
34900
- if (config.kind === "failed")
34901
- return offWithError(config.error);
34902
- const forced = brokerRouteForced(env);
34903
- if (typeof forced !== "boolean")
34904
- return forced;
34905
- const explicitUrl = nonEmpty(env.DISPATCH_URL);
34906
- const checkoutFile = explicitUrl === undefined ? config.checkout : null;
34907
- if (checkoutFile?.kind === "invalid")
34908
- return offWithError(checkoutFile.error);
34909
- const checkout = checkoutFile?.kind === "valid" ? checkoutFile : null;
34910
- const own = config.dispatch;
34911
- if (own.enabled === false) {
34912
- return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
34913
- }
34914
- if (checkout?.dispatch.enabled === false) {
34915
- return offWithNotice(`${checkout.path} sets dispatch.enabled to false: Dispatch is off`);
34916
- }
34917
- const checkoutServer = checkout?.dispatch.serverUrl;
34918
- const addressed = explicitUrl !== undefined || checkoutServer !== undefined || own.serverUrl !== undefined || own.enabled === true;
34919
- if (!addressed) {
34920
- const lost = lostDispatchUrlNotice(env, config);
34921
- if (lost !== undefined)
34922
- return offWithNotice(lost);
34923
- return offWithNotice(config.missing === null ? `${config.path} names no Dispatch server, and DISPATCH_URL is not set: Dispatch is off` : missingConfigNotice(config.path, config.missing, "Dispatch is off"));
34924
- }
34925
- if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
34926
- return offWithError("DISPATCH_URL must be an http or https URL");
34927
- }
34928
- let source = { kind: "none" };
34929
- if (!forced) {
34930
- try {
34931
- source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
34932
- } catch (error) {
34933
- return offWithError(messageFor(error));
34934
- }
34935
- }
34936
- if (source.kind === "none") {
34937
- let route;
34938
- try {
34939
- route = brokerRouteConfigured(env);
34940
- } catch (error) {
34941
- return offWithError(messageFor(error));
34942
- }
34943
- if (route.traded) {
34944
- const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
34945
- const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
34946
- return { enabled: true, url: brokered, urlSetting, source: { kind: "broker" } };
34947
- }
34948
- if (forced) {
34949
- 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`);
34950
- }
34951
- 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}`);
34952
- }
34953
- const url = withoutTrailingSlashes(explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL));
34954
- const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : source.kind === "file" ? `dispatch.serverUrl in ${source.path}` : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
34955
- return { enabled: true, url, urlSetting, source };
34956
- }
34957
- var DEFAULT_URL_SETTING = "Dispatch's default URL";
34958
- function linkNoticeFor(linkBase, setting) {
34959
- if (isCleanUrl(linkBase))
34960
- return;
34961
- return `${setting} is not a plain http(s) URL (it carries user info, a query, a fragment, '%' or '\\'), so the links Dispatch commands print are dispatch:// references; set DISPATCH_PUBLIC_URL to a plain https URL for dashboard links`;
34962
- }
34963
- function activeDispatchSettings(resolution) {
34964
- if (resolution.enabled)
34965
- return resolution;
34966
- if (resolution.error !== null)
34967
- throw new Error(`dispatch config: ${resolution.error}`);
34968
- return null;
34969
- }
34970
-
34971
35287
  // ../envoy-client/src/nats-credential.ts
34972
35288
  var NATS_AUTH_VAR = "NATS_AUTH";
34973
35289
  function noAuthService(source) {
@@ -35132,7 +35448,6 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
35132
35448
  admissions: () => admissions
35133
35449
  };
35134
35450
  }
35135
- var RENEW_FLOOR_MS = 1000;
35136
35451
  var RETRY_FIRST_MS = 2000;
35137
35452
  var RETRY_LAST_MS = 60000;
35138
35453
  var WARN_AGAIN_MS = 30 * 60000;
@@ -35189,11 +35504,7 @@ function warnedEvery(warn) {
35189
35504
  };
35190
35505
  }
35191
35506
  function renewDelay(expiry, now) {
35192
- const remaining = expiry - now;
35193
- if (remaining <= 0)
35194
- return 0;
35195
- const ahead = remaining - Math.min(DEFAULT_RENEW_BEFORE_MS, remaining / 2);
35196
- return Math.max(Math.min(RENEW_FLOOR_MS, remaining / 2), ahead);
35507
+ return renewalAt(expiry, now, DEFAULT_RENEW_BEFORE_MS) - now;
35197
35508
  }
35198
35509
  function keepNatsCredential(connection, credential, warn) {
35199
35510
  let stopped = false;
@@ -35367,13 +35678,13 @@ function resolvedInterval(raw, fallback) {
35367
35678
  return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
35368
35679
  }
35369
35680
  var ENVOY_INBOUND_VAR = "ENVOY_INBOUND";
35370
- function natsSeedFromEnvironment(env) {
35681
+ async function natsSeedFromEnvironment(env) {
35371
35682
  const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
35372
35683
  if (file !== undefined) {
35373
35684
  if (file === "")
35374
35685
  throw new Error("NATS_NKEY_SEED_FILE is set but empty");
35375
35686
  return {
35376
- value: readSecretFile("NATS_NKEY_SEED_FILE", file),
35687
+ value: await readSecretFile("NATS_NKEY_SEED_FILE", file),
35377
35688
  source: "the file NATS_NKEY_SEED_FILE names"
35378
35689
  };
35379
35690
  }
@@ -35402,23 +35713,23 @@ function requireFileServers(section, namedNatsUrls, filePath, remedy) {
35402
35713
  throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set ${remedy} for them`);
35403
35714
  }
35404
35715
  }
35405
- function natsSeed(env, section, namedNatsUrls, filePath) {
35406
- const fromEnvironment = natsSeedFromEnvironment(env);
35716
+ async function natsSeed(env, section, namedNatsUrls, filePath) {
35717
+ const fromEnvironment = await natsSeedFromEnvironment(env);
35407
35718
  if (fromEnvironment !== undefined || section.natsSeed === undefined)
35408
35719
  return fromEnvironment;
35409
35720
  requireFileServers(section, namedNatsUrls, filePath, "NATS_NKEY_SEED_FILE");
35410
35721
  return {
35411
- value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
35722
+ value: await fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
35412
35723
  source: `envoy.natsSeed in ${filePath}`
35413
35724
  };
35414
35725
  }
35415
- function natsCredential(env, section, namedNatsUrls, filePath, session) {
35726
+ async function natsCredential(env, section, namedNatsUrls, filePath, session) {
35416
35727
  const named = nonEmpty(env.NATS_AUTH);
35417
35728
  const auth = named !== undefined ? { value: named, source: NATS_AUTH_VAR } : section.natsAuth === undefined ? undefined : { value: section.natsAuth, source: `envoy.natsAuth in ${filePath}` };
35418
35729
  if (auth !== undefined && auth.value !== "broker" && auth.value !== "none") {
35419
35730
  throw new Error(`${auth.source} is neither broker nor none`);
35420
35731
  }
35421
- const seed = natsSeed(env, section, namedNatsUrls, filePath);
35732
+ const seed = await natsSeed(env, section, namedNatsUrls, filePath);
35422
35733
  if (seed !== undefined) {
35423
35734
  if (auth?.value === "broker") {
35424
35735
  throw new Error(`${auth.source} is ${auth.value}, and ${seed.source} names an nkey seed: set one of the two`);
@@ -35463,7 +35774,7 @@ function plainHttpOffMachine(url) {
35463
35774
  const host = URL.canParse(url) ? new URL(url) : undefined;
35464
35775
  return host?.protocol === "http:" && !LOOPBACK_HOST2.test(host.hostname) ? host.hostname : undefined;
35465
35776
  }
35466
- function envoySettings(env, config, options = {}) {
35777
+ async function envoySettings(env, config, options = {}) {
35467
35778
  if (config.kind === "failed")
35468
35779
  return offWithError(config.error);
35469
35780
  const section = config.envoy;
@@ -35494,7 +35805,7 @@ function envoySettings(env, config, options = {}) {
35494
35805
  let credential;
35495
35806
  let noBrokerRoute = "";
35496
35807
  try {
35497
- const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
35808
+ const source = await bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
35498
35809
  token: section.token,
35499
35810
  field: "envoy.token",
35500
35811
  path: config.path,
@@ -35507,7 +35818,7 @@ function envoySettings(env, config, options = {}) {
35507
35818
  if (!route.traded)
35508
35819
  noBrokerRoute = route.gap;
35509
35820
  } else {
35510
- credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
35821
+ credential = bearerCredential(source.kind === "variable" ? source.token : await fileBearer(source, url, "ENVOY", env));
35511
35822
  }
35512
35823
  } catch (error) {
35513
35824
  return offWithError(messageFor(error));
@@ -35527,7 +35838,7 @@ function envoySettings(env, config, options = {}) {
35527
35838
  inbound = {
35528
35839
  natsUrls,
35529
35840
  natsServersSetting: natsSetting,
35530
- natsCredential: natsCredential(env, section, namedNatsUrls, config.path, options.session)
35841
+ natsCredential: await natsCredential(env, section, namedNatsUrls, config.path, options.session)
35531
35842
  };
35532
35843
  } catch (error) {
35533
35844
  inbound = error instanceof NoSessionNamedError ? { off: messageFor(error), noSessionNamed: true } : { off: messageFor(error) };
@@ -35611,42 +35922,45 @@ function startNotice(config, dispatch, envoy, nats, lost) {
35611
35922
  }
35612
35923
  return parts.length === 0 ? null : parts.join("; ");
35613
35924
  }
35614
- function sessionSettings(file, env, options) {
35925
+ async function sessionSettings(file, env, options) {
35615
35926
  if (file.path === null) {
35616
35927
  const off = offWithError(file.error);
35617
35928
  return { dispatch: off, envoy: off, notice: `${file.error}: Dispatch and Envoy are off` };
35618
35929
  }
35619
- const config = readEnvoyConfig(file.path, env, options);
35620
- const dispatch = dispatchSettings(env, config, { session: options.session });
35621
- const envoy = envoySettings(env, config, { nats: options.nats, session: options.session });
35930
+ const config = await readEnvoyConfig(file.path, env, options);
35931
+ const [dispatch, envoy] = await Promise.all([
35932
+ dispatchSettings(env, config, { session: options.session }),
35933
+ envoySettings(env, config, { nats: options.nats, session: options.session })
35934
+ ]);
35622
35935
  return {
35623
35936
  dispatch,
35624
35937
  envoy,
35625
35938
  notice: startNotice(config, dispatch, envoy, options.nats !== false, config.kind === "read" ? lostDispatchUrlNotice(env, config) : undefined)
35626
35939
  };
35627
35940
  }
35628
- function sessionDispatchSettings(file, env, options) {
35941
+ async function sessionDispatchSettings(file, env, options) {
35629
35942
  if (file.path === null)
35630
35943
  return { dispatch: offWithError(file.error), warnings: [], missing: null };
35631
- const config = readEnvoyConfig(file.path, env, options);
35944
+ const config = await readEnvoyConfig(file.path, env, options);
35632
35945
  return {
35633
- dispatch: dispatchSettings(env, config, {
35946
+ dispatch: await dispatchSettings(env, config, {
35634
35947
  commands: options.commands,
35635
- session: options.session
35948
+ session: options.session,
35949
+ tokenFiles: options.tokenFiles
35636
35950
  }),
35637
35951
  warnings: config.kind === "read" ? config.warnings : [],
35638
35952
  missing: config.kind === "read" ? config.missing : null
35639
35953
  };
35640
35954
  }
35641
- function sessionDispatchUrl(file, env, options) {
35955
+ async function sessionDispatchUrl(file, env, options) {
35642
35956
  if (file.path === null)
35643
35957
  return;
35644
- return dispatchUrl(env, readEnvoyConfig(file.path, env, options));
35958
+ return dispatchUrl(env, await readEnvoyConfig(file.path, env, options));
35645
35959
  }
35646
- function sessionEnvoySettings(file, env, options) {
35960
+ async function sessionEnvoySettings(file, env, options) {
35647
35961
  if (file.path === null)
35648
35962
  return offWithError(file.error);
35649
- return envoySettings(env, readEnvoyConfig(file.path, env, options), {
35963
+ return envoySettings(env, await readEnvoyConfig(file.path, env, options), {
35650
35964
  nats: options.nats,
35651
35965
  session: options.session
35652
35966
  });
@@ -36395,7 +36709,11 @@ async function runDispatchCli(argv, rawEnv, io) {
36395
36709
  }
36396
36710
  const file = (env.DISPATCH_HOST === undefined ? null : handedConfigFile(env)) ?? sessionConfigFile(host, env);
36397
36711
  if (parsed.dryRun && !dryRunAsksDispatch(parsed.tool, parsed.args)) {
36398
- const settings = file.path === null ? null : sessionDispatchSettings(file, env, { cwd: io.cwd, session: sessionId }).dispatch;
36712
+ const settings = file.path === null ? null : (await sessionDispatchSettings(file, env, {
36713
+ cwd: io.cwd,
36714
+ session: sessionId,
36715
+ tokenFiles: true
36716
+ })).dispatch;
36399
36717
  const { problems } = await checkDispatchCall({
36400
36718
  tool: parsed.tool,
36401
36719
  args: parsed.args,
@@ -36412,9 +36730,10 @@ async function runDispatchCli(argv, rawEnv, io) {
36412
36730
  if (file.path === null) {
36413
36731
  return refuse(`dispatch: ${file.error}`, USAGE2, parsed.tool);
36414
36732
  }
36415
- const { dispatch: resolution, warnings } = sessionDispatchSettings(file, env, {
36733
+ const { dispatch: resolution, warnings } = await sessionDispatchSettings(file, env, {
36416
36734
  cwd: io.cwd,
36417
- session: sessionId
36735
+ session: sessionId,
36736
+ tokenFiles: true
36418
36737
  });
36419
36738
  const wholeJson = printsJson(parsed.tool, parsed.args);
36420
36739
  const note = (line) => wholeJson ? io.stderr(`${line}
@@ -36460,12 +36779,12 @@ ${result.text}`);
36460
36779
  for (const file of fileOperands(argv)) {
36461
36780
  let bytes;
36462
36781
  try {
36463
- const fd = openSync5(operandPath(io.cwd, file), constants4.O_RDONLY | constants4.O_NONBLOCK);
36782
+ const fd = openSync4(operandPath(io.cwd, file), constants4.O_RDONLY | constants4.O_NONBLOCK);
36464
36783
  try {
36465
36784
  if (fstatSync3(fd).isFile())
36466
- bytes = readFileSync7(fd);
36785
+ bytes = readFileSync6(fd);
36467
36786
  } finally {
36468
- closeSync5(fd);
36787
+ closeSync4(fd);
36469
36788
  }
36470
36789
  } catch {}
36471
36790
  files.push({ ...file, sha256: bytes === undefined ? null : bytesDigest(bytes) });
@@ -36496,7 +36815,7 @@ ${result.text}`);
36496
36815
  let topics;
36497
36816
  const readTopics = async () => {
36498
36817
  try {
36499
- const envoy = sessionEnvoySettings(file, env, {
36818
+ const envoy = await sessionEnvoySettings(file, env, {
36500
36819
  cwd: io.cwd,
36501
36820
  nats: false,
36502
36821
  session: sessionId
@@ -36599,7 +36918,7 @@ ${result.text}`);
36599
36918
  }
36600
36919
 
36601
36920
  // ../envoy-client/bin/dispatch.ts
36602
- var readText = (path) => readFileSync8(path === "-" ? 0 : path, "utf-8");
36921
+ var readText = (path) => readFileSync7(path === "-" ? 0 : path, "utf-8");
36603
36922
  var pending = [];
36604
36923
  var writeTo = (stream) => (text) => {
36605
36924
  const { promise, resolve } = Promise.withResolvers();