@sjawhar/claude-envoy 6.22.1 → 6.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "6.22.1"
5
+ "version": "6.23.0"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "6.22.1",
3
+ "version": "6.23.0",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
package/README.md CHANGED
@@ -307,6 +307,15 @@ from the installed plugin, or from npm:
307
307
  npx --package @sjawhar/codex-envoy dispatch login --device --person <address>
308
308
  ```
309
309
 
310
+ Where the deployment serves Dispatch sign-ins, the same command with `--scope person` (or
311
+ `--scope none`) signs a session or tool in to Dispatch alone instead: the person approves the code
312
+ on Dispatch's machine-login page, ticking the scopes it may hold, and the login enrolls no session
313
+ and reads no secret:
314
+
315
+ ```bash
316
+ npx --package @sjawhar/codex-envoy dispatch login --device --person <address> --scope person
317
+ ```
318
+
310
319
  It runs `dist/dispatch.js` with `bun`, as the plugin's server does, and follows the link npm
311
320
  makes for a package `bin` to find it.
312
321
 
@@ -13719,6 +13719,8 @@ var ActorOriginSchema = strictObject({
13719
13719
  session_title: string2().optional()
13720
13720
  }).readonly();
13721
13721
  var DISPATCH_SCOPES = ["person", "approve", "p0"];
13722
+ var DISPATCH_SIGN_IN_SCOPES = ["person", "p0"];
13723
+ var BROKER_REQUEST_REASON_MAX = 400;
13722
13724
  var ActorActSchema = strictObject({
13723
13725
  session: string2().optional(),
13724
13726
  session_proven: literal(true).optional(),
@@ -15296,7 +15298,7 @@ var dispatchToolSpecs = [
15296
15298
  {
15297
15299
  name: "dispatch_whoami",
15298
15300
  example: {},
15299
- description: "Who Dispatch takes this session for: {session, owner, service, project, project_scope}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee, when the parent is in the issue's own project, and then to the project's default assignee, which every project names, so every issue you create has an assignee. A question on an issue reaches the person it was handed to, else the issue's assignee, else the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the service a broker token naming no person names: a job's identity as its job entry lists it, the Kubernetes account an exchange entry lists, or the fleet of a machine nobody has signed in on; else null. project_scope is a broker token's project scope, and null for every other credential. A job's broker token has the project scope named or public, holds no OAuth scope and writes as its service: a route that needs an OAuth scope refuses it with 403 OAUTH_SCOPE_REQUIRED before Dispatch's project check runs. named names one project, and that check judges its writes as it judges a person's named token's for the same project: it refuses a write that belongs to the deployment, such as a project create, with 403 PROJECT_SCOPE_DEPLOYMENT. public names no one project, so it may write wherever a token that names no project may. An exchange entry's broker token that names its account has the project scope named and no project, and writes as that account wherever a token that names no project may. A machine's broker token that names a service has the project scope person; it may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the project your credential's token names, or null when it names none. A token that names a project also writes other projects' objects, as a credential that names none does. The one exception is a private project that the token does not name.",
15301
+ description: "Who Dispatch takes this session for: {session, owner, service, project, project_scope, scopes}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee, when the parent is in the issue's own project, and then to the project's default assignee, which every project names, so every issue you create has an assignee. A question on an issue reaches the person it was handed to, else the issue's assignee, else the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the service a broker token naming no person names: a job's identity as its job entry lists it, the Kubernetes account an exchange entry lists, or the fleet of a machine nobody has signed in on; else null. project_scope is a broker token's project scope, and null for every other credential. A job's broker token has the project scope named or public, holds no OAuth scope and writes as its service: a route that needs an OAuth scope refuses it with 403 OAUTH_SCOPE_REQUIRED before Dispatch's project check runs. named names one project, and that check judges its writes as it judges a person's named token's for the same project: it refuses a write that belongs to the deployment, such as a project create, with 403 PROJECT_SCOPE_DEPLOYMENT. public names no one project, so it may write wherever a token that names no project may. An exchange entry's broker token that names its account has the project scope named and no project, and writes as that account wherever a token that names no project may. A machine's broker token that names a service has the project scope person; it may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the project your credential's token names, or null when it names none. A token that names a project also writes other projects' objects, as a credential that names none does. The one exception is a private project that the token does not name. scopes is the OAuth scopes your credential holds, such as those a Dispatch sign-in's person approved, and [] for none; the tool's text names them, and scopes is null where Dispatch names none.",
15300
15302
  arguments: () => ({}),
15301
15303
  strict: true
15302
15304
  },
@@ -15932,6 +15934,9 @@ function inboxThreadRow(row) {
15932
15934
  function awaitsDecision(row) {
15933
15935
  return row.state !== "expired";
15934
15936
  }
15937
+ function signInScopes(row) {
15938
+ return Array.isArray(row.dispatch_scopes) ? row.dispatch_scopes : null;
15939
+ }
15935
15940
  // ../contracts/src/dispatch-api-messages.ts
15936
15941
  var messageDeliveryFields = {
15937
15942
  message_id: string2(),
@@ -17215,7 +17220,12 @@ var DISPATCH_READING_SURFACES = [
17215
17220
  surface: "change-view-diff"
17216
17221
  },
17217
17222
  {
17218
- files: ["packages/dispatch/web/src/features/credentials/CredentialRecordFacts.tsx"],
17223
+ files: [
17224
+ "packages/dispatch/web/src/features/credentials/CredentialRecordFacts.tsx",
17225
+ "packages/dispatch/web/src/features/credentials/CredentialRequestsSection.tsx",
17226
+ "packages/dispatch/web/src/features/credentials/MachineLoginPage.tsx",
17227
+ "packages/dispatch/web/src/features/credentials/MachineLoginsSection.tsx"
17228
+ ],
17219
17229
  reach: "/credentials/machine, a machine login request's reason",
17220
17230
  reason: `A credential request's reason is what the asking agent typed for it. ${ONE_LINE_FIELD_REASON}`,
