@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.
package/dist/dispatch.js CHANGED
@@ -14319,6 +14319,8 @@ var ActorOriginSchema = strictObject({
14319
14319
  session_title: string2().optional()
14320
14320
  }).readonly();
14321
14321
  var DISPATCH_SCOPES = ["person", "approve", "p0"];
14322
+ var DISPATCH_SIGN_IN_SCOPES = ["person", "p0"];
14323
+ var BROKER_REQUEST_REASON_MAX = 400;
14322
14324
  var ActorActSchema = strictObject({
14323
14325
  session: string2().optional(),
14324
14326
  session_proven: literal(true).optional(),
@@ -15896,7 +15898,7 @@ var dispatchToolSpecs = [
15896
15898
  {
15897
15899
  name: "dispatch_whoami",
15898
15900
  example: {},
15899
- 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.",
15901
+ 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.",
15900
15902
  arguments: () => ({}),
15901
15903
  strict: true
15902
15904
  },
@@ -16532,6 +16534,9 @@ function inboxThreadRow(row) {
16532
16534
  function awaitsDecision(row) {
16533
16535
  return row.state !== "expired";
16534
16536
  }
16537
+ function signInScopes(row) {
16538
+ return Array.isArray(row.dispatch_scopes) ? row.dispatch_scopes : null;
16539
+ }
16535
16540
  // ../contracts/src/dispatch-api-messages.ts
16536
16541
  var messageDeliveryFields = {
16537
16542
  message_id: string2(),
@@ -17815,7 +17820,12 @@ var DISPATCH_READING_SURFACES = [
17815
17820
  surface: "change-view-diff"
17816
17821
  },
17817
17822
  {
17818
- files: ["packages/dispatch/web/src/features/credentials/CredentialRecordFacts.tsx"],
17823
+ files: [
17824
+ "packages/dispatch/web/src/features/credentials/CredentialRecordFacts.tsx",
17825
+ "packages/dispatch/web/src/features/credentials/CredentialRequestsSection.tsx",
17826
+ "packages/dispatch/web/src/features/credentials/MachineLoginPage.tsx",
17827
+ "packages/dispatch/web/src/features/credentials/MachineLoginsSection.tsx"
17828
+ ],
17819
17829
  reach: "/credentials/machine, a machine login request's reason",
17820
17830
  reason: `A credential request's reason is what the asking agent typed for it. ${ONE_LINE_FIELD_REASON}`,
17821
17831
  record: false,
@@ -21078,21 +21088,25 @@ var LOGIN_COMMAND = "login";
21078
21088
  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.";
21079
21089
  function loginHelp() {
21080
21090
  return [
21081
- "Usage: dispatch login --device [--person <address>]",
21091
+ "Usage: dispatch login --device [--person <address>] [--scope <list>] [--reason <text>]",
21082
21092
  "",
21083
- `${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.`,
21093
+ `${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.`,
21084
21094
  "",
21085
21095
  "Flags:",
21086
21096
  " --device",
21087
21097
  " Log in with the broker's device grant: the only way there is, and required.",
21088
21098
  " --person <address>",
21089
21099
  " The person who approves the login, by the address they sign in to Dispatch with; else AGENT_SECRETS_PERSON.",
21100
+ " --scope <list>",
21101
+ " Create a Dispatch sign-in for the comma-separated scopes person, p0, or none. Omit it for a machine login.",
21102
+ " --reason <text>",
21103
+ " Name the session or tool. It may have at most 400 characters.",
21090
21104
  "",
21091
21105
  "It reads AGENT_SECRETS_URL, the broker, and needs no Dispatch host or session.",
21092
21106
  "",
21093
21107
  "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.",
21094
21108
  "",
21095
- "Example: dispatch login --device --person ada@example.com",
21109
+ "Example: dispatch login --device --person ada@example.com --scope person",
21096
21110
  ""
21097
21111
  ].join(`
21098
21112
  `);
@@ -22078,6 +22092,7 @@ var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
22078
22092
  var GRANT_TYPE_REFRESH = "refresh_token";
22079
22093
  var MACHINE_LOGIN_CLIENT_ID = "agent-secrets-helper";
22080
22094
  var MACHINE_LOGIN_SCOPE = "machine";
22095
+ var DISPATCH_LOGIN_SCOPE = "dispatch";
22081
22096
  var REQUEST_OBJECT_TYPE = "agent-secrets-request+jwt";
22082
22097
  var LAUNCHER_CREDENTIAL_DETAIL = "launcher_credential";
22083
22098
  var REQUEST_OBJECT_LIFETIME_SECONDS = 600;
@@ -22110,6 +22125,8 @@ var INSTANCE_PATTERN = "[A-Za-z0-9*?._\\[\\]-]{1,100}";
22110
22125
  var NUMBER = "[0-9]{1,6}";
22111
22126
  var CLAIM = "[A-Za-z0-9_.:-]{1,64}";
22112
22127
  var URI = "[A-Za-z0-9:/._-]{1,200}";
22128
+ var SCOPE_WORD = "[a-z][a-z0-9_-]{0,63}";
22129
+ var SCOPE_LIST = `${SCOPE_WORD}(?:, ${SCOPE_WORD}){0,7}`;
22113
22130
  var SESSION_RULE = "a session name is printable, carries no whitespace, '\\*' or '>', and is at most [0-9]{1,4} bytes";
22114
22131
  function escapeRegExp(text) {
22115
22132
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -22136,7 +22153,8 @@ var POLICY_SENTINELS = {
22136
22153
  sessionFixed: "exchange: the entry fixes the session name its tokens carry",
22137
22154
  projectsFixed: "exchange: the request names projects other than the one its entry gives",
22138
22155
  projectsNoPerson: "exchange: a token that names no person names no project",
22139
- restrictedOneProject: "exchange: a restricted member's machine login names exactly one project"
22156
+ restrictedOneProject: "exchange: a restricted member's machine login names exactly one project",
22157
+ restrictedSignIn: "exchange: a restricted member's Dispatch sign-in is given no token"
22140
22158
  };
22141
22159
  function policy(sentinel, format, ...slots) {
22142
22160
  return `${escapeRegExp(`The subject token was refused: ${POLICY_SENTINELS[sentinel]}: `)}${formatPattern(format, slots)}\\.`;
@@ -22175,6 +22193,7 @@ var POLICY_REFUSAL_PATTERNS = [
22175
22193
  policy("projectsFixed", "%s writes the project %s that its entry names, and the request named %s", IDENTITY, PROJECT_SLOT, PROJECT_LIST),
22176
22194
  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),
22177
22195
  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),
22196
+ 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),
22178
22197
  `${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])}\\.`
22179
22198
  ];
22180
22199
  var KNOWN_BROKER_REFUSAL_PATTERNS = [
@@ -22206,6 +22225,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
22206
22225
  "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
22207
22226
  "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
22208
22227
  "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\\.",
22228
+ "A Dispatch sign-in is minted whole with its approved scopes and cannot trade for 'read'\\.",
22209
22229
  "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
22210
22230
  `${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\\.`,
22211
22231
  `${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\\.`,
@@ -22215,6 +22235,10 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
22215
22235
  "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\\.",
22216
22236
  "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\\.",
22217
22237
  "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\\.",
22238
+ "this broker serves no Dispatch sign-in: BROKER_DISPATCH_SIGNIN is off",
22239
+ `the scope "${SCOPE_WORD}" is not consentable; a Dispatch sign-in may approve only ${SCOPE_LIST}`,
22240
+ "a machine login's launcher_credential detail carries no actions member, not even an empty list",
22241
+ "a device login names exactly one scope, machine or dispatch",
22218
22242
  ...POLICY_REFUSAL_PATTERNS
22219
22243
  ].map((source) => new RegExp(`^${source}$`));
22220
22244
  var LIBRARY_DESCRIPTIONS = [
@@ -22511,14 +22535,26 @@ class SignInEndedError extends Error {
22511
22535
  }
22512
22536
  }
22513
22537
  var DEVICE_LOGIN_COMMAND = "dispatch login --device";
22538
+ function deviceLoginCommand(dispatchScopes) {
22539
+ if (dispatchScopes === null)
22540
+ return DEVICE_LOGIN_COMMAND;
22541
+ return `${DEVICE_LOGIN_COMMAND} --scope ${dispatchScopes.join(",") || "none"}`;
22542
+ }
22514
22543
 
22515
22544
  class DeviceLoginEndedError extends Error {
22516
- constructor(login) {
22517
- super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${DEVICE_LOGIN_COMMAND}`);
22545
+ constructor(login, command) {
22546
+ super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${command}`);
22518
22547
  this.name = "DeviceLoginEndedError";
22519
22548
  }
22520
22549
  }
22521
22550
 
22551
+ class DeviceLoginReplacedError extends Error {
22552
+ constructor(file, command) {
22553
+ 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`);
22554
+ this.name = "DeviceLoginReplacedError";
22555
+ }
22556
+ }
22557
+
22522
22558
  class LockHeldError extends Error {
22523
22559
  constructor(lock, options) {
22524
22560
  super(`another process of this machine held ${lock} for all of this trade's time, so nothing was sent to the secrets broker`, options);
@@ -22526,7 +22562,7 @@ class LockHeldError extends Error {
22526
22562
  }
22527
22563
  }
22528
22564
  function isFinalRefusal(error) {
22529
- return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
22565
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError || error instanceof DeviceLoginReplacedError;
22530
22566
  }
22531
22567
 
22532
22568
  // ../envoy-client/src/envoy-config.ts
@@ -28308,6 +28344,16 @@ function wholeMember(json, name) {
28308
28344
  const value = json[name];
28309
28345
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
28310
28346
  }
28347
+ function scopesMember(json, name) {
28348
+ if (!Object.hasOwn(json, name))
28349
+ return null;
28350
+ const value = json[name];
28351
+ const consentable = DISPATCH_SIGN_IN_SCOPES;
28352
+ if (!Array.isArray(value) || new Set(value).size !== value.length || value.some((scope) => !consentable.includes(scope))) {
28353
+ 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>`);
28354
+ }
28355
+ return value;
28356
+ }
28311
28357
  function checkPrivate(info, what, forbidden, opens, notOwned) {
28312
28358
  const mode = info.mode & 511;
28313
28359
  if ((mode & forbidden) !== 0) {
@@ -28654,6 +28700,7 @@ async function readDeviceLogin(path) {
28654
28700
  if (key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
28655
28701
  throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a P-256 key`);
28656
28702
  }
28703
+ const dispatchScopes = scopesMember(json, "dispatch_scopes");
28657
28704
  const accessToken = member(json, "access_token");
28658
28705
  const accessText = member(json, "access_expires_at");
28659
28706
  const accessExpiresAt = accessToken === "" || accessText === "" ? null : new Date(accessText);
@@ -28666,7 +28713,8 @@ async function readDeviceLogin(path) {
28666
28713
  broker,
28667
28714
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
28668
28715
  accessExpiresAt: accessUsable ? accessExpiresAt : null,
28669
- accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
28716
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null,
28717
+ dispatchScopes
28670
28718
  };
28671
28719
  }
28672
28720
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -28697,6 +28745,7 @@ async function saveDeviceLogin(path, login, held, keep = false) {
28697
28745
  refresh_token: login.refreshToken,
28698
28746
  expires_at: login.expiresAt.toISOString(),
28699
28747
  broker: login.broker,
28748
+ ...login.dispatchScopes === null ? {} : { dispatch_scopes: login.dispatchScopes },
28700
28749
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
28701
28750
  access_token: login.accessToken,
28702
28751
  access_expires_at: login.accessExpiresAt.toISOString(),
@@ -28802,6 +28851,28 @@ function unpollableAnswer(answered, intervalSeconds, lifetimeSeconds, left) {
28802
28851
  return `${answer}: ${lapses}; ${verdict} ${remedy}`;
28803
28852
  }
28804
28853
 
28854
+ // ../cipher-client/src/device-login-scopes.ts
28855
+ function signInScopes2(scopes) {
28856
+ const consentable = DISPATCH_SIGN_IN_SCOPES;
28857
+ const unique = [...new Set(scopes)].sort();
28858
+ if (unique.some((scope) => !consentable.includes(scope))) {
28859
+ throw new RangeError(`a Dispatch sign-in may ask only for these scopes: ${DISPATCH_SIGN_IN_SCOPES.join(", ")}`);
28860
+ }
28861
+ return unique;
28862
+ }
28863
+ function signInScopesOf(answered, asked, exact) {
28864
+ const named = answered["dispatch_scopes"];
28865
+ if (answered.scope !== DISPATCH_LOGIN_SCOPE || !Array.isArray(named))
28866
+ return;
28867
+ const askedFor = asked;
28868
+ if (new Set(named).size !== named.length || named.some((scope) => !askedFor.includes(scope))) {
28869
+ return;
28870
+ }
28871
+ if (exact && named.length !== asked.length)
28872
+ return;
28873
+ return named;
28874
+ }
28875
+
28805
28876
  // ../cipher-client/src/dpop.ts
28806
28877
  import {
28807
28878
  createHash as createHash2,
@@ -28896,6 +28967,7 @@ function endsGrant(error) {
28896
28967
 
28897
28968
  // ../cipher-client/src/device-login.ts
28898
28969
  var BROKER_SETTING = "AGENT_SECRETS_URL";
28970
+ var NO_DISPATCH_SIGN_IN = "this broker serves no Dispatch sign-in: it predates them, or BROKER_DISPATCH_SIGNIN is off";
28899
28971
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
28900
28972
  function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
28901
28973
  if (leastLifeMs === undefined || lifeSeconds === null)
@@ -28980,6 +29052,11 @@ async function startDeviceLogin(options) {
28980
29052
  const brokerUrl = deviceLoginBroker(options.brokerUrl);
28981
29053
  const endpoint = brokerUrl + DEVICE_AUTHORIZATION_PATH;
28982
29054
  const person = options.person.trim();
29055
+ const dispatchScopes = options.dispatchScopes === undefined ? null : signInScopes2(options.dispatchScopes);
29056
+ if (options.reason !== undefined && Array.from(options.reason).length > BROKER_REQUEST_REASON_MAX) {
29057
+ throw new RangeError(`a device login's reason has at most ${BROKER_REQUEST_REASON_MAX} characters`);
29058
+ }
29059
+ const describe = dispatchScopes === null ? "this machine's device login" : "this Dispatch sign-in";
28983
29060
  const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
28984
29061
  const jwk = loginDpopKey(privateKey).publicJwk;
28985
29062
  const thumbprint = await calculateJwkThumbprint(jwk);
@@ -28990,20 +29067,31 @@ async function startDeviceLogin(options) {
28990
29067
  jti: randomUUID5(),
28991
29068
  iat,
28992
29069
  exp: iat + REQUEST_OBJECT_LIFETIME_SECONDS,
28993
- authorization_details: [{ type: LAUNCHER_CREDENTIAL_DETAIL, identifier: options.host }],
28994
- login_hint: person
29070
+ authorization_details: [
29071
+ {
29072
+ type: LAUNCHER_CREDENTIAL_DETAIL,
29073
+ identifier: options.host,
29074
+ ...dispatchScopes === null ? {} : { actions: dispatchScopes }
29075
+ }
29076
+ ],
29077
+ login_hint: person,
29078
+ ...options.reason === undefined ? {} : { reason: options.reason }
28995
29079
  };
28996
29080
  const request = await new CompactSign(new TextEncoder().encode(JSON.stringify(claims))).setProtectedHeader({ alg: "ES256", typ: REQUEST_OBJECT_TYPE, jwk }).sign(privateKey);
28997
29081
  const config = brokerConfiguration(brokerUrl, options.fetch ?? fetch);
28998
29082
  let answered;
28999
29083
  try {
29000
29084
  answered = await initiateDeviceAuthorization(config, {
29001
- scope: MACHINE_LOGIN_SCOPE,
29085
+ scope: dispatchScopes === null ? MACHINE_LOGIN_SCOPE : DISPATCH_LOGIN_SCOPE,
29002
29086
  dpop_jkt: thumbprint,
29003
29087
  request
29004
29088
  });
29005
29089
  } catch (error) {
29006
- throw brokerRefusal("ask for a code for", "this machine's device login", endpoint, error);
29090
+ const refusal = brokerRefusal("ask for a code for", describe, endpoint, error);
29091
+ if (dispatchScopes !== null && refusal instanceof BrokerRefusedError && refusal.status === 400 && refusal.code === "invalid_scope" && (refusal.said === "" || refusal.said === REFUSAL_TEXT_WITHHELD)) {
29092
+ throw new Error(`the secrets broker refused ${describe}: HTTP 400 invalid_scope: ${NO_DISPATCH_SIGN_IN}`);
29093
+ }
29094
+ throw refusal;
29007
29095
  }
29008
29096
  const intervalSeconds = Math.max(answered.interval ?? DEFAULT_POLL_SECONDS, LEAST_POLL_SECONDS);
29009
29097
  const lifetimeSeconds = Math.min(answered.expires_in, MOST_LIFETIME_SECONDS);
@@ -29023,7 +29111,9 @@ async function startDeviceLogin(options) {
29023
29111
  expiresAt,
29024
29112
  intervalSeconds,
29025
29113
  deviceCode: holdSecret(answered.device_code, expiresAt),
29026
- key: privateKey
29114
+ key: privateKey,
29115
+ dispatchScopes,
29116
+ describe
29027
29117
  };
29028
29118
  }
29029
29119
  function retryAfterMs2(error) {
@@ -29044,9 +29134,11 @@ async function finishDeviceLogin(started, options) {
29044
29134
  nonce: { value: "" }
29045
29135
  });
29046
29136
  const endpoint = started.brokerUrl + TOKEN_PATH;
29137
+ const again = deviceLoginCommand(started.dispatchScopes);
29138
+ const revoke = `Machine logins on ${started.verificationUri}`;
29047
29139
  const expired = (outages) => {
29048
29140
  const unreached = outages === 0 ? "" : `; the broker was unreachable or busy for the last ${outages === 1 ? "poll" : `${outages} polls`}`;
29049
- return new Error(`the code ${started.userCode} expired before ${started.person} approved this machine${unreached}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
29141
+ return new Error(`the code ${started.userCode} expired before ${started.person} approved ${started.describe}${unreached}; ask again with: ${again}`);
29050
29142
  };
29051
29143
  let interval = started.intervalSeconds;
29052
29144
  let outages = 0;
@@ -29055,7 +29147,7 @@ async function finishDeviceLogin(started, options) {
29055
29147
  if (!reached) {
29056
29148
  const first = `its first poll, ${seconds(pastTheMillisecond(interval) ? waitMs / 1000 : interval)} s on`;
29057
29149
  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}`;
29058
- throw new Error(`the code ${started.userCode} ${lapse}, so no poll could reach it; ask again with: ${DEVICE_LOGIN_COMMAND}`);
29150
+ throw new Error(`the code ${started.userCode} ${lapse}, so no poll could reach it; ask again with: ${again}`);
29059
29151
  }
29060
29152
  const endsAt = clock() + leftAtStart;
29061
29153
  while (true) {
@@ -29075,7 +29167,7 @@ async function finishDeviceLogin(started, options) {
29075
29167
  } catch (error) {
29076
29168
  const code = refusalCode(error);
29077
29169
  if (code === "access_denied") {
29078
- throw new Error(`this machine's device login was denied, not approved as ${started.person}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
29170
+ throw new Error(`${started.describe} was denied, not approved as ${started.person}; ask again with: ${again}`);
29079
29171
  }
29080
29172
  if (code === "expired_token" || code === "invalid_grant")
29081
29173
  throw expired(0);
@@ -29086,14 +29178,23 @@ async function finishDeviceLogin(started, options) {
29086
29178
  interval += 5;
29087
29179
  const pollAgain = code === "authorization_pending" || code === "slow_down" || unanswered;
29088
29180
  if (!pollAgain) {
29089
- const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
29090
- throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
29181
+ const refusal = brokerRefusal("poll the code of", started.describe, endpoint, error);
29182
+ throw new Error(`${refusal.message}; ask again with: ${again}`);
29091
29183
  }
29092
29184
  const asked = unanswered ? retryAfterMs2(error) : 0;
29093
29185
  waitMs = Math.max(waitMillisecondsOf(interval), asked);
29094
29186
  continue;
29095
29187
  }
29096
- const login = loginOf(started.key, started.brokerUrl, answered, Date.now());
29188
+ const issued = loginOf(started.key, started.brokerUrl, answered, Date.now());
29189
+ let dispatchScopes = null;
29190
+ if (started.dispatchScopes !== null) {
29191
+ const approved = signInScopesOf(answered, started.dispatchScopes, false);
29192
+ if (approved === undefined) {
29193
+ 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}`);
29194
+ }
29195
+ dispatchScopes = approved;
29196
+ }
29197
+ const login = { ...issued, dispatchScopes };
29097
29198
  let replaced = "";
29098
29199
  let saved = false;
29099
29200
  try {
@@ -29107,8 +29208,7 @@ async function finishDeviceLogin(started, options) {
29107
29208
  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`;
29108
29209
  return { ...login, replaced, lockLeft };
29109
29210
  }
29110
- const revoke = `Machine logins on ${started.verificationUri}`;
29111
- 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 });
29211
+ 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 });
29112
29212
  }
29113
29213
  return { ...login, replaced, lockLeft: "" };
29114
29214
  }
@@ -29150,10 +29250,10 @@ class DeviceLoginIdentity {
29150
29250
  return await withDeviceLoginLock(this.#path, async (held) => {
29151
29251
  let login = await readDeviceLogin(this.#path);
29152
29252
  if (withoutTrailingSlashes(login.broker) !== this.#brokerUrl) {
29153
- 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}`);
29253
+ 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)}`);
29154
29254
  }
29155
29255
  if (await calculateJwkThumbprint(loginDpopKey(login.key).publicJwk) !== thumbprint) {
29156
- 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`);
29256
+ throw new DeviceLoginReplacedError(DEVICE_LOGIN_FILE_NAMED, DEVICE_LOGIN_COMMAND);
29157
29257
  }
29158
29258
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
29159
29259
  const expires = login.accessExpiresAt?.getTime() ?? 0;
@@ -29196,14 +29296,30 @@ async function refreshDeviceLogin(path, login, options) {
29196
29296
  refresh_token: login.refreshToken
29197
29297
  });
29198
29298
  } catch (error) {
29199
- if (endsGrant(error))
29200
- throw new DeviceLoginEndedError(options.describe);
29299
+ if (endsGrant(error)) {
29300
+ throw new DeviceLoginEndedError(options.describe, deviceLoginCommand(login.dispatchScopes));
29301
+ }
29201
29302
  if (sent === 0 && statusOf(error) === 0)
29202
29303
  continue;
29203
29304
  throw brokerRefusal("refresh", options.describe, endpoint, error);
29204
29305
  }
29205
29306
  }
29206
- const next = loginOf(login.key, login.broker, answered, Date.now());
29307
+ const issued = loginOf(login.key, login.broker, answered, Date.now());
29308
+ let dispatchScopes = null;
29309
+ if (login.dispatchScopes !== null) {
29310
+ const kept = signInScopesOf(answered, login.dispatchScopes, true);
29311
+ if (kept === undefined) {
29312
+ 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)}`);
29313
+ }
29314
+ dispatchScopes = kept;
29315
+ } else if (answered.scope === DISPATCH_LOGIN_SCOPE) {
29316
+ const kept = signInScopesOf(answered, DISPATCH_SIGN_IN_SCOPES, false);
29317
+ if (kept === undefined) {
29318
+ 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>`);
29319
+ }
29320
+ dispatchScopes = kept;
29321
+ }
29322
+ const next = { ...issued, dispatchScopes };
29207
29323
  await saveDeviceLogin(path, next, options.held);
29208
29324
  return next;
29209
29325
  }
