granttap-mcp 0.8.191 → 0.8.193

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.
@@ -18,6 +18,7 @@ import type { ApprovalDecision, ApprovalRequest, Risk } from "../../../../packag
18
18
  import { createHash } from "node:crypto";
19
19
  import { randomId } from "../../../../packages/core/crypto";
20
20
  import { approvalPresentation } from "./approval-presentation";
21
+ import { removesOnlyTempPaths } from "../policy/shell/temp-removal";
21
22
 
22
23
  const HIGH = [
23
24
  /\brm\s+-rf?\b/,
@@ -31,7 +32,9 @@ const HIGH = [
31
32
  /:\s*>\s*\//, // truncate a file
32
33
  /\bchmod\s+-r\b/,
33
34
  ];
34
- const isHighRisk = (command: string): boolean => HIGH.some((re) => re.test(command.toLowerCase()));
35
+ const TEMP_REMOVAL = HIGH[0];
36
+ const isHighRisk = (command: string): boolean => HIGH.some((re) => re.test(command.toLowerCase())
37
+ && !(re === TEMP_REMOVAL && removesOnlyTempPaths(command)));
35
38
 
36
39
  /** Heuristic risk tag so the watch can color/rank the request at a glance. */
37
40
  export function guessRisk(tool: string, command: string | undefined): Risk {
@@ -27,3 +27,10 @@ eleven-minute lease only has to cover that window. The answer, or the reason a
27
27
  long run stopped, reaches the chat when the run ends; unattended runs are
28
28
  bounded at six hours. New-task startup events are status updates; the
29
29
  correlated result is terminal. Delivery integration tests live in `tests/delivery`.
30
+
31
+ The routing monitor writes one line for each phone request it drops
32
+ (`dropped-requests/`): one it cannot open or read, and one whose
33
+ handler failed before answering, such as an answer the relay queue gave up.
34
+ The line names the request's type and the reason, never its contents or keys,
35
+ and repeats at most once a minute with a count. Monitors that do not route
36
+ stay quiet; the router answers or says why it did not.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * One line in the monitor's log for each phone request it drops: one it cannot open, one this runtime
3
+ * cannot read, one it could not answer. A drop used to leave no trace, so a phone that waited in vain
4
+ * looked like a computer that had answered. Never a request's contents or keys; a line repeats at most
5
+ * once a minute and then says how many it stood for.
6
+ */
7
+ import { ZodError } from "zod";
8
+ import type { UnreadableFrame } from "../../../../../packages/core/relay-inbound";
9
+
10
+ const WHY: Record<UnreadableFrame["reason"], string> = {
11
+ "no-key": "it is sealed for a chat this computer holds no key for",
12
+ unopenable: "its chat's key does not open it",
13
+ "wrong-scope": "it names another chat than the one it is sealed for",
14
+ unknown: "this runtime cannot read it",
15
+ };
16
+ const KEPT = 64;
17
+
18
+ function reason(error: unknown): string {
19
+ if (error instanceof ZodError) return "the answer does not fit the protocol";
20
+ const message = error instanceof Error ? error.message : String(error);
21
+ return message.split("\n", 1)[0]!.trim().slice(0, 120) || "an unnamed error";
22
+ }
23
+
24
+ export function droppedRequestLog(write: (line: string) => void = (line) => { process.stderr.write(line); },
25
+ now: () => number = Date.now, spacingMs = 60_000) {
26
+ const shown = new Map<string, { at: number; since: number }>();
27
+ const note = (line: string): void => {
28
+ const last = shown.get(line);
29
+ if (last && now() - last.at < spacingMs) { last.since += 1; return; }
30
+ shown.delete(line);
31
+ shown.set(line, { at: now(), since: 0 });
32
+ while (shown.size > KEPT) shown.delete(shown.keys().next().value!);
33
+ write(`[monitor] ${line}${last?.since ? ` (${last.since} more like it since the last such line)` : ""}\n`);
34
+ };
35
+ return {
36
+ unreadable: (frame: UnreadableFrame) => note(`dropped a phone ${frame.type ?? "request"}: ${WHY[frame.reason]}`),
37
+ unanswered: (type: string, error: unknown) => note(`dropped a phone ${type} unanswered: ${reason(error)}`),
38
+ };
39
+ }
@@ -43,6 +43,7 @@ import { decorateTaskOriginCatalog } from '../../task-origins';
43
43
  import { publishCodexQuestions } from '../../codex-questions';
44
44
  import { publishClaudeOpenQuestions } from '../../claude-open-questions';
45
45
  import { startTaskActivities } from '../../task-activities';
46
+ import { droppedRequestLog } from '../dropped-requests';
46
47
  import type { PeerConfig } from '../../../../../packages/core/relay-client';
47
48
 
48
49
  const HISTORY_INTERVAL_MS = 60_000;
@@ -231,18 +232,7 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
231
232
  lastHistoryPublishedAt = next.lastHistoryPublishedAt;
232
233
  });
