worktrust 0.11.11 → 0.11.13

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.
@@ -1717,6 +1717,110 @@ export function agentsActiveRule(a ) {
1717
1717
  return null;
1718
1718
  }
1719
1719
 
1720
+ // ---- packages/remote-protocol/src/health.ts
1721
+ /**
1722
+ * THE COMPUTER'S HEALTH (owner, 2026-11-15: "the computer sometimes crashes from RAM/GPU load"). The Remote daemon reads
1723
+ * a few numbers of its own machine every 15 seconds, without a model and without sudo, and seals one `device.health`
1724
+ * body for each paired phone and browser. It travels on the TRANSIENT LANE (envelopes.ts), device-wide: the relay passes
1725
+ * it on to a phone that is there and keeps, buffers and records none of it, so the server never sees or stores a sample.
1726
+ *
1727
+ * Every field is a number, an enum or a flag, except a process's NAME: the program's basename (`ps -o comm=`), never its
1728
+ * arguments, its path or a window title. healthRule refuses a name that looks like a path or an argument, and refuses a
1729
+ * level that is not what healthLevel says of the numbers, so no sender can call a critical computer green.
1730
+ *
1731
+ * A reading that failed is null, never 0. `gpu_busy` is the GPU's own "Device Utilization %" reading (IOAccelerator),
1732
+ * 0 to 100, passed through as the device states it: no figure computed by the sender. Memory and load travel as counts
1733
+ * (MB, the load average times 100, the cores); a surface derives a share from them (healthView in the client).
1734
+ */
1735
+
1736
+ /** How often the daemon samples, and how far back "swap growing" looks. */
1737
+ export const HEALTH_SAMPLE_MS = 15_000;
1738
+ export const SWAP_GROWTH_WINDOW_MS = 120_000;
1739
+ /** Swap that grew by at least this much over the window is "growing" (a few MB of churn is not). */
1740
+ export const SWAP_GROWTH_MIN_MB = 64;
1741
+ /** Below this share of the memory free (with swap growing) the computer is red. */
1742
+ export const LOW_MEMORY_SHARE = 0.05;
1743
+ /** An hour of samples, in memory only (the client's history; never stored). */
1744
+ export const HEALTH_HISTORY_MS = 3_600_000;
1745
+ export const MAX_PROCESS_NAME = 64;
1746
+
1747
+ export const HEALTH_LEVELS = ["green", "yellow", "red", "unknown"] ;
1748
+
1749
+ /** macOS kern.memorystatus_vm_pressure_level 1, 2, 4; Linux PSI memory (`some`/`full` avg10). */
1750
+ export const MEMORY_PRESSURES = ["normal", "warn", "critical"] ;
1751
+
1752
+ export const HEALTH_REASONS = ["pressure_critical", "low_memory_swap_growing", "pressure_warn", "swap_growing"] ;
1753
+
1754
+ const MB = int(0, 16_777_216);
1755
+ export const HEALTH_PROCESS_SPEC = object({ name: text(MAX_PROCESS_NAME, 1), memory_mb: MB });
1756
+
1757
+ export const HEALTH_BODY_SPEC = object({
1758
+ sampled_at: int(0),
1759
+ level: oneOf(HEALTH_LEVELS),
1760
+ reasons: list(oneOf(HEALTH_REASONS), HEALTH_REASONS.length),
1761
+ pressure: nullable(oneOf(MEMORY_PRESSURES)),
1762
+ memory_total_mb: nullable(MB),
1763
+ memory_free_mb: nullable(MB),
1764
+ swap_used_mb: nullable(MB),
1765
+ /** Swap used now minus SWAP_GROWTH_WINDOW_MS ago; null until the daemon has a reading that old. */
1766
+ swap_growth_mb: nullable(int(-16_777_216, 16_777_216)),
1767
+ /** The one-minute load average times 100, and the logical cores it is shared by. */
1768
+ load_centi: nullable(int(0, 100_000_000)),
1769
+ cores: nullable(int(1, 4096)),
1770
+ gpu_busy: nullable(int(0, 100)),
1771
+ /** The three programs holding the most memory, by basename, summed over their processes. */
1772
+ top: list(HEALTH_PROCESS_SPEC, 3),
1773
+ /** True while the daemon starts no new session (level red); running sessions continue. */
1774
+ refusing: bool(),
1775
+ });
1776
+
1777
+ /**
1778
+ * THE THRESHOLDS, ONE PURE FUNCTION (the daemon, the CLI line and every surface read this). Red: pressure critical, or
1779
+ * under 5 % of the memory free while swap grew for two minutes. Yellow: pressure warn, or swap growing. Unknown: no
1780
+ * reading to judge by at all. Green otherwise.
1781
+ */
1782
+ export function healthLevel(input ) {
1783
+ const swapGrowing = input.swap_growth_mb !== null && input.swap_growth_mb >= SWAP_GROWTH_MIN_MB;
1784
+ const share = input.memory_total_mb && input.memory_free_mb !== null ? input.memory_free_mb / input.memory_total_mb : null;
1785
+ const reasons = [];
1786
+ if (input.pressure === "critical") reasons.push("pressure_critical");
1787
+ if (share !== null && share < LOW_MEMORY_SHARE && swapGrowing) reasons.push("low_memory_swap_growing");
1788
+ if (input.pressure === "warn") reasons.push("pressure_warn");
1789
+ if (swapGrowing) reasons.push("swap_growing");
1790
+ if (reasons.includes("pressure_critical") || reasons.includes("low_memory_swap_growing")) return { level: "red", reasons };
1791
+ if (reasons.length > 0) return { level: "yellow", reasons };
1792
+ if (input.pressure === null && share === null && input.swap_growth_mb === null) return { level: "unknown", reasons };
1793
+ return { level: "green", reasons };
1794
+ }
1795
+
1796
+ /**
1797
+ * A NAME THAT IS A PROGRAM'S BASENAME AND NOTHING ELSE. Refused: a path separator, a control character, a leading dash,
1798
+ * an argument after a space (` -x`, ` --flag`), an `=` (a setting), a URL scheme. Spaces and brackets stay: "Google
1799
+ * Chrome Helper (Renderer)" is one program's name.
1800
+ */
1801
+ export function processNameRefusal(name ) {
1802
+ if (name.length === 0 || name.length > MAX_PROCESS_NAME) return "length";
1803
+ if (/[/\\]/.test(name)) return "a path";
1804
+ if (/[\u0000-\u001f\u007f]/.test(name)) return "a control character";
1805
+ if (/^-|\s-{1,2}\S|=|:\/\//.test(name)) return "an argument";
1806
+ return null;
1807
+ }
1808
+
1809
+ /** The rules between fields, after the schema (events.ts validateEventBody). */
1810
+ export function healthRule(body ) {
1811
+ for (const p of body.top) {
1812
+ const bad = processNameRefusal(p.name);
1813
+ if (bad) return `top: a process name with ${bad}`;
1814
+ }
1815
+ if (new Set(body.top.map((p) => p.name)).size !== body.top.length) return "top: a name twice";
1816
+ if (body.top.some((p, n) => n > 0 && p.memory_mb > body.top[n - 1] .memory_mb)) return "top: largest first";
1817
+ if (body.memory_total_mb !== null && body.memory_free_mb !== null && body.memory_free_mb > body.memory_total_mb) return "memory_free_mb: above the total";
1818
+ const judged = healthLevel(body);
1819
+ if (judged.level !== body.level || judged.reasons.join() !== body.reasons.join()) return "level: not what the numbers say";
1820
+ if (body.refusing && body.level !== "red") return "refusing: only while red";
1821
+ return null;
1822
+ }
1823
+
1720
1824
  // ---- packages/remote-protocol/src/latency.ts
1721
1825
  /**
1722
1826
  * HOW LONG EACH HOP TOOK (owner, 2026-11-07: a prompt sent while the agent is busy waits, and the app must show it).
@@ -1734,6 +1838,41 @@ export function deliveryHops(r )
1734
1838
  return { to_relay_ms: span(r.sent_at, r.relay_ack_seen_at), on_computer_ms: span(r.received_at, r.accepted_at) };
1735
1839
  }
1736
1840
 
1841
+ // ---- packages/remote-protocol/src/desk.ts
1842
+ /**
1843
+ * CONTINUE A SESSION ON THIS COMPUTER (release 36, owner 2026-11-15; docs/remote-agents/DESK-SESSIONS.md). The computer's
1844
+ * newest Claude Code sessions in GRANTED projects, sealed in device.inventory `desk_sessions`, only for a phone that asked
1845
+ * `inventory.get` `desk_sessions` (an older phone refuses unknown keys and never receives it). Per session ONLY: Claude
1846
+ * Code's own session id, the project's id, the last activity, a title of at most 80 characters (Claude Code's own summary,
1847
+ * else the first line typed) and the model when recorded. Never more of the transcript. A phone continues one with
1848
+ * `agent.start` `resume` = `session_ref` under that project; the computer checks it is in its own list, that the project is
1849
+ * granted, and that nothing on the computer holds it (`in_use`).
1850
+ */
1851
+
1852
+ export const MAX_DESK_SESSIONS = 20;
1853
+ export const MAX_DESK_TITLE = 80;
1854
+ const CLAUDE_SESSION_REF = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1855
+
1856
+ export const DESK_SESSION_SPEC = object({
1857
+ session_ref: text(36, 36),
1858
+ project_id: id("prj"),
1859
+ last_activity_at: int(0),
1860
+ title: nullable(text(MAX_DESK_TITLE, 1)),
1861
+ model: nullable(text(128, 1)),
1862
+ });
1863
+
1864
+ /** device.inventory's field (events.ts spreads it): sealed only for a phone that asked `inventory.get` `desk_sessions`. */
1865
+ export const DESK_INVENTORY_FIELDS = { desk_sessions: optional(list(DESK_SESSION_SPEC, MAX_DESK_SESSIONS)) } ;
1866
+
1867
+ /** The rules between fields: a uuid each, each once, each under a project the same inventory lists. → null, or what is wrong. */
1868
+ export function deskRule(desk , projects ) {
1869
+ const rows = desk ?? [];
1870
+ if (rows.some((d) => !CLAUDE_SESSION_REF.test(d.session_ref))) return "a session_ref is Claude Code's own uuid";
1871
+ if (new Set(rows.map((d) => d.session_ref)).size !== rows.length) return "a session twice";
1872
+ if (rows.some((d) => !projects.some((p) => p.project_id === d.project_id))) return "under a project the inventory lists";
1873
+ return null;
1874
+ }
1875
+
1737
1876
  // ---- packages/remote-protocol/src/state-machine.ts
1738
1877
  /**
1739
1878
  * DELIVERY AND EXECUTION, AS A PURE FUNCTION. One command's state, from the phone's draft to its end:
@@ -2001,6 +2140,25 @@ export function deviceFingerprint(keys ) {
2001
2140
  return base32Groups(digest.subarray(0, 10));
2002
2141
  }
2003
2142
 
2143
+ /** The bytes of a commitment to a device's public keys: 128 bits of the SAME digest the fingerprint takes 80 of. */
2144
+ export const COMMITMENT_BYTES = 16;
2145
+
2146
+ /**
2147
+ * A 128-BIT COMMITMENT TO A DEVICE'S KEYS (CLI 0.11.12, the compact pairing code): the first sixteen bytes of the digest
2148
+ * whose first ten are the fingerprint. A code that carries it instead of both keys still pins the computer: the phone
2149
+ * takes the keys from the computer's issuer-signed binding in the first welcome and compares all 128 bits (handshake.ts
2150
+ * `pinnedCommitment`), and the fingerprint it pins from then on is read from the same bytes (`commitmentFingerprint`).
2151
+ */
2152
+ export function deviceCommitment(keys ) {
2153
+ return sha256(concatBytes(FINGERPRINT_DOMAIN, decodeKey(keys.ed25519_pub), decodeKey(keys.x25519_pub))).slice(0, COMMITMENT_BYTES);
2154
+ }
2155
+
2156
+ /** The fingerprint a commitment names: the same characters `deviceFingerprint` gives for the committed keys. */
2157
+ export function commitmentFingerprint(commitment ) {
2158
+ if (commitment.length !== COMMITMENT_BYTES) throw new TypeError("a commitment is 16 bytes");
2159
+ return base32Groups(commitment.subarray(0, 10));
2160
+ }
2161
+
2004
2162
  // ---- packages/remote-protocol/src/crypto/jws.ts
2005
2163
  /**
2006
2164
  * COMPACT SIGNED TOKENS: JWS (RFC 7515) with EdDSA over Ed25519 (RFC 8037), so the gateway can verify an assertion
@@ -2458,6 +2616,11 @@ export const COMMAND_PAYLOAD_SPECS = {
2458
2616
  * An older computer refuses the unknown field; the phone then asks again with `extended` alone (client-core.ts).
2459
2617
  */
2460
2618
  model_switch: optional(bool()),
2619
+ /**
2620
+ * Release 36: this phone reads `desk_sessions` (events.ts) and may continue one. Only with `extended`; an older computer
2621
+ * drops the unknown field, so the phone asks it by a probe of its own (client-core.ts, inventory-asks.ts).
2622
+ */
2623
+ desk_sessions: optional(bool()),
2461
2624
  }),