@@ -30302,6 +30418,10 @@ function tradeFailureReason(error) {
30302
30418
  return error.message;
30303
30419
  if (error instanceof SignInEndedError)
30304
30420
  return `the issuer no longer honours the sign-in on this machine; run: ${SIGNIN_COMMAND}`;
30421
+ if (error instanceof DeviceLoginEndedError)
30422
+ return scrub(error.message);
30423
+ if (error instanceof DeviceLoginReplacedError)
30424
+ return scrub(error.message);
30305
30425
  return natsFailureReason(error);
30306
30426
  }
30307
30427
  function isDeadline(error) {
@@ -30469,18 +30589,22 @@ function brokerTokenRefusals(token) {
30469
30589
  }
30470
30590
  };
30471
30591
  }
30472
- function warnedEvery(warn) {
30592
+ function warnedEvery(warn, options = {}) {
30473
30593
  let warnedAt;
30594
+ let warnedText;
30474
30595
  return {
30475
30596
  warn: (text) => {
30476
30597
  const now = Date.now();
30477
- if (warnedAt !== undefined && now - warnedAt < WARN_AGAIN_MS)
30598
+ const held = options.newTextAtOnce !== true || text === warnedText;
30599
+ if (held && warnedAt !== undefined && now - warnedAt < WARN_AGAIN_MS)
30478
30600
  return;
30479
30601
  warnedAt = now;
30602
+ warnedText = text;
30480
30603
  warn(text);
30481
30604
  },
30482
30605
  reset: () => {
30483
30606
  warnedAt = undefined;
30607
+ warnedText = undefined;
30484
30608
  }
30485
30609
  };
30486
30610
  }
@@ -30494,6 +30618,7 @@ function keepNatsCredential(connection, credential, warn) {
30494
30618
  let renewing = false;
30495
30619
  let renewAgain = false;
30496
30620
  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`));
30621
+ 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 });
30497
30622
  const refusal = warnedEvery(warn);
30498
30623
  const statuses = connection.status();
30499
30624
  const stop = () => {
@@ -30528,7 +30653,7 @@ function keepNatsCredential(connection, credential, warn) {
30528
30653
  schedule(0);
30529
30654
  return;
30530
30655
  }
30531
- renewal.warn(`could not be renewed (${tradeFailureReason(error)})`);
30656
+ (isFinalRefusal(error) ? ended : renewal).warn(`could not be renewed (${tradeFailureReason(error)})`);
30532
30657
  retry();
30533
30658
  return;
30534
30659
  }
@@ -30539,6 +30664,7 @@ function keepNatsCredential(connection, credential, warn) {
30539
30664
  }
30540
30665
  retries = 0;
30541
30666
  renewal.reset();
30667
+ ended.reset();
30542
30668
  schedule(renewDelay(credential.expiresAt().getTime(), Date.now()));
30543
30669
  };
30544
30670
  const tick = async () => {
@@ -39672,6 +39798,7 @@ async function whoamiCommand(context) {
39672
39798
  const projectScope = identity.kind === "agent" ? identity.project_scope ?? null : null;
39673
39799
  const readOnly = identity.scopes?.includes("read") === true;
39674
39800
  const cut = identity.kind === "agent" ? identity.cut ?? null : null;
39801
+ const scopes = identity.scopes ?? null;
39675
39802
  const session = proved ?? sessionId;
39676
39803
  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.";
39677
39804
  const brokerService = owner === null && service !== null && proved !== null;
@@ -39697,9 +39824,10 @@ async function whoamiCommand(context) {
39697
39824
  acting = `Session ${session} runs under the shared token: ${unowned}`;
39698
39825
  }
39699
39826
  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." : "";
39827
+ const holds = scopes === null ? "" : scopes.length === 0 ? " Its credential holds no scope." : ` Its credential holds the ${scopes.length === 1 ? "scope" : "scopes"} ${scopes.join(", ")}.`;
39700
39828
  return {
39701
- text: acting + elsewhere + projectSentence,
39702
- details: { session, owner, service, project, project_scope: projectScope }
39829
+ text: acting + elsewhere + projectSentence + holds,
39830
+ details: { session, owner, service, project, project_scope: projectScope, scopes }
39703
39831
  };
39704
39832
  }
39705
39833
  async function limitsCommand(context) {
@@ -39786,12 +39914,17 @@ function inboxThreadLine(row, now) {
39786
39914
  function credentialRequestLine(request) {
39787
39915
  const session = request.session ?? null;
39788
39916
  const pending = awaitsDecision(request);
39917
+ const asked = signInScopes(request);
39918
+ const reason = request.reason ?? "";
39789
39919
  return [
39790
- `- ${request.kind}`,
39920
+ asked === null ? `- ${request.kind}` : "- Dispatch sign-in",
39791
39921
  (request.identifiers ?? []).join(", "),
39922
+ ...asked === null ? [] : [`asks for ${asked.join(", ") || "no scope"}`],
39792
39923
  request.requested_at,
39793
39924
  ...pending ? [] : [request.expires_at === undefined ? "expired" : `expired ${request.expires_at}`],
39794
- ...session === null ? [] : [`session request=${session.request ?? "-"}, enrollment=${session.enrollment ?? "-"}`],
39925
+ ...asked !== null ? [
39926
+ reason === "" ? "gives no reason" : `requester's words (unchecked): ${JSON.stringify(reason)}`
39927
+ ] : session === null ? [] : [`session request=${session.request ?? "-"}, enrollment=${session.enrollment ?? "-"}`],
39795
39928
  ...!pending || request.approve_url === undefined ? [] : [request.approve_url]
39796
39929
  ].join(" \xB7 ");
