synabun 2.2.0 → 2.2.2

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.
Files changed (166) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +1 -1
  3. package/hooks/claude-code/pre-websearch.mjs +4 -1
  4. package/hooks/claude-code/prompt-submit.mjs +7 -0
  5. package/lib/release-scan.mjs +23 -10
  6. package/lib/virustotal.mjs +143 -39
  7. package/mcp-server/dist/http.d.ts +19 -0
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +55 -13
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +14 -9
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-route-flow.d.ts +118 -0
  15. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
  16. package/mcp-server/dist/services/browser-route-flow.js +339 -0
  17. package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
  18. package/mcp-server/dist/services/desktop-client.js +2 -2
  19. package/mcp-server/dist/services/desktop-client.js.map +1 -1
  20. package/mcp-server/dist/services/identity.d.ts +66 -3
  21. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  22. package/mcp-server/dist/services/identity.js +61 -4
  23. package/mcp-server/dist/services/identity.js.map +1 -1
  24. package/mcp-server/dist/services/neural-interface.d.ts +112 -1
  25. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  26. package/mcp-server/dist/services/neural-interface.js +555 -61
  27. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  28. package/mcp-server/dist/tools/bluesky.d.ts +20 -7
  29. package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
  30. package/mcp-server/dist/tools/bluesky.js +147 -45
  31. package/mcp-server/dist/tools/bluesky.js.map +1 -1
  32. package/mcp-server/dist/tools/browser-advanced.d.ts +11 -2
  33. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-advanced.js +131 -18
  35. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
  37. package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
  39. package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
  40. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  41. package/mcp-server/dist/tools/morelogin.js +4 -2
  42. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  43. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  44. package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
  45. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/helpers.js +1 -1
  47. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  48. package/mcp-server/package-lock.json +2 -2
  49. package/mcp-server/package.json +1 -1
  50. package/mcp-server/src/http.ts +58 -12
  51. package/mcp-server/src/index.ts +15 -9
  52. package/mcp-server/src/services/browser-route-flow.ts +402 -0
  53. package/mcp-server/src/services/desktop-client.ts +2 -2
  54. package/mcp-server/src/services/identity.ts +80 -4
  55. package/mcp-server/src/services/neural-interface.ts +572 -70
  56. package/mcp-server/src/tools/bluesky.ts +164 -51
  57. package/mcp-server/src/tools/browser-advanced.ts +121 -17
  58. package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
  59. package/mcp-server/src/tools/morelogin.ts +4 -2
  60. package/mcp-server/src/tools/youtube/helpers.ts +2 -2
  61. package/neural-interface/i18n/en.json +27 -0
  62. package/neural-interface/i18n/pt-BR.json +27 -0
  63. package/neural-interface/lib/assistant-api.js +64 -23
  64. package/neural-interface/lib/assistant-brains/codex.js +6 -1
  65. package/neural-interface/lib/assistant-catalog.js +20 -2
  66. package/neural-interface/lib/assistant-dispatch.js +31 -2
  67. package/neural-interface/lib/assistant-persona.js +1 -0
  68. package/neural-interface/lib/assistant-runtime.js +15 -1
  69. package/neural-interface/lib/assistant-tools.js +10 -1
  70. package/neural-interface/lib/browser-automation-routes.js +84 -0
  71. package/neural-interface/lib/browser-execution.js +16 -3
  72. package/neural-interface/lib/browser-owner.js +48 -0
  73. package/neural-interface/lib/browser-session-close.js +84 -0
  74. package/neural-interface/lib/browser-start-handoff.js +202 -0
  75. package/neural-interface/lib/browser-tool-policy.js +21 -4
  76. package/neural-interface/lib/browser-wedge-retire.js +64 -0
  77. package/neural-interface/lib/claude-agent-bridge.js +36 -1
  78. package/neural-interface/lib/claude-background-hold.js +239 -0
  79. package/neural-interface/lib/exec-loop-command.js +8 -0
  80. package/neural-interface/lib/http-guards.js +11 -6
  81. package/neural-interface/lib/loop-logger.js +6 -1
  82. package/neural-interface/lib/mcp-external-servers.js +64 -13
  83. package/neural-interface/lib/native-loop-providers.js +122 -10
  84. package/neural-interface/lib/native-loop-runtime.js +112 -11
  85. package/neural-interface/lib/opencode-native-boundary.js +155 -21
  86. package/neural-interface/lib/owner-authority.js +113 -37
  87. package/neural-interface/lib/page-session.js +81 -23
  88. package/neural-interface/lib/peer-identity.js +311 -47
  89. package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
  90. package/neural-interface/lib/pty-host/core.js +36 -0
  91. package/neural-interface/lib/pty-host/protocol.js +2 -0
  92. package/neural-interface/lib/skills/api-v2.js +13 -2
  93. package/neural-interface/lib/skills/creation-api.js +3 -1
  94. package/neural-interface/lib/skills/evals-api.js +5 -1
  95. package/neural-interface/lib/social-write-pacing.js +151 -0
  96. package/neural-interface/lib/terminal-token-redaction.js +293 -0
  97. package/neural-interface/lib/terminal-tokens.js +359 -0
  98. package/neural-interface/lib/worker-mcp-channel.js +45 -10
  99. package/neural-interface/package-lock.json +2 -2
  100. package/neural-interface/package.json +1 -1
  101. package/neural-interface/public/shared/agy/agy-render.js +41 -1
  102. package/neural-interface/public/shared/agy/agy-styles.js +5 -0
  103. package/neural-interface/public/shared/api.js +1 -0
  104. package/neural-interface/public/shared/assistant/asst-api.js +14 -2
  105. package/neural-interface/public/shared/assistant/asst-computer.js +73 -4
  106. package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
  107. package/neural-interface/public/shared/assistant/asst-motion-gate.js +80 -0
  108. package/neural-interface/public/shared/assistant/asst-panel.js +8 -4
  109. package/neural-interface/public/shared/assistant/asst-render.js +72 -11
  110. package/neural-interface/public/shared/assistant/asst-scene-styles.js +55 -23
  111. package/neural-interface/public/shared/assistant/asst-scenes.js +225 -79
  112. package/neural-interface/public/shared/assistant/asst-sidepanel-styles.js +4 -4
  113. package/neural-interface/public/shared/assistant/asst-style-cache.js +44 -0
  114. package/neural-interface/public/shared/assistant/asst-styles.js +26 -5
  115. package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
  116. package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
  117. package/neural-interface/public/shared/cp/cp-agents.js +8 -0
  118. package/neural-interface/public/shared/cp/cp-permissions.js +18 -2
  119. package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
  120. package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
  121. package/neural-interface/public/shared/judgments-log-origins.js +29 -0
  122. package/neural-interface/public/shared/loading-teardown.js +34 -0
  123. package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
  124. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +6 -1
  125. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
  126. package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
  127. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +5 -2
  128. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +16 -86
  129. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +6 -0
  130. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +88 -72
  131. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
  132. package/neural-interface/public/shared/owner-access.js +134 -0
  133. package/neural-interface/public/shared/owner-authority-view.js +92 -0
  134. package/neural-interface/public/shared/page-session.js +143 -14
  135. package/neural-interface/public/shared/poll-backoff.js +59 -0
  136. package/neural-interface/public/shared/settings/settings-data.js +6 -1
  137. package/neural-interface/public/shared/settings/settings-kit.js +11 -3
  138. package/neural-interface/public/shared/settings/settings-shell.js +7 -0
  139. package/neural-interface/public/shared/shown-children.js +72 -0
  140. package/neural-interface/public/shared/static-bg-state.js +22 -0
  141. package/neural-interface/public/shared/storage-retry.js +47 -0
  142. package/neural-interface/public/shared/storage.js +25 -4
  143. package/neural-interface/public/shared/styles.css +109 -8
  144. package/neural-interface/public/shared/synabun-mascot.js +27 -8
  145. package/neural-interface/public/shared/synabun-ticker.js +147 -12
  146. package/neural-interface/public/shared/synabun-tools.js +173 -0
  147. package/neural-interface/public/shared/tool-heartbeat.js +43 -0
  148. package/neural-interface/public/shared/tool-list-picker.js +3 -1
  149. package/neural-interface/public/shared/tool-list-view.js +23 -4
  150. package/neural-interface/public/shared/ui-automation-studio.js +8 -1
  151. package/neural-interface/public/shared/ui-claude-panel.js +238 -90
  152. package/neural-interface/public/shared/ui-judgments.js +37 -10
  153. package/neural-interface/public/shared/ui-loading.js +5 -4
  154. package/neural-interface/public/shared/ui-navbar.js +6 -0
  155. package/neural-interface/public/shared/ui-owner-access.js +191 -0
  156. package/neural-interface/public/shared/ui-owner-authority.js +162 -0
  157. package/neural-interface/public/shared/ui-sessions.js +45 -16
  158. package/neural-interface/public/shared/ui-settings.js +86 -15
  159. package/neural-interface/public/shared/ui-terminal.js +15 -7
  160. package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
  161. package/neural-interface/public/shared/ui-update.js +3 -0
  162. package/neural-interface/public/shared/ui-whiteboard.js +4 -0
  163. package/neural-interface/public/shared/window-keys.js +38 -0
  164. package/neural-interface/server.js +1240 -238
  165. package/npm-shrinkwrap.json +2 -2
  166. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,48 @@