17221
17231
  record: false,
@@ -19687,21 +19697,25 @@ var LOGIN_COMMAND = "login";
19687
19697
  var LOGIN_SENTENCE = "Logs this machine in at the secrets broker, once per machine, for a machine with no identity of its own, such as a laptop.";
19688
19698
  function loginHelp() {
19689
19699
  return [
19690
- "Usage: dispatch login --device [--person <address>]",
19700
+ "Usage: dispatch login --device [--person <address>] [--scope <list>] [--reason <text>]",
19691
19701
  "",
19692
- `${LOGIN_SENTENCE} It prints a code and the page to type it into; the person the login names approves it there, signed in to Dispatch. The login is then kept in the file AGENT_SECRETS_DEVICE_LOGIN_FILE names (default ~/.config/legion/device-login.json), mode 0600, and every session that sets AGENT_SECRETS_MACHINE_IDENTITY=device-login trades it for its broker token.`,
19702
+ `${LOGIN_SENTENCE} With --scope, it makes a Dispatch sign-in for a session or tool instead: the person approves the scopes it asks for, ticking some or all of them, and its tokens hold those scopes alone, never approve; it enrolls no session and reads no secret. Whatever is ticked, the session writes in Dispatch and works on Envoy as its own session within its person's projects; the scope person adds acting as the person, the scope p0, which the page shows unticked until the person ticks it, adds making an issue's own priority 0, and --scope none asks for no scope. A broker serves Dispatch sign-ins only where its deployment turns them on. It prints a code and the page to type it into; the person the login names approves it there, signed in to Dispatch. The login is then kept in the file AGENT_SECRETS_DEVICE_LOGIN_FILE names (default ~/.config/legion/device-login.json), mode 0600, in place of any login that file held, and every session started after that sets AGENT_SECRETS_MACHINE_IDENTITY=device-login trades it for its broker token. A session already running refuses to trade a new login, a scope change included: start a new session to trade it, since the broker keeps a session's name for the principal that wrote under it, and each Dispatch sign-in is a principal of its own, as is each person's machine login, so that session started again is refused, except where a machine login replaced the same person's machine login, which the client cannot tell, since the login file names no person. To keep a machine login and a Dispatch sign-in on one machine, name another file for one of them.`,
19693
19703
  "",
19694
19704
  "Flags:",
19695
19705
  " --device",
19696
19706
  " Log in with the broker's device grant: the only way there is, and required.",
19697
19707
  " --person <address>",
19698
19708
  " The person who approves the login, by the address they sign in to Dispatch with; else AGENT_SECRETS_PERSON.",
19709
+ " --scope <list>",
19710
+ " Create a Dispatch sign-in for the comma-separated scopes person, p0, or none. Omit it for a machine login.",
19711
+ " --reason <text>",
19712
+ " Name the session or tool. It may have at most 400 characters.",
19699
19713
  "",
19700
19714
  "It reads AGENT_SECRETS_URL, the broker, and needs no Dispatch host or session.",
19701
19715
  "",
19702
19716
  "It exits 0 once the login is kept; 1 when the broker could not be reached or refused it, the person denied it, its code expired, or the login could not be kept; and 2 on a usage error, before any request.",
19703
19717
  "",
19704
- "Example: dispatch login --device --person ada@example.com",
19718
+ "Example: dispatch login --device --person ada@example.com --scope person",
19705
19719
  ""
19706
19720
  ].join(`
19707
19721
  `);
@@ -22817,6 +22831,7 @@ var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
22817
22831
  var GRANT_TYPE_REFRESH = "refresh_token";
22818
22832
  var MACHINE_LOGIN_CLIENT_ID = "agent-secrets-helper";
22819
22833
  var MACHINE_LOGIN_SCOPE = "machine";
22834
+ var DISPATCH_LOGIN_SCOPE = "dispatch";
22820
22835
  var REQUEST_OBJECT_TYPE = "agent-secrets-request+jwt";
22821
22836
  var LAUNCHER_CREDENTIAL_DETAIL = "launcher_credential";
22822
22837
  var REQUEST_OBJECT_LIFETIME_SECONDS = 600;
@@ -22849,6 +22864,8 @@ var INSTANCE_PATTERN = "[A-Za-z0-9*?._\\[\\]-]{1,100}";
22849
22864
  var NUMBER = "[0-9]{1,6}";
22850
22865
  var CLAIM = "[A-Za-z0-9_.:-]{1,64}";
22851
22866
  var URI = "[A-Za-z0-9:/._-]{1,200}";
22867
+ var SCOPE_WORD = "[a-z][a-z0-9_-]{0,63}";
22868
+ var SCOPE_LIST = `${SCOPE_WORD}(?:, ${SCOPE_WORD}){0,7}`;
22852
22869
  var SESSION_RULE = "a session name is printable, carries no whitespace, '\\*' or '>', and is at most [0-9]{1,4} bytes";
22853
22870
  function escapeRegExp(text) {
22854
22871
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -22875,7 +22892,8 @@ var POLICY_SENTINELS = {
22875
22892
  sessionFixed: "exchange: the entry fixes the session name its tokens carry",
22876
22893
  projectsFixed: "exchange: the request names projects other than the one its entry gives",
22877
22894
  projectsNoPerson: "exchange: a token that names no person names no project",
22878
- restrictedOneProject: "exchange: a restricted member's machine login names exactly one project"
22895
+ restrictedOneProject: "exchange: a restricted member's machine login names exactly one project",
22896
+ restrictedSignIn: "exchange: a restricted member's Dispatch sign-in is given no token"
22879
22897
  };
22880
22898
  function policy(sentinel, format, ...slots) {
22881
22899
  return `${escapeRegExp(`The subject token was refused: ${POLICY_SENTINELS[sentinel]}: `)}${formatPattern(format, slots)}\\.`;
@@ -22914,6 +22932,7 @@ var POLICY_REFUSAL_PATTERNS = [
22914
22932
  policy("projectsFixed", "%s writes the project %s that its entry names, and the request named %s", IDENTITY, PROJECT_SLOT, PROJECT_LIST),
22915
22933
  policy("projectsFixed", "%s's entry gives its token the projects %s, and the request named %s, which that list does not name", IDENTITY, JOB_LIST, PROJECT_SLOT),
22916
22934
  policy("restrictedOneProject", "%s is a restricted member, who sees only the projects that name them, and the trade asked for %d; set AGENT_SECRETS_PROJECTS to the one project this session works on", PERSON_SLOT, NUMBER),
22935
+ policy("restrictedSignIn", "%s is a restricted member, whose machine's token is held to one project, and a Dispatch sign-in acts in every project its person may reach; sign in to Dispatch in a browser instead", PERSON_SLOT),
22917
22936
  `${escapeRegExp("The subject token was refused: ")}${formatPattern("the subject token was not minted for %s, which is the audience this broker accepts from %s", [URI, URI])}\\.`
22918
22937
  ];
22919
22938
  var KNOWN_BROKER_REFUSAL_PATTERNS = [
@@ -22945,6 +22964,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
22945
22964
  "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
22946
22965
  "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
22947
22966
  "The scope 'read' narrows a token to reading, and a job entry's token is minted whole, with no scope: ask for it without that scope\\.",
22967
+ "A Dispatch sign-in is minted whole with its approved scopes and cannot trade for 'read'\\.",
22948
22968
  "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
22949
22969
  `${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\\.`,
22950
22970
  `${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\\.`,
@@ -22954,6 +22974,10 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
22954
22974
  "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\\.",
22955
22975
  "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\\.",
22956
22976
  "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\\.",
22977
+ "this broker serves no Dispatch sign-in: BROKER_DISPATCH_SIGNIN is off",
22978
+ `the scope "${SCOPE_WORD}" is not consentable; a Dispatch sign-in may approve only ${SCOPE_LIST}`,
22979
+ "a machine login's launcher_credential detail carries no actions member, not even an empty list",
22980
+ "a device login names exactly one scope, machine or dispatch",
22957
22981
  ...POLICY_REFUSAL_PATTERNS
22958
22982
  ].map((source) => new RegExp(`^${source}$`));
22959
22983
  var LIBRARY_DESCRIPTIONS = [
@@ -23250,14 +23274,26 @@ class SignInEndedError extends Error {
23250
23274
  }
23251
23275
  }
23252
23276
  var DEVICE_LOGIN_COMMAND = "dispatch login --device";
23277
+ function deviceLoginCommand(dispatchScopes) {
23278
+ if (dispatchScopes === null)
23279
+ return DEVICE_LOGIN_COMMAND;
23280
+ return `${DEVICE_LOGIN_COMMAND} --scope ${dispatchScopes.join(",") || "none"}`;
23281
+ }
23253
23282
 
23254
23283
  class DeviceLoginEndedError extends Error {
23255
- constructor(login) {
23256
- super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${DEVICE_LOGIN_COMMAND}`);
23284
+ constructor(login, command) {
23285
+ super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${command}`);
23257
23286
  this.name = "DeviceLoginEndedError";
23258
23287
  }
23259
23288
  }
23260
23289
 
23290
+ class DeviceLoginReplacedError extends Error {
23291
+ constructor(file, command) {
23292
+ super(`${file} holds another login than the one this process started with, since ${command} ran again; start a new session to trade the new one: the secrets broker keeps a session's name for the principal that wrote under it, and each Dispatch sign-in is a principal of its own, as is each person's machine login, so this session started again is refused, except where a machine login replaced the same person's machine login, which this process cannot tell, since the login file names no person`);
23293
+ this.name = "DeviceLoginReplacedError";
23294
+ }
23295
+ }
23296
+
23261
23297
  class LockHeldError extends Error {
23262
23298
  constructor(lock, options) {
23263
23299
  super(`another process of this machine held ${lock} for all of this trade's time, so nothing was sent to the secrets broker`, options);
@@ -23265,7 +23301,7 @@ class LockHeldError extends Error {
23265
23301
  }
23266
23302
  }
23267
23303
  function isFinalRefusal(error) {
23268
- return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
23304
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError || error instanceof DeviceLoginReplacedError;
23269
23305
  }
23270
23306
 
23271
23307
  // ../envoy-client/src/envoy-config.ts
@@ -33555,6 +33591,7 @@ async function whoamiCommand(context) {
33555
33591
  const projectScope = identity.kind === "agent" ? identity.project_scope ?? null : null;
33556
33592
  const readOnly = identity.scopes?.includes("read") === true;
33557
33593
  const cut = identity.kind === "agent" ? identity.cut ?? null : null;
33594
+ const scopes = identity.scopes ?? null;
33558
33595
  const session = proved ?? sessionId;
33559
33596
  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.";
33560
33597
  const brokerService = owner === null && service !== null && proved !== null;
@@ -33580,9 +33617,10 @@ async function whoamiCommand(context) {
33580
33617
  acting = `Session ${session} runs under the shared token: ${unowned}`;
33581
33618
  }
33582
33619
  const projectSentence = readOnly ? "" : project !== null ? ` Its token names project ${project}.` : writesAsService ? " It names no one project, so it may write wherever a token that names no project may." : "";
33620
+ const holds = scopes === null ? "" : scopes.length === 0 ? " Its credential holds no scope." : ` Its credential holds the ${scopes.length === 1 ? "scope" : "scopes"} ${scopes.join(", ")}.`;
33583
33621
  return {
33584
- text: acting + elsewhere + projectSentence,
33585
- details: { session, owner, service, project, project_scope: projectScope }
33622
+ text: acting + elsewhere + projectSentence + holds,
33623
+ details: { session, owner, service, project, project_scope: projectScope, scopes }
33586
33624
  };
33587
33625
  }
33588
33626
  async function limitsCommand(context) {
@@ -33669,12 +33707,17 @@ function inboxThreadLine(row, now) {
33669
33707
  function credentialRequestLine(request) {
33670
33708
  const session = request.session ?? null;
33671
33709
  const pending = awaitsDecision(request);
33710
+ const asked = signInScopes(request);
33711
+ const reason = request.reason ?? "";
33672
33712
  return [
33673
- `- ${request.kind}`,
33713
+ asked === null ? `- ${request.kind}` : "- Dispatch sign-in",
33674
33714
  (request.identifiers ?? []).join(", "),
33715
+ ...asked === null ? [] : [`asks for ${asked.join(", ") || "no scope"}`],
33675
33716
  request.requested_at,
33676
33717
  ...pending ? [] : [request.expires_at === undefined ? "expired" : `expired ${request.expires_at}`],
33677
- ...session === null ? [] : [`session request=${session.request ?? "-"}, enrollment=${session.enrollment ?? "-"}`],
33718
+ ...asked !== null ? [
33719
+ reason === "" ? "gives no reason" : `requester's words (unchecked): ${JSON.stringify(reason)}`
33720
+ ] : session === null ? [] : [`session request=${session.request ?? "-"}, enrollment=${session.enrollment ?? "-"}`],
33678
33721
  ...!pending || request.approve_url === undefined ? [] : [request.approve_url]
33679
33722
  ].join(" \xB7 ");
33680
33723
  }
@@ -36645,6 +36688,16 @@ function wholeMember(json, name) {
36645
36688
  const value = json[name];
36646
36689
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
36647
36690
  }
36691
+ function scopesMember(json, name) {
36692
+ if (!Object.hasOwn(json, name))
36693
+ return null;
36694
+ const value = json[name];
36695
+ const consentable = DISPATCH_SIGN_IN_SCOPES;
36696
+ if (!Array.isArray(value) || new Set(value).size !== value.length || value.some((scope) => !consentable.includes(scope))) {
36697
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: ${name}, where it is given, is a list of distinct Dispatch scopes a sign-in may hold (${DISPATCH_SIGN_IN_SCOPES.join(", ")}); make the Dispatch sign-in again with: ${DEVICE_LOGIN_COMMAND} --scope <list>`);
36698
+ }
36699
+ return value;
36700
+ }
36648
36701
  function checkPrivate(info, what, forbidden, opens, notOwned) {
36649
36702
  const mode = info.mode & 511;
36650
36703
  if ((mode & forbidden) !== 0) {
@@ -36991,6 +37044,7 @@ async function readDeviceLogin(path) {
36991
37044
  if (key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
36992
37045
  throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a P-256 key`);
36993
37046
  }
37047
+ const dispatchScopes = scopesMember(json, "dispatch_scopes");
36994
37048
  const accessToken = member(json, "access_token");
36995
37049
  const accessText = member(json, "access_expires_at");
36996
37050
  const accessExpiresAt = accessToken === "" || accessText === "" ? null : new Date(accessText);
@@ -37003,7 +37057,8 @@ async function readDeviceLogin(path) {
37003
37057
  broker,
37004
37058
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
37005
37059
  accessExpiresAt: accessUsable ? accessExpiresAt : null,
37006
- accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
37060
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null,
37061
+ dispatchScopes
37007
37062
  };
37008
37063
  }
37009
37064
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -37034,6 +37089,7 @@ async function saveDeviceLogin(path, login, held, keep = false) {
37034
37089
  refresh_token: login.refreshToken,
37035
37090
  expires_at: login.expiresAt.toISOString(),
37036
37091
  broker: login.broker,
37092
+ ...login.dispatchScopes === null ? {} : { dispatch_scopes: login.dispatchScopes },
37037
37093
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
37038
37094
  access_token: login.accessToken,
37039
37095
  access_expires_at: login.accessExpiresAt.toISOString(),
@@ -37139,6 +37195,28 @@ function unpollableAnswer(answered, intervalSeconds, lifetimeSeconds, left) {
37139
37195
  return `${answer}: ${lapses}; ${verdict} ${remedy}`;
37140
37196
  }
37141
37197
 
37198
+ // ../cipher-client/src/device-login-scopes.ts
37199
+ function signInScopes2(scopes) {
37200
+ const consentable = DISPATCH_SIGN_IN_SCOPES;
37201
+ const unique = [...new Set(scopes)].sort();
37202
+ if (unique.some((scope) => !consentable.includes(scope))) {
37203
+ throw new RangeError(`a Dispatch sign-in may ask only for these scopes: ${DISPATCH_SIGN_IN_SCOPES.join(", ")}`);
37204
+ }
37205
+ return unique;
37206
+ }
37207
+ function signInScopesOf(answered, asked, exact) {
37208
+ const named = answered["dispatch_scopes"];
37209
+ if (answered.scope !== DISPATCH_LOGIN_SCOPE || !Array.isArray(named))
37210
+ return;
37211
+ const askedFor = asked;
37212
+ if (new Set(named).size !== named.length || named.some((scope) => !askedFor.includes(scope))) {
37213
+ return;
37214
+ }
37215
+ if (exact && named.length !== asked.length)
37216
+ return;
37217
+ return named;
37218
+ }
37219
+
37142
37220
  // ../cipher-client/src/dpop.ts
37143
37221
  import {
37144
37222
  createHash as createHash2,
@@ -37233,6 +37311,7 @@ function endsGrant(error) {
37233
37311
 
37234
37312
  // ../cipher-client/src/device-login.ts
37235
37313
  var BROKER_SETTING = "AGENT_SECRETS_URL";
37314
+ var NO_DISPATCH_SIGN_IN = "this broker serves no Dispatch sign-in: it predates them, or BROKER_DISPATCH_SIGNIN is off";
37236
37315
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
37237
37316
  function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
37238
37317
  if (leastLifeMs === undefined || lifeSeconds === null)
@@ -37317,6 +37396,11 @@ async function startDeviceLogin(options) {
37317
37396
  const brokerUrl = deviceLoginBroker(options.brokerUrl);
37318
37397
  const endpoint = brokerUrl + DEVICE_AUTHORIZATION_PATH;
37319
37398
  const person = options.person.trim();
37399
+ const dispatchScopes = options.dispatchScopes === undefined ? null : signInScopes2(options.dispatchScopes);
37400
+ if (options.reason !== undefined && Array.from(options.reason).length > BROKER_REQUEST_REASON_MAX) {
37401
+ throw new RangeError(`a device login's reason has at most ${BROKER_REQUEST_REASON_MAX} characters`);
37402
+ }
37403
+ const describe = dispatchScopes === null ? "this machine's device login" : "this Dispatch sign-in";
37320
37404
  const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
37321
37405
  const jwk = loginDpopKey(privateKey).publicJwk;
37322
37406
  const thumbprint = await calculateJwkThumbprint(jwk);
@@ -37327,20 +37411,31 @@ async function startDeviceLogin(options) {
37327
37411
  jti: randomUUID5(),
37328
37412
  iat,
37329
37413
  exp: iat + REQUEST_OBJECT_LIFETIME_SECONDS,
37330
- authorization_details: [{ type: LAUNCHER_CREDENTIAL_DETAIL, identifier: options.host }],
37331
- login_hint: person
37414
+ authorization_details: [
37415
+ {
37416
+ type: LAUNCHER_CREDENTIAL_DETAIL,
37417
+ identifier: options.host,
37418
+ ...dispatchScopes === null ? {} : { actions: dispatchScopes }
37419
+ }
37420
+ ],
37421
+ login_hint: person,
37422
+ ...options.reason === undefined ? {} : { reason: options.reason }
37332
37423
  };
37333
37424
  const request = await new CompactSign(new TextEncoder().encode(JSON.stringify(claims))).setProtectedHeader({ alg: "ES256", typ: REQUEST_OBJECT_TYPE, jwk }).sign(privateKey);
37334
37425
  const config = brokerConfiguration(brokerUrl, options.fetch ?? fetch);
37335
37426
  let answered;
37336
37427
  try {
37337
37428
  answered = await initiateDeviceAuthorization(config, {
37338
- scope: MACHINE_LOGIN_SCOPE,
37429
+ scope: dispatchScopes === null ? MACHINE_LOGIN_SCOPE : DISPATCH_LOGIN_SCOPE,
37339
37430
  dpop_jkt: thumbprint,
37340
37431
  request
37341
37432
  });
37342
37433
  } catch (error) {
37343
- throw brokerRefusal("ask for a code for", "this machine's device login", endpoint, error);
37434
+ const refusal = brokerRefusal("ask for a code for", describe, endpoint, error);
37435
+ if (dispatchScopes !== null && refusal instanceof BrokerRefusedError && refusal.status === 400 && refusal.code === "invalid_scope" && (refusal.said === "" || refusal.said === REFUSAL_TEXT_WITHHELD)) {
37436
+ throw new Error(`the secrets broker refused ${describe}: HTTP 400 invalid_scope: ${NO_DISPATCH_SIGN_IN}`);
37437
+ }
37438
+ throw refusal;
37344
37439
  }
37345
37440
  const intervalSeconds = Math.max(answered.interval ?? DEFAULT_POLL_SECONDS, LEAST_POLL_SECONDS);
37346
37441
  const lifetimeSeconds = Math.min(answered.expires_in, MOST_LIFETIME_SECONDS);
@@ -37360,7 +37455,9 @@ async function startDeviceLogin(options) {
37360
37455
  expiresAt,
37361
37456
  intervalSeconds,
37362
37457
  deviceCode: holdSecret(answered.device_code, expiresAt),
37363
- key: privateKey
37458
+ key: privateKey,
37459
+ dispatchScopes,
37460
+ describe
37364
37461
  };
37365
37462
  }
37366
37463
  function retryAfterMs2(error) {
@@ -37381,9 +37478,11 @@ async function finishDeviceLogin(started, options) {
37381
37478
  nonce: { value: "" }
37382
37479
  });
37383
37480
  const endpoint = started.brokerUrl + TOKEN_PATH;
37481
+ const again = deviceLoginCommand(started.dispatchScopes);
37482
+ const revoke = `Machine logins on ${started.verificationUri}`;
37384
37483
  const expired = (outages) => {
37385
37484
  const unreached = outages === 0 ? "" : `; the broker was unreachable or busy for the last ${outages === 1 ? "poll" : `${outages} polls`}`;
37386
- return new Error(`the code ${started.userCode} expired before ${started.person} approved this machine${unreached}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
37485
+ return new Error(`the code ${started.userCode} expired before ${started.person} approved ${started.describe}${unreached}; ask again with: ${again}`);
37387
37486
  };
37388
37487
  let interval = started.intervalSeconds;
37389
37488
  let outages = 0;
@@ -37392,7 +37491,7 @@ async function finishDeviceLogin(started, options) {
37392
37491
  if (!reached) {
37393
37492
  const first = `its first poll, ${seconds(pastTheMillisecond(interval) ? waitMs / 1000 : interval)} s on`;
37394
37493
  const lapse = leftAtStart <= 0 ? `had lapsed before ${first}` : named > leftAtStart ? `would lapse here before ${first}, as this machine polls a device code for an hour at most` : `lapses in ${seconds(leftAtStart / 1000)} s, no later than ${first}`;
37395
- throw new Error(`the code ${started.userCode} ${lapse}, so no poll could reach it; ask again with: ${DEVICE_LOGIN_COMMAND}`);
37494
+ throw new Error(`the code ${started.userCode} ${lapse}, so no poll could reach it; ask again with: ${again}`);
37396
37495
  }
37397
37496
  const endsAt = clock() + leftAtStart;
37398
37497
  while (true) {
@@ -37412,7 +37511,7 @@ async function finishDeviceLogin(started, options) {
37412
37511
  } catch (error) {
37413
37512
  const code = refusalCode(error);
37414
37513
  if (code === "access_denied") {
37415
- throw new Error(`this machine's device login was denied, not approved as ${started.person}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
37514
+ throw new Error(`${started.describe} was denied, not approved as ${started.person}; ask again with: ${again}`);
37416
37515
  }
37417
37516
  if (code === "expired_token" || code === "invalid_grant")
37418
37517
  throw expired(0);
@@ -37423,14 +37522,23 @@ async function finishDeviceLogin(started, options) {
37423
37522
  interval += 5;
37424
37523
  const pollAgain = code === "authorization_pending" || code === "slow_down" || unanswered;
37425
37524
  if (!pollAgain) {
37426
- const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
37427
- throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
37525
+ const refusal = brokerRefusal("poll the code of", started.describe, endpoint, error);
37526
+ throw new Error(`${refusal.message}; ask again with: ${again}`);
37428
37527
  }
37429
37528
  const asked = unanswered ? retryAfterMs2(error) : 0;
37430
37529
  waitMs = Math.max(waitMillisecondsOf(interval), asked);
37431
37530
  continue;
37432
37531
  }
37433
- const login = loginOf(started.key, started.brokerUrl, answered, Date.now());
37532
+ const issued = loginOf(started.key, started.brokerUrl, answered, Date.now());
37533
+ let dispatchScopes = null;
37534
+ if (started.dispatchScopes !== null) {
37535
+ const approved = signInScopesOf(answered, started.dispatchScopes, false);
37536
+ if (approved === undefined) {
37537
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered ${started.describe} with no scope dispatch, or with dispatch_scopes that are not distinct scopes it asked for, as a broker too old for Dispatch sign-ins does. It may hold the sign-in live as launcher credential ${issued.credentialId}; revoke it in ${revoke}, then log in again with: ${again}`);
37538
+ }
37539
+ dispatchScopes = approved;
37540
+ }
37541
+ const login = { ...issued, dispatchScopes };
37434
37542
  let replaced = "";
37435
37543
  let saved = false;
37436
37544
  try {
@@ -37444,8 +37552,7 @@ async function finishDeviceLogin(started, options) {
37444
37552
  const lockLeft = `this process could not let go of the lock beside ${DEVICE_LOGIN_FILE_NAMED} (${messageOf(error)}); another process takes it over once it is ${DEVICE_LOGIN_STALE_LOCK_MS / 1000} s old`;
37445
37553
  return { ...login, replaced, lockLeft };
37446
37554
  }
37447
- const revoke = `Machine logins on ${started.verificationUri}`;
37448
- throw new Error(error instanceof KeptCopyError ? `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it in its place: ${messageOf(error)}, which then needs no revoke. Where the copy is not used, delete it, since it holds the login's key and refresh token, and revoke the credential in ${revoke}: it stays live until it lapses or is revoked` : `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it: ${messageOf(error)}. The credential stays live until it lapses or is revoked: revoke it in ${revoke}, and log in again with: ${DEVICE_LOGIN_COMMAND}`, { cause: error });
37555
+ throw new Error(error instanceof KeptCopyError ? `${started.person} approved ${started.describe}, launcher credential ${login.credentialId}, but this machine could not keep it in its place: ${messageOf(error)}, which then needs no revoke. Where the copy is not used, delete it, since it holds the login's key and refresh token, and revoke the credential in ${revoke}: it stays live until it lapses or is revoked` : `${started.person} approved ${started.describe}, launcher credential ${login.credentialId}, but this machine could not keep it: ${messageOf(error)}. The credential stays live until it lapses or is revoked: revoke it in ${revoke}, and log in again with: ${again}`, { cause: error });
37449
37556
  }
37450
37557
  return { ...login, replaced, lockLeft: "" };
37451
37558
  }
@@ -37487,10 +37594,10 @@ class DeviceLoginIdentity {
37487
37594
  return await withDeviceLoginLock(this.#path, async (held) => {
37488
37595
  let login = await readDeviceLogin(this.#path);
37489
37596
  if (withoutTrailingSlashes(login.broker) !== this.#brokerUrl) {
37490
- throw new Error(`${DEVICE_LOGIN_FILE_NAMED} was made at another secrets broker than ${BROKER_SETTING} names; log this machine in at this one with: ${DEVICE_LOGIN_COMMAND}`);
37597
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED} was made at another secrets broker than ${BROKER_SETTING} names; log in at this one again with: ${deviceLoginCommand(login.dispatchScopes)}`);
37491
37598
  }
37492
37599
  if (await calculateJwkThumbprint(loginDpopKey(login.key).publicJwk) !== thumbprint) {
37493
- throw new Error(`${DEVICE_LOGIN_FILE_NAMED} holds another login than the one this process started with, since ${DEVICE_LOGIN_COMMAND} ran again; start this session again to trade the new one`);
37600
+ throw new DeviceLoginReplacedError(DEVICE_LOGIN_FILE_NAMED, DEVICE_LOGIN_COMMAND);
37494
37601
  }
37495
37602
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
37496
37603
  const expires = login.accessExpiresAt?.getTime() ?? 0;
@@ -37533,14 +37640,30 @@ async function refreshDeviceLogin(path, login, options) {
37533
37640
  refresh_token: login.refreshToken
37534
37641
  });
37535
37642
  } catch (error) {
37536
- if (endsGrant(error))
37537
- throw new DeviceLoginEndedError(options.describe);
37643
+ if (endsGrant(error)) {
37644
+ throw new DeviceLoginEndedError(options.describe, deviceLoginCommand(login.dispatchScopes));
37645
+ }
37538
37646
  if (sent === 0 && statusOf(error) === 0)
37539
37647
  continue;
37540
37648
  throw brokerRefusal("refresh", options.describe, endpoint, error);
37541
37649
  }
37542
37650
  }
37543
- const next = loginOf(login.key, login.broker, answered, Date.now());
37651
+ const issued = loginOf(login.key, login.broker, answered, Date.now());
37652
+ let dispatchScopes = null;
37653
+ if (login.dispatchScopes !== null) {
37654
+ const kept = signInScopesOf(answered, login.dispatchScopes, true);
37655
+ if (kept === undefined) {
37656
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered the refresh of a Dispatch sign-in without the scope dispatch and the scopes its person approved (${login.dispatchScopes.join(", ") || "none"}). The sign-in stays live; revoke it in Dispatch's Machine logins page, then log in again with: ${deviceLoginCommand(login.dispatchScopes)}`);
37657
+ }
37658
+ dispatchScopes = kept;
37659
+ } else if (answered.scope === DISPATCH_LOGIN_SCOPE) {
37660
+ const kept = signInScopesOf(answered, DISPATCH_SIGN_IN_SCOPES, false);
37661
+ if (kept === undefined) {
37662
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered the refresh under the scope dispatch, so this is a Dispatch sign-in, with dispatch_scopes that are not distinct scopes a sign-in may hold, and ${DEVICE_LOGIN_FILE_NAMED} names none its person approved. The sign-in stays live; revoke it in Dispatch's Machine logins page, then log in again with: ${DEVICE_LOGIN_COMMAND} --scope <the scopes to approve>`);
37663
+ }
37664
+ dispatchScopes = kept;
37665
+ }
37666
+ const next = { ...issued, dispatchScopes };
37544
37667
  await saveDeviceLogin(path, next, options.held);
37545
37668
  return next;
37546
37669
  }
@@ -38639,6 +38762,10 @@ function tradeFailureReason(error) {
38639
38762
  return error.message;
38640
38763
  if (error instanceof SignInEndedError)
38641
38764
  return `the issuer no longer honours the sign-in on this machine; run: ${SIGNIN_COMMAND}`;
38765
+ if (error instanceof DeviceLoginEndedError)
38766
+ return scrub(error.message);
38767
+ if (error instanceof DeviceLoginReplacedError)
38768
+ return scrub(error.message);
38642
38769
  return natsFailureReason(error);
38643
38770
  }
38644
38771
  function isDeadline(error) {
@@ -38806,18 +38933,22 @@ function brokerTokenRefusals(token) {
38806
38933
  }
38807
38934
  };
38808
38935
  }
38809
- function warnedEvery(warn) {
38936
+ function warnedEvery(warn, options = {}) {
38810
38937
  let warnedAt;
38938
+ let warnedText;
38811
38939
  return {
38812
38940
  warn: (text) => {
38813
38941
  const now = Date.now();
38814
- if (warnedAt !== undefined && now - warnedAt < WARN_AGAIN_MS)
38942
+ const held = options.newTextAtOnce !== true || text === warnedText;
38943
+ if (held && warnedAt !== undefined && now - warnedAt < WARN_AGAIN_MS)
38815
38944
  return;
38816
38945
  warnedAt = now;
38946
+ warnedText = text;
38817
38947
  warn(text);
38818
38948
  },
38819
38949
  reset: () => {
38820
38950
  warnedAt = undefined;
38951
+ warnedText = undefined;
38821
38952
  }
38822
38953
  };
38823
38954
  }
@@ -38831,6 +38962,7 @@ function keepNatsCredential(connection, credential, warn) {
38831
38962
  let renewing = false;
38832
38963
  let renewAgain = false;
38833
38964
  const renewal = warnedEvery((why) => warn(`the NATS connection's broker token ${why}; it is tried again, and the connection reconnects once a token is live`));
38965
+ const ended = warnedEvery((why) => warn(`the NATS connection's broker token ${why}; no renewal cures it, so once the token in hand lapses the NATS server refuses each redial of the connection while the refusal lasts`), { newTextAtOnce: true });
38834
38966
  const refusal = warnedEvery(warn);
38835
38967
  const statuses = connection.status();
38836
38968
  const stop = () => {
@@ -38865,7 +38997,7 @@ function keepNatsCredential(connection, credential, warn) {
38865
38997
  schedule(0);
38866
38998
  return;
38867
38999
  }
38868
- renewal.warn(`could not be renewed (${tradeFailureReason(error)})`);
39000
+ (isFinalRefusal(error) ? ended : renewal).warn(`could not be renewed (${tradeFailureReason(error)})`);
38869
39001
  retry();
38870
39002
  return;
38871
39003
  }
@@ -38876,6 +39008,7 @@ function keepNatsCredential(connection, credential, warn) {
38876
39008
  }
38877
39009
  retries = 0;
38878
39010
  renewal.reset();
39011
+ ended.reset();
38879
39012
  schedule(renewDelay(credential.expiresAt().getTime(), Date.now()));
38880
39013
  };
38881
39014
  const tick = async () => {