39797
39930
  }
@@ -40086,6 +40219,8 @@ import { hostname as hostname4 } from "os";
40086
40219
  function parseLogin(argv) {
40087
40220
  let device = false;
40088
40221
  let person;
40222
+ let scope;
40223
+ let reason;
40089
40224
  for (let at = 0;at < argv.length; at += 1) {
40090
40225
  const word = argv[at];
40091
40226
  if (word === "--help" || word === "-h")
@@ -40100,11 +40235,31 @@ function parseLogin(argv) {
40100
40235
  at += 1;
40101
40236
  } else if (word.startsWith("--person=")) {
40102
40237
  person = word.slice("--person=".length);
40238
+ } else if (word === "--scope") {
40239
+ const next = argv[at + 1];
40240
+ if (next === undefined)
40241
+ return { kind: "refused", problem: "--scope needs a list" };
40242
+ scope = next;
40243
+ at += 1;
40244
+ } else if (word.startsWith("--scope=")) {
40245
+ scope = word.slice("--scope=".length);
40246
+ } else if (word === "--reason") {
40247
+ const next = argv[at + 1];
40248
+ if (next === undefined)
40249
+ return { kind: "refused", problem: "--reason needs text" };
40250
+ reason = next;
40251
+ at += 1;
40252
+ } else if (word.startsWith("--reason=")) {
40253
+ reason = word.slice("--reason=".length);
40103
40254
  } else {
40104
40255
  return { kind: "refused", problem: `unknown argument ${JSON.stringify(word)}` };
40105
40256
  }
40106
40257
  }
40107
- return { kind: "login", device, person };
40258
+ if (scope === undefined) {
40259
+ return { kind: "login", device, dispatchScopes: undefined, person, reason };
40260
+ }
40261
+ const dispatchScopes = scope.trim() === "none" ? [] : scope.split(",").map((word) => word.trim());
40262
+ return { kind: "login", device, dispatchScopes, person, reason };
40108
40263
  }