2462
2625
  /** This computer's remote settings, each optional. Pausing from the phone is soft; `worktrust remote disable` at the
2463
2626
  * desk is the hard off, which no message can undo. */
@@ -2617,6 +2780,7 @@ export function validateCommandPayload (type , value
2617
2780
  const i = payload ;
2618
2781
  if (i.device_name !== undefined && (i.extended !== true || !deviceNameOk(i.device_name))) return refuse("payload", "$payload.device_name: printable words, with extended");
2619
2782
  if (i.model_switch !== undefined && i.extended !== true) return refuse("payload", "$payload.model_switch: with extended");
2783
+ if (i.desk_sessions !== undefined && i.extended !== true) return refuse("payload", "$payload.desk_sessions: with extended");
2620
2784
  }
2621
2785
  if (type === "attachment.put") { const bad = attachmentRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
2622
2786
  if (type === "preview.render") { const bad = previewRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
@@ -2734,6 +2898,7 @@ export const REJECT_REASONS = [
2734
2898
  "busy", // the agent is mid-turn and the command needs it idle (a release: its tasks still run, or no slot for a pipeline)
2735
2899
  "unreviewed", // the project's pipeline file was not reviewed at the keyboard, or changed since (2026-11-07)
2736
2900
  "not_allowed", // the computer did not allow it at its keyboard (a browser endorsement without allow-endorse), or the sender may not (2026-11-09)
2901
+ "in_use", // release 36: the desk session to continue is open on the computer; sent only to a phone that asked `desk_sessions` (others hear `busy`)
2737
2902
  ] ;
2738
2903
 
2739
2904
  export const FAIL_REASONS = ["agent_exited", "adapter_error", "not_ready", "timeout", "internal"] ;
@@ -2883,7 +3048,7 @@ export const EVENT_BODY_SPECS = {
2883
3048
  agent_options: optional(list(AGENT_OPTIONS_SPEC, 16)),
2884
3049
  modes_allowed: optional(list(oneOf(AGENT_MODES), AGENT_MODES.length)),
2885
3050
  /** Part B (owner, 2026-11-12), only for an `extended` phone: the settings page's admin switch, folders, connections (crypto/admin.ts). */
2886
- ...ADMIN_INVENTORY_FIELDS,
3051
+ ...ADMIN_INVENTORY_FIELDS, ...DESK_INVENTORY_FIELDS, // release 36: `desk_sessions`, only for a phone that asked (desk.ts)
2887
3052
  sessions: list(
2888
3053
  object({
2889
3054
  session_id: id("ses"),
@@ -2921,19 +3086,16 @@ export const EVENT_BODY_SPECS = {
2921
3086
  ...TRANSFER_EVENT_SPECS,
2922
3087
  /** The live preview (release 19, live-preview.ts): its state, and its frames on the transient lane only. */
2923
3088
  ...LIVE_EVENT_SPECS,
3089
+ /** The computer's health (health.ts), every 15 s on the transient lane, device-wide: passed on, kept by nobody. */
3090
+ "device.health": HEALTH_BODY_SPEC,
2924
3091
  } ;
2925
3092
 
2926
3093
  export const DEVICE_EVENT_TYPES = Object.keys(EVENT_BODY_SPECS) ;
2927
3094
 
2928
3095
  /** The one device event about the computer as a whole; every other names a session. */
2929
- export const DEVICE_SCOPED_EVENTS = new Set (["device.inventory", "project.created", "preview.targets", "preview.image", "preview.rendered", "release.updated", "release.page", "pipeline.updated", "agents.active"]);
3096
+ export const DEVICE_SCOPED_EVENTS = new Set (["device.inventory", "project.created", "preview.targets", "preview.image", "preview.rendered", "release.updated", "release.page", "pipeline.updated", "agents.active", "device.health"]);
2930
3097
  /** Events that answer one command, so their envelope names it (command_id is required). */
2931
- export const COMMAND_RECEIPT_EVENTS = new Set ([
2932
- "command.device_received",
2933
- "command.agent_accepted",
2934
- "command.rejected",
2935
- "command.queued",
2936
- ]);
3098
+ export const COMMAND_RECEIPT_EVENTS = new Set (["command.device_received", "command.agent_accepted", "command.rejected", "command.queued"]);
2937
3099
 
2938
3100
  export const isDeviceEventType = (value ) =>
2939
3101
  typeof value === "string" && Object.hasOwn(EVENT_BODY_SPECS, value);
@@ -2985,6 +3147,10 @@ export function validateEventBody (type , value
2985
3147
  const bad = agentsActiveRule(checked.value );
2986
3148
  if (bad) return refuse("payload", `$body: ${bad}`);
2987
3149
  }
3150
+ if (type === "device.health") {
3151
+ const bad = healthRule(checked.value );
3152
+ if (bad) return refuse("payload", `$body: ${bad}`);
3153
+ }
2988
3154
  if (type === "agent.attention") {
2989
3155
  const a = validateAttention(value, "$body");
2990
3156
  if (!a.ok) return refuse("payload", a.detail);
@@ -2997,6 +3163,7 @@ export function validateEventBody (type , value
2997
3163
  }
2998
3164
  // One report per (adapter, mode) since release 19: Claude Code structured and in a terminal are two reports.
2999
3165
  if (new Set(inv.adapters.map((a) => `${a.adapter}/${a.mode}`)).size !== inv.adapters.length) return refuse("payload", "$body.adapters: an adapter twice");
3166
+ { const desk = deskRule(inv.desk_sessions, inv.projects); if (desk) return refuse("payload", `$body.desk_sessions: ${desk}`); }
3000
3167
  }
3001
3168
  return checked;
3002
3169
  }
@@ -3081,9 +3248,12 @@ export const COMMAND_ENVELOPE_SPEC = object({
3081
3248
  * So the stream stays gap-free for every phone, whoever followed. Only the types below may take the lane.
3082
3249
  */
3083
3250
  export const EVENT_LANES = ["transient"] ;
3084
- export const TRANSIENT_EVENT_TYPES = new Set (["agent.screen", "preview.frame"]);
3085
- /** Types that may ONLY travel on the transient lane (a live preview's frames: never journaled, never replayed). */
3086
- export const TRANSIENT_ONLY_TYPES = new Set (["preview.frame"]);
3251
+ export const TRANSIENT_EVENT_TYPES = new Set (["agent.screen", "preview.frame", "device.health"]);
3252
+ /**
3253
+ * Types that may ONLY travel on the transient lane (a live preview's frames: never journaled, never replayed), and the
3254
+ * computer's health (health.ts, 2026-11-15): device-wide, so its lane is the device stream's, with its own rising number.
3255
+ */
3256
+ export const TRANSIENT_ONLY_TYPES = new Set (["preview.frame", "device.health"]);
3087
3257
  export const isTransientEvent = (e ) => e.lane === "transient";
3088
3258
 
3089
3259
  export const EVENT_ENVELOPE_SPEC = object({
@@ -3224,9 +3394,10 @@ export function validateEventEnvelope(value ) {
3224
3394
  if (!COMMAND_RECEIPT_EVENTS.has(type) && DEVICE_SCOPED_EVENTS.has(type) !== (e.session_id === null))
3225
3395
  return refuse("shape", "$event.session_id: a session event names a session, a device event none");
3226
3396
  if (COMMAND_RECEIPT_EVENTS.has(type) && e.command_id === null) return refuse("shape", "$event.command_id: a receipt names its command");
3227
- if (isTransientEvent(e) && (!TRANSIENT_EVENT_TYPES.has(type) || e.command_id !== null || e.session_id === null || e.notify !== "none"))
3228
- return refuse("shape", "$event.lane: only a pushed screen or frame, of a session, without a command or a push hint, is transient");
3229
- if (TRANSIENT_ONLY_TYPES.has(type) && !isTransientEvent(e)) return refuse("shape", "$event.lane: a live preview's frame travels on the transient lane only");
3397
+ // A session's screen or frame names its session; the computer's health names none (DEVICE_SCOPED_EVENTS, checked above).
3398
+ if (isTransientEvent(e) && (!TRANSIENT_EVENT_TYPES.has(type) || e.command_id !== null || (e.session_id === null) !== DEVICE_SCOPED_EVENTS.has(type) || e.notify !== "none"))
3399
+ return refuse("shape", "$event.lane: only a pushed screen or frame of a session, or the computer's health, without a command or a push hint, is transient");
3400
+ if (TRANSIENT_ONLY_TYPES.has(type) && !isTransientEvent(e)) return refuse("shape", "$event.lane: a live preview's frame and the computer's health travel on the transient lane only");
3230
3401
  return checked;
3231
3402
  }
3232
3403
 
@@ -3874,8 +4045,9 @@ export function importChannel(stored ) {
3874
4045
  * &s=<32-byte one-time secret>&e=<expiry, unix seconds>
3875
4046
  *
3876
4047
  * (worktrust://remote/pair#... is the same invite for a phone without the app link). Everything sits in the FRAGMENT, which
3877
- * a browser never sends: no server, not app.worktrust.io and not the gateway, ever receives the secret. The invite lives five
3878
- * minutes and is spent by its first use; the computer refuses a second.
4048
+ * a browser never sends: no server, not app.worktrust.io and not the gateway, ever receives the secret. The invite lives ten
4049
+ * minutes (five until CLI 0.11.12; owner 2026-11-15: "time to scan: 10 minutes") and is spent by its first use; the computer
4050
+ * refuses a second. Since CLI 0.11.12 the computer draws the COMPACT form below for WorkTrust's own relay.
3879
4051
  *
3880
4052
  * WHY IT CONFIRMS THE PHONE. Whoever scanned the QR saw the computer's screen: that is the keyboard confirmation, done by
3881
4053
  * the camera. The secret is mixed into the first handshake as a pre-shared key (`pairingPsk`, HKDF over "worktrust-remote-
@@ -3890,7 +4062,7 @@ export function importChannel(stored ) {
3890
4062
  */
3891
4063
 
3892
4064
  export const PAIRING_INVITE_VERSION = 1;
3893
- export const PAIRING_INVITE_LIFETIME_S = 300;
4065
+ export const PAIRING_INVITE_LIFETIME_S = 600;
3894
4066
  export const PAIRING_LINK_BASE = "https://app.worktrust.io/remote/pair";
3895
4067
  export const PAIRING_APP_LINK_BASE = "worktrust://remote/pair";
3896
4068
 
@@ -3926,7 +4098,7 @@ function checkInvite(value , nowMs ) {
3926
4098
  return accept(invite);
3927
4099
  }
3928
4100
 
3929
- /** The computer: a fresh invite for its own keys, five minutes. */
4101
+ /** The computer: a fresh invite for its own keys, ten minutes. */
3930
4102
  export function createPairingInvite(input ) {
3931
4103
  const invite = { v: PAIRING_INVITE_VERSION, g: input.gateway, d: input.deviceId, k: input.ed25519_pub, x: input.x25519_pub, s: toBase64Url(input.random(32)), e: Math.floor(input.nowMs / 1000) + PAIRING_INVITE_LIFETIME_S };
3932
4104
  const checked = checkInvite(invite, input.nowMs);
@@ -3991,6 +4163,82 @@ export function generatePairingCode(random ) {
3991
4163
  }
3992
4164
  export const isPairingCode = (value ) => typeof value === "string" && /^[0-9A-HJKMNP-TV-Z]{8}$/.test(value);
3993
4165
 
4166
+ /**
4167
+ * THE COMPACT PAIRING CODE (CLI 0.11.12, owner 2026-11-15: "the QR in the terminal must be about 4 x 4 cm"). For WorkTrust's
4168
+ * own relay the computer draws `https://app.worktrust.io/remote/pair#<58 characters>`: RFC 4648 base32 (A-Z, 2-7, so the
4169
+ * tail is a QR ALPHANUMERIC segment at 5.5 bits a character) of 36 bytes:
4170
+ *
4171
+ * seed (16 bytes) the one-time secret; both ends expand it (HKDF, "worktrust-remote-pair-v2-seed") to the 32-byte
4172
+ * `s` of the long form, so pairingPsk, the proofs and the daemon's invite.json are unchanged
4173
+ * commitment (16 bytes) the first 128 bits of the fingerprint's own digest over the computer's two public keys
4174
+ * (keys.ts deviceCommitment); the phone checks all 128 against the keys in the computer's
4175
+ * issuer-signed binding at the first welcome (handshake.ts pinnedCommitment) and pins the
4176
+ * fingerprint read from the same bytes
4177
+ * e (4 bytes) the expiry, unix seconds, big-endian
4178
+ *
4179
+ * WHAT IS LEFT OUT, AND WHY IT IS STILL SAFE. `k` and `x` (86 characters): the phone never used them for more than an 80-bit
4180
+ * fingerprint pin; the commitment is a 128-bit pin of the same digest, so a forged computer needs a second preimage of
4181
+ * 128 bits. `d` (26): the phone finds the device id in its account's device list by that fingerprint; a list naming
4182
+ * another device under it meets the commitment and the computer's own binding in the handshake and is refused. `g` (40):
4183
+ * the compact form means the build's own relay; any other relay keeps the long form. `v` (4): the fragment's shape is its
4184
+ * version (the long form always holds `=`). The secret is 128 bits instead of 256: offline guessing of a pairing proof
4185
+ * the relay saw costs 2^128 HKDF evaluations, and the invite is spent once within its ten minutes.
4186
+ *
4187
+ * PAYLOAD BUDGET (level L, the CLI's QR, scripts/remote-qr.mjs): `https://app.worktrust.io/remote/pair#` is a 37-byte BYTE
4188
+ * segment (4 + 8 + 296 = 308 bits) and the 58 characters an ALPHANUMERIC one (4 + 9 + 29 * 11 = 332 bits): 640 bits, the
4189
+ * exact capacity of version 4 at level L (80 data codewords), 33 modules, 37 with the 2-module quiet zone. The long form
4190
+ * without `g` was 220 bytes: version 9, 53 modules (61 with the 4-module quiet zone of 0.11.10).
4191
+ */
4192
+ export const PAIRING_SEED_BYTES = 16;
4193
+ const COMPACT_BYTE_COUNT = PAIRING_SEED_BYTES + COMMITMENT_BYTES + 4;
4194
+ /** 36 bytes in base32: 58 characters, the last carrying two zero bits. */
4195
+ export const COMPACT_PAIRING_LENGTH = Math.ceil((COMPACT_BYTE_COUNT * 8) / 5);
4196
+ const RFC4648_BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
4197
+ const COMPACT_SHAPE = new RegExp(`^[A-Z2-7]{${COMPACT_PAIRING_LENGTH}}$`);
4198
+ const SEED_INFO = utf8Encode("worktrust-remote-pair-v2-seed");
4199
+
4200
+ /** A fragment in the compact form (58 base32 characters, nothing else). */
4201
+ export const isCompactPairing = (fragment ) => typeof fragment === "string" && COMPACT_SHAPE.test(fragment);
4202
+
4203
+ /** The 32-byte secret (base64url, the long form's `s`) both ends derive from a compact code's 16-byte seed. */
4204
+ export function expandPairingSeed(seed ) {
4205
+ if (seed.length !== PAIRING_SEED_BYTES) throw new TypeError("a pairing seed is 16 bytes");
4206
+ return toBase64Url(hkdfSha256(seed, new Uint8Array(0), SEED_INFO, 32));
4207
+ }
4208
+
4209
+ /** The computer: the 58-character fragment. */
4210
+ export function encodeCompactPairing(p ) {
4211
+ if (p.seed.length !== PAIRING_SEED_BYTES || p.commitment.length !== COMMITMENT_BYTES || !Number.isInteger(p.e) || p.e < 0 || p.e > 0xffffffff) throw new TypeError("not a compact pairing");
4212
+ const bytes = concatBytes(p.seed, p.commitment, new Uint8Array([p.e >>> 24, (p.e >>> 16) & 255, (p.e >>> 8) & 255, p.e & 255]));
4213
+ let out = "", acc = 0, bits = 0;
4214
+ for (const b of bytes) {
4215
+ acc = (acc << 8) | b; bits += 8;
4216
+ while (bits >= 5) { bits -= 5; out += RFC4648_BASE32[(acc >> bits) & 31] ; }
4217
+ acc &= (1 << bits) - 1;
4218
+ }
4219
+ return bits > 0 ? out + RFC4648_BASE32[(acc << (5 - bits)) & 31] : out;
4220
+ }
4221
+
4222
+ /** What the phone reads from a compact code: the long form's secret, the commitment and the fingerprint it names. */
4223
+
4224
+ /** The phone: a compact fragment, or a refusal (its shape, a non-zero padding, an expired or too long-lived code). */
4225
+ export function decodeCompactPairing(fragment , nowMs ) {
4226
+ if (!isCompactPairing(fragment)) return refuse("shape", "$compact");
4227
+ const bytes = new Uint8Array(COMPACT_BYTE_COUNT);
4228
+ let acc = 0, bits = 0, at = 0;
4229
+ for (const ch of fragment) {
4230
+ acc = (acc << 5) | RFC4648_BASE32.indexOf(ch); bits += 5;
4231
+ if (bits >= 8) { bits -= 8; bytes[at++] = (acc >> bits) & 255; }
4232
+ acc &= (1 << bits) - 1;
4233
+ }
4234
+ if (acc !== 0) return refuse("shape", "$compact: not canonical");
4235
+ const e = ((bytes[32] << 24) >>> 0) + (bytes[33] << 16) + (bytes[34] << 8) + bytes[35] ;
4236
+ if (e * 1000 + CLOCK_SKEW_MS < nowMs) return refuse("expired", "$compact.e");
4237
+ if (e * 1000 > nowMs + PAIRING_INVITE_LIFETIME_S * 1000 + CLOCK_SKEW_MS) return refuse("lifetime", "$compact.e: lives too long");
4238
+ const commitment = bytes.slice(PAIRING_SEED_BYTES, PAIRING_SEED_BYTES + COMMITMENT_BYTES);
4239
+ return accept({ secret: expandPairingSeed(bytes.slice(0, PAIRING_SEED_BYTES)), commitment, fingerprint: commitmentFingerprint(commitment), e });
4240
+ }
4241
+
3994
4242
  // ---- packages/remote-protocol/src/crypto/handshake.ts
3995
4243
  /**
3996
4244
  * THE HANDSHAKE: a phone and a computer agree two keys the relay cannot know.
@@ -4160,6 +4408,7 @@ export function completeHandshake(input
4160
4408
  if (psk && !pairProofValid(psk, "welcome", withoutProof, proof )) return refuse("not_confirmed", "$welcome.pair_proof");
4161
4409
  const fingerprint = bindingFingerprint(computer.value);
4162
4410
  if (input.pinnedFingerprint !== null && input.pinnedFingerprint !== fingerprint) return refuse("not_confirmed", "$welcome: the computer's key changed");
4411
+ if (input.pinnedCommitment && !equalBytes(deviceCommitment(computer.value), input.pinnedCommitment)) return refuse("not_confirmed", "$welcome: not the computer the code committed to");
4163
4412
  const expected = highestCommon(hello.versions, welcome.versions);
4164
4413
  if (expected === null || welcome.protocol_version !== expected) return refuse("downgrade", "$welcome.protocol_version: not the highest common");
4165
4414
  if (expected < MIN_PROTOCOL_VERSION) return refuse("downgrade", "$welcome.protocol_version: below the minimum");
@@ -4326,6 +4575,56 @@ export function deviceSignatureValid(bytes , signature , publ
4326
4575
  export const requestTimeValid = (iat , nowMs ) =>
4327
4576
  typeof iat === "number" && Number.isSafeInteger(iat) && Math.abs(nowMs - iat) <= CLOCK_SKEW_MS;
4328
4577
 
4578
+ // ---- packages/remote-protocol/src/crypto/app-pin.ts
4579
+ /**
4580
+ * THE APP PIN OPENS REMOTE, WITH A SERVER-HELD HALF (owner, 2026-11-15, B18; docs/MOBILE.md §The app PIN opens Remote,
4581
+ * docs/remote-agents/ISSUER.md §2e). One writer for every value the phone, the Passport app and the database must agree
4582
+ * on, so a test computes exactly what each side computes:
4583
+ *
4584
+ * P scrypt(app PIN, a 16-byte salt that never leaves the phone): the phone's, never sent (mobile keyring/app-pin.ts)
4585
+ * V HMAC-SHA256(P, "worktrust-app-pin/verifier/v1\n" ‖ device_id): the verifier the server keeps; it cannot be
4586
+ * guessed without the phone's salt, and it is never answered by any door
4587
+ * proof HMAC-SHA256(V, "worktrust-app-pin/proof/v1\n" ‖ device_id ‖ "\n" ‖ challenge hex): one per server challenge;
4588
+ * the database computes the same (20261115400100 `remote_app_pin_release`) and compares
4589
+ * KEK HKDF-SHA256(P ‖ S, salt = device_id, info = "worktrust-app-pin/kek/v1"): seals the vault's wrapping key; S is
4590
+ * the half only the server keeps (sealed under the app's own secret) and releases after a right proof
4591
+ *
4592
+ * And the two signed requests: enrolling is signed by the phone's BOUND remote key (only an open vault holds it), a
4593
+ * release by the door key that enrollment named (kept in the keychain beside the box, so it binds the request to this
4594
+ * install). Domain-separated like every other request (issuer-requests.ts), so neither opens anything else.
4595
+ */
4596
+
4597
+ const toHex = (bytes ) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4598
+ export const APP_PIN_CHALLENGE = /^[0-9a-f]{64}$/;
4599
+
4600
+ /** V, as hex (64): what enrollment hands the server. */
4601
+ export const appPinVerifier = (p , deviceId ) =>
4602
+ hmacSha256(p, utf8Encode(`worktrust-app-pin/verifier/v1\n${deviceId}`));
4603
+
4604
+ /** The answer to one challenge, as hex (64). */
4605
+ export const appPinProof = (verifier , deviceId , challenge ) =>
4606
+ toHex(hmacSha256(verifier, utf8Encode(`worktrust-app-pin/proof/v1\n${deviceId}\n${challenge}`)));
4607
+
4608
+ /** The key the vault's wrapping key is sealed under for the app PIN's road: neither P nor S alone makes it. */
4609
+ export const appPinKek = (p , s , deviceId ) =>
4610
+ hkdfSha256(concatBytes(p, s), utf8Encode(deviceId), utf8Encode("worktrust-app-pin/kek/v1"), 32);
4611
+
4612
+ export const appPinHex = toHex;
4613
+
4614
+ /** The door key's public half (base64url, 32 bytes) from its 32-byte seed; it signs with issuer-requests.ts `deviceSign`. */
4615
+ export const appPinDoorPublic = (seed ) => toBase64Url(ed25519PublicKey(seed));
4616
+
4617
+ const ENROLL = utf8Encode("worktrust-app-pin/v1/enroll\n");
4618
+ const RELEASE = utf8Encode("worktrust-app-pin/v1/release\n");
4619
+
4620
+ /** Signed by the phone's bound remote Ed25519 key: the new verifier, door key and half, now. */
4621
+ export const appPinEnrollBytes = (b ) =>
4622
+ concatBytes(ENROLL, canonicalBytes({ device_id: b.device_id, door_pub: b.door_pub, half: b.half, iat: b.iat, verifier: b.verifier }));
4623
+
4624
+ /** Signed by the enrolled door key: this proof for this challenge on this phone. */
4625
+ export const appPinReleaseBytes = (b ) =>
4626
+ concatBytes(RELEASE, canonicalBytes({ challenge: b.challenge, device_id: b.device_id, proof: b.proof }));
4627
+
4329
4628
  // ---- packages/remote-protocol/src/gateway.ts
4330
4629
  /**
4331
4630
  * THE GATEWAY'S OWN FRAMES (2026-11-07, docs/remote-agents/GATEWAY.md). Every WebSocket message between a device and the
package/remote-qr.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  * WorkTrust app). ISO/IEC 18004: byte mode, error correction level M (or L), the smallest version 1 to 40 that holds the data,
4
4
  * the mask with the lowest penalty, format and version information. `qrMatrix(text)` gives the modules (true = dark);
5
5
  * `renderQr(matrix)` draws them with half-block characters, two module rows per line, black on an explicitly white
6
- * background with a four-module white quiet zone, so it scans in a light or a dark terminal.
6
+ * background with a white quiet zone (two modules since 0.11.12), so it scans in a light or a dark terminal.
7
7
  *
8
8
  * Held by scripts/test-remote-qr.mjs against reference matrices from an independent encoder (recorded fixtures) and an
9
9
  * independent structural decoder in the test itself.
@@ -56,16 +56,40 @@ export function reedSolomon(data, degree) {
56
56
  return rem;
57
57
  }
58
58
 
59
- function codewords(bytes, level = "M") {
59
+ /**
60
+ * SEGMENTS (CLI 0.11.12): a code is one BYTE segment, as before, or a byte segment followed by an ALPHANUMERIC one (ISO/IEC
61
+ * 18004 7.4.4: 0-9, A-Z, space and $%*+-./:, two characters in 11 bits). `segmentsOf` splits only a link whose fragment is
62
+ * all alphanumeric (the compact pairing code, remote-protocol pairing.ts); every other text stays one byte segment, so
63
+ * every code drawn before is drawn the same.
64
+ */
65
+ export const ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
66
+ export function segmentsOf(text) {
67
+ const hash = text.lastIndexOf("#"), tail = hash >= 0 ? text.slice(hash + 1) : "";
68
+ if (tail.length < 16 || [...tail].some((ch) => !ALPHANUMERIC.includes(ch))) return [{ mode: "byte", data: text }];
69
+ return [{ mode: "byte", data: text.slice(0, hash + 1) }, { mode: "alphanumeric", data: tail }];
70
+ }
71
+ const countBits = (mode, v) => (mode === "byte" ? (v < 10 ? 8 : 16) : v < 10 ? 9 : v < 27 ? 11 : 13);
72
+ const segmentBits = (seg, v) => 4 + countBits(seg.mode, v) + (seg.mode === "byte" ? new TextEncoder().encode(seg.data).length * 8 : Math.floor(seg.data.length / 2) * 11 + (seg.data.length % 2) * 6);
73
+
74
+ function codewords(segments, level = "M") {
60
75
  let version = 1;
61
- const need = (v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8;
76
+ const need = (v) => segments.reduce((sum, seg) => sum + segmentBits(seg, v), 0);
62
77
  while (version <= 40 && need(version) > dataCodewords(version, level) * 8) version += 1;
63
78
  if (version > 40) throw new RangeError("too much data for one QR code");
64
79
  const capacity = dataCodewords(version, level) * 8, bits = [];
65
80
  const put = (value, length) => { for (let i = length - 1; i >= 0; i -= 1) bits.push((value >>> i) & 1); };
66
- put(0b0100, 4);
67
- put(bytes.length, version < 10 ? 8 : 16);
68
- for (const b of bytes) put(b, 8);
81
+ for (const seg of segments) {
82
+ if (seg.mode === "byte") {
83
+ const bytes = new TextEncoder().encode(seg.data);
84
+ put(0b0100, 4); put(bytes.length, countBits("byte", version));
85
+ for (const b of bytes) put(b, 8);
86
+ } else {
87
+ put(0b0010, 4); put(seg.data.length, countBits("alphanumeric", version));
88
+ const at = (i) => ALPHANUMERIC.indexOf(seg.data[i]);
89
+ for (let i = 0; i + 1 < seg.data.length; i += 2) put(at(i) * 45 + at(i + 1), 11);
90
+ if (seg.data.length % 2) put(at(seg.data.length - 1), 6);
91
+ }
92
+ }
69
93
  put(0, Math.min(4, capacity - bits.length));
70
94
  while (bits.length % 8) bits.push(0);
71
95
  for (let pad = 0; bits.length < capacity; pad += 1) put(pad % 2 ? 0x11 : 0xec, 8);
@@ -164,18 +188,22 @@ export function penalty(m) {
164
188
  return points + Math.abs(Math.ceil((dark * 100) / (size * size) / 5) - 10) * 10;
165
189
  }
166
190
 
167
- /** The modules of the QR code for `text` (UTF-8 bytes), `mask` chosen by penalty unless given. */
168
- export function qrMatrix(text, forcedMask = null, level = "M") {
169
- const { version, out } = codewords(new TextEncoder().encode(text), level);
191
+ /** The modules of the QR code for `text` (UTF-8 bytes, one byte segment unless `segments` says otherwise), `mask` chosen by penalty unless given. */
192
+ export function qrMatrix(text, forcedMask = null, level = "M", segments = [{ mode: "byte", data: text }]) {
193
+ const { version, out } = codewords(segments, level);
170
194
  if (forcedMask !== null) return { version, mask: forcedMask, modules: place(version, out, forcedMask, level) };
171
195
  let best = null;
172
196
  for (let mask = 0; mask < 8; mask += 1) { const modules = place(version, out, mask, level), score = penalty(modules); if (!best || score < best.score) best = { version, mask, modules, score }; }
173
197
  return { version: best.version, mask: best.mask, modules: best.modules };
174
198
  }
175
199
 
176
- /** The quiet zone, in modules, around every code the CLI draws (the standard's four; its ground is drawn white). */
177
- export const QUIET = 4;
178
- /** Half blocks, black on white, a four-module quiet zone. `color` false gives the plain characters (dark = block). */
200
+ /**
201
+ * THE QUIET ZONE, in modules, around every code the CLI draws: two (CLI 0.11.12, owner 2026-11-15: "about 4 x 4 cm"), half
202
+ * the standard's four. A terminal code is drawn on its own explicitly white ground, so the margin a printed code needs
203
+ * against the paper's surroundings is the ground itself; the phone's scanner and the iOS camera read a 2-module margin.
204
+ */
205
+ export const QUIET = 2;
206
+ /** Half blocks, black on white, the quiet zone above. `color` false gives the plain characters (dark = block). */
179
207
  export function renderQr(modules, { color = true } = {}) {
180
208
  const quiet = QUIET, size = modules.length + quiet * 2;
181
209
  const dark = (r, c) => { const rr = r - quiet, cc = c - quiet; return rr >= 0 && cc >= 0 && rr < modules.length && cc < modules.length && modules[rr][cc]; };
@@ -190,11 +218,14 @@ export function renderQr(modules, { color = true } = {}) {
190
218
 
191
219
  /**
192
220
  * EVERY QR THE CLI DRAWS GOES THROUGH HERE (owner, 2026-11-14: "make the QR more compact"): the approval, the pairing and the
193
- * one-scan code alike, level L, half blocks (two module rows per terminal line), the white quiet zone, so a version-10 code
194
- * is 33 lines by 65 columns and fits an 80-column terminal. `color` as renderQr: the ground drawn white on a terminal with
195
- * colours, the plain characters otherwise (a pipe, NO_COLOR). check-remote-cli and cli-01110-cases hold that no other path
196
- * draws one.
221
+ * one-scan code alike, level L, half blocks (one character per module across, two module rows per terminal line), the
222
+ * white quiet zone, and since 0.11.12 an alphanumeric segment for a compact pairing fragment (segmentsOf). Sizes, level L:
223
+ * the compact pairing code is version 4 (33 modules): 37 characters by 19 lines; the approval link alone version 4; the
224
+ * one-scan approval with its compact fragment version 5 (37 modules): 41 by 21. At a 13 px monospace font (a cell about
225
+ * 7.8 px wide, so one module about 7.8 px square) 37 characters are about 289 px: 7.6 cm at 96 px an inch, 5.8 cm on a
226
+ * 127 px-an-inch laptop screen. `color` as renderQr: the ground drawn white on a terminal with colours, the plain characters
227
+ * otherwise (a pipe, NO_COLOR). check-remote-cli and cli-01110-cases hold that no other path draws one.
197
228
  */
198
229
  export function terminalQr(text, { color = true } = {}) {
199
- return renderQr(qrMatrix(text, null, "L").modules, { color });
230
+ return renderQr(qrMatrix(text, null, "L", segmentsOf(text)).modules, { color });
200
231
  }