1
+ # SynaBun v.2.2.2
2
+
3
+ 2.2.2 makes browser automations hold on to their tabs: a lost tab is announced and replaced instead of failing quietly, and one run can no longer close a browser session other runs are using. It also fixes a slow interface on Windows, tightens SynaBun's security on macOS, and tidies how SynaBun tool calls appear in the side panels.
4
+
5
+ ## 🛠 Fixed
6
+
7
+ - **A lost browser tab is announced** — When an agent's tab was closed under it, the next browser call quietly ran on a blank page, so agents read empty results or opened extra tabs. Now the answer starts by naming the replacement tab and telling the agent to keep using it. `browser_session` lists your own tabs, says which one you are working in, and has a new `status` action. Settings that only you may change, such as the browser profile, are refused with a clear message instead of being silently ignored.
8
+ - **Codex browser calls no longer end with a stray note** — Codex sends a tab id with every browser call, and `browser_session` used to answer with a "has no parameter" note each time. It now accepts the tab id, and the replacement-tab notice no longer runs into the rest of the answer.
9
+ - **One slow tab no longer ends every run's tab** — When one tab in a shared browser session got stuck and could not be replaced quickly, SynaBun closed the whole session, and every other run working there lost its tab. Now only the stuck tab is closed while the others still respond. A browser tool whose tab closes midway says so instead of reporting an empty page. An agent can no longer stop a MoreLogin profile that another automation is still using.
10
+ - **Closing a shared browser session no longer breaks other runs** — When an automation closed a session other automations were still using, it now releases only its own tab and the session stays open. Bluesky runs whose tab disappears find their way back on their own instead of failing with "Session not found".
11
+ - **Scheduled social automations no longer stop at their pacing gap** — Bluesky schedules that wait between posts could end the run during the wait, after the first post. SynaBun now handles the gap itself, waiting 60 to 120 seconds between writes on the same account, and a run waits for its own background work before finishing. Interactive use is never delayed.
12
+ - **Safer owner checks on macOS** — When SynaBun could not identify the process behind a connection, it fell back to trusting the caller. On macOS it now refuses owner actions until it can identify the caller, and an open tab recovers on its own once it can. Windows and Linux are unchanged.
13
+ - **Slow whiteboard and frozen interface on Windows** — A few style rules made every small change restyle the whole page, so dragging on the whiteboard stuttered and opening a console froze the window for over a second. The interface is now smooth again. The "Agents may use it" label in Settings → Connected tools now sits next to its switch.
14
+ - **A page without access says so** — When a page is refused owner access, it now shows a banner with a Reload button and marks the affected sections as "No access" instead of looking empty, and it stops polling the server. Escape closes Notifications and Automation Studio again, and Settings → Memory no longer fails to open.
15
+ - **No notification after every step of an OpenCode worker** — A dispatched OpenCode worker with limited permissions sent a system notification for every tool step. You now get one notification when the task completes.
16
+ - **SynaBun tool calls look like SynaBun cards in every panel** — Calls to Bluesky, YouTube, Search Console, agents, the Style Guide and other SynaBun tools showed as generic MCP rows with raw tool names. They now get a readable name such as "Bluesky · Post" and a short summary. Consecutive tool calls are grouped, and the ×N badge expands to show the folded calls.
17
+ - **No more purple lines splitting long tool calls** — In the Claude Code panel, a SynaBun tool call that ran longer than 30 seconds was split by an empty agent card. Long calls now show their elapsed time on the call's own card.
18
+ - **Collapsed Codex cards show their summary** — A collapsed SynaBun card in the Codex panel said "Tool call" while it ran. It now shows the same summary as an expanded one.
19
+ - **One broken MCP config no longer breaks the Assistant** — An unreadable or malformed MCP configuration from one provider stopped the Assistant from listing its models and tools. The other providers now keep working, and the Assistant says which provider's servers it could not check.
20
+ - **The AI decisions log filter stays current** — The origin filter in Settings → AI decisions no longer keeps offering origins that are gone.
21
+
22
+ ## ⚙️ Changed
23
+
24
+ - **Agents recover from a lost browser session** — An agent whose browser session is gone now opens a new one and carries on, and stops only if that fails too.
25
+
26
+ ---
27
+
28
+ # SynaBun v.2.2.1
29
+
30
+ 2.2.1 is a fix release: shared browser runs work again with MoreLogin, screenshots reach OpenAI models in the Assistant, and the Assistant no longer keeps the CPU busy while a worker runs.
31
+
32
+ ## ✨ New
33
+
34
+ - **Profiling the app with a debug client** — Developers can set `SYNABUN_ALLOW_DEBUG_CLIENT` to a port when starting SynaBun, so a local browser started with remote debugging on that port can load the app and profile it. It is off unless you set it.
35
+
36
+ ## 🛠 Fixed
37
+
38
+ - **Shared browser runs refused with an unclear error** — With MoreLogin as the browser, tasks that needed the browser could fail with a generic "unverified OpenCode serve" error even when OpenCode had nothing to do with the task. They now run, and a real refusal names its cause.
39
+ - **Screenshots ignored by OpenAI models in the Assistant** — Screenshots attached with the paperclip or sent from the whiteboard now reach Codex and OpenAI models as images.
40
+ - **High CPU while a worker ran** — The Assistant window used most of a CPU core while a worker was running. It now stays near idle.
41
+ - **Settings showed placeholders for ordinary MCP values** — When hiding secrets in MCP server settings, SynaBun also hid ordinary words such as the project name. Now only real credentials are hidden.
42
+ - **File Explorer git menu hidden under the toolbar** — The branch and commit menu now opens above the top-right toolbar instead of underneath it.
43
+
44
+ ---
45
+
1
46
  # SynaBun v.2.2.0