40109
40264
  async function loginCommand(argv, env, io) {
40110
40265
  const refuse = (problem, code) => {
@@ -40143,15 +40298,26 @@ async function loginCommand(argv, env, io) {
40143
40298
  return refuse(messageFor(error), USAGE);
40144
40299
  }
40145
40300
  const host = deviceLoginHost(hostname4());
40301
+ let started;
40146
40302
  try {
40147
- const started = await startDeviceLogin({
40303
+ started = await startDeviceLogin({
40148
40304
  brokerUrl,
40305
+ dispatchScopes: parsed.dispatchScopes,
40149
40306
  person,
40150
40307
  host,
40308
+ reason: parsed.reason,
40151
40309
  fetch: io.fetchImpl
40152
40310
  });
40311
+ } catch (error) {
40312
+ if (error instanceof RangeError)
40313
+ return refuse(`${error.message}. Run dispatch login --help.`, USAGE);
40314
+ io.print(`dispatch login: ${messageFor(error)}`);
40315
+ return REFUSED;
40316
+ }
40317
+ try {
40318
+ const naming = parsed.reason === undefined ? host : `${JSON.stringify(parsed.reason)} on ${host}`;
40153
40319
  io.print([
40154
- `dispatch login: to log this machine (${host}) in at the secrets broker at ${urlForText(started.brokerUrl, BROKER_URL_VAR)}, ${person} approves it:`,
40320
+ `dispatch login: for ${person} to approve ${started.describe} (${naming}) through the secrets broker at ${urlForText(started.brokerUrl, BROKER_URL_VAR)}:`,
40155
40321
  ` open ${started.verificationUriComplete ?? started.verificationUri}`,
40156
40322
  ` and enter the code ${started.userCode}`,
40157
40323
  `dispatch login: the code is good until ${started.expiresAt.toISOString()}; waiting for the approval.`
@@ -40159,8 +40325,11 @@ async function loginCommand(argv, env, io) {
40159
40325
  `));
40160
40326
  const login = await finishDeviceLogin(started, { path, fetch: io.fetchImpl, sleep: io.sleep });
40161
40327
  const lines = [
40162
- `dispatch login: approved. This machine's device login is kept in ${DEVICE_LOGIN_FILE_NAMED}; its launcher credential ${login.credentialId} lasts until ${login.expiresAt.toISOString()}, and each refresh moves that on.`
40328
+ `dispatch login: approved. ${started.describe.charAt(0).toUpperCase()}${started.describe.slice(1)} is kept in ${DEVICE_LOGIN_FILE_NAMED}; its launcher credential ${login.credentialId} lasts until ${login.expiresAt.toISOString()}, and each refresh moves that on.`
40163
40329
  ];
40330
+ if (login.dispatchScopes !== null) {
40331
+ lines.push(`dispatch login: approved Dispatch scopes: ${login.dispatchScopes.join(", ") || "none"}.`);
40332
+ }
40164
40333
  if (login.lockLeft !== "") {
40165
40334
  lines.push(`dispatch login: the login is kept, but ${login.lockLeft}.`);
40166
40335
  }