worktrust 0.11.6 → 0.11.8

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.
@@ -26,13 +26,17 @@ export const renewBytes = (body) => P.concatBytes(RENEW, P.canonicalBytes(body))
26
26
 
27
27
  export class IssuerMissing extends Error {}
28
28
  export class PairingRefused extends Error {}
29
+ /** The request's window ended with no approval (0.11.7: the terminal offers a new QR code). */
30
+ export class PairingExpired extends PairingRefused {}
31
+ /** The person denied it on the phone or in the browser (0.11.7). */
32
+ export class PairingDenied extends PairingRefused {}
29
33
 
30
34
  async function post(origin, path, body) {
31
35
  const response = await fetch(`${origin}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) });
32
36
  return { status: response.status, json: await response.json().catch(() => ({})) };
33
37
  }
34
38
 
35
- /** `remote enable`'s question: the app's QR here (Enter), or the browser. Not a terminal, or --yes: the browser, as before. */
39
+ /** Which road, the app's QR here (Enter) or the browser; not a terminal, or --yes: the browser. Since 0.11.7 the person names the road (`remote app` | `remote web`, or the menu); kept for a caller that asks. */
36
40
  export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), yes = false, prompt = null } = {}) {
37
41
  if (!interactive || yes) return "web";
38
42
  const rl = prompt ? null : createInterface({ input: process.stdin, output: process.stdout });
@@ -45,7 +49,7 @@ export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), y
45
49
  * Pair, and return the verified binding. `keys` holds the secret pair (never sent), `issuerKeys` the pinned keys. `road`:
46
50
  * "web" opens the approval page in the browser; "app" draws its link with `showQr` for the WorkTrust app and opens nothing.
47
51
  */
48
- export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now }) {
52
+ export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now, countdown = null }) {
49
53
  const verifier = randomBytes(32).toString("base64url");
50
54
  const code_challenge = createHash("sha256").update(verifier).digest("base64url");
51
55
  const state = randomBytes(24).toString("base64url");
@@ -62,12 +66,16 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
62
66
  });
63
67
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
64
68
  }
69
+ let bar = null;
70
+ const settle = (line) => { bar?.stop(line); bar = null; };
65
71
  try {
66
72
  const pairing = await post(origin, "/api/remote/pair", { flow: device ? "device" : "loopback", host, os, ...claim, code_challenge_method: "S256", proof, ...(device ? {} : { port: server.address().port, state }) }).catch(() => null);
67
73
  if (!pairing) throw new PairingRefused(`cannot reach ${origin}`);
68
74
  if (pairing.status === 404) throw new IssuerMissing(`${origin} has no remote-key issuer yet (POST /api/remote/pair answered 404). Nothing was changed; remote control needs a Passport app with the issuer (docs/remote-agents/ISSUER.md).`);
69
75
  if (pairing.status !== 200) throw new PairingRefused(`pairing refused (${pairing.json.error ?? pairing.status})`);
70
76
  const { device_code, user_code, expires_in = 600, interval = 3, authorize_url, verification_uri, features = [] } = pairing.json;
77
+ // THE WINDOW IS THE ISSUER'S (0.11.7): its expires_at when it says one, else its expires_in from now; the bar drains over it.
78
+ const asked = now(), until = Number.isFinite(pairing.json.expires_at) ? pairing.json.expires_at : asked + expires_in * 1000;
71
79
  if (!features.includes("remote-binding-v1")) throw new PairingRefused(`${origin} does not offer remote bindings (remote-binding-v1)`);
72
80
  const fingerprint = P.deviceFingerprint(publicKeys);
73
81
  say(` Your code: ${user_code} This computer's remote key: ${fingerprint}`);
@@ -85,7 +93,7 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
85
93
  // The browser's one-time code arrives at 127.0.0.1; a phone's approval only by polling (device code and verifier).
86
94
  let code = null;
87
95
  void answer.then((c) => { code = c; });
88
- const until = now() + expires_in * 1000;
96
+ bar = countdown?.({ expiresAt: until, windowMs: until - asked }) ?? null;
89
97
  let wait = Math.max(1, interval) * 1000;
90
98
  while (!code && !exchanged && now() < until) {
91
99
  await Promise.race([answer, new Promise((resolve) => setTimeout(resolve, wait))]);
@@ -93,22 +101,27 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
93
101
  const reply = await post(origin, "/api/remote/token", { device_code, code_verifier: verifier }).catch(() => null);
94
102
  if (reply?.status === 200) exchanged = reply;
95
103
  else if (reply?.json?.error === "slow_down") wait += 2000;
96
- else if (reply?.json?.error === "access_denied" || reply?.json?.error === "expired_token") throw new PairingRefused(`pairing ended (${reply.json.error})`);
104
+ else if (reply?.json?.error === "access_denied") { settle(`Denied ${road === "app" ? "on your phone" : "in the browser"}. Nothing was changed.`); throw new PairingDenied("pairing ended (access_denied)"); }
105
+ else if (reply?.json?.error === "expired_token") { settle("This request expired."); throw new PairingExpired("pairing ended (expired_token)"); }
97
106
  // authorization_pending, or invalid_grant from an issuer before 2026-11-12 (no codeless loopback poll): wait on.
98
107
  }
99
- if (!exchanged && !code) throw new PairingRefused("no approval arrived in time");
108
+ if (!exchanged && !code) { settle("This request expired."); throw new PairingExpired("no approval arrived in time"); }
109
+ settle(code || road !== "app" ? "✓ Approved in the browser" : "✓ Approved on your phone");
100
110
  if (!exchanged) exchanged = await post(origin, "/api/remote/token", { device_code, code, code_verifier: verifier });
101
111
  } else {
102
112
  say(` On any device open ${verification_uri} and type the code.`);
103
- const until = now() + expires_in * 1000;
113
+ bar = countdown?.({ expiresAt: until, windowMs: until - asked }) ?? null;
104
114
  let wait = interval * 1000;
105
115
  while (now() < until) {
106
116
  await new Promise((resolve) => setTimeout(resolve, wait));
107
117
  const reply = await post(origin, "/api/remote/token", { device_code, code_verifier: verifier }).catch(() => null);
108
- if (reply?.status === 200) { exchanged = reply; break; }
118
+ if (reply?.status === 200) { exchanged = reply; settle("✓ Approved"); break; }
109
119
  if (reply?.json?.error === "slow_down") wait += 2000;
110
- else if (reply?.json?.error && reply.json.error !== "authorization_pending") throw new PairingRefused(`pairing ended (${reply.json.error})`);
120
+ else if (reply?.json?.error === "access_denied") { settle("Denied. Nothing was changed."); throw new PairingDenied("pairing ended (access_denied)"); }
121
+ else if (reply?.json?.error === "expired_token") { settle("This request expired."); throw new PairingExpired("pairing ended (expired_token)"); }
122
+ else if (reply?.json?.error && reply.json.error !== "authorization_pending") { settle(); throw new PairingRefused(`pairing ended (${reply.json.error})`); }
111
123
  }
124
+ if (!exchanged) { settle("This request expired."); throw new PairingExpired("no approval arrived in time"); }
112
125
  }
113
126
  if (!exchanged || exchanged.status !== 200 || typeof exchanged.json.binding !== "string") throw new PairingRefused(`the approval could not be exchanged (${exchanged?.json?.error ?? "no answer"})`);
114
127
  if (Object.keys(issuerKeys).length === 0) throw new PairingRefused("this release pins no WorkTrust issuer key yet, so the binding cannot be verified; nothing was saved");
@@ -116,7 +129,7 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
116
129
  if (!verified.ok) throw new PairingRefused(`the binding does not verify (${verified.code}); nothing was saved`);
117
130
  if (verified.value.ed25519_pub !== publicKeys.ed25519_pub || verified.value.x25519_pub !== publicKeys.x25519_pub) throw new PairingRefused("the binding names other keys; nothing was saved");
118
131
  return { binding: exchanged.json.binding, device_id: verified.value.device_id, sub: verified.value.sub, exp: verified.value.exp, account: typeof exchanged.json.account === "string" ? exchanged.json.account.slice(0, 120) : null };
119
- } finally { server?.close(); }
132
+ } finally { settle(); server?.close(); }
120
133
  }