2
47
 
3
48
  2.2.0 is a reliability release: it fixes a slow memory buildup in long-running chat panels, makes closing a minimized OpenCode tab actually stop that conversation, and cleans up terminal processes left behind by a crash.
package/README.md CHANGED
@@ -178,7 +178,7 @@ Everything SynaBun stores is in one folder outside the app: `~/.synabun` on macO
178
178
 
179
179
  ## Links
180
180
 
181
- - [Changelog](./CHANGELOG.md): what is new in 2.2.0 and before
181
+ - [Changelog](./CHANGELOG.md): what is new in 2.2.2 and before
182
182
  - [Security](./SECURITY.md): security model and how to report a vulnerability
183
183
  - [Contributing](./CONTRIBUTING.md): bug reports and feature requests are welcome as [issues](https://github.com/danilokhury/Synabun/issues); pull requests are not accepted
184
184
  - [Website](https://synabun.ai), [docs](https://synabun.ai/docs) and [blog](https://synabun.ai/blog)
@@ -61,7 +61,10 @@ async function handleInput() {
61
61
  try {
62
62
  const controller = new AbortController();
63
63
  const timeout = setTimeout(() => controller.abort(), 2000);
64
- const res = await fetch(`${NI_BASE}/api/browser/sessions`, { signal: controller.signal });
64
+ // An agent's own call (X-Synabun-Role): the browser routes answer a request with no agent header only from
65
+ // SynaBun's own page (its page secret), so a bare request would be refused and read as "not reachable".
66
+ // Naming no run, it is an automation without an id: the list still shows every session (owner keys masked).
67
+ const res = await fetch(`${NI_BASE}/api/browser/sessions`, { signal: controller.signal, headers: { 'X-Synabun-Role': 'hook' } });
65
68
  clearTimeout(timeout);
66
69
  if (res.ok) {
67
70
  niReachable = true;
@@ -168,6 +168,10 @@ function extractFormattingRules(task) {
168
168
  return rules.map(r => `- ${r}`).join('\n');
169
169
  }
170
170
 
171
+ // What a loop does when its browser session or tab goes away: browserSessionLossRule() of
172
+ // neural-interface/lib/browser-tool-policy.js word for word, then the no-substitute line.
173
+ const BROWSER_SESSION_LOSS_RULE = 'If your browser session or tab is lost (closed, disconnected, "Session not found", "Tab … not found", or a browser tool says it is gone), call browser_session with action "create" and continue in the session and tab it returns (pass those ids from then on, if you pass ids). When the answer of a browser tool starts with a notice that a replacement tab is open ("Your tab … was lost; a replacement tab … is open"), or says a new tab already replaced the lost one, continue in that tab (its tabId from then on): do not create another. Create one only when nothing announced a replacement and your browser calls keep failing because the session or tab is gone. Only if creating one fails too, stop and report it. Never substitute another browser or tool.';
174
+
171
175
  function buildBrowserNote(state) {
172
176
  if (!state.usesBrowser) return '';
173
177
  const lines = [
@@ -195,6 +199,9 @@ function buildBrowserNote(state) {
195
199
  '2. Use ONLY SynaBun browser_* MCP tools. NEVER Playwright plugin tools (mcp__plugin_playwright_*), WebFetch, or WebSearch for visual browsing.',
196
200
  '3. browser_type truncates ~100 chars: type in <=90-char chunks. Reply inline, never the modal.',
197
201
  '4. Login / CAPTCHA / wall: STOP, screenshot, report to the user, and WAIT. Do NOT fall back to web search.',
202
+ // A copy of browserSessionLossRule() (neural-interface/lib/browser-tool-policy.js; a hook cannot import it):
203
+ // neural-interface/tests/browser-session-loss-server.test.mjs checks the two are the same.
204
+ `5. ${BROWSER_SESSION_LOSS_RULE}`,
198
205
  '=== END BROWSER ENFORCEMENT ===',
199
206
  );
200
207
  // Facebook posting playbook (analytics-derived). Kept in sync with FACEBOOK_PLAYBOOK in
@@ -5,24 +5,37 @@ import { basename, resolve } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import { applyReviews, credentials, hashFile, reports, VirusTotal } from './virustotal.mjs';
7
7
 
8
- export async function scanRelease({ files = [], urls = [], out, prefix = 'virustotal', reviewFile, client = new VirusTotal(), now = Date.now() }) {
8
+ /**
9
+ * `fallback(items)` (optional) runs after every scan of this run and may only turn
10
+ * an error item into an auditable status approved() checks on its own
11
+ * (the desktop gate's dmg equivalence, scripts/release/lib/dmg-equivalence.mjs).
12
+ */
13
+ export async function scanRelease({ files = [], urls = [], out, prefix = 'virustotal', reviewFile, client = new VirusTotal(), now = Date.now(), fallback }) {
9
14
  if (!files.length && !urls.length) throw new Error('No scan subjects supplied');
10
- const items = [];
15
+ // Missing/mismatched local bytes are hard errors, never reviewable detections:
16
+ // every file is checked before the first VirusTotal request.
17
+ const subjects = [];
11
18
  for (const file of files) {
12
19
  const path = typeof file === 'string' ? file : file.path;
13
20
  const expected = typeof file === 'string' ? undefined : file.sha256;
14
- // Missing/mismatched local bytes are hard errors, never reviewable detections.
15
21
  const sha256 = await hashFile(path);
16
22
  if (expected && sha256 !== expected) throw new Error(`SHA-256 mismatch: ${basename(path)}`);
17
- try { items.push(await client.file(path, sha256)); }
18
- catch (error) { items.push({ kind: 'file', name: basename(path), sha256, status: 'error', analysis_status: 'unavailable', error: error.message }); }
19
- }
20
- for (const url of urls) {
21
- try { items.push(await client.url(url)); }
22
- catch (error) { items.push({ kind: 'url', name: url, status: 'error', analysis_status: 'unavailable', error: error.message }); }
23
+ subjects.push({ path, sha256 });
23
24
  }
25
+ // Scans run concurrently so slow analyses (large dmgs) wait at the same time;
26
+ // the client's pace() still starts requests one at a time at the API rate.
27
+ // Items keep input order (files, then URLs) whatever finishes first.
28
+ const items = await Promise.all([
29
+ ...subjects.map(({ path, sha256 }) => client.file(path, sha256)
30
+ .catch(error => ({ kind: 'file', name: basename(path), sha256, status: 'error', analysis_status: 'unavailable', error: error.message }))),
31
+ ...urls.map(url => client.url(url)
32
+ .catch(error => ({ kind: 'url', name: url, status: 'error', analysis_status: 'unavailable', error: error.message }))),
33
+ ]);
24
34
  const reviews = reviewFile ? JSON.parse(await readFile(reviewFile, 'utf8')) : [];
25
- const result = reports(applyReviews(items, reviews, now));
35
+ const settled = fallback ? await fallback(items) : items;
36
+ // A fallback may change error items only: a verdict VirusTotal gave is never rewritten.
37
+ if (!Array.isArray(settled) || settled.length !== items.length || settled.some((item, i) => item !== items[i] && (items[i].status !== 'error' || !['error', 'equivalent-to-clean'].includes(item?.status) || item.name !== items[i].name || item.sha256 !== items[i].sha256))) throw new Error('VirusTotal fallback may only settle error items');
38
+ const result = reports(applyReviews(settled, reviews, now));
26
39
  await mkdir(out, { recursive: true });
27
40
  await writeFile(resolve(out, `${prefix}.json`), result.json);
28
41
  await writeFile(resolve(out, `${prefix}.md`), result.markdown);
@@ -6,6 +6,17 @@ import { basename } from 'node:path';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
 
8
8
  export const DIRECT_LIMIT = 32 * 1024 * 1024;
9
+ // Files above this size go through the large-upload URL, where VirusTotal can take
10
+ // long to show the analysis; they get the large deadline when it is the longer one.
11
+ export const LARGE_FILE = DIRECT_LIMIT;
12
+ export const MAX_SCAN_MINUTES = 240;
13
+ /** A deadline in minutes from the environment: a number above 0, at most MAX_SCAN_MINUTES. */
14
+ export function scanMinutes(value, fallback, name) {
15
+ if (value === undefined || value === null || String(value).trim() === '') return fallback;
16
+ const text = String(value).trim(); const minutes = Number(text);
17
+ if (!/^\d+(\.\d+)?$/.test(text) || !(minutes > 0) || minutes > MAX_SCAN_MINUTES) throw new Error(`${name} must be a number of minutes above 0 and at most ${MAX_SCAN_MINUTES}`);
18
+ return minutes;
19
+ }
9
20
  export const UPLOAD_LIMIT = 650 * 1024 * 1024;
10
21
  export const API = 'https://www.virustotal.com/api/v3/';
11
22
  export const README_VERIFICATION = '<!-- synabun:verification:start -->\nPackage verification: [downloadable VirusTotal reports and SHA-256 hashes](https://github.com/danilokhury/Synabun/releases/latest). Match the report to your exact version and file hash. Reports record engine coverage and analysis dates; they are not a guarantee of safety. Website results describe URL reputation, not a vulnerability audit.\n<!-- synabun:verification:end -->';
@@ -43,28 +54,38 @@ export async function* multipart(path, boundary) {
43
54
  }
44
55
 
45
56
  export class VirusTotal {
46
- constructor({ key, fetchImpl = globalThis.fetch, sleep = delay, now = Date.now, intervalMs = 15500, requestMs = 120000, uploadMs = 900000, scanMs = 1200000, pollMs = 30000, retries = 3 } = {}) {
57
+ constructor({ key, env = process.env, fetchImpl = globalThis.fetch, sleep = delay, now = Date.now, intervalMs = 15500, requestMs = 120000,
58
+ uploadMs = scanMinutes(env.SYNABUN_VT_UPLOAD_MINUTES, 15, 'SYNABUN_VT_UPLOAD_MINUTES') * 60000,
59
+ scanMs = scanMinutes(env.SYNABUN_VT_SCAN_MINUTES, 15, 'SYNABUN_VT_SCAN_MINUTES') * 60000,
60
+ largeScanMs = scanMinutes(env.SYNABUN_VT_LARGE_SCAN_MINUTES, 15, 'SYNABUN_VT_LARGE_SCAN_MINUTES') * 60000,
61
+ largeFileBytes = LARGE_FILE, pollMs = 30000, retries = 3 } = {}) {
47
62
  this.key = credentials(key); this.fetch = fetchImpl; this.sleep = sleep; this.now = now;
48
- Object.assign(this, { intervalMs, requestMs, uploadMs, scanMs, pollMs, retries }); this.nextRequest = 0; this.queue = Promise.resolve();
63
+ for (const [name, value] of Object.entries({ scanMs, largeScanMs, uploadMs, pollMs })) if (!Number.isFinite(value) || value <= 0) throw new Error(`VirusTotal ${name} must be a positive number`);
64
+ Object.assign(this, { intervalMs, requestMs, uploadMs, scanMs, largeScanMs, largeFileBytes, pollMs, retries }); this.nextRequest = 0; this.queue = Promise.resolve();
49
65
  }
50
- async wait(ms, deadline) {
51
- if (this.now() + ms >= deadline) throw new Error('VirusTotal analysis deadline exceeded; retry the same bytes later');
66
+ /** The analysis deadline for one file (it starts once the upload is done): large files get the longer one, never a shorter one. */
67
+ scanMsFor(size) { return size > this.largeFileBytes ? Math.max(this.scanMs, this.largeScanMs) : this.scanMs; }
68
+ /** How many polls fit before `until`; bounds every waiting loop even if the clock stalls. */
69
+ pollLimit(until) { return Math.min(10000, Math.max(1, Math.ceil((until - this.now()) / this.pollMs) + 1)); }
70
+ /** `phase` names the clock in the error: 'upload' (lookup, upload URL, upload) or 'analysis'. */
71
+ async wait(ms, deadline, phase = 'analysis') {
72
+ if (this.now() + ms >= deadline) throw new Error(`VirusTotal ${phase} deadline exceeded; retry the same bytes later`);
52
73
  if (ms > 0) await this.sleep(ms);
53
74
  }
54
- async pace(deadline) {
75
+ async pace(deadline, phase = 'analysis') {
55
76
  // Reserve request starts serially, even when library callers scan concurrently.
56
77
  const turn = this.queue.then(async () => {
57
- await this.wait(Math.max(0, this.nextRequest - this.now()), deadline);
58
- if (this.now() >= deadline) throw new Error('VirusTotal analysis deadline exceeded');
78
+ await this.wait(Math.max(0, this.nextRequest - this.now()), deadline, phase);
79
+ if (this.now() >= deadline) throw new Error(`VirusTotal ${phase} deadline exceeded`);
59
80
  this.nextRequest = this.now() + this.intervalMs;
60
81
  });
61
82
  this.queue = turn.catch(() => {});
62
83
  await turn;
63
84
  }
64
- async request(path, { method = 'GET', body, headers = {}, deadline = this.now() + this.scanMs, notFound = false, timeoutMs = this.requestMs } = {}) {
85
+ async request(path, { method = 'GET', body, headers = {}, deadline = this.now() + this.scanMs, phase = 'analysis', notFound = false, timeoutMs = this.requestMs } = {}) {
65
86
  const url = trustedUrl(path.startsWith('https:') ? path : API + path);
66
87
  for (let attempt = 0; attempt <= this.retries; attempt++) {
67
- await this.pace(deadline);
88
+ await this.pace(deadline, phase);
68
89
  let response;
69
90
  let payload;
70
91
  try {
@@ -80,59 +101,126 @@ export class VirusTotal {
80
101
  }
81
102
  payload = Buffer.concat(chunks).toString('utf8');
82
103
  } catch {
104
+ if (this.now() >= deadline) throw new Error(`VirusTotal ${phase} deadline exceeded; retry the same bytes later`);
83
105
  if (attempt === this.retries) throw new Error('VirusTotal request failed or timed out; no verdict available');
84
- await this.wait(1000 * 2 ** attempt, deadline); continue;
106
+ await this.wait(1000 * 2 ** attempt, deadline, phase); continue;
85
107
  }
86
108
  if (response.status === 404 && notFound) return null;
87
109
  if (response.status === 429 || response.status >= 500) {
88
110
  if (attempt === this.retries) throw new Error(`VirusTotal HTTP ${response.status}; retry budget exhausted`);
89
111
  const retry = response.headers.get('retry-after');
90
112
  const ms = retry && /^\d+(\.\d+)?$/.test(retry) ? Number(retry) * 1000 : retry ? Date.parse(retry) - this.now() : 1000 * 2 ** attempt;
91
- await this.wait(Math.max(1000, Number.isFinite(ms) ? ms : 1000), deadline); continue;
113
+ await this.wait(Math.max(1000, Number.isFinite(ms) ? ms : 1000), deadline, phase); continue;
92
114
  }
93
- if (!response.ok) throw new Error(`VirusTotal HTTP ${response.status}; no verdict available`);
115
+ if (!response.ok) throw Object.assign(new Error(`VirusTotal HTTP ${response.status}; no verdict available`), { status: response.status });
94
116
  try { return JSON.parse(payload); } catch { throw new Error('VirusTotal returned invalid JSON'); }
95
117
  }
96
118
  }
97
- async poll(id, deadline) {
119
+ /**
120
+ * Polls analyses/{id}. A 404 there is an analysis VirusTotal has accepted but
121
+ * does not show yet (a large upload takes a while to appear): it counts as
122
+ * queued. With `settle` the poll stops at `until` and returns null, so the
123
+ * caller can look at the file object instead; without it, it throws.
124
+ */
125
+ async poll(id, deadline, { until = deadline, settle = false } = {}) {
98
126
  if (typeof id !== 'string' || !id) throw new Error('VirusTotal did not return an analysis ID');
99
- for (let count = 0; count < 40; count++) {
100
- const result = await this.request(`analyses/${encodeURIComponent(id)}`, { deadline });
101
- const status = result?.data?.attributes?.status;
127
+ const limit = this.pollLimit(until);
128
+ for (let count = 0; count < limit; count++) {
129
+ const result = await this.request(`analyses/${encodeURIComponent(id)}`, { deadline, notFound: true });
130
+ const status = result === null ? 'queued' : result?.data?.attributes?.status;
102
131
  if (status === 'completed') return result;
103
132
  if (!['queued', 'in-progress'].includes(status)) throw new Error('VirusTotal returned an unknown analysis status');
133
+ if (this.now() + this.pollMs >= until) break;
134
+ await this.wait(this.pollMs, deadline);
135
+ }
136
+ if (settle) return null;
137
+ throw new Error(`VirusTotal analysis unfinished after ${limit} polls; retry later`);
138
+ }
139
+ /** The file object, identity-checked; null while VirusTotal does not have it. */
140
+ async fileObject(sha256, deadline, phase = 'analysis') {
141
+ const object = await this.request(`files/${sha256}`, { deadline, phase, notFound: true });
142
+ if (object && (object.data?.id !== sha256 || object.data?.attributes?.sha256 !== sha256)) throw new Error('VirusTotal file SHA-256 mismatch');
143
+ return object;
144
+ }
145
+ /**
146
+ * Waits on files/{sha256} until it carries a fresh analysis (the same fresh()
147
+ * rule and evidence checks as a cached verdict). Used when VirusTotal says the
148
+ * file is already submitted (409), when an analysis never showed as completed,
149
+ * and when the object exists but is still being analysed. Returns null at
150
+ * `until`; past `deadline` it throws like every other wait.
151
+ */
152
+ async awaitFile(subject, deadline, { until = deadline, analysisId = null } = {}) {
153
+ const limit = this.pollLimit(until);
154
+ for (let count = 0; count < limit; count++) {
155
+ const a = (await this.fileObject(subject.sha256, deadline))?.data?.attributes;
156
+ if (a && this.fresh(a.last_analysis_date)) return this.evidence(subject, a.last_analysis_stats, a.last_analysis_results, a.last_analysis_date, 'awaited', analysisId);
157
+ if (this.now() + this.pollMs >= until) break;
104
158
  await this.wait(this.pollMs, deadline);
105
159
  }
106
- throw new Error('VirusTotal analysis unfinished after 40 polls; retry later');
160
+ return null;
107
161
  }
108
162
  async file(path, expectedHash) {
109
163
  const size = (await stat(path)).size;
110
164
  if (size > UPLOAD_LIMIT) throw new Error(`VirusTotal 650 MB upload limit exceeded: ${basename(path)}`);
111
165
  const sha256 = await hashFile(path);
112
166
  if (expectedHash && sha256 !== expectedHash) throw new Error(`SHA-256 mismatch: ${basename(path)}`);
113
- const deadline = this.now() + this.scanMs;
114
- const cached = await this.request(`files/${sha256}`, { deadline, notFound: true });
115
- let report;
167
+ // Two clocks, one after the other, so the wall time of a file is at most uploadMs + scanMsFor(size):
168
+ // - the upload clock (uploadMs) runs from here and covers what comes before VirusTotal has the
169
+ // bytes: the files/{sha} lookup, files/upload_url, the upload POST (or files/{sha}/analyse),
170
+ // their pace() turns and retries. The upload request's timeout is what is left of it.
171
+ // - the analysis clock (scanMsFor(size)) starts when that phase ends: right after the lookup when
172
+ // the object is cached without an analysis date (it is awaited, and a reanalysis asked for after
173
+ // that runs on the analysis clock already started), else when the upload or analyse POST answers,
174
+ // 409 AlreadySubmitted included. It covers the polls, the settle fallback and awaitFile.
175
+ const budget = this.scanMsFor(size);
176
+ const uploadDeadline = this.now() + this.uploadMs;
177
+ let deadline = null, settle = null;
178
+ const startAnalysis = () => {
179
+ if (deadline !== null) return;
180
+ deadline = this.now() + budget;
181
+ // The last quarter of the deadline is kept for the file object, whatever the analysis did.
182
+ settle = deadline - Math.floor(budget / 4);
183
+ };
184
+ const before = () => deadline === null ? { deadline: uploadDeadline, phase: 'upload' } : { deadline, phase: 'analysis' };
185
+ const subject = { kind: 'file', name: basename(path), sha256, size };
186
+ const cached = await this.fileObject(sha256, uploadDeadline, 'upload');
116
187
  const a = cached?.data?.attributes;
117
- if (cached && (cached.data.id !== sha256 || a?.sha256 !== sha256)) throw new Error('VirusTotal file SHA-256 mismatch');
188
+ let report = null;
118
189
  if (cached && this.fresh(a?.last_analysis_date)) {
119
- report = this.evidence({ kind: 'file', name: basename(path), sha256, size }, a.last_analysis_stats, a.last_analysis_results, a.last_analysis_date, 'cached');
190
+ report = this.evidence(subject, a.last_analysis_stats, a.last_analysis_results, a.last_analysis_date, 'cached');
120
191
  } else {
121
- let analysis;
122
- if (cached) analysis = await this.request(`files/${sha256}/analyse`, { method: 'POST', deadline });
123
- else {
124
- const upload = size > DIRECT_LIMIT ? (await this.request('files/upload_url', { deadline }))?.data : API + 'files';
125
- if (typeof upload !== 'string') throw new Error('VirusTotal did not return an upload URL');
126
- const boundary = `synabun-${sha256}`;
127
- const head = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${safeName(basename(path))}"\r\nContent-Type: application/octet-stream\r\n\r\n`;
128
- const tail = `\r\n--${boundary}--\r\n`;
129
- analysis = await this.request(upload, { method: 'POST', deadline, timeoutMs: this.uploadMs, body: () => multipart(path, boundary),
130
- headers: { 'content-type': `multipart/form-data; boundary=${boundary}`, 'content-length': String(Buffer.byteLength(head) + size + Buffer.byteLength(tail)) } });
192
+ // An object without an analysis date is still being analysed: wait for it before asking again.
193
+ if (cached && a?.last_analysis_date == null) { startAnalysis(); report = await this.awaitFile(subject, deadline, { until: settle }); }
194
+ if (!report) {
195
+ let analysis = null;
196
+ try {
197
+ if (cached) analysis = await this.request(`files/${sha256}/analyse`, { method: 'POST', ...before() });
198
+ else {
199
+ const upload = size > DIRECT_LIMIT ? (await this.request('files/upload_url', before()))?.data : API + 'files';
200
+ if (typeof upload !== 'string') throw new Error('VirusTotal did not return an upload URL');
201
+ const boundary = `synabun-${sha256}`;
202
+ const head = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${safeName(basename(path))}"\r\nContent-Type: application/octet-stream\r\n\r\n`;
203
+ const tail = `\r\n--${boundary}--\r\n`;
204
+ analysis = await this.request(upload, { method: 'POST', ...before(), timeoutMs: this.uploadMs, body: () => multipart(path, boundary),
205
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}`, 'content-length': String(Buffer.byteLength(head) + size + Buffer.byteLength(tail)) } });
206
+ }
207
+ } catch (error) {
208
+ // 409 AlreadySubmitted: these bytes are already being analysed. Never upload again; wait for the file object.
209
+ if (error.status !== 409) throw error;
210
+ }
211
+ startAnalysis();
212
+ const analysisId = analysis ? analysis.data?.id : null;
213
+ if (analysis && (typeof analysisId !== 'string' || !analysisId)) throw new Error('VirusTotal did not return an analysis ID');
214
+ const result = analysisId ? await this.poll(analysisId, deadline, { until: settle, settle: true }) : null;
215
+ if (result) {
216
+ if (result.meta?.file_info?.sha256 !== sha256) throw new Error('VirusTotal analysis SHA-256 mismatch');
217
+ const attrs = result.data.attributes;
218
+ report = this.evidence(subject, attrs.stats, attrs.results, attrs.date, cached ? 'reanalysed' : 'uploaded', analysisId);
219
+ } else {
220
+ report = await this.awaitFile(subject, deadline, { analysisId });
221
+ if (!report) throw new Error('VirusTotal analysis unfinished before the deadline; retry the same bytes later');
222
+ }
131
223
  }
132
- const result = await this.poll(analysis?.data?.id, deadline);
133
- if (result.meta?.file_info?.sha256 !== sha256) throw new Error('VirusTotal analysis SHA-256 mismatch');
134
- const attrs = result.data.attributes;
135
- report = this.evidence({ kind: 'file', name: basename(path), sha256, size }, attrs.stats, attrs.results, attrs.date, cached ? 'reanalysed' : 'uploaded', analysis.data.id);
136
224
  }
137
225
  if (await hashFile(path) !== sha256 || (await stat(path)).size !== size) throw new Error(`Artifact changed during scanning: ${basename(path)}`);
138
226
  return report;
@@ -189,15 +277,31 @@ export function applyReviews(items, reviews = [], now = Date.now()) {
189
277
  return { ...item, review: { reviewer: review.reviewer, reason: review.reason, reference: review.reference, reviewed_at: review.reviewed_at, expires_at: review.expires_at } };
190
278
  });
191
279
  }
192
- export const approved = items => items.length > 0 && items.every(item => item.status === 'no-detections' || (item.status === 'detections' && item.review));
280
+ export const EQUIVALENT_TO_CLEAN = 'equivalent-to-clean';
281
+ /**
282
+ * A macOS dmg VirusTotal gave no verdict for passes only as 'equivalent-to-clean':
283
+ * the release gate found its .app byte-identical to the .app of the same-arch zip,
284
+ * and that zip, by the exact name and SHA-256 recorded, is in the same report
285
+ * with no detections (an owner-reviewed detection does not count).
286
+ */
287
+ export function equivalentToClean(item, items) {
288
+ const e = item?.equivalence, zip = e?.matched_zip;
289
+ if (item?.status !== EQUIVALENT_TO_CLEAN || item.kind !== 'file' || !/\.dmg$/.test(item.name ?? '') || !/^[a-f0-9]{64}$/.test(item.sha256 ?? '')) return false;
290
+ if (!zip || typeof zip.name !== 'string' || zip.name !== item.name.replace(/\.dmg$/, '.zip') || !/^[a-f0-9]{64}$/.test(zip.sha256 ?? '')) return false;
291
+ if (!/^[a-f0-9]{64}$/.test(e.app_manifest_digest ?? '') || !Number.isInteger(e.file_count) || e.file_count < 1) return false;
292
+ return items.some(other => other.kind === 'file' && other.name === zip.name && other.sha256 === zip.sha256 && other.status === 'no-detections');
293
+ }
294
+ export const approved = items => items.length > 0 && items.every(item => item.status === 'no-detections' || (item.status === 'detections' && item.review) || equivalentToClean(item, items));
193
295
  const md = value => String(value).replace(/[|\r\n<>`\[\]\\]/g, ' ');
194
296
  export function reports(items) {
195
297
  const sorted = [...items].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
196
- const report = { schema: 1, policy: { minimum_file_engines: 10, minimum_url_engines: 20, max_age_days: 7 }, approved: approved(sorted), items: sorted };
298
+ const report = { schema: 1, policy: { minimum_file_engines: 10, minimum_url_engines: 20, max_age_days: 7,
299
+ dmg_without_verdict: 'accepted only as equivalent-to-clean: its .app is byte-identical to the .app of the same-arch zip, which has no detections in this report' }, approved: approved(sorted), items: sorted };
197
300
  const markdown = ['## VirusTotal verification', '', 'Match the exact file and SHA-256. Results describe engine detections and coverage at the analysis date, not a guarantee of safety. Website results describe URL reputation, not a vulnerability audit.', '',
198
301
  '| Package / URL | SHA-256 | Status | Supported / total engines | Analysis date | Report |', '| --- | --- | --- | --- | --- | --- |',
199
- ...sorted.map(i => `| ${md(i.name)} | ${i.sha256} | ${i.status}${i.review ? ' (owner reviewed)' : ''} | ${i.supported_engines ?? 0} / ${i.total_engines ?? 0} | ${md(i.analysis_date ?? 'unavailable')} | ${i.permalink ? `[VirusTotal](${i.permalink})` : 'unavailable'} |`), '',
302
+ ...sorted.map(i => `| ${md(i.name)} | ${i.sha256} | ${i.status}${i.review ? ' (owner reviewed)' : ''}${i.status === EQUIVALENT_TO_CLEAN ? ` (no VirusTotal verdict; app identical to clean-scanned ${md(i.equivalence?.matched_zip?.name ?? 'unknown')})` : ''} | ${i.supported_engines ?? 0} / ${i.total_engines ?? 0} | ${md(i.analysis_date ?? 'unavailable')} | ${i.permalink ? `[VirusTotal](${i.permalink})` : 'unavailable'} |`), '',
200
303
  ...sorted.filter(i => i.review).map(i => `Review for ${md(i.name)} (${i.sha256}), evidence ${i.evidence_digest}: ${md(i.review.reviewer)}; ${md(i.review.reason)}; reference ${md(i.review.reference)}; expires ${md(i.review.expires_at)}.`),
304
+ ...sorted.filter(i => i.status === EQUIVALENT_TO_CLEAN).map(i => `${md(i.name)} (${i.sha256}): no VirusTotal verdict (${md(i.virustotal_error ?? 'unavailable')}); app identical to clean-scanned ${md(i.equivalence?.matched_zip?.name)} (${md(i.equivalence?.matched_zip?.sha256)}): ${md(i.equivalence?.app)}, ${i.equivalence?.file_count} entries, app tree digest ${md(i.equivalence?.app_manifest_digest)}.`),
201
305
  ...sorted.filter(i => i.error).map(i => `${md(i.name)}: ${md(i.error)}`), ''].join('\n');
202
306
  return { json: JSON.stringify(report, null, 2) + '\n', markdown, report };
203
307
  }
@@ -27,12 +27,31 @@ export interface McpRoutesOptions {
27
27
  * answers, the session has exactly that selection and X-Synabun-Tools is ignored.
28
28
  */
29
29
  selectionFor?: (req: Request) => McpSessionSelection | null | undefined;
30
+ /**
31
+ * The host's check of a run's pin (the Neural Interface's terminal tokens, neural-interface/lib/terminal-tokens.js):
32
+ * true when this request may route as `pin` with the X-Synabun-Terminal-Token it carries (`token`, or null). A pin
33
+ * it refuses (a run SynaBun gave a token to, named without that token) is not this caller's: the request routes as
34
+ * its own MCP session, so it never shares that run's identity (its browser pins, its recovered tab) and never sends
35
+ * the run's id to the Neural Interface. Without it, every pin is taken as it is said (the standalone server).
36
+ */
37
+ terminalAuth?: (pin: string, token: string | null) => boolean;
30
38
  }
31
39
  /**
32
40
  * A session's tools, decided once, at initialize: the resolver's answer (strict), else the X-Synabun-Tools header
33
41
  * (focus only: it steers the instructions, never what the session can reach), else focus on every group.
34
42
  */
35
43
  export declare function sessionSelection(req: Request, options?: McpRoutesOptions): ToolSelection;
44
+ /**
45
+ * What proves this request's X-Synabun-Terminal pin: its X-Synabun-Terminal-Token, else (an Assistant brain, whose pin
46
+ * the Neural Interface binds to its launch credential) its X-Synabun-Brain-Token. None for a tunnel caller (a remote
47
+ * MCP-key holder) or a malformed one.
48
+ */
49
+ export declare function requestTerminalToken(req: Pick<Request, 'get'>): string | null;
50
+ /**
51
+ * The X-Synabun-Terminal pin this request may route as: the header's, unless the host's terminalAuth refuses it (a
52
+ * run's pin without that run's token, or a check that threw: fail closed), then none.
53
+ */
54
+ export declare function acceptedTerminalPin(req: Pick<Request, 'get'>, options?: McpRoutesOptions): string | null;
36
55
  /** The X-Synabun-Brain-Token of one request (whatsapp_send_file); none for a tunnel caller (a remote MCP-key holder). */
37
56
  export declare function requestBrainCredential(req: Pick<Request, 'get'>): string | null;
38
57
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;GAcG;AAGH,OAAgB,EAAE,KAAK,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,SAAS,CAAC;AAU7D,OAAO,EAA0C,KAAK,QAAQ,EAAE,KAAK,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAuCvH,mGAAmG;AACnG,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,IAAI,CAAC,EAAE,QAAQ,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,mBAAmB,GAAG,IAAI,GAAG,SAAS,CAAC;CACzE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,gBAAqB,GAAG,aAAa,CAsB5F;AAgFD,yHAAyH;AACzH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,GAAG,IAAI,CAE/E;AAcD;;;;GAIG;AACH,wBAAsB,UAAU,kBAU/B;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAsHtE"}
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;GAcG;AAGH,OAAgB,EAAE,KAAK,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,SAAS,CAAC;AAU7D,OAAO,EAA0C,KAAK,QAAQ,EAAE,KAAK,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAyCvH,mGAAmG;AACnG,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,IAAI,CAAC,EAAE,QAAQ,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,mBAAmB,GAAG,IAAI,GAAG,SAAS,CAAC;IACxE;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,KAAK,OAAO,CAAC;CAC/D;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,gBAAqB,GAAG,aAAa,CAsB5F;AAuCD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,GAAG,IAAI,CAG7E;AAGD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,GAAG,IAAI,CAY5G;AA6CD,yHAAyH;AACzH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,GAAG,IAAI,CAE/E;AAkBD;;;;GAIG;AACH,wBAAsB,UAAU,kBAU/B;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAuHtE"}
@@ -25,7 +25,7 @@ import { createMcpServer, refreshServerSchemas, onSchemaRefresh, setServerRole,
25
25
  import { ToolListRefreshBarrier } from './services/tool-list-refresh-barrier.js';
26
26
  import { selectionFromList, unreadableSelection } from './services/tool-runtime.js';
27
27
  import { TOOL_LIST_LIMITS } from './services/tool-catalog.js';
28
- import { markHttpMode, obtainIdentity, sanitizeBrainCredential, sanitizeDesktopGrant, sanitizePin, sanitizeRole, runWithBrainCredential, runWithIdentity, releaseIdentity, startIdentitySweeper, } from './services/identity.js';
28
+ import { markHttpMode, obtainIdentity, sanitizeBrainCredential, sanitizeDesktopGrant, sanitizePin, sanitizeRole, sanitizeTerminalToken, runWithBrainCredential, runWithIdentity, runWithTerminalToken, releaseIdentity, startIdentitySweeper, } from './services/identity.js';
29
29
  let initialized = false;
30
30
  let initPromise = null;
31
31
  // Warm-server pool: registering 100+ tools (with Zod schema construction)
@@ -111,12 +111,50 @@ onSchemaRefresh(() => {
111
111
  catch { /* per-session best-effort */ }
112
112
  }
113
113
  });
114
+ /**
115
+ * What proves this request's X-Synabun-Terminal pin: its X-Synabun-Terminal-Token, else (an Assistant brain, whose pin
116
+ * the Neural Interface binds to its launch credential) its X-Synabun-Brain-Token. None for a tunnel caller (a remote
117
+ * MCP-key holder) or a malformed one.
118
+ */
119
+ export function requestTerminalToken(req) {
120
+ if (req.get('cf-connecting-ip'))
121
+ return null;
122
+ return sanitizeTerminalToken(req.get('x-synabun-terminal-token')) ?? sanitizeBrainCredential(req.get('x-synabun-brain-token'));
123
+ }
124
+ const refusedPinsLogged = new Set();
125
+ /**
126
+ * The X-Synabun-Terminal pin this request may route as: the header's, unless the host's terminalAuth refuses it (a
127
+ * run's pin without that run's token, or a check that threw: fail closed), then none.
128
+ */
129
+ export function acceptedTerminalPin(req, options = {}) {
130
+ const pin = sanitizePin(req.get('x-synabun-terminal'));
131
+ if (!pin || typeof options.terminalAuth !== 'function')
132
+ return pin;
133
+ let accepted = false;
134
+ try {
135
+ accepted = options.terminalAuth(pin, requestTerminalToken(req)) === true;
136
+ }
137
+ catch {
138
+ accepted = false;
139
+ }
140
+ if (accepted)
141
+ return pin;
142
+ if (!refusedPinsLogged.has(pin)) {
143
+ refusedPinsLogged.add(pin);
144
+ if (refusedPinsLogged.size > 1000)
145
+ refusedPinsLogged.delete(refusedPinsLogged.values().next().value);
146
+ console.error(`[mcp-http] X-Synabun-Terminal ${pin} came without that run's terminal token: routed as its own MCP session`);
147
+ }
148
+ return null;
149
+ }
114
150
  /**
115
151
  * Per-request caller identity. Explicit X-Synabun-* headers (injected into the
116
152
  * launch config of loops, scheduled loops, and sidepanel sessions) win; plain
117
- * CLI windows fall back to their unique Mcp-Session-Id.
153
+ * CLI windows fall back to their unique Mcp-Session-Id. A pin the host's
154
+ * terminalAuth refused (`pin` null) counts as no pin, and so do the browser
155
+ * pins that came with it.
118
156
  */
119
- function deriveIdentity(req, sid) {
157
+ function deriveIdentity(req, sid, pin = sanitizePin(req.get('x-synabun-terminal'))) {
120
158
  const memoryContext = {
121
159
  project: req.get('x-synabun-project')?.slice(0, 200),
122
160
  session: req.get('x-synabun-memory-session')?.slice(0, 200),
@@ -129,7 +167,7 @@ function deriveIdentity(req, sid) {
129
167
  const remote = !!req.get('cf-connecting-ip');
130
168
  const role = remote ? null : sanitizeRole(req.get('x-synabun-role'));
131
169
  const desktopGrant = remote ? null : sanitizeDesktopGrant(req.get('x-synabun-desktop-grant'));
132
- const headerTerminal = sanitizePin(req.get('x-synabun-terminal'));
170
+ const headerTerminal = pin;
133
171
  if (headerTerminal) {
134
172
  const identity = obtainIdentity(headerTerminal, {
135
173
  source: 'header',
@@ -156,11 +194,14 @@ export function requestBrainCredential(req) {
156
194
  return req.get('cf-connecting-ip') ? null : sanitizeBrainCredential(req.get('x-synabun-brain-token'));
157
195
  }
158
196
  /**
159
- * Handle one request inside its caller identity and its own brain-credential context: the
160
- * X-Synabun-Brain-Token of THIS request, never one another request left on a shared identity.
197
+ * Handle one request inside its caller identity and its own credential contexts: the X-Synabun-Brain-Token and the
198
+ * X-Synabun-Terminal-Token of THIS request (the latter only with the pin it came with, which the host accepted),
199
+ * never one another request left on a shared identity.
161
200
  */
162
- function runRequest(req, sid, fn) {
163
- return runWithBrainCredential(requestBrainCredential(req), () => runWithIdentity(deriveIdentity(req, sid), fn));
201
+ function runRequest(req, sid, options, fn) {
202
+ const pin = acceptedTerminalPin(req, options);
203
+ const token = pin ? requestTerminalToken(req) : null;
204
+ return runWithTerminalToken(pin && token ? { terminal: pin, token } : null, () => runWithBrainCredential(requestBrainCredential(req), () => runWithIdentity(deriveIdentity(req, sid, pin), fn)));
164
205
  }
165
206
  function jsonRpcError(res, status, code, message) {
166
207
  res.status(status).json({ jsonrpc: '2.0', error: { code, message }, id: null });
@@ -217,7 +258,7 @@ export function createMcpRoutes(options = {}) {
217
258
  res.once('finish', () => { if (res.statusCode === 200)
218
259
  toolListBarriers.get(entry.server)?.listed(); });
219
260
  }
220
- await runRequest(req, sid, () => entry.transport.handleRequest(req, res, req.body));
261
+ await runRequest(req, sid, options, () => entry.transport.handleRequest(req, res, req.body));
221
262
  return;
222
263
  }
223
264
  // New client — must be an initialize request.
@@ -232,8 +273,9 @@ export function createMcpRoutes(options = {}) {
232
273
  sessionIdGenerator: () => randomUUID(),
233
274
  onsessioninitialized: (newSid) => {
234
275
  mcpSessions.set(newSid, { transport, server, lastSeen: Date.now() });
235
- deriveIdentity(req, newSid);
236
- const terminal = sanitizePin(req.get('x-synabun-terminal'));
276
+ // The pin the host accepted (terminalAuth): a refused one is no pin, here as on every later request.
277
+ const terminal = acceptedTerminalPin(req, options);
278
+ deriveIdentity(req, newSid, terminal);
237
279
  // The warm server was built role-less, on focus. The SDK awaits this
238
280
  // hook BEFORE dispatching the initialize request, so binding the
239
281
  // selection and the role here makes the handshake instructions and
@@ -274,7 +316,7 @@ export function createMcpRoutes(options = {}) {
274
316
  catch { /* already closed */ }
275
317
  };
276
318
  await server.connect(transport);
277
- await runRequest(req, undefined, () => transport.handleRequest(req, res, req.body));
319
+ await runRequest(req, undefined, options, () => transport.handleRequest(req, res, req.body));
278
320
  }
279
321
  catch (error) {
280
322
  console.error('MCP HTTP error:', error);
@@ -293,7 +335,7 @@ export function createMcpRoutes(options = {}) {
293
335
  }
294
336
  entry.lastSeen = Date.now();
295
337
  try {
296
- await runRequest(req, sid, () => entry.transport.handleRequest(req, res));
338
+ await runRequest(req, sid, options, () => entry.transport.handleRequest(req, res));
297
339
  }
298
340
  catch (error) {
299
341
  console.error('MCP HTTP error:', error);