233
234
 
234
- const off = client.onMessage((payload: Payload, peerPublicKey) => work.run(async () => {
235
- if (payload.type === "hello" && payload.role === "phone") {
236
- confirmPendingController(client.room, peerPublicKey);
237
- recordControllerName(peerPublicKey, payload.deviceName);
238
- if (leadership.acquire()) {
239
- await client.send(approvalsStatus(), 'phone', { peerPublicKey, reliable: false, ttlMs: 90_000 })
240
- .catch(() => {});
241
- await replayNativeQuestions(client, peerPublicKey);
242
- }
243
- }
244
- return await handleMonitorMessage(client, payload, { leadership, subscriptions, publish, peerPublicKey });
245
- }));
235
+ const off = listenToPhones(client, { leadership, subscriptions, publish, work });
246
236
 
247
237
  const offConnected = client.onConnected?.(() => publish().catch(() => {}));
248
238
 
@@ -297,6 +287,33 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
297
287
  };
298
288
  }
299
289
 
290
+ /** Phone payloads go to the monitor's router; a request it drops is said in one line (`dropped-requests`). */
291
+ function listenToPhones(client: RelayClient, input: { leadership: ReturnType<typeof monitorLeadership>;
292
+ subscriptions: Set<string>; publish: (forceHistory?: boolean) => Promise<void>; work: ReturnType<typeof monitorWork> }) {
293
+ const { leadership, subscriptions, publish, work } = input;
294
+ const dropped = droppedRequestLog();
295
+ // Every MCP server hears the phone too; only the one that routes says what it could not take.
296
+ const offUnreadable = client.onUnreadable?.((frame) => { if (leadership.acquire()) dropped.unreadable(frame); });
297
+ const off = client.onMessage((payload: Payload, peerPublicKey) => work.run(async () => {
298
+ if (payload.type === "hello" && payload.role === "phone") {
299
+ confirmPendingController(client.room, peerPublicKey);
300
+ recordControllerName(peerPublicKey, payload.deviceName);
301
+ if (leadership.acquire()) {
302
+ await client.send(approvalsStatus(), 'phone', { peerPublicKey, reliable: false, ttlMs: 90_000 })
303
+ .catch(() => {});
304
+ await replayNativeQuestions(client, peerPublicKey);
305
+ }
306
+ }
307
+ try {
308
+ return await handleMonitorMessage(client, payload, { leadership, subscriptions, publish, peerPublicKey });
309
+ } catch (error) {
310
+ if (leadership.acquire()) dropped.unanswered(payload.type, error);
311
+ return false;
312
+ }
313
+ }));
314
+ return () => { offUnreadable?.(); off(); };
315
+ }
316
+
300
317
  /** Work a runtime update waits for. A run a newer monitor can take over is not among it (`reply/survival`). */
