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.
- package/CHANGELOG.md +45 -0
- package/README.md +1 -1
- package/hooks/claude-code/pre-websearch.mjs +4 -1
- package/hooks/claude-code/prompt-submit.mjs +7 -0
- package/lib/release-scan.mjs +23 -10
- package/lib/virustotal.mjs +143 -39
- package/mcp-server/dist/http.d.ts +19 -0
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +55 -13
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +14 -9
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.d.ts +118 -0
- package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
- package/mcp-server/dist/services/browser-route-flow.js +339 -0
- package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
- package/mcp-server/dist/services/desktop-client.js +2 -2
- package/mcp-server/dist/services/desktop-client.js.map +1 -1
- package/mcp-server/dist/services/identity.d.ts +66 -3
- package/mcp-server/dist/services/identity.d.ts.map +1 -1
- package/mcp-server/dist/services/identity.js +61 -4
- package/mcp-server/dist/services/identity.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +112 -1
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +555 -61
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/tools/bluesky.d.ts +20 -7
- package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
- package/mcp-server/dist/tools/bluesky.js +147 -45
- package/mcp-server/dist/tools/bluesky.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +11 -2
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +131 -18
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
- package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
- package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
- package/mcp-server/dist/tools/morelogin.js +4 -2
- package/mcp-server/dist/tools/morelogin.js.map +1 -1
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
- package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +58 -12
- package/mcp-server/src/index.ts +15 -9
- package/mcp-server/src/services/browser-route-flow.ts +402 -0
- package/mcp-server/src/services/desktop-client.ts +2 -2
- package/mcp-server/src/services/identity.ts +80 -4
- package/mcp-server/src/services/neural-interface.ts +572 -70
- package/mcp-server/src/tools/bluesky.ts +164 -51
- package/mcp-server/src/tools/browser-advanced.ts +121 -17
- package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
- package/mcp-server/src/tools/morelogin.ts +4 -2
- package/mcp-server/src/tools/youtube/helpers.ts +2 -2
- package/neural-interface/i18n/en.json +27 -0
- package/neural-interface/i18n/pt-BR.json +27 -0
- package/neural-interface/lib/assistant-api.js +64 -23
- package/neural-interface/lib/assistant-brains/codex.js +6 -1
- package/neural-interface/lib/assistant-catalog.js +20 -2
- package/neural-interface/lib/assistant-dispatch.js +31 -2
- package/neural-interface/lib/assistant-persona.js +1 -0
- package/neural-interface/lib/assistant-runtime.js +15 -1
- package/neural-interface/lib/assistant-tools.js +10 -1
- package/neural-interface/lib/browser-automation-routes.js +84 -0
- package/neural-interface/lib/browser-execution.js +16 -3
- package/neural-interface/lib/browser-owner.js +48 -0
- package/neural-interface/lib/browser-session-close.js +84 -0
- package/neural-interface/lib/browser-start-handoff.js +202 -0
- package/neural-interface/lib/browser-tool-policy.js +21 -4
- package/neural-interface/lib/browser-wedge-retire.js +64 -0
- package/neural-interface/lib/claude-agent-bridge.js +36 -1
- package/neural-interface/lib/claude-background-hold.js +239 -0
- package/neural-interface/lib/exec-loop-command.js +8 -0
- package/neural-interface/lib/http-guards.js +11 -6
- package/neural-interface/lib/loop-logger.js +6 -1
- package/neural-interface/lib/mcp-external-servers.js +64 -13
- package/neural-interface/lib/native-loop-providers.js +122 -10
- package/neural-interface/lib/native-loop-runtime.js +112 -11
- package/neural-interface/lib/opencode-native-boundary.js +155 -21
- package/neural-interface/lib/owner-authority.js +113 -37
- package/neural-interface/lib/page-session.js +81 -23
- package/neural-interface/lib/peer-identity.js +311 -47
- package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
- package/neural-interface/lib/pty-host/core.js +36 -0
- package/neural-interface/lib/pty-host/protocol.js +2 -0
- package/neural-interface/lib/skills/api-v2.js +13 -2
- package/neural-interface/lib/skills/creation-api.js +3 -1
- package/neural-interface/lib/skills/evals-api.js +5 -1
- package/neural-interface/lib/social-write-pacing.js +151 -0
- package/neural-interface/lib/terminal-token-redaction.js +293 -0
- package/neural-interface/lib/terminal-tokens.js +359 -0
- package/neural-interface/lib/worker-mcp-channel.js +45 -10
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/shared/agy/agy-render.js +41 -1
- package/neural-interface/public/shared/agy/agy-styles.js +5 -0
- package/neural-interface/public/shared/api.js +1 -0
- package/neural-interface/public/shared/assistant/asst-api.js +14 -2
- package/neural-interface/public/shared/assistant/asst-computer.js +73 -4
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +80 -0
- package/neural-interface/public/shared/assistant/asst-panel.js +8 -4
- package/neural-interface/public/shared/assistant/asst-render.js +72 -11
- package/neural-interface/public/shared/assistant/asst-scene-styles.js +55 -23
- package/neural-interface/public/shared/assistant/asst-scenes.js +225 -79
- package/neural-interface/public/shared/assistant/asst-sidepanel-styles.js +4 -4
- package/neural-interface/public/shared/assistant/asst-style-cache.js +44 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +26 -5
- package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
- package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
- package/neural-interface/public/shared/cp/cp-agents.js +8 -0
- package/neural-interface/public/shared/cp/cp-permissions.js +18 -2
- package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
- package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
- package/neural-interface/public/shared/judgments-log-origins.js +29 -0
- package/neural-interface/public/shared/loading-teardown.js +34 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +6 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +5 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +16 -86
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +6 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +88 -72
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
- package/neural-interface/public/shared/owner-access.js +134 -0
- package/neural-interface/public/shared/owner-authority-view.js +92 -0
- package/neural-interface/public/shared/page-session.js +143 -14
- package/neural-interface/public/shared/poll-backoff.js +59 -0
- package/neural-interface/public/shared/settings/settings-data.js +6 -1
- package/neural-interface/public/shared/settings/settings-kit.js +11 -3
- package/neural-interface/public/shared/settings/settings-shell.js +7 -0
- package/neural-interface/public/shared/shown-children.js +72 -0
- package/neural-interface/public/shared/static-bg-state.js +22 -0
- package/neural-interface/public/shared/storage-retry.js +47 -0
- package/neural-interface/public/shared/storage.js +25 -4
- package/neural-interface/public/shared/styles.css +109 -8
- package/neural-interface/public/shared/synabun-mascot.js +27 -8
- package/neural-interface/public/shared/synabun-ticker.js +147 -12
- package/neural-interface/public/shared/synabun-tools.js +173 -0
- package/neural-interface/public/shared/tool-heartbeat.js +43 -0
- package/neural-interface/public/shared/tool-list-picker.js +3 -1
- package/neural-interface/public/shared/tool-list-view.js +23 -4
- package/neural-interface/public/shared/ui-automation-studio.js +8 -1
- package/neural-interface/public/shared/ui-claude-panel.js +238 -90
- package/neural-interface/public/shared/ui-judgments.js +37 -10
- package/neural-interface/public/shared/ui-loading.js +5 -4
- package/neural-interface/public/shared/ui-navbar.js +6 -0
- package/neural-interface/public/shared/ui-owner-access.js +191 -0
- package/neural-interface/public/shared/ui-owner-authority.js +162 -0
- package/neural-interface/public/shared/ui-sessions.js +45 -16
- package/neural-interface/public/shared/ui-settings.js +86 -15
- package/neural-interface/public/shared/ui-terminal.js +15 -7
- package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
- package/neural-interface/public/shared/ui-update.js +3 -0
- package/neural-interface/public/shared/ui-whiteboard.js +4 -0
- package/neural-interface/public/shared/window-keys.js +38 -0
- package/neural-interface/server.js +1240 -238
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -23,11 +23,25 @@
|
|
|
23
23
|
// • allowed: everything else — the owner's own browser (Safari's WebKit networking, Chrome's network service,
|
|
24
24
|
// Firefox, Arc…), the SynaBun app's window, the owner's own terminal.
|
|
25
25
|
//
|
|
26
|
-
// No allowlist: nothing the owner uses has to be known for it to keep working.
|
|
27
|
-
// (
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
26
|
+
// No allowlist: nothing the owner uses has to be known for it to keep working. A client socket that is no longer in
|
|
27
|
+
// the table when it is looked up (the client closed it before its request was read) is refused: a browser waiting for
|
|
28
|
+
// its answer still holds its socket.
|
|
29
|
+
//
|
|
30
|
+
// When there is no answer, two cases are told apart (the verdict's `kind`, peerAuthority() reads it for every caller):
|
|
31
|
+
// • unsupported — the lookup does not run on this server: another platform than macOS, or SYNABUN_PEER_IDENTITY=off
|
|
32
|
+
// (the owner's explicit choice, logged at start). The callers keep their rules from before this module, so
|
|
33
|
+
// Windows and Linux work as they always did;
|
|
34
|
+
// • failed — the lookup should have run here (macOS) and could not: netstat or ps missing, denied (a server started
|
|
35
|
+
// inside a sandbox), slow past the cap, an output this parser does not read, a connection with no address, or an
|
|
36
|
+
// error in the lookup itself. That is no proof of who is asking, so the request gets no owner authority: no page
|
|
37
|
+
// secret, no brain credential, and the owner's writes, reads and sockets are answered 503 PEER_UNAVAILABLE (the
|
|
38
|
+
// app's pages and every other read still load). A failure that may pass (a timeout, a busy system) is tried once
|
|
39
|
+
// more at once and is kept on its connection for a moment only (NEGATIVE_TTL_MS), so an open tab recovers by
|
|
40
|
+
// itself; a client that left is never kept. The server probes netstat and ps once at start (probe()), keeps the
|
|
41
|
+
// state for GET /api/health (`ownerAuthority`: ok / degraded / unsupported / off), says the change in one loud log
|
|
42
|
+
// line, and the page shows a banner while it is degraded (public/shared/ui-owner-authority.js).
|
|
43
|
+
// Only a machine elsewhere on the network ('remote', below) still keeps the rules from before without a lookup: what to
|
|
44
|
+
// do about a LAN client is a separate decision (TODO(peer-identity-remote): decide the LAN policy).
|
|
31
45
|
//
|
|
32
46
|
// Cheap: one `netstat -anvl -p tcp` (~4 ms on macOS, one sysctl) per NEW connection, shared by every lookup that is
|
|
33
47
|
// waiting when it starts; the process table (`ps`, ~20 ms) is read only for a process not seen in the last few
|
|
@@ -42,7 +56,9 @@
|
|
|
42
56
|
// of a brain's environment (`ps -E` cannot be blocked between processes of one user) and sent through a relay is
|
|
43
57
|
// dropped from the request, which then has no brain authority.
|
|
44
58
|
//
|
|
45
|
-
// macOS only (netstat's process:pid column, ps -E). Elsewhere every answer is "unknown" (the rules from
|
|
59
|
+
// macOS only (netstat's process:pid column, ps -E). Elsewhere every answer is "unknown, unsupported" (the rules from
|
|
60
|
+
// before). On macOS a credential whose check could not run (the lookup failed, or ps -E could not be read) is dropped
|
|
61
|
+
// too: nothing proves the brain sent it.
|
|
46
62
|
// Parsers and the classifier are pure and unit-tested (tests/peer-identity.test.mjs); the reader takes an injected
|
|
47
63
|
// `run` so tests drive it with fixed tables.
|
|
48
64
|
|
|
@@ -66,7 +82,11 @@ const LSOF = '/usr/sbin/lsof';
|
|
|
66
82
|
export const lsofCwdArgs = (pid) => ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'];
|
|
67
83
|
const TABLE_TIMEOUT_MS = 1500;
|
|
68
84
|
const PS_TIMEOUT_MS = 2000;
|
|
69
|
-
|
|
85
|
+
/** The longest one attempt at a lookup may keep a request waiting (a failure that may pass gets one more attempt). */
|
|
86
|
+
export const LOOKUP_CAP_MS = 2500;
|
|
87
|
+
/** How long a failed lookup is kept on its connection: a burst of requests is not looked up again each, an open tab
|
|
88
|
+
* is soon. */
|
|
89
|
+
export const NEGATIVE_TTL_MS = 2000;
|
|
70
90
|
const PS_SNAPSHOT_TTL_MS = 2000;
|
|
71
91
|
// A process's parents and command line do not change while it lives (a parent that exits leaves it to launchd, which
|
|
72
92
|
// only ever takes an agent or a browser out of the chain, never puts one in): kept half an hour, checked against
|
|
@@ -439,7 +459,7 @@ export function agentProcesses() {
|
|
|
439
459
|
* `agentPids`: processes SynaBun started for an agent (registerAgentProcess), refused like an agent's tree
|
|
440
460
|
* @returns {{ self:boolean, refuse: null | { why:string, kind:string, pid:number, name:string } }}
|
|
441
461
|
*/
|
|
442
|
-
export function classifyPeerChain(chain, { selfPid = process.pid, listening = new Set(), synabunMcp = 0, agentPids = AGENT_PROCESSES } = {}) {
|
|
462
|
+
export function classifyPeerChain(chain, { selfPid = process.pid, listening = new Set(), synabunMcp = 0, agentPids = AGENT_PROCESSES, debugClient = null } = {}) {
|
|
443
463
|
const list = Array.isArray(chain) ? chain : [];
|
|
444
464
|
if (!list.length) return { self: false, refuse: null };
|
|
445
465
|
if (list[0].pid === selfPid) return { self: true, refuse: null };
|
|
@@ -447,11 +467,17 @@ export function classifyPeerChain(chain, { selfPid = process.pid, listening = ne
|
|
|
447
467
|
const refuse = (p, kind, why) => ({ self: false, refuse: { kind, why, pid: p.pid, name: nameOf(p) } });
|
|
448
468
|
const peerKinds = processKinds(list[0]);
|
|
449
469
|
const mcp = Number(synabunMcp) > 0 && list[0].pid === Number(synabunMcp);
|
|
470
|
+
let exempted = false;
|
|
450
471
|
for (let i = 0; i < list.length; i++) {
|
|
451
472
|
const p = list[i];
|
|
452
473
|
if (!p || p.pid === selfPid || p.pid <= 1) break; // this server's own ancestry, and launchd, are not the peer's
|
|
453
474
|
const k = i === 0 ? peerKinds : processKinds(p);
|
|
454
|
-
|
|
475
|
+
// Local profiling (SYNABUN_ALLOW_DEBUG_CLIENT, debugClientPolicy): only the remote-debugging flag is forgiven, and
|
|
476
|
+
// only on the port the policy names; every other rule below still applies to this process and its parents. The
|
|
477
|
+
// process holds its debug port open itself, so the listener rule is not asked of that one process.
|
|
478
|
+
const debugOk = !!k.automation && debugClientExempt(p, k, debugClient);
|
|
479
|
+
if (debugOk) exempted = true;
|
|
480
|
+
if (k.automation && !debugOk) return refuse(p, 'automation-browser', `a browser started for automation (${k.automation})`);
|
|
455
481
|
if (k.agent) return refuse(p, 'agent', `an AI agent's process tree (${k.agent})`);
|
|
456
482
|
const startedFor = agentPids?.get?.(p.pid);
|
|
457
483
|
if (startedFor) return refuse(p, 'agent', `an AI agent's process tree (${startedFor}, started by SynaBun)`);
|
|
@@ -464,12 +490,47 @@ export function classifyPeerChain(chain, { selfPid = process.pid, listening = ne
|
|
|
464
490
|
// A program that serves TCP itself and calls SynaBun is relaying for whoever reached it (a dev server's proxy,
|
|
465
491
|
// a small SOCKS / HTTP proxy). The owner's browsers are left out of this one rule (their network process, or a
|
|
466
492
|
// browser that holds a socket for its own reasons): their automation flags are what is asked of them.
|
|
467
|
-
if (i <= 1 && !peerKinds.browser && listening.has(p.pid)) return refuse(p, 'listener', 'a program that also listens for connections (a relay or proxy)');
|
|
493
|
+
if (i <= 1 && !peerKinds.browser && !debugOk && listening.has(p.pid)) return refuse(p, 'listener', 'a program that also listens for connections (a relay or proxy)');
|
|
468
494
|
}
|
|
495
|
+
if (exempted && !mcp) return { self: false, refuse: null, debugExempt: true };
|
|
469
496
|
if (mcp) return refuse(list[0], 'synabun-mcp', 'SynaBun\'s own MCP server over HTTP (it calls for whichever MCP client reached it)');
|
|
470
497
|
return { self: false, refuse: null };
|
|
471
498
|
}
|
|
472
499
|
|
|
500
|
+
// ── Local profiling exemption (off unless the server's own environment asks) ─
|
|
501
|
+
//
|
|
502
|
+
// SYNABUN_ALLOW_DEBUG_CLIENT=1 (any debug port) or =<port> (only --remote-debugging-port=<port>) lets a client process
|
|
503
|
+
// started with --remote-debugging-port hold the owner's authority, so SynaBun's own window can be profiled over CDP.
|
|
504
|
+
// Read from the environment the server was started with only (server.js reads it before DATA_HOME/.env is loaded:
|
|
505
|
+
// never from a file a client can write), loopback peers only (127.0.0.0/8, ::1), and only that flag: a
|
|
506
|
+
// --remote-debugging-pipe, MoreLogin, Playwright WebKit / Firefox automation, agents, relays and every other rule
|
|
507
|
+
// still refuse.
|
|
508
|
+
|
|
509
|
+
/** The policy from an environment object: { enabled, port } (port null = any). Anything but 1/on/true/yes or a port is off. */
|
|
510
|
+
export function debugClientPolicy(env = process.env) {
|
|
511
|
+
const raw = String(env?.SYNABUN_ALLOW_DEBUG_CLIENT ?? '').trim().toLowerCase();
|
|
512
|
+
if (/^(?:1|on|true|yes)$/.test(raw)) return { enabled: true, port: null };
|
|
513
|
+
if (/^[0-9]{4,5}$/.test(raw) && Number(raw) >= 1024 && Number(raw) <= 65535) return { enabled: true, port: Number(raw) };
|
|
514
|
+
return { enabled: false, port: null };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Whether this process's automation flag is the one the policy forgives. */
|
|
518
|
+
export function debugClientExempt(proc, kinds, policy) {
|
|
519
|
+
if (!policy?.enabled || kinds?.automation !== 'remote debugging') return false;
|
|
520
|
+
const la = lower(proc?.args);
|
|
521
|
+
if (/(?:^|\s)--remote-debugging-pipe(?:[=\s]|$)/.test(la)) return false;
|
|
522
|
+
// The other automation rules are asked as if the flag were not there: MoreLogin, Playwright, Firefox automation.
|
|
523
|
+
if (MORELOGIN_PATH_RE.test(String(proc?.comm ?? '')) || lower(proc?.ucomm).trim().startsWith('morelogin')) return false;
|
|
524
|
+
if (/(?:^|\s)--inspector-pipe(?:\s|$)/.test(la) || /\/pw_run\.sh(?:\s|$)/.test(la) || /(?:^|\s)-juggler(?:-pipe)?(?:\s|$)/.test(la) || /(?:^|\s)--?marionette(?:\s|$)/.test(la)) return false;
|
|
525
|
+
if (/(?:^|\s)--(?:enable-automation|headless)(?:[=\s]|$)/.test(la)) return false;
|
|
526
|
+
const ports = [...la.matchAll(/(?:^|\s)--remote-debugging-port(?:=|\s+)([0-9]+)(?=\s|$)/g)].map((m) => Number(m[1]));
|
|
527
|
+
if (!ports.length) return false;
|
|
528
|
+
return policy.port == null || ports.every((n) => n === policy.port);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** Whether a normalized address is loopback. */
|
|
532
|
+
export const isLoopbackAddress = (addr) => /^127\.\d+\.\d+\.\d+$/.test(String(addr || '')) || String(addr || '') === '::1';
|
|
533
|
+
|
|
473
534
|
/** The environment part of `ps -E` output for one process, given the same process's line without -E. */
|
|
474
535
|
export function envPart(withEnv, plain) {
|
|
475
536
|
const w = String(withEnv ?? '');
|
|
@@ -493,6 +554,65 @@ export function envHoldsCredential(env, credential) {
|
|
|
493
554
|
}
|
|
494
555
|
}
|
|
495
556
|
|
|
557
|
+
// ── Verdicts without an answer, and what a verdict means for the owner's authority ─
|
|
558
|
+
|
|
559
|
+
/** The lookup does not run on this server (another platform, SYNABUN_PEER_IDENTITY=off): the callers' rules from before. */
|
|
560
|
+
export function unsupportedPeerVerdict(reason = 'peer lookup is not available here') {
|
|
561
|
+
return { status: 'unknown', kind: 'unsupported', retryable: false, reason: String(reason) };
|
|
562
|
+
}
|
|
563
|
+
/** The lookup should have run here (macOS) and could not: no owner authority for the request (503 PEER_UNAVAILABLE). */
|
|
564
|
+
export function failedPeerVerdict(reason = 'the lookup failed', { retryable = false } = {}) {
|
|
565
|
+
return { status: 'unknown', kind: 'failed', retryable: retryable === true, reason: String(reason) };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const TRANSIENT_CODES = new Set(['ETIMEDOUT', 'EAGAIN', 'EMFILE', 'ENFILE', 'ENOMEM', 'EBUSY', 'EINTR']);
|
|
569
|
+
/**
|
|
570
|
+
* Whether a failure of netstat / ps may pass by itself: its own timeout ended it (execFile kills it and says
|
|
571
|
+
* `killed` / `signal`), or the system was short of something for a moment (no process slot, no file descriptor).
|
|
572
|
+
* A program that is missing (ENOENT), denied (EPERM, EACCES: a sandbox) or answers what cannot be read does not.
|
|
573
|
+
*/
|
|
574
|
+
export function isTransientLookupError(error) {
|
|
575
|
+
if (!error || typeof error !== 'object') return false;
|
|
576
|
+
if (error.killed === true || (typeof error.signal === 'string' && error.signal)) return true;
|
|
577
|
+
return TRANSIENT_CODES.has(String(error.code || ''));
|
|
578
|
+
}
|
|
579
|
+
/** A short reason for a failed program ("timed out", "EPERM", "netstat named no processes…"). */
|
|
580
|
+
function failureText(error) {
|
|
581
|
+
if (error && typeof error === 'object' && (error.killed === true || (typeof error.signal === 'string' && error.signal))) return 'timed out';
|
|
582
|
+
return String(error?.code || error?.message || error || 'failed');
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* What a request's peer verdict means for the owner's authority: the one reading lib/page-session.js,
|
|
587
|
+
* lib/owner-authority.js and lib/assistant-api.js share. Pure, never throws.
|
|
588
|
+
* { decision: 'before' } never looked up, the lookup does not run here (unsupported: another platform or
|
|
589
|
+
* SYNABUN_PEER_IDENTITY=off), or a machine elsewhere on the network: the caller's rules
|
|
590
|
+
* from before decide
|
|
591
|
+
* { decision: 'allowed', self } the owner's own process (or this server itself)
|
|
592
|
+
* { decision: 'refused', code: 'PEER_REFUSED', kind, why, pid, name, gone } never the owner's authority (the caller
|
|
593
|
+
* still applies its own exceptions, such as an agent's own call)
|
|
594
|
+
* { decision: 'unavailable', code: 'PEER_UNAVAILABLE', retryable, reason } macOS, the lookup failed: no owner
|
|
595
|
+
* authority, and the caller answers 503 (a verdict of a shape this does not know is
|
|
596
|
+
* taken as this one: never the rules from before by accident)
|
|
597
|
+
*/
|
|
598
|
+
export function peerAuthority(verdict) {
|
|
599
|
+
if (verdict === undefined || verdict === null) return { decision: 'before', reason: 'not looked up' };
|
|
600
|
+
if (typeof verdict !== 'object') return { decision: 'unavailable', code: 'PEER_UNAVAILABLE', retryable: false, reason: 'the lookup gave no answer' };
|
|
601
|
+
if (verdict.status === 'ok') {
|
|
602
|
+
if (!verdict.refuse) return { decision: 'allowed', self: verdict.self === true };
|
|
603
|
+
const r = verdict.refuse;
|
|
604
|
+
return { decision: 'refused', code: 'PEER_REFUSED', kind: String(r.kind || 'refused'), why: String(r.why || 'a process that may not act as the owner'), pid: r.pid ?? null, name: String(r.name || ''), gone: false };
|
|
605
|
+
}
|
|
606
|
+
if (verdict.status === 'gone') {
|
|
607
|
+
return { decision: 'refused', code: 'PEER_REFUSED', kind: 'gone', why: String(verdict.reason || 'the connection closed before its request was identified'), pid: verdict.pid ?? null, name: '', gone: true };
|
|
608
|
+
}
|
|
609
|
+
// TODO(peer-identity-remote): a client on another machine of the network keeps the rules from before; whether a LAN
|
|
610
|
+
// client may ever hold the page secret is a separate decision (isRemote() reads headers only).
|
|
611
|
+
if (verdict.status === 'remote') return { decision: 'before', reason: 'another machine' };
|
|
612
|
+
if (verdict.status === 'unknown' && verdict.kind === 'unsupported') return { decision: 'before', reason: String(verdict.reason || 'peer lookup is not available here') };
|
|
613
|
+
return { decision: 'unavailable', code: 'PEER_UNAVAILABLE', retryable: verdict.retryable === true, reason: String(verdict.reason || 'the lookup failed') };
|
|
614
|
+
}
|
|
615
|
+
|
|
496
616
|
// ── The reader ───────────────────────────────────────────────────────────────
|
|
497
617
|
|
|
498
618
|
function defaultRun(file, args, { timeout }) {
|
|
@@ -515,7 +635,7 @@ function thisMachineAddresses() {
|
|
|
515
635
|
|
|
516
636
|
/**
|
|
517
637
|
* @param {object} [o]
|
|
518
|
-
* @param {string} [o.platform] process.platform; only darwin is looked up (everything else is "unknown").
|
|
638
|
+
* @param {string} [o.platform] process.platform; only darwin is looked up (everything else is "unknown, unsupported").
|
|
519
639
|
* @param {number} [o.selfPid] this server's pid (its own in-process calls are trusted).
|
|
520
640
|
* @param {(file:string, args:string[], opts:{timeout:number}) => Promise<string>} [o.run] runs a program (execFile-shaped).
|
|
521
641
|
* @param {() => Set<string>} [o.localAddresses] this computer's addresses (normalized).
|
|
@@ -525,10 +645,20 @@ function thisMachineAddresses() {
|
|
|
525
645
|
* @param {string[]} [o.synabunRoots] this server's install (the folder holding mcp-server/): its MCP server over HTTP
|
|
526
646
|
* is told apart from other listening programs (isSynabunMcpServer). None: it is refused as a listener, as any relay.
|
|
527
647
|
* @param {(path:string) => string} [o.realpath] fs.realpathSync (tests inject one).
|
|
648
|
+
* @param {number} [o.lookupCapMs] the cap of one attempt (LOOKUP_CAP_MS; tests shorten it).
|
|
649
|
+
* @param {number} [o.negativeTtlMs] how long a failed lookup is kept on its connection (NEGATIVE_TTL_MS).
|
|
528
650
|
*/
|
|
529
|
-
export function createPeerIdentity({ platform = process.platform, selfPid = process.pid, run = defaultRun, localAddresses = null, log = () => {}, now = Date.now, disabled = false, synabunRoots = [], realpath = realpathSync } = {}) {
|
|
651
|
+
export function createPeerIdentity({ platform = process.platform, selfPid = process.pid, run = defaultRun, localAddresses = null, log = () => {}, now = Date.now, disabled = false, synabunRoots = [], realpath = realpathSync, debugClient = null, lookupCapMs = LOOKUP_CAP_MS, negativeTtlMs = NEGATIVE_TTL_MS } = {}) {
|
|
530
652
|
const supported = platform === 'darwin' && !disabled;
|
|
531
|
-
|
|
653
|
+
const capMs = Number.isFinite(lookupCapMs) && lookupCapMs > 0 ? lookupCapMs : LOOKUP_CAP_MS;
|
|
654
|
+
const ttlMs = Number.isFinite(negativeTtlMs) && negativeTtlMs >= 0 ? negativeTtlMs : NEGATIVE_TTL_MS;
|
|
655
|
+
const debugPolicy = debugClient?.enabled ? { enabled: true, port: Number.isInteger(debugClient.port) ? debugClient.port : null } : null;
|
|
656
|
+
if (debugPolicy) { try { log(`[peer-identity] WARNING: SYNABUN_ALLOW_DEBUG_CLIENT is set: a loopback client started with --remote-debugging-port${debugPolicy.port ? `=${debugPolicy.port}` : ''} is taken as the owner (local profiling only; unset it when done)`); } catch { /* logger */ } }
|
|
657
|
+
if (disabled) { try { log('[peer-identity] off (SYNABUN_PEER_IDENTITY=off, the owner\'s explicit choice): no peer lookup; the page secret, the owner\'s routes and the brain credential keep their rules from before (a local process that fetches a page gets the secret)'); } catch { /* logger */ } }
|
|
658
|
+
/** "Not looked up here" for this server: off, or another platform. */
|
|
659
|
+
const unsupportedReason = disabled ? 'SYNABUN_PEER_IDENTITY=off' : `peer lookup is not available on ${platform}`;
|
|
660
|
+
/** No answer: a failure where the lookup runs (macOS), the rules from before anywhere else. */
|
|
661
|
+
const noAnswer = (reason, { retryable = false } = {}) => (supported ? failedPeerVerdict(reason, { retryable }) : unsupportedPeerVerdict(unsupportedReason));
|
|
532
662
|
const bySocket = new WeakMap();
|
|
533
663
|
const chains = new Map(); // pid → { at, ucomm, chain }
|
|
534
664
|
const envs = new Map(); // `${pid}\0${credential}` → { at, holds }
|
|
@@ -541,7 +671,7 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
|
|
|
541
671
|
return typeof real === 'string' && real !== written ? [written, real] : [written];
|
|
542
672
|
}))];
|
|
543
673
|
const logged = new Map(); // key → last time
|
|
544
|
-
const stats = { lookups: 0, tableReads: 0, psReads: 0, envReads: 0, refused: 0, unknown: 0, gone: 0, totalMs: 0, maxMs: 0 };
|
|
674
|
+
const stats = { lookups: 0, tableReads: 0, psReads: 0, envReads: 0, refused: 0, unknown: 0, failed: 0, retries: 0, gone: 0, totalMs: 0, maxMs: 0 };
|
|
545
675
|
let addrCache = null;
|
|
546
676
|
let addrAt = 0;
|
|
547
677
|
|
|
@@ -552,6 +682,81 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
|
|
|
552
682
|
if (logged.size > 500) logged.delete(logged.keys().next().value);
|
|
553
683
|
try { log(line); } catch { /* a logger's own failure */ }
|
|
554
684
|
};
|
|
685
|
+
const say = (line) => { try { log(line); } catch { /* a logger's own failure */ } };
|
|
686
|
+
|
|
687
|
+
// ── The state of the owner's authority (GET /api/health `ownerAuthority`, the page's banner) ──
|
|
688
|
+
// off / unsupported never change. On macOS it is ok until the start probe or a lookup fails (degraded, with the
|
|
689
|
+
// reason), and ok again after a whole lookup works (one that read the process table, not just this server's own
|
|
690
|
+
// call, which needs netstat only). Each change is said once, loudly; a lookup that keeps failing is not said again.
|
|
691
|
+
const iso = (ms) => { try { return new Date(ms).toISOString(); } catch { return null; } };
|
|
692
|
+
let authority = disabled
|
|
693
|
+
? { state: 'off', reason: 'SYNABUN_PEER_IDENTITY=off', retryable: false, since: iso(now()) }
|
|
694
|
+
: !supported
|
|
695
|
+
? { state: 'unsupported', reason: unsupportedReason, retryable: false, since: iso(now()) }
|
|
696
|
+
: { state: 'ok', reason: null, retryable: false, since: iso(now()) };
|
|
697
|
+
let probed = null; // the start probe's promise
|
|
698
|
+
function degrade(reason, { retryable = false, source = 'lookup' } = {}) {
|
|
699
|
+
if (!supported) return;
|
|
700
|
+
const text = String(reason || 'the lookup failed');
|
|
701
|
+
if (authority.state === 'degraded') {
|
|
702
|
+
// The same outage, said once. Its reason stays what it was (the page's banner is dismissed by it), unless a cause
|
|
703
|
+
// that does not pass by itself follows one that might (a denial after a timeout): that one is the news.
|
|
704
|
+
if (authority.reason !== text) {
|
|
705
|
+
if (authority.retryable && !retryable) authority = { ...authority, reason: text, retryable: false };
|
|
706
|
+
note(`degraded:${text}`, `[peer-identity] still degraded: ${text}`);
|
|
707
|
+
}
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
authority = { state: 'degraded', reason: text, retryable, since: iso(now()) };
|
|
711
|
+
say(`[peer-identity] DEGRADED (${source}): SynaBun cannot tell which local program is calling it (${text}). Until a lookup works again it hands out no page secret, takes no brain credential and answers the owner's writes, reads and sockets 503 PEER_UNAVAILABLE; pages and other reads still load. If this persists, start SynaBun outside any sandbox, or set SYNABUN_PEER_IDENTITY=off in ~/.synabun/.env and restart (the rules from before, without this protection).`);
|
|
712
|
+
}
|
|
713
|
+
function restore(source = 'lookup') {
|
|
714
|
+
if (!supported || authority.state === 'ok') return;
|
|
715
|
+
const was = authority.reason;
|
|
716
|
+
authority = { state: 'ok', reason: null, retryable: false, since: iso(now()) };
|
|
717
|
+
say(`[peer-identity] owner authority restored (${source}): local programs are identified again${was ? ` (it was: ${was})` : ''}`);
|
|
718
|
+
}
|
|
719
|
+
/** What a lookup said about the lookup itself: a whole answer restores, a failure degrades (one about a single
|
|
720
|
+
* connection — it has no address any more — says nothing about the tools). */
|
|
721
|
+
function noteOutcome(verdict) {
|
|
722
|
+
if (!supported || !verdict || typeof verdict !== 'object') return;
|
|
723
|
+
if (verdict.status === 'unknown' && verdict.kind === 'failed') { if (!verdict.connection) degrade(verdict.reason, { retryable: verdict.retryable === true }); }
|
|
724
|
+
else if (verdict.status === 'ok' && !verdict.self) restore();
|
|
725
|
+
}
|
|
726
|
+
/** The state for GET /api/health: { state: 'ok'|'degraded'|'unsupported'|'off', reason, retryable, since }. */
|
|
727
|
+
function authorityState() {
|
|
728
|
+
return { state: authority.state, reason: authority.reason, retryable: authority.retryable === true, since: authority.since };
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* The start probe (server.js runs it once, at start): netstat and ps, as a lookup runs them. A failure is the
|
|
732
|
+
* degraded state at once, with its reason in the log and in GET /api/health, before any owner's request meets it.
|
|
733
|
+
* Off macOS (or off) there is nothing to probe. Never rejects; asked twice, it runs once.
|
|
734
|
+
*/
|
|
735
|
+
function probe() {
|
|
736
|
+
if (!supported) return Promise.resolve(authorityState());
|
|
737
|
+
if (probed) return probed;
|
|
738
|
+
probed = (async () => {
|
|
739
|
+
const failures = [];
|
|
740
|
+
let retryable = false;
|
|
741
|
+
try {
|
|
742
|
+
const table = parseNetstatTcp(await run(NETSTAT, NETSTAT_ARGS, { timeout: TABLE_TIMEOUT_MS }));
|
|
743
|
+
if (!table.rows.length) failures.push('netstat listed no TCP sockets');
|
|
744
|
+
else if (!table.rows.some((r) => r.pid > 0)) failures.push('netstat named no processes (an unknown output layout)');
|
|
745
|
+
} catch (error) { failures.push(`netstat: ${failureText(error)}`); retryable = retryable || isTransientLookupError(error); }
|
|
746
|
+
try {
|
|
747
|
+
const parents = parsePsParents(await run(PS, ['-Ao', 'pid=,ppid=,ucomm='], { timeout: PS_TIMEOUT_MS }));
|
|
748
|
+
if (!parents.size) failures.push('ps listed no processes');
|
|
749
|
+
else if (!parents.has(selfPid)) failures.push('ps did not list this server');
|
|
750
|
+
} catch (error) { failures.push(`ps: ${failureText(error)}`); retryable = retryable || isTransientLookupError(error); }
|
|
751
|
+
if (failures.length) degrade(failures.join('; '), { retryable, source: 'start probe' });
|
|
752
|
+
else {
|
|
753
|
+
say('[peer-identity] start probe: netstat and ps answer; the owner\'s authority is checked against the calling process');
|
|
754
|
+
restore('start probe');
|
|
755
|
+
}
|
|
756
|
+
return authorityState();
|
|
757
|
+
})().catch((error) => { degrade(`the probe failed (${error?.message || error})`, { source: 'start probe' }); return authorityState(); });
|
|
758
|
+
return probed;
|
|
759
|
+
}
|
|
555
760
|
const isThisMachine = (addr) => {
|
|
556
761
|
if (typeof localAddresses === 'function') { try { return localAddresses().has(addr); } catch { return false; } }
|
|
557
762
|
if (!addrCache || now() - addrAt > LOCAL_ADDR_TTL_MS) { addrCache = thisMachineAddresses(); addrAt = now(); }
|
|
@@ -664,37 +869,65 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
|
|
|
664
869
|
const remotePort = Number(socket?.remotePort);
|
|
665
870
|
const local = normalizeAddress(socket?.localAddress);
|
|
666
871
|
const localPort = Number(socket?.localPort);
|
|
667
|
-
|
|
872
|
+
// (on macOS: no proof of who is asking, about this one connection — it says nothing about the tools)
|
|
873
|
+
if (!remote || !remotePort || !localPort) return { ...noAnswer('the connection has no address'), connection: true };
|
|
874
|
+
// TODO(peer-identity-remote): another machine of the network is not looked up and keeps the rules from before.
|
|
668
875
|
if (!isThisMachine(remote)) return { status: 'remote' };
|
|
669
|
-
if (!supported) return
|
|
876
|
+
if (!supported) return unsupportedPeerVerdict(unsupportedReason);
|
|
670
877
|
let table;
|
|
671
|
-
try { table = await tcpTable(); } catch (error) { return
|
|
878
|
+
try { table = await tcpTable(); } catch (error) { return failedPeerVerdict(`netstat: ${failureText(error)}`, { retryable: isTransientLookupError(error) }); }
|
|
672
879
|
const row = table.rows.find((r) => r.local.port === remotePort && r.local.addr === remote && r.foreign.port === localPort && (r.foreign.addr === local || !local));
|
|
673
880
|
if (!row || !row.pid) return { status: 'gone', reason: 'the connection closed before its request was identified', ms: now() - started };
|
|
674
881
|
if (row.pid === selfPid) return { status: 'ok', self: true, pid: row.pid, name: row.name, chain: [], refuse: null, ms: now() - started };
|
|
675
882
|
let chain;
|
|
676
|
-
try { chain = await chainOf(row.pid, row.name, table.startedAt); } catch (error) { return {
|
|
883
|
+
try { chain = await chainOf(row.pid, row.name, table.startedAt); } catch (error) { return { ...failedPeerVerdict(`ps: ${failureText(error)}`, { retryable: isTransientLookupError(error) }), pid: row.pid }; }
|
|
677
884
|
// The process table was read and the client is not in it: it sent its request and exited without waiting for the
|
|
678
885
|
// answer (a one-shot relay). A browser or a brain waits for its answer; this is treated like a closed socket.
|
|
679
886
|
if (!chain || !chain.length) return { status: 'gone', reason: 'the client process exited before it was identified', pid: row.pid, ms: now() - started };
|
|
680
887
|
let synabunMcp = 0;
|
|
681
888
|
try { synabunMcp = await synabunMcpPid(chain[0], table.listening); } catch { synabunMcp = 0; }
|
|
682
|
-
const verdict = classifyPeerChain(chain, { selfPid, listening: table.listening, synabunMcp });
|
|
889
|
+
const verdict = classifyPeerChain(chain, { selfPid, listening: table.listening, synabunMcp, debugClient: isLoopbackAddress(remote) ? debugPolicy : null });
|
|
890
|
+
if (verdict.debugExempt) note(`debug:${row.pid}`, `[peer-identity] WARNING: accepted a debug client as the owner (pid ${row.pid}, ${row.name || chain[0].ucomm}) under SYNABUN_ALLOW_DEBUG_CLIENT`);
|
|
683
891
|
return { status: 'ok', self: verdict.self, pid: row.pid, name: row.name || chain[0].ucomm, chain, refuse: verdict.refuse, ms: now() - started };
|
|
684
892
|
}
|
|
685
893
|
|
|
686
|
-
/**
|
|
894
|
+
/** One attempt, capped: the request never waits past `capMs` for it (the programs it started end by their own timeouts). */
|
|
895
|
+
function attempt(socket) {
|
|
896
|
+
let timer = null;
|
|
897
|
+
const cap = new Promise((resolve) => { timer = setTimeout(() => resolve(noAnswer(`the lookup took over ${capMs} ms`, { retryable: true })), capMs); timer.unref?.(); });
|
|
898
|
+
const work = Promise.resolve().then(() => identify(socket)).catch((error) => noAnswer(`the lookup failed (${error?.message || error})`));
|
|
899
|
+
return Promise.race([work, cap]).finally(() => clearTimeout(timer));
|
|
900
|
+
}
|
|
901
|
+
/** A lookup, and once more at once when its failure may pass (a timeout, a busy system). */
|
|
902
|
+
async function settle(socket) {
|
|
903
|
+
const first = await attempt(socket);
|
|
904
|
+
if (!(first.status === 'unknown' && first.kind === 'failed' && first.retryable && !first.connection)) return first;
|
|
905
|
+
stats.retries++;
|
|
906
|
+
const second = await attempt(socket);
|
|
907
|
+
return second.status === 'unknown' && second.kind === 'failed' ? { ...second, retried: true } : second;
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* The peer of a request's connection, looked up once per connection (keep-alive requests share it). Never rejects.
|
|
911
|
+
* Kept on the connection: an answer (ok, another machine, not looked up here) for its lifetime; a failed lookup for
|
|
912
|
+
* `ttlMs` only (a burst of requests shares it, the next one after that looks again, so an open tab recovers once the
|
|
913
|
+
* lookup works); a client that left never (gone: the next request on it is looked up afresh).
|
|
914
|
+
*/
|
|
687
915
|
function lookup(req) {
|
|
688
916
|
const socket = req?.socket || req?.connection || null;
|
|
689
|
-
if (!socket || typeof socket !== 'object') return Promise.resolve({
|
|
690
|
-
|
|
691
|
-
if (
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
917
|
+
if (!socket || typeof socket !== 'object') return Promise.resolve({ ...noAnswer('no connection'), connection: true });
|
|
918
|
+
const kept = bySocket.get(socket);
|
|
919
|
+
if (kept && (kept.pending || kept.until > now())) return kept.promise;
|
|
920
|
+
const entry = { pending: true, until: 0, promise: null };
|
|
921
|
+
entry.promise = settle(socket).then((verdict) => {
|
|
922
|
+
entry.pending = false;
|
|
923
|
+
noteOutcome(verdict);
|
|
924
|
+
const failed = verdict.status === 'unknown' && verdict.kind === 'failed';
|
|
925
|
+
entry.until = verdict.status === 'gone' ? 0 : failed ? now() + ttlMs : Infinity;
|
|
926
|
+
if (!(entry.until > now()) && bySocket.get(socket) === entry) bySocket.delete(socket);
|
|
927
|
+
return verdict;
|
|
928
|
+
});
|
|
929
|
+
bySocket.set(socket, entry);
|
|
930
|
+
return entry.promise;
|
|
698
931
|
}
|
|
699
932
|
|
|
700
933
|
/** Whether some process in `chain` (the peer up to this server) holds the credential in its own environment. */
|
|
@@ -726,21 +959,36 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
|
|
|
726
959
|
|
|
727
960
|
/**
|
|
728
961
|
* Express middleware: looks the peer up when `needs(req)` says the request asks for, or carries, the owner's
|
|
729
|
-
* authority, and keeps the verdict on the request (
|
|
730
|
-
* brain's own process tree is removed from the request.
|
|
731
|
-
* rules from before in force
|
|
962
|
+
* authority, and keeps the verdict on the request (peerAuthority() reads it). A brain credential from a peer outside
|
|
963
|
+
* the brain's own process tree is removed from the request. It never answers a request itself: on another platform
|
|
964
|
+
* (or off) a lookup that cannot run leaves the rules from before in force; on macOS it leaves a failed verdict, which
|
|
965
|
+
* the owner gate and the page secret answer with 503 PEER_UNAVAILABLE.
|
|
732
966
|
*/
|
|
733
967
|
function middleware({ needs = () => false } = {}) {
|
|
734
968
|
// Express 4 does not catch a rejected promise: the decision is made apart from next(), which is called exactly
|
|
735
|
-
// once whatever happens in it
|
|
969
|
+
// once whatever happens in it.
|
|
736
970
|
return function peerIdentity(req, res, next) {
|
|
737
971
|
if (disabled) return next();
|
|
738
972
|
let wanted = false;
|
|
739
|
-
|
|
973
|
+
// A needs() that throws cannot say the request asks for nothing: where the lookup runs, it is looked up.
|
|
974
|
+
try { wanted = needs(req) === true; } catch { wanted = supported; }
|
|
740
975
|
const credential = typeof req.headers?.[BRAIN_HEADER] === 'string' ? req.headers[BRAIN_HEADER].trim() : null;
|
|
741
976
|
if (!wanted && !credential) return next();
|
|
742
977
|
decide(req, wanted, credential).then(() => next(), (error) => {
|
|
743
|
-
|
|
978
|
+
try {
|
|
979
|
+
if (supported) {
|
|
980
|
+
// Never the rules from before by accident: on macOS a decision that broke is a lookup that failed, with no
|
|
981
|
+
// owner authority and no brain credential for this request. (A request that cannot even hold the verdict
|
|
982
|
+
// is left without one, which the callers of a server whose lookup runs take as a failed lookup too.)
|
|
983
|
+
const verdict = failedPeerVerdict(`the lookup failed (${error?.message || error})`);
|
|
984
|
+
if (req.headers && credential) delete req.headers[BRAIN_HEADER];
|
|
985
|
+
noteOutcome(verdict);
|
|
986
|
+
note(`error:${error?.message}`, `[peer-identity] the lookup failed (${error?.message || error}): no owner authority for this request (503 PEER_UNAVAILABLE)`);
|
|
987
|
+
req[PEER_VERDICT] = verdict;
|
|
988
|
+
} else {
|
|
989
|
+
note(`error:${error?.message}`, `[peer-identity] the lookup failed (${error?.message || error}); the page secret's rules from before apply`);
|
|
990
|
+
}
|
|
991
|
+
} catch { /* a request that cannot be written to: see above */ }
|
|
744
992
|
next();
|
|
745
993
|
});
|
|
746
994
|
};
|
|
@@ -749,44 +997,60 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
|
|
|
749
997
|
async function decide(req, wanted, credential) {
|
|
750
998
|
const t0 = now();
|
|
751
999
|
let peer;
|
|
752
|
-
try { peer = await lookup(req); } catch (error) { peer =
|
|
1000
|
+
try { peer = await lookup(req); } catch (error) { peer = noAnswer(`the lookup failed (${error?.message || error})`); }
|
|
1001
|
+
if (!peer || typeof peer !== 'object') peer = noAnswer('the lookup gave no answer');
|
|
753
1002
|
const ms = now() - t0;
|
|
754
1003
|
stats.lookups++; stats.totalMs += ms; if (ms > stats.maxMs) stats.maxMs = ms;
|
|
755
1004
|
req[PEER_VERDICT] = peer;
|
|
756
|
-
if (peer.status === 'unknown') {
|
|
1005
|
+
if (peer.status === 'unknown') {
|
|
1006
|
+
stats.unknown++;
|
|
1007
|
+
if (peer.kind === 'failed') {
|
|
1008
|
+
stats.failed++;
|
|
1009
|
+
note(`failed:${peer.reason}`, `[peer-identity] could not tell who is asking (${peer.reason}${peer.retried ? ', tried twice' : ''}): no page secret, owner authority or brain credential for it (503 PEER_UNAVAILABLE)`);
|
|
1010
|
+
} else note(`unknown:${peer.reason}`, `[peer-identity] could not tell who is asking (${peer.reason}); the page secret's rules from before apply`);
|
|
1011
|
+
}
|
|
757
1012
|
if (peer.status === 'gone') { stats.gone++; note(`gone`, `[peer-identity] ${peer.reason || 'a connection closed before its request was identified'}: no owner authority for it`); }
|
|
758
1013
|
if (peer.status === 'ok' && peer.refuse && wanted) {
|
|
759
1014
|
stats.refused++;
|
|
760
1015
|
note(`refuse:${peer.refuse.pid}:${peer.refuse.kind}`, `[peer-identity] no page secret / owner authority for pid ${peer.refuse.pid} (${peer.refuse.name}): ${peer.refuse.why}`);
|
|
761
1016
|
}
|
|
762
1017
|
if (!credential) return;
|
|
1018
|
+
// Kept: from this server itself, from the brain's own tree (it holds the credential in its environment), or where
|
|
1019
|
+
// no lookup runs (another platform: the credential alone, as before). Dropped: from anywhere else, from a client
|
|
1020
|
+
// that left, and on macOS whenever its check could not run (the lookup failed, or ps -E could not be read).
|
|
763
1021
|
let keep = true;
|
|
764
1022
|
if (peer.status === 'gone') keep = false;
|
|
1023
|
+
else if (peer.status === 'unknown' && peer.kind === 'failed') keep = false;
|
|
765
1024
|
else if (peer.status === 'ok' && !peer.self) {
|
|
766
1025
|
try { keep = await chainHoldsCredential(peer.chain || [], credential); } catch (error) {
|
|
767
|
-
keep =
|
|
768
|
-
|
|
1026
|
+
keep = false;
|
|
1027
|
+
// The whole request then has no proven caller: answered 503 (retryable when ps -E only timed out).
|
|
1028
|
+
const failed = { ...failedPeerVerdict(`ps -E: ${failureText(error)}`, { retryable: isTransientLookupError(error) }), pid: peer.pid };
|
|
1029
|
+
req[PEER_VERDICT] = failed;
|
|
1030
|
+
noteOutcome(failed);
|
|
1031
|
+
note(`env:${error?.code || error?.message}`, `[peer-identity] could not read a brain's environment (${failureText(error)}): the brain credential was dropped and the request has no owner authority (503 PEER_UNAVAILABLE)`);
|
|
769
1032
|
}
|
|
770
1033
|
}
|
|
771
1034
|
if (!keep) {
|
|
772
1035
|
delete req.headers[BRAIN_HEADER];
|
|
773
|
-
|
|
1036
|
+
const why = peer.status === 'unknown' ? `its check could not run (${peer.reason})` : 'outside the brain\'s own process tree';
|
|
1037
|
+
note(`brain:${peer.pid || peer.status}`, `[peer-identity] a brain credential came from pid ${peer.pid || '?'} (${peer.name || (peer.status === 'gone' ? 'closed connection' : 'not identified')}), ${why}: it was dropped from the request`);
|
|
774
1038
|
}
|
|
775
1039
|
}
|
|
776
1040
|
|
|
777
1041
|
/**
|
|
778
|
-
* Why this request may not hold or use the owner's page secret (a short sentence), or null
|
|
779
|
-
*
|
|
1042
|
+
* Why this request may not hold or use the owner's page secret (a short sentence), or null: a refused peer, a client
|
|
1043
|
+
* that left, and on macOS a lookup that failed (no proof of who is asking). Null when the peer is allowed, was never
|
|
1044
|
+
* looked up, or is not looked up here (another platform, off, another machine): the caller's rules from before.
|
|
780
1045
|
*/
|
|
781
1046
|
function refusal(req) {
|
|
782
|
-
const
|
|
783
|
-
if (
|
|
784
|
-
if (
|
|
785
|
-
if (peer.status === 'ok' && peer.refuse) return `${peer.refuse.why}: pid ${peer.refuse.pid} (${peer.refuse.name})`;
|
|
1047
|
+
const auth = peerAuthority(req?.[PEER_VERDICT]);
|
|
1048
|
+
if (auth.decision === 'refused') return auth.gone ? auth.why : `${auth.why}: pid ${auth.pid} (${auth.name})`;
|
|
1049
|
+
if (auth.decision === 'unavailable') return `a request SynaBun could not identify (${auth.reason})`;
|
|
786
1050
|
return null;
|
|
787
1051
|
}
|
|
788
1052
|
|
|
789
|
-
return { supported, lookup, middleware, refusal, chainHoldsCredential, stats: () => ({ ...stats, avgMs: stats.lookups ? Math.round((stats.totalMs / stats.lookups) * 10) / 10 : 0 }) };
|
|
1053
|
+
return { supported, lookup, middleware, refusal, chainHoldsCredential, probe, authorityState, stats: () => ({ ...stats, avgMs: stats.lookups ? Math.round((stats.totalMs / stats.lookups) * 10) / 10 : 0 }) };
|
|
790
1054
|
}
|
|
791
1055
|
|
|
792
1056
|
/** Exposed for tests: whether an address is a literal IP (4 or 6). */
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { scrubTokenText } from './terminal-token-redaction.js';
|
|
2
|
+
|
|
1
3
|
const API_KEY_ERRORS = {
|
|
2
4
|
invalid_key: { status: 400, message: "That doesn't look like an API key for this provider." },
|
|
3
5
|
oauth_token: { status: 400, message: "That's a Claude sign-in token. Use Sign in with Claude." },
|
|
@@ -27,9 +29,12 @@ export function validateProviderApiKey(provider, key) {
|
|
|
27
29
|
return key;
|
|
28
30
|
}
|
|
29
31
|
|
|
30
|
-
// Defense in depth for native diagnostics/events. Never forward credential fields.
|
|
32
|
+
// Defense in depth for native diagnostics/events. Never forward credential fields. SynaBun's own run secrets go too
|
|
33
|
+
// (a terminal token, a brain's launch credential: lib/terminal-token-redaction.js), first, so a provider-key pattern
|
|
34
|
+
// inside one never leaves a piece of it: the Claude Code panel's and brain's events and the Codex panel's messages
|
|
35
|
+
// (and its app-server's output) pass here.
|
|
31
36
|
export function redactProviderSecrets(value) {
|
|
32
|
-
if (typeof value === 'string') return value.replace(/sk-[A-Za-z0-9_-]{16,}/g, '[redacted]');
|
|
37
|
+
if (typeof value === 'string') return scrubTokenText(value).replace(/sk-[A-Za-z0-9_-]{16,}/g, '[redacted]');
|
|
33
38
|
if (Array.isArray(value)) return value.map(redactProviderSecrets);
|
|
34
39
|
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
|
|
35
40
|
.filter(([key]) => !/^(api_?key|access_?token|refresh_?token|id_?token|authorization)$/i.test(key))
|
|
@@ -20,6 +20,7 @@ import { EV, OP, HOST_DEFAULTS } from './protocol.js';
|
|
|
20
20
|
import { createEventLoopMonitor } from '../event-loop-monitor.js';
|
|
21
21
|
import { withPathEnv } from '../augmented-path.js';
|
|
22
22
|
import { killOwnedPty } from './lifetime.js';
|
|
23
|
+
import { createTokenStreamRedactor } from '../terminal-token-redaction.js';
|
|
23
24
|
|
|
24
25
|
const IS_WIN = process.platform === 'win32';
|
|
25
26
|
const IS_LINUX = process.platform === 'linux';
|
|
@@ -129,6 +130,12 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
|
|
|
129
130
|
profile: spec.profile || null,
|
|
130
131
|
loopOwned: !!spec.loopOwned,
|
|
131
132
|
tap: !!spec.tap,
|
|
133
|
+
// A session whose environment holds a run's terminal token (a loop's PTY): what it prints is scrubbed of
|
|
134
|
+
// token-shaped values before anything gets it (clients, the snapshot model, the tap to the main process), so an
|
|
135
|
+
// agent that runs `env` writes no live token to a loop's log, a link's capture or a reconnect snapshot.
|
|
136
|
+
// The exact tokens in its environment are handed to it too, so their base64 and hex are masked as well.
|
|
137
|
+
redactor: spec.redactTokens ? createTokenStreamRedactor({ secrets: [spec.env?.SYNABUN_TERMINAL_TOKEN, spec.env?.SYNABUN_BRAIN_TOKEN].filter((v) => typeof v === 'string') }) : null,
|
|
138
|
+
redactTimer: null,
|
|
132
139
|
clients: new Set(),
|
|
133
140
|
outputBytes: 0,
|
|
134
141
|
coalesce: '',
|
|
@@ -157,6 +164,11 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
|
|
|
157
164
|
// ── Output path ──
|
|
158
165
|
function onPtyData(s, data) {
|
|
159
166
|
if (s.exited) return;
|
|
167
|
+
if (s.redactor) {
|
|
168
|
+
data = s.redactor.push(data);
|
|
169
|
+
holdRedactedTail(s);
|
|
170
|
+
if (!data) return;
|
|
171
|
+
}
|
|
160
172
|
s.coalesce += data;
|
|
161
173
|
if (s.coalesce.length >= cfg.coalesceBurstBytes) { flush(s); return; }
|
|
162
174
|
if (!s.flushScheduled) {
|
|
@@ -165,6 +177,23 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
|
|
|
165
177
|
}
|
|
166
178
|
}
|
|
167
179
|
|
|
180
|
+
// The end of a chunk that could be a token's beginning waits for the next chunk; when none comes within
|
|
181
|
+
// redactHoldMs it goes out (a held token beginning masked), and what continues it later is masked when it comes:
|
|
182
|
+
// the redactor remembers the characters it passed on, so no wait between pieces lets a whole token through.
|
|
183
|
+
function holdRedactedTail(s) {
|
|
184
|
+
if (s.redactTimer) { clearTimeout(s.redactTimer); s.redactTimer = null; }
|
|
185
|
+
if (!s.redactor?.pending()) return;
|
|
186
|
+
s.redactTimer = setTimeout(() => {
|
|
187
|
+
s.redactTimer = null;
|
|
188
|
+
if (s.exited || !s.redactor?.pending()) return;
|
|
189
|
+
const rest = s.redactor.flush();
|
|
190
|
+
if (!rest) return;
|
|
191
|
+
s.coalesce += rest;
|
|
192
|
+
flush(s);
|
|
193
|
+
}, cfg.redactHoldMs);
|
|
194
|
+
s.redactTimer.unref?.();
|
|
195
|
+
}
|
|
196
|
+
|
|
168
197
|
function flush(s) {
|
|
169
198
|
s.flushScheduled = false;
|
|
170
199
|
if (!s.coalesce) return;
|
|
@@ -479,6 +508,12 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
|
|
|
479
508
|
counters.exits++;
|
|
480
509
|
if (s.pausedWatch) { clearInterval(s.pausedWatch); s.pausedWatch = null; }
|
|
481
510
|
s.ptyPaused = false;
|
|
511
|
+
// What the scrubber still holds is the end of the output.
|
|
512
|
+
if (s.redactor) {
|
|
513
|
+
if (s.redactTimer) { clearTimeout(s.redactTimer); s.redactTimer = null; }
|
|
514
|
+
const rest = s.redactor.flush();
|
|
515
|
+
if (rest) s.coalesce += rest;
|
|
516
|
+
}
|
|
482
517
|
// Final bytes first — to clients, the model and the tap — then the exit.
|
|
483
518
|
flush(s);
|
|
484
519
|
s.exited = true;
|
|
@@ -498,6 +533,7 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
|
|
|
498
533
|
if (s.graceTimer) { clearTimeout(s.graceTimer); s.graceTimer = null; }
|
|
499
534
|
if (s.resize.timer) { clearTimeout(s.resize.timer); s.resize.timer = null; }
|
|
500
535
|
if (s.tapTimer) { clearTimeout(s.tapTimer); s.tapTimer = null; }
|
|
536
|
+
if (s.redactTimer) { clearTimeout(s.redactTimer); s.redactTimer = null; }
|
|
501
537
|
for (const c of s.clients) clearLagState(c);
|
|
502
538
|
for (const f of s.tempFiles.splice(0)) unlink(f).catch(() => {});
|
|
503
539
|
try { s.model.dispose(); } catch {}
|