121
134
 
122
135
  /** A fresh binding for the same keys before the old one ends (POST /api/remote/renew). Null when the issuer has none. */
package/remote-policy.mjs CHANGED
@@ -193,6 +193,21 @@ export const REASONS = Object.freeze({
193
193
  other: "only edits inside the project, reviewed test, build and lint commands, and messages shown whole are approved from a phone",
194
194
  });
195
195
 
196
+ /**
197
+ * THE PROJECT AN ACTION IS JUDGED AGAINST (CLI 0.11.7, several projects in one session): the session's main project,
198
+ * unless the file the agent names lies inside one of the session's extra projects (`extraPaths`, resolved at the start
199
+ * from the computer's own inventory, never a phone's path); then that one. The action's files are absolute paths, so the
200
+ * phone shows which project an edit is in.
201
+ */
202
+ export function projectForAction(session, input) {
203
+ const extras = Array.isArray(session?.extraPaths) ? session.extraPaths : [];
204
+ const named = input && typeof input === "object" ? input.file_path ?? input.notebook_path ?? input.path : null;
205
+ if (extras.length === 0 || typeof named !== "string") return session.projectPath;
206
+ const target = canonicalTarget(named, session.projectPath);
207
+ if (!target || isInside(session.projectPath, target)) return session.projectPath;
208
+ return extras.find((p) => isInside(p, target)) ?? session.projectPath;
209
+ }
210
+
196
211
  /** The one gate between a classified action and the phone. Nothing else in the daemon may decide this. */
197
212
  export const phoneMayDecide = (action) => P.APPROVAL_CLASSES.includes(action?.class) && P.isRemoteApprovable(action.class);
198
213
 
@@ -8,10 +8,16 @@
8
8
  * name of [A-Za-z0-9._-] that does not start with a dot and does not exist yet. The computer makes that folder and nothing
9
9
  * else (no parents, no files), checks after making it that it sits directly inside the root, grants it as a project, and
10
10
  * runs `git init` in it only when the person enabled that for the root. Nothing a phone sends names a path.
11
+ *
12
+ * BROAD ROOTS OPEN EXISTING PROJECTS (owner, 2026-11-12: "broad roots, not full access"; CLI 0.11.7). The inventory also
13
+ * lists the git projects that already lie DIRECTLY inside each root (rootProjects), most recently changed first, within
14
+ * the inventory's 30; a phone may start a session in one by the id the inventory gave, never by a path. Each is held to
15
+ * the granted-project rule (canonicalProject: never the home folder or above it, never a folder of secrets) and must
16
+ * still sit directly inside its root once every link is resolved, so a link in a root that points elsewhere opens nothing.
11
17
  */
12
18
  import { execFileSync } from "node:child_process";
13
19
  import { createHmac } from "node:crypto";
14
- import { existsSync, lstatSync, mkdirSync, realpathSync, rmdirSync } from "node:fs";
20
+ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmdirSync, statSync } from "node:fs";
15
21
  import { homedir } from "node:os";
16
22
  import { basename, dirname, join, relative, sep } from "node:path";
17
23
  import * as P from "./remote-protocol.mjs";
@@ -85,3 +91,35 @@ export function createProject(o) {
85
91
  return { ok: true, git, project: { project_id, label: o.name.slice(0, 256), path: made.slice(0, 4096), root_id: o.root.root_id } };
86
92
  }
87
93
 