301
318
  function monitorWork() {
302
319
  return runtimeWorkTracker(() => blockingDeliveries().length > 0 || lateRunsSettling() || adoptedRunsSettling()
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { guessRisk } from "../host/adapters";
8
8
  import { isSafeReadonlyShell } from "./shell/safe-shell";
9
+ import { removesOnlyTempPaths } from "./shell/temp-removal";
9
10
  export { isSafeReadonlyShell } from "./shell/safe-shell";
10
11
 
11
12
  export type ActionClass =
@@ -49,7 +50,7 @@ export function classifyAction(tool: string, command: string | null | undefined)
49
50
  if (/\bgit\s+reset\s+--hard\b/.test(c)) return "git_force";
50
51
 
51
52
  if (
52
- /\brm\s+-rf?\b/.test(c) ||
53
+ (/\brm\s+-rf?\b/.test(c) && !removesOnlyTempPaths(command ?? "")) ||
53
54
  /\bsudo\b/.test(c) ||
54
55
  /\b(drop|truncate)\s+table\b/.test(c) ||
55
56
  /\bdd\s+if=/.test(c) ||
@@ -5,6 +5,15 @@ grammar used by Cursor's safe auto-accept path. Unrecognized options and shell
5
5
  syntax require a decision. The Project policy and machine-level deny still run
6
6
  before this legacy auto-accept check.
7
7
 
8
+ `temp-removal.ts` decides when `rm -rf` is ordinary work rather than a destructive action: every
9
+ `rm` in the command starts its own simple command, takes only `-r`, `-R`, `-f` or `-v`, and names
10
+ literal absolute paths whose real parent folder lies inside `/tmp`, `/private/tmp` or the system
11
+ temp folder. Variables, command substitution, globs, quotes other than plain single quotes, `..`,
12
+ `.`, a trailing slash, a redirection, the temp root itself, a missing parent folder or a parent
13
+ reached through a symbolic link out of the temp folder make it destructive again, so "All except
14
+ push" still asks. `sudo` and the other destructive patterns are unaffected. The approval's risk
15
+ tag follows the same rule.
16
+
8
17
  See [the policy module](../README.md) and the repository engineering index.
9
18
 
10
19
  License: this module is distributed under the GrantTap Commercial Source License in the repository-root
@@ -0,0 +1,66 @@
1
+ /**
2
+ * `rm -rf` of a scratch folder a chat made under the system temp folder is ordinary work, not a
3
+ * destructive action. Only plain commands qualify: every `rm` starts its own simple command, takes
4
+ * only `-r`/`-R`/`-f`/`-v` flags, and names literal absolute paths whose real parent lies inside a
5
+ * temp root. Shell expansion, globs, `..`, a trailing slash or the temp root itself make it ask again.
6
+ */
7
+ import { realpathSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { dirname } from "node:path";
10
+
11
+ const SEPARATORS = /;|&&|\|\||\||&|\n|\(|\)/;
12
+ const UNSAFE = /[$`*?[\]{}~<>\\"]/;
13
+ const FLAG = /^-[rRfv]+$/;
14
+ const PATH = /^\/[A-Za-z0-9._@%+=:,/-]+$/;
15
+
16
+ function realOrSelf(path: string): string {
17
+ try { return realpathSync(path); } catch { return path; }
18
+ }
19
+
20
+ function tempRoots(): string[] {
21
+ const roots = ["/tmp", "/private/tmp", tmpdir()].map(realOrSelf).map(root => root.replace(/\/+$/, ""));
22
+ return [...new Set(roots.filter(root => root.length > 1))];
23
+ }
24
+
25
+ /** The path's real parent must exist inside a temp root; the path itself must lie below it. */
26
+ function insideTemp(path: string, roots: string[]): boolean {
27
+ if (!PATH.test(path) || path.endsWith("/")) return false;
28
+ const parts = path.split("/").filter(Boolean);
29
+ if (parts.some(part => part === "." || part === "..")) return false;
30
+ let parent: string;
31
+ try { parent = realpathSync(dirname(path)); } catch { return false; }
32
+ return roots.some(root => parent === root || parent.startsWith(`${root}/`))
33
+ && !roots.includes(realOrSelf(path));
34
+ }
35
+
36
+ function unquote(token: string): string | undefined {
37
+ const quoted = /^'([^']*)'$/.exec(token);
38
+ if (quoted) return quoted[1];
39
+ return token.includes("'") ? undefined : token;
40
+ }
41
+
42
+ /** True when the command removes something and every removal is a literal path under a temp root. */
43
+ export function removesOnlyTempPaths(command: string): boolean {
44
+ const roots = tempRoots();
45
+ let removals = 0;
46
+ for (const segment of command.split(SEPARATORS)) {
47
+ const tokens = segment.trim().split(/\s+/).filter(Boolean);
48
+ const at = tokens.findIndex((token, index) => token === "rm" || token === "/bin/rm"
49
+ || (token === "command" && tokens[index + 1] === "rm"));
50
+ if (at === -1) continue;
51
+ if (at !== 0) return false;
52
+ if (UNSAFE.test(segment)) return false;
53
+ const args = tokens.slice(tokens[0] === "command" ? 2 : 1).map(unquote);
54
+ if (args.some(arg => arg === undefined)) return false;
55
+ let paths = 0, literal = false;
56
+ for (const arg of args as string[]) {
57
+ if (!literal && arg === "--") { literal = true; continue; }
58
+ if (!literal && arg.startsWith("-")) { if (!FLAG.test(arg)) return false; continue; }
59
+ if (!insideTemp(arg, roots)) return false;
60
+ paths += 1;
61
+ }
62
+ if (paths === 0) return false;
63
+ removals += 1;
64
+ }
65
+ return removals > 0;
66
+ }
@@ -33,6 +33,13 @@ not send `confirmWhileWorking: true`. Otherwise the paths not yet staged are add
33
33
  staged work stays staged and out of the commit. The repository's hooks run; a hook's refusal is
34
34
  `failed`. Nothing is pushed, and no option bypasses hooks or signing.
35
35
 
36
- Tests live in `tests/`, against real temporary repositories.
36
+ Both answers travel in the relay queue's control lane, like a picture's chunks, ahead of catalogs,
37
+ Mesh snapshots and load reports. In 0.8.190 they waited among those replaceable snapshots: on a
38
+ computer whose upload was backed up they reached the phone after it had stopped waiting, or were
39
+ dropped for newer traffic, and the phone's sheet only spun.
40
+
41
+ Tests live in `tests/`, against real temporary repositories. `phone-round-trip.test.ts` carries a
42
+ listing and a commit from a phone-role client through a loopback relay, both encryption layers and
43
+ the monitor's routing, while the computer's upload is backed up with load reports.
37
44
 
38
45
  Licensed under the GrantTap Commercial Source License. See the repository root `LICENSE`.
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
10
10
  Install the supported CLI on this computer, then run:
11
11
 
12
12
  ```bash
13
- npm install -g granttap-mcp@0.8.191
13
+ npm install -g granttap-mcp@0.8.193
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.191\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.193\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.191";
10
+ const PACKAGE = "granttap-mcp@0.8.193";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.191",
3
+ "version": "0.8.193",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -3,7 +3,10 @@
3
3
  Public entry: `RelayClient` in `relay-client.ts`. Machine and phone endpoints
4
4
  seal every payload for an authorized peer. `relay-inbound` authenticates routing,
5
5
  peer keys and optional per-task encryption before a consumer receives content.
6
- The relay sees routing metadata and opaque ciphertext only.
6
+ The relay sees routing metadata and opaque ciphertext only. A frame an allowed
7
+ peer sealed that no consumer can read (no key for its chat, a key that does not
8
+ open it, a chat other than its seal's, or a type this runtime does not know) is
9
+ reported to `onUnreadable` listeners by reason and payload name, never content.
7
10
 
8
11
  Ordinary consumers return true only after durable application acceptance.
9
12
  `RelayMessageAcceptance` binds replay protection to ciphertext, including across
@@ -14,6 +14,13 @@ superseded; only a queue of controls refuses with "relay outbound queue is full"
14
14
  A burst of catalog and Mesh refreshes for hundreds of short runs once filled the
15
15
  queue and refused 103 Graph answers in a day; a Graph answer now also travels in
16
16
  the control lane.
17
+ Every answer a phone waits on travels there too (`PHONE_ANSWERS`): a requested
18
+ picture, a chat's changes and commit result, a computer's phones and cache
19
+ (`device.manage.result`), files and schedules. A Mesh Task's result goes from
20
+ computer to computer over its own transport and is not listed. On a Mac whose
21
+ snapshot lane was dropping frames, the phones list and the Changes sheet waited
22
+ until the phone gave up. `tests/phone-answers.test.ts` reads every `*.result`
23
+ type from the protocol, so a new phone answer cannot be left in the snapshot lane.
17
24
 
18
25
  Disconnect rejects the current write as well as queued frames. Catalog and
19
26
  history publishers can retry on the next connection even if the previous
@@ -41,8 +48,11 @@ a requester retain the complete authorized recipient set. Every explicit target
41
48
  passes the pairing and controller authorization checks. Routing never deletes a
42
49
  pairing or changes approval policy.
43
50
 
44
- Requested image chunks retain their local scheduling priority through task
45
- encryption and precede background transcript backfill. The local `urgent` send
51
+ Answers a phone waits on (image chunks, a chat's changes, a commit's result)
52
+ retain their local scheduling priority through task encryption and precede
53
+ background transcript backfill. Queued behind a backed-up upload, a chat's
54
+ changes once arrived after the phone had stopped waiting, or were dropped as a
55
+ superseded snapshot without a word. The local `urgent` send
46
56
  hint is never serialized into relay routing metadata and does not request APNs.
47
57
  The image-priority test receives and decrypts both layers and verifies ordering
48
58
  while preserving every background frame and the existing six-millisecond pace.
@@ -110,8 +110,15 @@ export class OutboundFrameQueue {
110
110
  }
111
111
  }
112
112
 
113
- export const priorityControlPayload = (type: Payload["type"]) => type === "hello" || type === "session.image.chunk" || type.startsWith("approval.")
114
- || type.startsWith("config.") || type.startsWith("pairing.") || type === "session.key.grant"
113
+ /**
114
+ * Answers a phone waits on go here, never among replaceable snapshots: a snapshot can be dropped for
115
+ * newer traffic, and an answer behind a backed-up upload arrives after the phone stopped waiting.
116
+ */
117
+ const PHONE_ANSWERS = new Set<Payload["type"]>(["session.image.chunk", "session.changes.result", "session.commit.result",
118
+ "device.manage.result", "session.workspace.result", "task.schedules.result"]);
119
+
120
+ export const priorityControlPayload = (type: Payload["type"]) => type === "hello" || PHONE_ANSWERS.has(type)
121
+ || type.startsWith("approval.") || type.startsWith("config.") || type.startsWith("pairing.") || type === "session.key.grant"
115
122
  || type === "delivery.receipt" || type === "sessions.status" || type === "machine.heartbeat" || type === "approvals.status";
116
123
 
117
124
  export async function sendEncryptedPayload(queue: OutboundFrameQueue, config: PeerConfig,
@@ -5,7 +5,7 @@ import WebSocket from "ws";
5
5
  import { ManagedRelayLease, RelaySocketHealth, RelayReconnectBackoff, RelayConnectionNotifications, relayUpgradeHeaders } from "./socket-lifecycle";
6
6
  import { RelayLinkWatch, type LinkStuckReport } from "./socket-lifecycle/link-watch";
7
7
  import { OutboundFrameQueue, sendEncryptedPayload, priorityControlPayload } from "./outbound-scheduler";
8
- import { openRelayMessage, parseRelayControl, waitForRelayPayload } from "./relay-inbound";
8
+ import { openRelayMessage, parseRelayControl, waitForRelayPayload, type UnreadableFrame } from "./relay-inbound";
9
9
  import { consumeTaskJobOffer, type TaskDispatchListener } from "./task-dispatch";
10
10
  import { Payload, type Role } from "../protocol/schema";
11
11
  import { clearSharedBoxKeys, peerPublicKeys } from "./crypto";
@@ -37,6 +37,7 @@ export class RelayClient {
37
37
  for (const listener of this.linkStuckListeners) { try { listener(report); } catch { /* the watch outlives a listener */ } }
38
38
  } });
39
39
  private readonly refusalLoggedAt = new Map<string, number>();
40
+ private readonly unreadableListeners = new Set<(frame: UnreadableFrame) => void>();
40
41
  private readonly sessionKeys = new Map<string, string>();
41
42
  private readonly replay: RelayMessageAcceptance;
42
43
  /** Read state this connection already handed to the relay, which replays it to joining phones. */
@@ -174,7 +175,9 @@ export class RelayClient {
174
175
  }));
175
176
  return;
176
177
  }
177
- const opened = openRelayMessage(this.cfg, control, this.sessionKeys, key => this.peerIsAllowed(key));
178
+ const opened = openRelayMessage(this.cfg, control, this.sessionKeys, key => this.peerIsAllowed(key), frame => {
179
+ for (const listener of this.unreadableListeners) { try { listener(frame); } catch { /* a report never stops the socket */ } }
180
+ });
178
181
  if (!opened || opened.payload.type === "task.dispatch") return;
179
182
  const { env, payload, peerPublicKey, fingerprint } = opened;
180
183
  if (this.replay.hasAccepted(fingerprint)) {
@@ -312,6 +315,12 @@ export class RelayClient {
312
315
  return this.connections.subscribe(listener);
313
316
  }
314
317
 
318
+ /** Told of each frame an allowed peer sealed for this side that no consumer could read; see `UnreadableFrame`. */
319
+ onUnreadable(listener: (frame: UnreadableFrame) => void): () => void {
320
+ this.unreadableListeners.add(listener);
321
+ return () => { this.unreadableListeners.delete(listener); };
322
+ }
323
+
315
324
  onMessage(l: Listener): () => void {
316
325
  this.listeners.add(l);
317
326
  return () => this.listeners.delete(l);
@@ -10,9 +10,23 @@ export function parseRelayControl(raw: string): unknown {
10
10
  catch { return null; }
11
11
  }
12
12
 
13
+ /**
14
+ * Why a frame an allowed peer sealed for us reached no consumer: sealed for a chat whose key is not
15
+ * held (`no-key`), not opened by that key (`unopenable`), naming another chat than its seal
16
+ * (`wrong-scope`), or of a type or shape this runtime does not read (`unknown`). Never its contents;
17
+ * `type` only when it is a plain payload name.
18
+ */
19
+ export type UnreadableFrame = { reason: 'no-key' | 'unopenable' | 'wrong-scope' | 'unknown'; type?: string };
20
+ type Unreadable = (frame: UnreadableFrame) => void;
21
+
22
+ const payloadType = (body: unknown): string | undefined => {
23
+ const type = body && typeof body === 'object' && 'type' in body ? body.type : undefined;
24
+ return typeof type === 'string' && /^[a-z][a-z0-9.-]{0,63}$/.test(type) ? type : undefined;
25
+ };
26
+
13
27
  /** Authenticate routing, peer identity and optional task encryption before consumers run. */
14
28
  export function openRelayMessage(cfg: PeerConfig, raw: unknown, sessionKeys: Map<string, string>,
15
- peerAllowed: (key: string) => boolean) {
29
+ peerAllowed: (key: string) => boolean, unreadable: Unreadable = () => {}) {
16
30
  const parsed = Envelope.safeParse(raw);
17
31
  if (!parsed.success) return undefined;
18
32
  const env = parsed.data;
@@ -31,27 +45,34 @@ export function openRelayMessage(cfg: PeerConfig, raw: unknown, sessionKeys: Map
31
45
  const paths = parsedPayload.error.issues.map(issue => `${issue.path.join('.')}:${issue.code}`);
32
46
  console.error(`[granttap] dropped pairing.join (${paths.join(',') || 'invalid'})`);
33
47
  }
48
+ unreadable({ reason: 'unknown', type: payloadType(body) });
34
49
  return undefined;
35
50
  }
36
- const payload = unwrapTaskPayload(parsedPayload.data, cfg.role, sessionKeys);
51
+ const payload = unwrapTaskPayload(parsedPayload.data, cfg.role, sessionKeys, unreadable);
37
52
  if (!payload) return undefined;
38
53
  const fingerprint = createHash('sha256').update(env.nonce).update('.').update(env.box).digest('base64url');
39
54
  return { env, payload, peerPublicKey: opened.peerPublicKey, fingerprint };
40
55
  }
41
56
 
42
- function unwrapTaskPayload(payload: Payload, role: string, sessionKeys: Map<string, string>): Payload | undefined {
57
+ function unwrapTaskPayload(payload: Payload, role: string, sessionKeys: Map<string, string>,
58
+ unreadable: Unreadable): Payload | undefined {
43
59
  if (payload.type === 'session.key.grant') {
44
60
  if (role === 'machine' && !['task', 'project'].includes(payload.purpose ?? '')) return undefined;
45
61
  return payload;
46
62
  }
47
63
  if (payload.type !== 'session.sealed') return payload;
48
64
  const key = sessionKeys.get(payload.sessionId);
49
- if (!key) return undefined;
50
- const inner = Payload.safeParse(openWithTransferKey(payload.nonce, payload.box, key));
51
- if (!inner.success || inner.data.type === 'session.key.grant' || inner.data.type === 'session.sealed') return undefined;
65
+ if (!key) { unreadable({ reason: 'no-key' }); return undefined; }
66
+ const body = openWithTransferKey(payload.nonce, payload.box, key);
67
+ if (body === null) { unreadable({ reason: 'unopenable' }); return undefined; }
68
+ const inner = Payload.safeParse(body);
69
+ if (!inner.success || inner.data.type === 'session.key.grant' || inner.data.type === 'session.sealed') {
70
+ unreadable({ reason: 'unknown', type: payloadType(body) });
71
+ return undefined;
72
+ }
52
73
  const sessionId = 'sessionId' in inner.data ? inner.data.sessionId : undefined;
53
74
  if (!payload.sessionId.trim() || typeof sessionId !== 'string' || !sessionId.trim()
54
- || sessionId !== payload.sessionId) return undefined;
75
+ || sessionId !== payload.sessionId) { unreadable({ reason: 'wrong-scope', type: inner.data.type }); return undefined; }
55
76
  return inner.data;
56
77
  }
57
78