94
+
95
+ /** A git project's folder: it holds `.git` (a folder, or a worktree's file). */
96
+ const isGitProject = (path) => { try { lstatSync(join(path, ".git")); return true; } catch { return false; } };
97
+
98
+ /**
99
+ * The existing git projects directly inside the roots, as session projects { project_id, path, root_id, from_root: true },
100
+ * newest change first, leaving out what `granted` already lists; at most `limit`. Read at the computer, every time.
101
+ */
102
+ export function rootProjects(roots, projectSecret, granted = [], limit = MAX_PROJECTS) {
103
+ const taken = new Set(granted.map((p) => p.path)), found = [];
104
+ for (const r of roots) {
105
+ const root = checkRoot(r.path);
106
+ if (!root.ok || root.path !== r.path) continue; // moved, gone, or now a link elsewhere
107
+ let names = [];
108
+ try { names = readdirSync(root.path, { withFileTypes: true }).filter((d) => (d.isDirectory() || d.isSymbolicLink()) && !d.name.startsWith(".")).map((d) => d.name); } catch { continue; }
109
+ for (const name of names.slice(0, 2000)) {
110
+ const canonical = canonicalProject(join(root.path, name));
111
+ if (!canonical.ok || dirname(canonical.path) !== root.path || taken.has(canonical.path) || !isGitProject(canonical.path)) continue;
112
+ let changed = 0;
113
+ try { changed = statSync(canonical.path).mtimeMs; } catch { continue; }
114
+ taken.add(canonical.path);
115
+ found.push({ project_id: projectIdOf(projectSecret, canonical.path), path: canonical.path, root_id: r.root_id, from_root: true, changed });
116
+ }
117
+ }
118
+ return found.sort((a, b) => b.changed - a.changed).slice(0, Math.max(0, limit)).map(({ changed, ...p }) => p);
119
+ }
120
+
121
+ /** What a session may run in: the granted projects, then the existing projects inside the roots, 30 in all (the inventory's). */
122
+ export function sessionProjects({ projects, roots, projectSecret }) {
123
+ const granted = projects().slice(0, MAX_PROJECTS);
124
+ return [...granted, ...rootProjects(roots(), projectSecret, granted, MAX_PROJECTS - granted.length)];
125
+ }
@@ -367,6 +367,7 @@ export const ID_PREFIXES = {
367
367
  stp: "a step of an agent run",
368
368
  pli: "an item of an agent's own plan (its to-do list), stable across the plan's versions",
369
369
  sag: "a subagent an agent started, for the agent map",
370
+ fld: "a folder a computer suggests for projects (one it detected itself; a phone names it by this id, never by a path)",
370
371
  rot: "a root folder on a computer where a phone may create new project folders (worktrust remote roots add)",
371
372
  att: "a file sent from the phone into a session's project inbox (transfer.ts)",
372
373
  pvw: "one local preview render (transfer.ts)",
@@ -557,6 +558,39 @@ export const PERMISSION_MODES = ["ask", "plan"] ;
557
558
 
558
559
  export const MAX_MODELS_PER_ADAPTER = 200;
559
560
 
561
+ /**
562
+ * AGENT MODES WITH A CEILING SET AT THE COMPUTER (owner, 2026-11-12; CLI 0.11.7). `permission_modes` above stays the
563
+ * closed pair every phone and computer before 0.11.7 knows; the finer choice travels BESIDE it, in optional fields an
564
+ * older peer never receives (the inventory's `agent_options` only reaches a phone that asked with `inventory.get`
565
+ * `extended`, and only a phone that read them sends `agent.start` `agent_mode`). Each agent mode stands on one of the two
566
+ * permission modes (AGENT_MODE_BASE), which `agent.start` still carries: `manual` asks for everything the person's own
567
+ * rules do not decide (the old `ask`), `edit` lets the agent edit files inside the session's projects without asking
568
+ * (Claude Code's acceptEdits), `plan` is read-only planning, `auto` is the agent's own automatic mode where it offers one
569
+ * (Claude Code's auto). The computer offers only what its agent's own help names, and allows only what the person allowed
570
+ * at its keyboard (`worktrust remote modes allow edit|auto`; default manual and plan). The deny rules (no push, no
571
+ * install, no deploy, no secret) hold in every mode.
572
+ */
573
+ export const AGENT_MODES = ["manual", "edit", "plan", "auto"] ;
574
+
575
+ export const AGENT_MODE_BASE = Object.freeze({ manual: "ask", edit: "ask", plan: "plan", auto: "ask" });
576
+ /** The modes a computer allows before its person allowed more at the keyboard: today's behaviour. */
577
+ export const DEFAULT_ALLOWED_MODES = Object.freeze(["manual", "plan"]);
578
+ /** How hard the agent thinks, where its own help names the levels (Claude Code's --effort). */
579
+ export const AGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] ;
580
+
581
+ /** Extra projects one session may reach besides its main one (Claude Code's --add-dir), each from the inventory. */
582
+ export const MAX_EXTRA_PROJECTS = 4;
583
+
584
+ /** What one reported adapter offers beyond `permission_modes` (sealed, in an extended device.inventory). */
585
+ export const AGENT_OPTIONS_SPEC = object({
586
+ adapter: oneOf(ADAPTER_IDS),
587
+ mode: oneOf(ADAPTER_MODES),
588
+ agent_modes: list(oneOf(AGENT_MODES), AGENT_MODES.length, 1),
589
+ efforts: list(oneOf(AGENT_EFFORTS), AGENT_EFFORTS.length),
590
+ /** How many extra projects a session of this adapter may reach; 0: single-project. */
591
+ extra_projects: int(0, MAX_EXTRA_PROJECTS),
592
+ });
593
+
560
594
  export const CAPABILITIES_SPEC = object({
561
595
  start: bool(),
562
596
  attach: bool(),
@@ -1900,16 +1934,17 @@ export function deviceFingerprint(keys ) {
1900
1934
  // ---- packages/remote-protocol/src/crypto/jws.ts
1901
1935
  /**
1902
1936
  * COMPACT SIGNED TOKENS: JWS (RFC 7515) with EdDSA over Ed25519 (RFC 8037), so the gateway can verify an assertion
1903
- * with any standard library, and so can the phone and the computer with this package. Three token types, told apart
1937
+ * with any standard library, and so can the phone and the computer with this package. Four token types, told apart
1904
1938
  * by `typ` and never interchangeable:
1905
1939
  * wt-remote-binding+jwt the Passport app binds a device's remote keys to an account
1906
1940
  * wt-remote-auth+jwt the Passport app authorizes one device at the gateway for five minutes
1907
1941
  * wt-remote-approval+jwt a phone decides one pending approval
1942
+ * wt-remote-admin+jwt the Passport app vouches for one settings change of one computer (crypto/admin.ts)
1908
1943
  * The verifier fixes alg, typ and the key set before it looks at the token: a token cannot choose how it is checked.
1909
1944
  * Header and payload are canonical JSON, so one claim set has one signing input.
1910
1945
  */
1911
1946
 
1912
- export const TOKEN_TYPES = ["wt-remote-binding+jwt", "wt-remote-auth+jwt", "wt-remote-approval+jwt"] ;
1947
+ export const TOKEN_TYPES = ["wt-remote-binding+jwt", "wt-remote-auth+jwt", "wt-remote-approval+jwt", "wt-remote-admin+jwt"] ;
1913
1948
 
1914
1949
  export const MAX_TOKEN_CHARS = 4096;
1915
1950
 
@@ -2085,6 +2120,141 @@ export function checkEndorsement(input , o
2085
2120
  return accept({ device_id: bound.value.device_id, fingerprint: deviceFingerprint(keys), keys, binding: bound.value, nonce: e.nonce, expires_at: e.expires_at });
2086
2121
  }
2087
2122
 
2123
+ // ---- packages/remote-protocol/src/crypto/admin.ts
2124
+ /**
2125
+ * A COMPUTER'S SETTINGS CHANGED FROM THE APP OR THE WEB (part B of CLI 0.11.7, owner 2026-11-12; docs/remote-agents/
2126
+ * PROTOCOL.md §Managing a computer from the app, ISSUER.md §2d). The person changes one remote setting of a paired computer
2127
+ * on the phone or in the browser; the CHANGE travels sealed to the computer like any command, and beside it a short-lived
2128
+ * ADMIN PROOF the Passport app signed with the issuer's key after the person's authenticator answered for THIS change:
2129
+ *
2130
+ * wt-remote-admin+jwt { iss: app.worktrust.io, aud: remote.worktrust.io, sub, device_id, change_hash, setting, via,
2131
+ * iat, exp ≤ iat + 300, jti }
2132
+ *
2133
+ * `sub` is the account's opaque reference (the same as every binding of that account), `device_id` the COMPUTER the
2134
+ * change is for, `change_hash` the SHA-256 of the exact change (adminChangeHash: domain-separated, canonical JSON), and
2135
+ * `setting` which of the four kinds it is, for the audit row and the e-mail. The server sees the hash and the kind,
2136
+ * never the change itself (a folder's name stays sealed between the phone and the computer).
2137
+ *
2138
+ * THE COMPUTER VERIFIES (verifyAdminProof) against the issuer keys pinned in its own build: the type, the issuer and
2139
+ * audience, the lifetime (five minutes at most, the protocol's skew), the device id is its own, the account is its own
2140
+ * binding's, the hash is of the change it received, the kind matches, and the jti was never spent here (one use). Then
2141
+ * the change goes through the same rules a typed one does (remote-settings.mjs applySettingsChange), and only while the
2142
+ * person left `worktrust remote admin on` at the keyboard.
2143
+ *
2144
+ * NO PATH TRAVELS. A folder is named by the id the computer offered (`fld_`, its own HMAC of a folder IT detected), a new
2145
+ * folder by one folder NAME (one segment, made in the home folder by the computer), a root by its `rot_` id, a connection
2146
+ * by its device id. The computer resolves every id from its own lists at the moment it applies the change.
2147
+ */
2148
+
2149
+ /** An admin proof lives five minutes at most: long enough to reach a sleeping laptop's relay queue, short enough to be one act. */
2150
+ export const MAX_ADMIN_PROOF_LIFETIME_S = 300;
2151
+ /** The kinds of setting, for the audit row and the e-mail ("allowed modes", "folders", "roots", "connections"). */
2152
+ export const ADMIN_SETTINGS = ["modes", "folders", "roots", "connections"] ;
2153
+
2154
+ /** Where the person approved it: the native app, or a browser. */
2155
+ export const ADMIN_VIA = ["phone", "browser"] ;
2156
+
2157
+ /** A new folder's name: one segment of letters, digits, space, `.`, `_` or `-`, never starting with a dot, never ending in a space or dot. */
2158
+ export const ADMIN_FOLDER_NAME = /^[A-Za-z0-9_-](?:[A-Za-z0-9 ._-]{0,98}[A-Za-z0-9_-])?$/;
2159
+ export const adminFolderNameOk = (name ) => typeof name === "string" && ADMIN_FOLDER_NAME.test(name) && !name.includes("..");
2160
+
2161
+ /**
2162
+ * THE CHANGES A PHONE OR A BROWSER MAY ASK, AND NOTHING ELSE (a closed union on `what`; exact keys, so no `path` can ride
2163
+ * along). Raising a mode above manual and plan, adding a suggested folder as a root, making one new folder for projects,
2164
+ * a root's git-init switch or its removal, and closing one connection. The admin switch itself is not here: it is turned
2165
+ * on and off at the keyboard only (`worktrust remote admin on|off`).
2166
+ */
2167
+ export const ADMIN_CHANGE_SPEC = union("what", {
2168
+ modes: object({ what: oneOf(["modes"]), mode: oneOf(["edit", "auto"]), allowed: bool() }),
2169
+ folder: object({ what: oneOf(["folder"]), folder_id: id("fld") }),
2170
+ new_folder: object({ what: oneOf(["new_folder"]), name: text(100, 1) }),
2171
+ root: object({ what: oneOf(["root"]), root_id: id("rot"), act: oneOf(["remove", "git_init_on", "git_init_off"]) }),
2172
+ connection: object({ what: oneOf(["connection"]), device_id: id("dev") }),
2173
+ });
2174
+
2175
+ /** What rides in `device.configure`: the change and its proof, sealed together. */
2176
+ export const SETTINGS_CHANGE_SPEC = object({ change: ADMIN_CHANGE_SPEC, proof: token(4096) });
2177
+
2178
+ /** The kind a change is, as the proof and the audit name it. */
2179
+ export function settingOf(change ) {
2180
+ if (change.what === "modes") return "modes";
2181
+ if (change.what === "folder" || change.what === "new_folder") return "folders";
2182
+ if (change.what === "root") return "roots";
2183
+ return "connections";
2184
+ }
2185
+
2186
+ /** The rule between fields the schema cannot say; null when the change is well formed. */
2187
+ export function adminChangeRule(change ) {
2188
+ if (change.what === "new_folder" && !adminFolderNameOk(change.name)) return "name: one folder name of [A-Za-z0-9 ._-], not starting with a dot";
2189
+ return null;
2190
+ }
2191
+
2192
+ const D_CHANGE = utf8Encode("worktrust-remote/v1/admin-change\n");
2193
+ /** The change's hash as the proof names it: SHA-256 over a domain label and the change's canonical JSON. */
2194
+ export const adminChangeHash = (change ) => toBase64Url(sha256(concatBytes(D_CHANGE, canonicalBytes(change))));
2195
+
2196
+ export const ADMIN_PROOF_CLAIMS_SPEC = object({
2197
+ iss: oneOf([PASSPORT_ISSUER]),
2198
+ aud: oneOf([GATEWAY_AUDIENCE]),
2199
+ sub: id("usr"),
2200
+ device_id: id("dev"),
2201
+ change_hash: b64({ exact: 32 }),
2202
+ setting: oneOf(ADMIN_SETTINGS),
2203
+ via: oneOf(ADMIN_VIA),
2204
+ iat: int(0),
2205
+ exp: int(0),
2206
+ jti: id("jti"),
2207
+ });
2208
+
2209
+ /** For the Passport app only: validate, then sign with the issuer's current key. */
2210
+ export function issueAdminProof(claims , issuerSecret , kid ) {
2211
+ const shaped = validate(ADMIN_PROOF_CLAIMS_SPEC, claims, "$admin");
2212
+ if (!shaped.ok) throw new TypeError(shaped.detail);
2213
+ if (claims.exp <= claims.iat || claims.exp - claims.iat > MAX_ADMIN_PROOF_LIFETIME_S) throw new RangeError("admin proof lifetime");
2214
+ return signToken("wt-remote-admin+jwt", kid, claims, issuerSecret);
2215
+ }
2216
+
2217
+ /** The computer's one check of an admin proof. Every refusal leaves the settings untouched. */
2218
+ export function verifyAdminProof(token , expect ) {
2219
+ const verified = verifyToken(token, "wt-remote-admin+jwt", expect.issuerKeys);
2220
+ if (!verified.ok) return verified;
2221
+ const claims = verified.value.claims;
2222
+ if (claims.iss !== PASSPORT_ISSUER) return refuse("issuer", "$admin.iss");
2223
+ if (claims.aud !== GATEWAY_AUDIENCE) return refuse("audience", "$admin.aud");
2224
+ const shaped = validate(ADMIN_PROOF_CLAIMS_SPEC, claims, "$admin");
2225
+ if (!shaped.ok) return shaped;
2226
+ const a = shaped.value;
2227
+ const times = checkTimes(a.iat, a.exp, expect.now, MAX_ADMIN_PROOF_LIFETIME_S, CLOCK_SKEW_MS);
2228
+ if (!times.ok) return times;
2229
+ if (a.device_id !== expect.deviceId) return refuse("wrong_device", "$admin.device_id: another computer");
2230
+ if (a.sub !== expect.sub) return refuse("account_mismatch", "$admin.sub: another account");
2231
+ if (a.change_hash !== adminChangeHash(expect.change) || a.setting !== settingOf(expect.change)) return refuse("action_mismatch", "$admin.change_hash: another change");
2232
+ if (expect.spendJti(a.jti, a.exp) === "seen") return refuse("replay", "$admin.jti: already used");
2233
+ return accept(a);
2234
+ }
2235
+
2236
+ /**
2237
+ * THE INVENTORY'S PART-B FIELDS (events.ts device.inventory spreads them), sealed only for a phone that asked `extended`:
2238
+ * what the computer's settings page draws. `admin`: whether the person left `worktrust remote admin on` (a change from the
2239
+ * app is honoured only then). `folders`: the folders the computer itself suggests for projects (its own detected folders,
2240
+ * with how many git projects each holds, and the root it already is, if any), each by an id the computer derived: a phone
2241
+ * adds one by that id, never by a path. `connections`: the phones and browsers linked to it, by the name each told it
2242
+ * (inventory.get `device_name`) or its kind and fingerprint.
2243
+ */
2244
+ export const ADMIN_INVENTORY_FIELDS = {
2245
+ admin: optional(bool()),
2246
+ folders: optional(list(object({ folder_id: id("fld"), label: text(256, 1), projects: int(0, 2000), root_id: nullable(id("rot")) }), 12)),
2247
+ connections: optional(list(object({
2248
+ device_id: id("dev"),
2249
+ name: text(64, 1),
2250
+ kind: oneOf(["phone", "browser"]),
2251
+ fingerprint: text(19, 1),
2252
+ state: oneOf(["confirmed", "pending"]),
2253
+ since: nullable(int(0)),
2254
+ last_seen: nullable(int(0)),
2255
+ }), 40)),
2256
+ } ;
2257
+
2088
2258
  // ---- packages/remote-protocol/src/commands.ts
2089
2259
  /**
2090
2260
  * THE COMMANDS A PHONE MAY SEND, AND NOTHING ELSE. A fixed list, each with a sealed payload schema. A computer refuses
@@ -2108,6 +2278,8 @@ export const MAX_PROMPT_CHARS = 65_536;
2108
2278
  export const PROJECT_NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/;
2109
2279
  export const projectNameOk = (name ) => typeof name === "string" && PROJECT_NAME.test(name);
2110
2280
  export const MAX_SESSION_NAME = 100;
2281
+ /** A phone's or a browser's own name, as it tells a computer (inventory.get `device_name`). */
2282
+ export const MAX_DEVICE_NAME = 64;
2111
2283
 
2112
2284
  export const COMMAND_PAYLOAD_SPECS = {
2113
2285
  /**
@@ -2129,6 +2301,16 @@ export const COMMAND_PAYLOAD_SPECS = {
2129
2301
  * person can also attach at the desk. Absent means structured, as before.
2130
2302
  */
2131
2303
  mode: optional(oneOf(ADAPTER_MODES)),
2304
+ /**
2305
+ * CLI 0.11.7 (owner, 2026-11-12), each optional and sent only to a computer whose extended inventory offered it: the
2306
+ * agent mode (adapters.ts AGENT_MODES; it must stand on `permission_mode`, AGENT_MODE_BASE), the effort level, and the
2307
+ * extra projects the session may reach, by the ids the inventory gave (never a path). The computer checks each again
2308
+ * against its own options and the ceiling its person set at the keyboard (checkAgentOptions); an older computer
2309
+ * refuses the unknown field and starts nothing.
2310
+ */
2311
+ agent_mode: optional(oneOf(AGENT_MODES)),
2312
+ effort: optional(oneOf(AGENT_EFFORTS)),
2313
+ extra_project_ids: optional(list(id("prj"), MAX_EXTRA_PROJECTS)),
2132
2314
  }),
2133
2315
  /**
2134
2316
  * A new turn for an agent that waits for input. Sent while a turn runs, it waits (command.queued) and runs when the turn
@@ -2177,13 +2359,35 @@ export const COMMAND_PAYLOAD_SPECS = {
2177
2359
  */
2178
2360
  "screen.read": object({ lines: int(1, 2000), follow: optional(bool()) }),
2179
2361
  /** Ask for a device.inventory; `refresh_models` runs the agents' own model listers first. */
2180
- "inventory.get": object({ refresh_models: bool() }),
2362
+ /**
2363
+ * `extended` (CLI 0.11.7): this phone reads the inventory's optional 0.11.7 fields (`agent_options`, `modes_allowed`);
2364
+ * the computer then sends them on every inventory sealed for this phone, and to no other. An older computer refuses
2365
+ * the unknown field (command.rejected), which tells the phone to ask again without it.
2366
+ */
2367
+ "inventory.get": object({
2368
+ refresh_models: bool(),
2369
+ extended: optional(bool()),
2370
+ /**
2371
+ * Part B (owner, 2026-11-12): this phone's or browser's own name ("iPhone 16 Pro", "Browser on macOS"), sent only with
2372
+ * `extended`, sealed, so `remote connections` on the computer says which device it is instead of "Phone 9M8N". The
2373
+ * hello itself is relay-visible and carries no text, so the name rides in the first sealed command after it. An older
2374
+ * computer refuses the field with `extended` and the phone asks again without both.
2375
+ */
2376
+ device_name: optional(text(MAX_DEVICE_NAME, 1)),
2377
+ }),
2181
2378
  /** This computer's remote settings, each optional. Pausing from the phone is soft; `worktrust remote disable` at the
2182
2379
  * desk is the hard off, which no message can undo. */
2183
2380
  "device.configure": object({
2184
2381
  remote_enabled: optional(bool()),
2185
2382
  default_adapter: optional(nullable(oneOf(ADAPTER_IDS))),
2186
2383
  default_model: optional(nullable(text(128, 1))),
2384
+ /**
2385
+ * Part B (owner, 2026-11-12; crypto/admin.ts): one change of this computer's remote settings, approved in the app or on
2386
+ * the web with the person's authenticator, with the issuer-signed proof bound to this computer and this exact change.
2387
+ * Travels alone (no other field beside it). The computer verifies the proof against its pinned issuer keys and applies
2388
+ * the change through its own rules, only while `worktrust remote admin on`; an older computer refuses the field.
2389
+ */
2390
+ settings_change: optional(SETTINGS_CHANGE_SPEC),
2187
2391
  }),
2188
2392
  /** This phone disconnects itself from this computer (owner, 2026-11-07): the computer drops the phone from its
2189
2393
  * confirmed list and its channels, as `worktrust remote phones remove` does at the keyboard. Sent sealed and signed
@@ -2298,6 +2502,9 @@ export const COMMAND_TTL_MS = {
2298
2502
  "pipeline.cancel": 2 * MINUTE,
2299
2503
  };
2300
2504
 
2505
+ /** A device's own name: printable, no control or format character, not only spaces. */
2506
+ export const deviceNameOk = (name ) => typeof name === "string" && name.trim().length > 0 && name.length <= MAX_DEVICE_NAME && !/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/.test(name);
2507
+
2301
2508
  export const isCommandType = (value ) =>
2302
2509
  typeof value === "string" && Object.hasOwn(COMMAND_PAYLOAD_SPECS, value);
2303
2510
 
@@ -2316,6 +2523,16 @@ export function validateCommandPayload (type , value
2316
2523
  } else if ((a.text === null) === (a.option === null)) return refuse("payload", "$payload: exactly one of text and option");
2317
2524
  }
2318
2525
  if (type === "device.configure" && Object.keys(payload).length === 0) return refuse("payload", "$payload: names no setting");
2526
+ if (type === "device.configure") {
2527
+ const c = payload ;
2528
+ if (c.settings_change !== undefined && Object.keys(c).length !== 1) return refuse("payload", "$payload.settings_change: travels alone");
2529
+ const bad = c.settings_change ? adminChangeRule(c.settings_change.change) : null;
2530
+ if (bad) return refuse("payload", `$payload.settings_change.change.${bad}`);
2531
+ }
2532
+ if (type === "inventory.get") {
2533
+ const i = payload ;
2534
+ if (i.device_name !== undefined && (i.extended !== true || !deviceNameOk(i.device_name))) return refuse("payload", "$payload.device_name: printable words, with extended");
2535
+ }
2319
2536
  if (type === "attachment.put") { const bad = attachmentRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
2320
2537
  if (type === "preview.render") { const bad = previewRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
2321
2538
  if (type === "preview.live_start") { const bad = liveStartRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
@@ -2573,6 +2790,15 @@ export const EVENT_BODY_SPECS = {
2573
2790
  projects: list(object({ project_id: id("prj"), label: label(256), path: label(4096), last_used_at: nullable(int(0)), root_id: optional(nullable(id("rot"))), main: optional(label(4096)) }), 30),
2574
2791
  /** Where a phone may create a new project (project.create), each added at the keyboard (2026-11-07). */
2575
2792
  roots: optional(list(object({ root_id: id("rot"), label: label(256), git_init: bool() }), 20)),
2793
+ /**
2794
+ * CLI 0.11.7, only in an inventory sealed for a phone that asked `extended` (an older phone refuses unknown keys and
2795
+ * never receives them): what each adapter offers beyond `permission_modes`, and the modes this computer's person
2796
+ * allowed at the keyboard. A mode offered but not allowed is shown greyed out; neither is ever trusted from a phone.
2797
+ */
2798
+ agent_options: optional(list(AGENT_OPTIONS_SPEC, 16)),
2799
+ modes_allowed: optional(list(oneOf(AGENT_MODES), AGENT_MODES.length)),
2800
+ /** Part B (owner, 2026-11-12), only for an `extended` phone: the settings page's admin switch, folders, connections (crypto/admin.ts). */
2801
+ ...ADMIN_INVENTORY_FIELDS,
2576
2802
  sessions: list(
2577
2803
  object({
2578
2804
  session_id: id("ses"),
@@ -3050,6 +3276,29 @@ export function checkStart(payload , report
3050
3276
  return null;
3051
3277
  }
3052
3278
 
3279
+ /**
3280
+ * THE 0.11.7 START OPTIONS, CHECKED AT THE COMPUTER (owner, 2026-11-12): the agent mode, the effort and the extra
3281
+ * projects of an agent.start, against the options the computer itself offers for that adapter (`options`, from its own
3282
+ * agents' help), the modes its person allowed at the keyboard (`allowed`, the ceiling), and the project ids its own
3283
+ * inventory lists (`known`). Never trusted from the phone. → the mode the session runs in, or a reject reason:
3284
+ * `unsupported` for what the agent does not offer (or a mode that does not stand on `permission_mode`), `not_allowed`
3285
+ * for a mode above the ceiling, `not_found` for an extra project the inventory does not list.
3286
+ */
3287
+
3288
+ export function checkAgentOptions(payload , projectId , options , allowed , known ) {
3289
+ const agentMode = payload.agent_mode ?? (payload.permission_mode === "plan" ? "plan" : "manual");
3290
+ if (AGENT_MODE_BASE[agentMode] !== payload.permission_mode) return "unsupported";
3291
+ if (payload.agent_mode !== undefined && !(options?.agent_modes ?? []).includes(agentMode)) return "unsupported";
3292
+ if (!allowed.includes(agentMode)) return "not_allowed";
3293
+ const effort = payload.effort ?? null;
3294
+ if (effort !== null && !(options?.efforts ?? []).includes(effort)) return "unsupported";
3295
+ const extras = payload.extra_project_ids ?? [];
3296
+ if (extras.length > (options?.extra_projects ?? 0)) return "unsupported";
3297
+ if (new Set(extras).size !== extras.length || extras.includes(projectId ?? "")) return "unsupported";
3298
+ if (extras.some((id) => !known.has(id))) return "not_found";
3299
+ return { agentMode, effort, extraProjectIds: extras };
3300
+ }
3301
+
3053
3302
  // ---- packages/remote-protocol/src/steered.ts
3054
3303
  /**
3055
3304
  * REMOTE-STEERED SESSIONS ARE MARKED, NEVER COUNTED AS A PERSON'S AI HOURS BY THEMSELVES. The agents the daemon runs
@@ -3519,7 +3768,7 @@ export function importChannel(stored ) {
3519
3768
 
3520
3769
  // ---- packages/remote-protocol/src/crypto/pairing.ts
3521
3770
  /**
3522
- * PAIRING BY SCANNING THE COMPUTER'S SCREEN (owner, 2026-11-07). `worktrust remote enable` and `worktrust remote pair` draw
3771
+ * PAIRING BY SCANNING THE COMPUTER'S SCREEN (owner, 2026-11-07). `worktrust remote app` (or `remote web`) and `worktrust remote pair` draw
3523
3772
  * a QR code in the terminal; the WorkTrust app scans it. The QR holds one link:
3524
3773
  *
3525
3774
  * https://app.worktrust.io/remote/pair#v=1&g=<gateway origin>&d=<computer device id>&k=<Ed25519 pub>&x=<X25519 pub>
package/remote-run.mjs CHANGED
@@ -13,7 +13,8 @@ import { closeSync, openSync, readFileSync, rmSync, writeSync, constants } from
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import * as P from "./remote-protocol.mjs";
16
- import { loadPreviewGrants } from "./remote-store.mjs";
16
+ import { loadPreviewGrants, loadRoots } from "./remote-store.mjs";
17
+ import { sessionProjects } from "./remote-projects.mjs";
17
18
  import { ensureRemoteDir, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
18
19
  import { openJournal } from "./remote-journal.mjs";
19
20
  import { inventory as listAgents, offered } from "./remote-inventory.mjs";
@@ -30,6 +31,7 @@ import { createPipelines } from "./remote-pipeline.mjs";
30
31
  import { createAttachments } from "./remote-attachments.mjs";
31
32
  import { createPreview } from "./remote-preview.mjs";
32
33
  import { createLivePreview } from "./remote-live-preview.mjs";
34
+ import { SETTING_WORDS } from "./remote-admin.mjs";
33
35
  import { appendPipelineMark } from "./remote-steered.mjs";
34
36
  import { createDaemonCore } from "./remote-daemon.mjs";
35
37
  import { connectGateway, webSocketAvailable } from "./remote-transport.mjs";
@@ -37,7 +39,11 @@ import { connectGateway, webSocketAvailable } from "./remote-transport.mjs";
37
39
  const HERE = dirname(fileURLToPath(import.meta.url));
38
40
  const log = (kind, fields = {}) => process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), kind, ...fields })}\n`);
39
41
  // A browser a phone added (2026-11-09, remote-endorse.mjs) is said in words too, so it is never news only in a JSON line.
40
- const notice = (kind, fields) => { if (kind === "browser_endorsed") process.stderr.write(` ! A browser was added by your phone ${fields.by}: ${fields.fingerprint}. See or remove it: npx worktrust remote phones\n`); };
42
+ const notice = (kind, fields) => {
43
+ if (kind === "browser_endorsed") process.stderr.write(` ! A browser was added by your phone ${fields.by}: ${fields.fingerprint}. See or remove it: npx worktrust remote phones\n`);
44
+ // Part B: a change approved in the app or on the web with the authenticator, signed by WorkTrust and verified here.
45
+ if (kind === "settings_changed") process.stderr.write(` ! ${SETTING_WORDS[fields.setting] ?? "a remote setting"} changed from ${fields.by}, approved there with your authenticator. To keep every change at this keyboard: npx worktrust remote admin off\n`);
46
+ };
41
47
  const logged = (kind, fields = {}) => { log(kind, fields); notice(kind, fields); };
42
48
 
43
49
  export function agentEnv(settings, base = process.env) {
@@ -97,13 +103,13 @@ function lock() {
97
103
  export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) } = {}) {
98
104
  ensureRemoteDir();
99
105
  const settings = loadSettings(), identity = loadIdentity(), keys = loadKeys();
100
- if (!settings.enabled) throw new Error("remote is off on this computer: run `worktrust remote enable`");
101
- if (!identity || !keys) throw new Error("this computer is not paired for remote: run `worktrust remote enable`");
102
- if (!settings.gateway) throw new Error("no gateway is set: the production gateway is not live yet; for local tests pass --gateway ws://127.0.0.1:<port> to `worktrust remote enable`");
106
+ if (!settings.enabled) throw new Error("remote is off on this computer: run `worktrust remote app` (or `remote web`)");
107
+ if (!identity || !keys) throw new Error("this computer is not paired for remote: run `worktrust remote app` (or `remote web`)");
108
+ if (!settings.gateway) throw new Error("no gateway is set: the production gateway is not live yet; for local tests pass --gateway ws://127.0.0.1:<port> to `worktrust remote app` (or `remote web`)");
103
109
  if (!webSocketAvailable()) throw new Error(`remote needs Node 22.4 or later (this is ${process.versions.node})`);
104
110
  const keysOf = issuerKeys(settings.gateway);
105
111
  const claims = P.verifyBinding(identity.binding, { issuerKeys: keysOf, now: Date.now(), kind: "computer", deviceId: identity.device_id });
106
- if (!claims.ok) throw new Error(`this computer's binding does not verify (${claims.code}): run \`worktrust remote enable\` again`);
112
+ if (!claims.ok) throw new Error(`this computer's binding does not verify (${claims.code}): run \`worktrust remote app\` (or \`remote web\`) again`);
107
113
  if (claims.value.exp * 1000 - Date.now() < 7 * 86400_000 && identity.origin) {
108
114
  // A binding lives thirty days: renewed in its last week while the device is still approved (docs/remote-agents/ISSUER.md §4).
109
115
  const { renewBinding } = await import("./remote-pairing.mjs");
@@ -133,7 +139,8 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
133
139
  const socket = await approvals.listen(runDir);
134
140
  let releases = null; // set below; the hooks run only once events flow
135
141
  const sessions = createSessions({ ...ctx, approvals, runDir, node: process.execPath, bridgePath: join(HERE, "remote-approval-bridge.mjs"), socket: () => socket,
136
- settings: loadSettings, projects: loadProjects, inventory: () => inventory({ env: agentEnv(loadSettings()) }), agentEnv: () => agentEnv(loadSettings()), replay: core.replay,
142
+ // A session runs in a granted project or in an existing project inside a root (0.11.7), each by the inventory's id.
143
+ settings: loadSettings, projects: () => sessionProjects({ projects: loadProjects, roots: loadRoots, projectSecret: keys.projectSecret }), inventory: () => inventory({ env: agentEnv(loadSettings()) }), agentEnv: () => agentEnv(loadSettings()), replay: core.replay,
137
144
  onTaskEnded: (id, outcome) => releases.taskEnded(id, outcome), onActivity: () => releases?.activity(),
138
145
  onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)), attachments });
139
146
  ctx.onApprovalOpened = sessions.onApprovalOpened; ctx.onApprovalSettled = sessions.onApprovalSettled;