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
@@ -15,39 +15,173 @@ export function nativeServeCapability({ version, commandLine = false, passwordFr
15
15
  return !commandLine && passwordFrom === 'stdout' && NATIVE_SERVE_VERSIONS.includes(bare);
16
16
  }
17
17
 
18
+ // Why a serve is not native-safe, in words that name what to change.
19
+ export function nativeServeReason({ version, commandLine = false, passwordFrom } = {}) {
20
+ if (commandLine) return 'command-line';
21
+ if (passwordFrom !== 'stdout') return 'password';
22
+ return nativeServeCapability({ version, commandLine, passwordFrom }) ? null : 'version';
23
+ }
24
+
25
+ const BASE = `Native browser WebSockets require authenticated OpenCode ${NATIVE_SERVE_VERSIONS.join(' or ')} serves with private stdout credentials; wait for startup, stop unverified serves or use the verified executable path.`;
26
+
27
+ const MAX_COMMAND = 200;
28
+ const short = (text, max = MAX_COMMAND) => {
29
+ const one = String(text ?? '').replace(/\s+/g, ' ').trim();
30
+ return one.length > max ? `${one.slice(0, max - 1)}…` : one;
31
+ };
32
+ const pidOf = (o) => (Number.isInteger(o?.pid) && o.pid > 0 ? o.pid : null);
33
+
34
+ // The fields of an offender a caller may see (a route's answer, a dispatch error): what names the serve, never its
35
+ // token or the rest of its record. A command line is shortened.
36
+ export function narrowOffenders(offenders = []) {
37
+ return (Array.isArray(offenders) ? offenders : []).map((o) => {
38
+ const out = { reason: String(o?.reason || 'unknown'), pid: pidOf(o), port: Number(o?.port) > 0 ? Number(o.port) : null };
39
+ if (o?.path) out.path = short(o.path, 400);
40
+ if (o?.command) out.command = short(o.command, 400);
41
+ if (o?.version) out.version = String(o.version).trim();
42
+ if (o?.reason === 'record') { out.kind = o.kind || null; out.claimable = !!o.claimable; }
43
+ return out;
44
+ });
45
+ }
46
+
47
+ function describeOffender(o) {
48
+ const pid = pidOf(o);
49
+ const where = [pid ? `pid ${pid}` : null, o.port ? `port ${o.port}` : null].filter(Boolean).join(', ');
50
+ const what = [o.path || null, o.command ? `command ${short(o.command)}` : null, o.version ? `version ${String(o.version).trim()}` : null].filter(Boolean).join(', ');
51
+ const head = `OpenCode serve ${where || '(unknown process)'}${what ? ` (${what})` : ''}`;
52
+ switch (o.reason) {
53
+ case 'version': return `${head}: this OpenCode version is not one whose authentication SynaBun verified (${NATIVE_SERVE_VERSIONS.join(', ')}); install one of them, or stop this serve (close the OpenCode panel${pid ? ` / end pid ${pid}` : ''})`;
54
+ case 'command-line': return `${head}: started from the OpenCode command line set in Settings (its version cannot be read); clear it so SynaBun starts the verified executable, or stop this serve`;
55
+ case 'password': return `${head}: started without a private stdout password`;
56
+ case 'starting': return `${head}: still starting; try again once OpenCode answers`;
57
+ case 'untracked-port': return `${head}: answers on a port SynaBun did not start in this run; stop the process listening on port ${o.port}`;
58
+ case 'record': {
59
+ const kind = o.kind ? `, kind ${o.kind}` : '';
60
+ if (o.claimable) return `${head}: left running by an earlier SynaBun that has ended${kind}; it could not be stopped automatically: end ${pid ? `pid ${pid}` : 'that serve'}`;
61
+ // Not confirmed: the owner may still run, or the OS could not say whether this pid is still that serve (a pid
62
+ // is reused once its process ends). Never ask the user to end a number that may be another program now.
63
+ return `${head}: on record from another SynaBun process, or one whose identity the OS could not confirm${kind}. It is unconfirmed${pid ? ` whether pid ${pid} is still this serve (the number may belong to another program by now)` : ''}: check ${pid ? `that pid ${pid}'s command line is the one shown (ps -o command= -p ${pid}; on Windows, Task Manager → Details → Command line column)` : 'the OpenCode serves that are running'} before ending it, or close the other SynaBun`;
64
+ }
65
+ default: return `${head}: not verified`;
66
+ }
67
+ }
68
+
69
+ export function nativeServeError(offenders = []) {
70
+ const list = offenders.map(describeOffender);
71
+ const error = new Error(list.length ? `${BASE} Blocking: ${list.join('; ')}.` : BASE);
72
+ error.code = 'NATIVE_SERVE_UNVERIFIED';
73
+ error.offenders = narrowOffenders(offenders);
74
+ return error;
75
+ }
76
+
77
+ const nativeContextClosed = () => Object.assign(new Error('The browser closed while SynaBun was checking its OpenCode serves; nothing was attached.'), { code: 'NATIVE_CONTEXT_CLOSED' });
78
+ const nativeAttachAborted = () => Object.assign(new Error('The browser request ended while SynaBun was checking its OpenCode serves; nothing was attached.'), { code: 'NATIVE_ATTACH_ABORTED' });
79
+ const defaultSleep = (ms) => new Promise((done) => { const t = setTimeout(done, ms); t.unref?.(); });
80
+
18
81
  export function createNativeServeBoundary() {
19
82
  const processes = new Map();
83
+ // Every native context that relies on the boundary, attached or still being checked (a reservation): while any is
84
+ // held, assertLaunch refuses an unverified serve. A context is held from before its check until it closes, its
85
+ // browser disconnects or its attachment fails.
20
86
  const contexts = new Map();
21
- const error = () => new Error(`Native browser WebSockets require authenticated OpenCode ${NATIVE_SERVE_VERSIONS.join(' or ')} serves with private stdout credentials; wait for startup, stop unverified serves or use the verified executable path.`);
87
+ function offenders({ ports = [], unverifiedRecords = [] } = {}) {
88
+ const out = [];
89
+ const verified = new Set();
90
+ for (const [proc, e] of processes) {
91
+ const base = { pid: proc.pid || null, port: e.port, path: e.path || null, version: e.version || null };
92
+ if (!e.safe) out.push({ ...base, reason: e.reason || 'version' });
93
+ else if (!e.ready) out.push({ ...base, reason: 'starting' });
94
+ else verified.add(e.port);
95
+ }
96
+ for (const port of ports) {
97
+ const n = Number(port);
98
+ if (verified.has(n) || out.some(o => o.port === n)) continue;
99
+ out.push({ pid: null, port: n, reason: 'untracked-port' });
100
+ }
101
+ // A record has the serve's command line (its identity), not a path; never its token.
102
+ for (const r of unverifiedRecords) out.push({ pid: r?.pid || null, port: r?.port || null, kind: r?.kind || null, command: r?.command || null, claimable: !!r?.claimable, reason: 'record' });
103
+ return out;
104
+ }
105
+ function reserve(context) {
106
+ const held = contexts.get(context);
107
+ if (held) return held;
108
+ const browser = context.browser?.() || null;
109
+ const release = () => {
110
+ if (contexts.get(context) !== release) return;
111
+ contexts.delete(context);
112
+ context.removeListener('close', release);
113
+ browser?.removeListener('disconnected', release);
114
+ };
115
+ contexts.set(context, release);
116
+ context.once('close', release);
117
+ browser?.once('disconnected', release);
118
+ return release;
119
+ }
120
+ function check(state) {
121
+ const blocking = offenders(state);
122
+ if (blocking.length) throw nativeServeError(blocking);
123
+ }
22
124
  return {
23
- assertLaunch(safe) { if (!safe && contexts.size) throw error(); },
24
- track(proc, { port, safe = false }) {
125
+ offenders,
126
+ reserve,
127
+ holds: (context) => contexts.has(context),
128
+ assertLaunch(safe, info = {}) {
129
+ if (!safe && contexts.size) {
130
+ const e = nativeServeError([{ pid: null, port: info.port || null, path: info.path || null, version: info.version || null, reason: info.reason || 'version' }]);
131
+ e.message = `A native browser is attached, so this unverified OpenCode serve is not started. ${e.message}`;
132
+ throw e;
133
+ }
134
+ },
135
+ track(proc, { port, safe = false, version = null, path = null, reason = null }) {
25
136
  if (!proc || proc.exitCode != null || proc.signalCode != null) return;
26
- processes.set(proc, { port: Number(port), safe, ready: false });
137
+ processes.set(proc, { port: Number(port), safe, ready: false, version, path, reason: safe ? null : (reason || 'version') });
27
138
  const release = () => processes.delete(proc);
28
139
  proc.once('exit', release);
29
140
  proc.once('error', () => { if (!proc.pid) release(); });
30
141
  },
31
142
  ready(proc) { const entry = processes.get(proc); if (entry) entry.ready = true; },
32
- protect(context, { ports, unverifiedRecords = [] }) {
143
+ // Synchronous: check now, then hold the context. A context already held is returned as it is.
144
+ protect(context, state) {
33
145
  if (contexts.has(context)) return contexts.get(context);
34
- const verified = new Set();
35
- for (const { port, safe, ready } of processes.values()) {
36
- if (!safe || !ready) throw error();
37
- verified.add(port);
146
+ check(state);
147
+ return reserve(context);
148
+ },
149
+ // The context is held (a pending reservation assertLaunch honours) before anything is waited for; then, bounded,
150
+ // SynaBun repairs what it can: a sweep of the records an ended SynaBun left (started at once, in the background,
151
+ // waited for at most `sweepMs`) and SynaBun's own verified serves still starting (waited for at most `waitMs`).
152
+ // Any other blocker refuses at once. `deadline` (an absolute time) and `signal` end the wait early. On every
153
+ // failure the reservation is released; nothing is cached, so the next attempt reads the live state again.
154
+ async attach(context, { state, sweep = null, waitMs = 20_000, sweepMs = 10_000, deadline = Infinity, signal = null, pollMs = 250, now = Date.now, sleep = defaultSleep } = {}) {
155
+ const release = reserve(context);
156
+ const held = () => contexts.get(context) === release;
157
+ try {
158
+ const start = now();
159
+ const end = Number.isFinite(deadline) ? deadline : Infinity;
160
+ const waitEnd = Math.min(start + Math.max(0, waitMs), end);
161
+ const sweepEnd = Math.min(start + Math.max(0, sweepMs), end);
162
+ let current = state();
163
+ let sweeping = false;
164
+ if (sweep && current.unverifiedRecords?.length) {
165
+ sweeping = true;
166
+ Promise.resolve().then(sweep).catch(() => {}).finally(() => { sweeping = false; });
167
+ }
168
+ for (;;) {
169
+ if (!held()) throw nativeContextClosed();
170
+ if (signal?.aborted) throw nativeAttachAborted();
171
+ const blocking = offenders(current);
172
+ if (!blocking.length) return release;
173
+ const t = now();
174
+ const waitable = (o) => (o.reason === 'starting' && t < waitEnd)
175
+ || (o.reason === 'record' && o.claimable && sweeping && t < sweepEnd);
176
+ if (!blocking.every(waitable)) throw nativeServeError(blocking);
177
+ const until = Math.max(...blocking.map(o => (o.reason === 'starting' ? waitEnd : sweepEnd)));
178
+ await sleep(Math.max(1, Math.min(pollMs, until - t)));
179
+ current = state();
180
+ }
181
+ } catch (error) {
182
+ release();
183
+ throw error;
38
184
  }
39
- if ([...ports].some(port => !verified.has(Number(port))) || unverifiedRecords.length) throw error();
40
- const browser = context.browser();
41
- const release = () => {
42
- if (contexts.get(context) !== release) return;
43
- contexts.delete(context);
44
- context.removeListener('close', release);
45
- browser.removeListener('disconnected', release);
46
- };
47
- contexts.set(context, release);
48
- context.once('close', release);
49
- browser.once('disconnected', release);
50
- return release;
51
185
  },
52
186
  };
53
187
  }
@@ -38,12 +38,22 @@
38
38
  //
39
39
  // Never refused by this module: the owner's own browser and the SynaBun app (the peer lookup allows them), this
40
40
  // server itself, a request from outside (the tunnel, the invite proxy: the guest rules decide those, and the
41
- // tunnel's own process would otherwise read as a relay), and any request whose peer could not be looked up (the
42
- // rules from before apply: a failed lookup never locks the owner out).
41
+ // tunnel's own process would otherwise read as a relay), and wherever the lookup does not run (another platform than
42
+ // macOS, or SYNABUN_PEER_IDENTITY=off: the rules from before apply, so Windows and Linux work as they always did).
43
+ //
44
+ // A lookup that failed on macOS (lib/peer-identity.js: netstat or ps missing, denied, slow past the cap, unreadable)
45
+ // proves nothing about who is asking, so it holds none of the owner's powers: every request this module covers —
46
+ // the owner's writes (an agent's pinned call and an agent-open route too: a relay can send a pin), the owner's reads,
47
+ // the secret reads, the owner's sockets — is answered 503 PEER_UNAVAILABLE (`retryable` when the lookup timed out,
48
+ // with Retry-After), and /ws/sync stays open, read-only. The app's pages and every other read still load. Two writes
49
+ // keep the rules from before even then (DEGRADED_OPEN_PATHS): the server's restart and stop, which take nothing from
50
+ // the request, are what the desktop app's quit, the uninstaller and the owner's way out (SYNABUN_PEER_IDENTITY=off,
51
+ // then a restart) need, and an agent's tree may call them anyway. A request it should have looked up and has no
52
+ // verdict for (`required`: a server whose lookup runs) is taken as a failed lookup, never as the rules from before.
43
53
 
44
54
  import { readFileSync } from 'node:fs';
45
55
  import { AGENT_HEADERS, sendGuardError } from './http-guards.js';
46
- import { BRAIN_HEADER, PEER_VERDICT } from './peer-identity.js';
56
+ import { BRAIN_HEADER, PEER_VERDICT, failedPeerVerdict, peerAuthority } from './peer-identity.js';
47
57
  import { ADMIN_ONLY_PREFIXES, routedForms } from './request-gate.js';
48
58
 
49
59
  const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
@@ -73,6 +83,12 @@ export const AGENT_CALL_KINDS = Object.freeze(['agent', 'synabun-mcp']);
73
83
  * it can reach SynaBun at all, and the CLI and the MCP tools read some of them). The hooks' own routes are not here.
74
84
  */
75
85
  export const OWNER_READ_PREFIXES = Object.freeze([...ADMIN_ONLY_PREFIXES.filter((prefix) => prefix !== '/api/hook-'), '/api/git']);
86
+ /**
87
+ * The writes a failed lookup does not refuse (the rules from before): the server's restart and stop. They take nothing
88
+ * from the request, an agent's tree may call them anyway, and the desktop app's quit, the uninstaller and the in-app
89
+ * Restart (the way out of a degraded server: SYNABUN_PEER_IDENTITY=off, then a restart) depend on them. Whole paths.
90
+ */
91
+ export const DEGRADED_OPEN_PATHS = Object.freeze(['/api/server/restart', '/api/server/shutdown']);
76
92
  /** The owner's sockets: a terminal, the agent panels, the Assistant, the browser panel. */
77
93
  export const OWNER_SOCKET_PREFIXES = Object.freeze(['/ws/terminal/', '/ws/claude-skin', '/ws/codex-skin', '/ws/opencode-v2', '/ws/antigravity', '/ws/assistant/', '/ws/browser/']);
78
94
  /** Sockets that stay open for the app's pages to draw, read-only for a peer the owner's powers are refused to. */
@@ -129,6 +145,29 @@ export function proxyRefusalText(req, refuse) {
129
145
  return template.replace(/\{(\w+)\}/g, (whole, key) => (params[key] != null ? params[key] : whole));
130
146
  }
131
147
 
148
+ // ── A lookup that failed (macOS): 503 PEER_UNAVAILABLE ───────────────────────
149
+
150
+ /** The code of every answer to a request whose peer could not be identified (lib/peer-identity.js, macOS). */
151
+ export const PEER_UNAVAILABLE = 'PEER_UNAVAILABLE';
152
+ /** Retry-After for it: soon after a timeout or a busy moment, later for a lookup that cannot run at all. */
153
+ export function retryAfterSeconds(down) { return down?.retryable === true ? 2 : 30; }
154
+ /** Why SynaBun did not act as the owner, and what to do (`ownerAuthority.peerUnavailable`), in the request's language. */
155
+ export function peerUnavailableText(req, down) {
156
+ const template = ownerCopy(requestLocale(req)).peerUnavailable;
157
+ const params = { reason: String(down?.reason || 'the lookup failed').slice(0, 160) };
158
+ if (typeof template !== 'string' || !template) return `SynaBun could not check which program sent this (${params.reason}), so it refused to act as the owner. Reload the page to try again.`;
159
+ return template.replace(/\{(\w+)\}/g, (whole, key) => (params[key] != null ? params[key] : whole));
160
+ }
161
+ /** The answer's body: { ok: false, code: 'PEER_UNAVAILABLE', error, retryable, reason }. */
162
+ export function peerUnavailableBody(req, down) {
163
+ return { ok: false, code: PEER_UNAVAILABLE, error: peerUnavailableText(req, down), retryable: down?.retryable === true, reason: String(down?.reason || 'the lookup failed') };
164
+ }
165
+ /** Answer 503 PEER_UNAVAILABLE (never cached, Retry-After). Used by the owner gate, the page secret and the Assistant API. */
166
+ export function sendPeerUnavailable(res, req, down) {
167
+ try { res.setHeader?.('Retry-After', String(retryAfterSeconds(down))); res.setHeader?.('Cache-Control', 'no-store'); } catch { /* headers already sent */ }
168
+ return res.status(503).json(peerUnavailableBody(req, down));
169
+ }
170
+
132
171
  /** Does a request say it is an agent's own call (a pin, or a brain credential that survived the peer check)? */
133
172
  export function isAgentCall(req) {
134
173
  const h = req?.headers || {};
@@ -136,28 +175,34 @@ export function isAgentCall(req) {
136
175
  }
137
176
 
138
177
  /**
139
- * Where an HTTP request stands: `gated` (one of the owner's writes, one of the owner's reads, or a secret read), and
178
+ * Where an HTTP request stands: `gated` (one of the owner's writes, one of the owner's reads, or a secret read),
140
179
  * `agentOpen` (an agent's tree may call it without a pin: every owner's read but the secret ones, and the
141
- * AGENT_OPEN_PREFIXES writes). A path with no safe reading is gated.
180
+ * AGENT_OPEN_PREFIXES writes) and `degradedOpen` (a failed lookup does not refuse it: DEGRADED_OPEN_PATHS, every
181
+ * reading of the path one of them). A path with no safe reading is gated.
142
182
  */
143
183
  export function restScope(req) {
144
184
  const method = String(req?.method || 'GET').toUpperCase();
145
185
  const forms = routedForms(String(req?.path ?? req?.url ?? ''));
146
- if (!forms) return { gated: !SAFE_METHODS.has(method), agentOpen: false, reason: 'no safe reading of the path' };
186
+ if (!forms) return { gated: !SAFE_METHODS.has(method), agentOpen: false, degradedOpen: false, reason: 'no safe reading of the path' };
147
187
  if (SAFE_METHODS.has(method)) {
148
- if (method === 'OPTIONS') return { gated: false, agentOpen: false };
188
+ if (method === 'OPTIONS') return { gated: false, agentOpen: false, degradedOpen: false };
149
189
  const reveal = String(req?.query?.reveal || '') === '1';
150
190
  if (forms.some((form) => form === '/api/mcp-key' || (reveal && form.startsWith('/api/mcp/env/')))) {
151
- return { gated: true, agentOpen: false, reason: 'a read that hands out a secret' };
191
+ return { gated: true, agentOpen: false, degradedOpen: false, reason: 'a read that hands out a secret' };
152
192
  }
153
193
  // (ADMIN_ONLY_PREFIXES are plain prefixes, as lib/request-gate.js reads them)
154
194
  const ownerRead = forms.some((form) => OWNER_READ_PREFIXES.some((prefix) => form.startsWith(prefix)));
155
- return { gated: ownerRead, agentOpen: true, reason: ownerRead ? 'one of the owner\'s reads' : null };
195
+ return { gated: ownerRead, agentOpen: true, degradedOpen: false, reason: ownerRead ? 'one of the owner\'s reads' : null };
156
196
  }
157
- if (!forms.some((form) => under(form, '/api'))) return { gated: false, agentOpen: false };
197
+ if (!forms.some((form) => under(form, '/api'))) return { gated: false, agentOpen: false, degradedOpen: false };
158
198
  const open = (form) => FEATURE_OPEN_PREFIXES.some((prefix) => under(form, prefix)) && !NEVER_OPEN_PREFIXES.some((prefix) => under(form, prefix));
159
- if (forms.every(open)) return { gated: false, agentOpen: false };
160
- return { gated: true, agentOpen: forms.every((form) => AGENT_OPEN_PREFIXES.some((prefix) => under(form, prefix))), reason: 'one of the owner\'s writes' };
199
+ if (forms.every(open)) return { gated: false, agentOpen: false, degradedOpen: false };
200
+ return {
201
+ gated: true,
202
+ agentOpen: forms.every((form) => AGENT_OPEN_PREFIXES.some((prefix) => under(form, prefix))),
203
+ degradedOpen: forms.every((form) => DEGRADED_OPEN_PATHS.includes(form)),
204
+ reason: 'one of the owner\'s writes',
205
+ };
161
206
  }
162
207
 
163
208
  /** Where a socket stands: `owner` (refused to the peers below) or `readOnly` (open, read-only for them). */
@@ -169,37 +214,48 @@ export function socketScope(pathname) {
169
214
  }
170
215
 
171
216
  /**
172
- * The decision for one request whose peer verdict is on it (or not: then only the marker counts).
217
+ * The decision for one request whose peer verdict is on it (or not: then only the marker counts, unless `required`).
173
218
  * @param {object} req
174
- * @param {{ agentOpen?: boolean, fromWorkerBrowser?: (req) => boolean }} o
175
- * @returns {{ code: string, error: string, hint?: string, peer?: object } | null} `hint: 'proxy'` (with the relay's
176
- * kind, pid and name) when the peer carries requests for others: `error` then says what to do, in the request's language
219
+ * @param {{ agentOpen?: boolean, degradedOpen?: boolean, required?: boolean, fromWorkerBrowser?: (req) => boolean }} o
220
+ * `required`: the lookup runs on this server (macOS, not off), so a covered request without a verdict was never
221
+ * identified and is taken as a failed lookup; `degradedOpen`: a failed lookup leaves this one to the rules from before
222
+ * @returns {{ status: 403|503, code: string, error: string, hint?: string, peer?: object, retryable?: boolean, reason?: string } | null}
223
+ * `hint: 'proxy'` (with the relay's kind, pid and name) when the peer carries requests for others: `error` then says
224
+ * what to do, in the request's language; status 503 with code PEER_UNAVAILABLE when the peer could not be identified
177
225
  */
178
- export function ownerRefusal(req, { agentOpen = false, fromWorkerBrowser = () => false } = {}) {
226
+ export function ownerRefusal(req, { agentOpen = false, degradedOpen = false, required = false, fromWorkerBrowser = () => false } = {}) {
179
227
  let marked = false;
180
228
  try { marked = !!fromWorkerBrowser(req); } catch { marked = false; }
181
- if (marked) return { code: 'WORKER_BROWSER', error: 'SynaBun\'s automation browser cannot act as the owner: it reads SynaBun\'s pages, clicks and screenshots; the owner\'s own settings, files and actions are the owner\'s, from the owner\'s browser or the app.' };
182
- const peer = req?.[PEER_VERDICT];
183
- if (!peer) return null;
184
- if (peer.status === 'gone') return { code: 'PEER_REFUSED', error: `This is the owner's, and ${peer.reason || 'the connection closed before its request was identified'}.` };
185
- if (peer.status !== 'ok' || peer.self || !peer.refuse) return null;
186
- if (AGENT_CALL_KINDS.includes(peer.refuse.kind) && (agentOpen || isAgentCall(req))) return null; // an agent's own call: its route's rules
187
- if (PROXY_REFUSAL_KINDS.includes(peer.refuse.kind)) {
188
- return { code: 'PEER_REFUSED', error: proxyRefusalText(req, peer.refuse), hint: 'proxy', peer: { kind: peer.refuse.kind, pid: peer.refuse.pid, name: peer.refuse.name } };
229
+ if (marked) return { status: 403, code: 'WORKER_BROWSER', error: 'SynaBun\'s automation browser cannot act as the owner: it reads SynaBun\'s pages, clicks and screenshots; the owner\'s own settings, files and actions are the owner\'s, from the owner\'s browser or the app.' };
230
+ const verdict = req?.[PEER_VERDICT];
231
+ const auth = verdict == null && required ? peerAuthority(failedPeerVerdict('the request was not identified')) : peerAuthority(verdict);
232
+ if (auth.decision === 'before' || auth.decision === 'allowed') return null;
233
+ if (auth.decision === 'unavailable') {
234
+ if (degradedOpen) return null; // the server's restart and stop: the rules from before (DEGRADED_OPEN_PATHS)
235
+ return { status: 503, code: PEER_UNAVAILABLE, error: peerUnavailableText(req, auth), retryable: auth.retryable, reason: auth.reason };
236
+ }
237
+ if (auth.gone) return { status: 403, code: 'PEER_REFUSED', error: `This is the owner's, and ${auth.why}.` };
238
+ if (AGENT_CALL_KINDS.includes(auth.kind) && (agentOpen || isAgentCall(req))) return null; // an agent's own call: its route's rules
239
+ if (PROXY_REFUSAL_KINDS.includes(auth.kind)) {
240
+ return { status: 403, code: 'PEER_REFUSED', error: proxyRefusalText(req, auth), hint: 'proxy', peer: { kind: auth.kind, pid: auth.pid, name: auth.name } };
189
241
  }
190
- return { code: 'PEER_REFUSED', error: `This is the owner's, from the owner's own browser or the app; this request comes from ${peer.refuse.why}: pid ${peer.refuse.pid} (${peer.refuse.name}).` };
242
+ return { status: 403, code: 'PEER_REFUSED', error: `This is the owner's, from the owner's own browser or the app; this request comes from ${auth.why}: pid ${auth.pid} (${auth.name}).` };
191
243
  }
192
244
 
193
245
  /**
194
246
  * @param {object} o
195
247
  * @param {() => ({ fromWorkerBrowser(req): boolean } | null)} [o.pageSession] the page session (read at request time)
196
248
  * @param {(req) => boolean} [o.isRemote] a request from outside (the tunnel, the invite proxy): the guest rules decide
197
- * @param {{ lookup(req): Promise<object> }} [o.peer] lib/peer-identity.js (for sockets: no middleware runs for them)
249
+ * @param {{ lookup(req): Promise<object>, supported?: boolean }} [o.peer] lib/peer-identity.js (for sockets: no
250
+ * middleware runs for them). `supported` (macOS, not off): a covered request without a verdict, or a socket whose
251
+ * lookup threw, is a failed lookup (503), never the rules from before.
198
252
  * @param {(line: string) => void} [o.log]
199
253
  */
200
254
  export function createOwnerAuthority({ pageSession = () => null, isRemote = () => false, peer = null, log = () => {} } = {}) {
201
255
  const fromWorkerBrowser = (req) => { const s = pageSession(); return typeof s?.fromWorkerBrowser === 'function' ? s.fromWorkerBrowser(req) : false; };
202
256
  const remote = (req) => { try { return isRemote(req) === true; } catch { return false; } };
257
+ /** The lookup runs here (macOS, not off): no verdict is no proof. */
258
+ const required = peer?.supported === true;
203
259
  const logged = new Map();
204
260
  const note = (key, line) => {
205
261
  const now = Date.now();
@@ -216,34 +272,54 @@ export function createOwnerAuthority({ pageSession = () => null, isRemote = () =
216
272
  }
217
273
 
218
274
  /** Express middleware, mounted after the peer middleware: 403 for a refused request to one of the owner's routes
219
- * (its writes, its reads, a secret read). */
275
+ * (its writes, its reads, a secret read), 503 PEER_UNAVAILABLE (with Retry-After) for one whose peer could not be
276
+ * identified on macOS. */
220
277
  function restGate(req, res, next) {
221
278
  let scope;
222
- try { scope = restScope(req); } catch { scope = { gated: true, agentOpen: false }; }
279
+ try { scope = restScope(req); } catch { scope = { gated: true, agentOpen: false, degradedOpen: false }; }
223
280
  if (!scope.gated || remote(req)) return next();
224
- const refused = ownerRefusal(req, { agentOpen: scope.agentOpen, fromWorkerBrowser });
281
+ const refused = ownerRefusal(req, { agentOpen: scope.agentOpen, degradedOpen: scope.degradedOpen, required, fromWorkerBrowser });
225
282
  if (!refused) return next();
226
- note(`${refused.code}:${req[PEER_VERDICT]?.pid || 'marker'}:${String(req.path).slice(0, 80)}`, `[owner-authority] refused ${req.method} ${String(req.path).slice(0, 120)}: ${refused.hint === 'proxy' ? `${req[PEER_VERDICT]?.refuse?.why}: pid ${refused.peer?.pid} (${refused.peer?.name})` : refused.error}`);
283
+ note(`${refused.code}:${req[PEER_VERDICT]?.pid || (refused.code === PEER_UNAVAILABLE ? refused.reason : 'marker')}:${String(req.path).slice(0, 80)}`, `[owner-authority] ${refused.code === PEER_UNAVAILABLE ? 'unavailable (503)' : 'refused'} ${req.method} ${String(req.path).slice(0, 120)}: ${refused.hint === 'proxy' ? `${req[PEER_VERDICT]?.refuse?.why}: pid ${refused.peer?.pid} (${refused.peer?.name})` : refused.code === PEER_UNAVAILABLE ? `the caller could not be identified (${refused.reason})` : refused.error}`);
284
+ if (refused.code === PEER_UNAVAILABLE) return sendPeerUnavailable(res, req, refused);
227
285
  if (refused.hint) return res.status(403).json({ ok: false, code: refused.code, error: refused.error, hint: refused.hint, peer: refused.peer });
228
286
  return sendGuardError(res, 403, refused.code, refused.error);
229
287
  }
230
288
 
231
289
  /**
232
290
  * The decision for a WebSocket upgrade (no middleware runs for one): looks the peer up for an owner socket and for
233
- * /ws/sync. → { refuse: boolean, readOnly: boolean, code?, error? }. Never rejects; a lookup that cannot run
234
- * refuses nothing.
291
+ * /ws/sync. → { refuse: boolean, readOnly: boolean, status?: 403|503, code?, error?, retryable? }. Never rejects. A
292
+ * peer that could not be identified on macOS gets no owner socket (status 503) and a read-only /ws/sync; where the
293
+ * lookup does not run, nothing is refused for it.
235
294
  */
236
295
  async function checkUpgrade(req, pathname) {
237
296
  const scope = socketScope(pathname);
238
297
  if ((!scope.owner && !scope.readOnly) || remote(req)) return { refuse: false, readOnly: false };
239
298
  if (peer && typeof peer.lookup === 'function' && !req[PEER_VERDICT]) {
240
- try { req[PEER_VERDICT] = await peer.lookup(req); } catch { /* unknown: the rules from before */ }
299
+ try { req[PEER_VERDICT] = await peer.lookup(req); } catch (error) {
300
+ // A lookup that threw is a lookup that failed where it runs; elsewhere the rules from before.
301
+ if (required) req[PEER_VERDICT] = failedPeerVerdict(`the lookup failed (${error?.message || error})`);
302
+ }
241
303
  }
242
- const refused = ownerRefusal(req, { agentOpen: false, fromWorkerBrowser });
304
+ const refused = ownerRefusal(req, { agentOpen: false, required, fromWorkerBrowser });
243
305
  if (!refused) return { refuse: false, readOnly: false };
244
- note(`ws:${refused.code}:${req[PEER_VERDICT]?.pid || 'marker'}:${pathname}`, `[owner-authority] ${scope.owner ? 'refused' : 'read-only'} socket ${pathname}: ${refused.error}`);
306
+ note(`ws:${refused.code}:${req[PEER_VERDICT]?.pid || 'marker'}:${pathname}`, `[owner-authority] ${scope.owner ? (refused.code === PEER_UNAVAILABLE ? 'unavailable (503)' : 'refused') : 'read-only'} socket ${pathname}: ${refused.code === PEER_UNAVAILABLE ? `the caller could not be identified (${refused.reason})` : refused.error}`);
307
+ return scope.owner ? { refuse: true, readOnly: false, ...refused } : { refuse: false, readOnly: true, ...refused };
308
+ }
309
+
310
+ /**
311
+ * The decision for an upgrade whose check itself broke (checkUpgrade never rejects; this is the guard for what it
312
+ * cannot foresee, server.js's rejection path): where the lookup runs, as for a failed lookup (an owner socket refused
313
+ * with 503, /ws/sync read-only); elsewhere, and for a request from outside, the rules from before.
314
+ */
315
+ function upgradeFailed(req, pathname, error) {
316
+ const scope = socketScope(pathname);
317
+ if (!required || (!scope.owner && !scope.readOnly) || remote(req)) return { refuse: false, readOnly: false };
318
+ const reason = `the socket's check failed (${error?.message || error || 'no reason'})`;
319
+ note(`ws-failed:${pathname}`, `[owner-authority] ${scope.owner ? 'unavailable (503)' : 'read-only'} socket ${pathname}: ${reason}`);
320
+ const refused = { status: 503, code: PEER_UNAVAILABLE, error: peerUnavailableText(req, { reason }), retryable: false, reason };
245
321
  return scope.owner ? { refuse: true, readOnly: false, ...refused } : { refuse: false, readOnly: true, ...refused };
246
322
  }
247
323
 
248
- return { needsLookup, restGate, checkUpgrade, restScope, socketScope };
324
+ return { needsLookup, restGate, checkUpgrade, upgradeFailed, restScope, socketScope };
249
325
  }
@@ -40,12 +40,19 @@
40
40
  // used asks it too: a request from SynaBun's automation browser, a browser started for automation, an agent's
41
41
  // process tree or a relay is never handed the secret (the pages, GET /api/page-session, a Studio read's attach) and
42
42
  // never counts as the owner (verify), whatever host, port, cookie or marker it carries, and a service worker there
43
- // gets a worker that takes itself away (serviceWorker). A lookup that could not run leaves the rules above.
43
+ // gets a worker that takes itself away (serviceWorker). The verdict is read through peerAuthority(), as the owner gate
44
+ // reads it. A lookup that does not run on this server (another platform, SYNABUN_PEER_IDENTITY=off) leaves the rules
45
+ // above. A lookup that failed on macOS (`peer.supported`) is no proof of who is asking: the page still loads, but
46
+ // without the secret, verify is false, GET /api/page-session and require() answer 503 PEER_UNAVAILABLE (never a 403
47
+ // the page would try to cure: public/shared/page-session.js does not retry it), and the service worker is the one
48
+ // that takes itself away. There, a request that hands out or carries the secret without a verdict on it was never
49
+ // identified, and counts as a failed lookup too.
44
50
 
45
51
  import { randomBytes, timingSafeEqual } from 'node:crypto';
46
52
  import { isIP } from 'node:net';
47
53
  import { parseCookies } from './http-guards.js';
48
- import { ipv6Groups, mappedIPv4 } from './peer-identity.js';
54
+ import { PEER_VERDICT, failedPeerVerdict, ipv6Groups, mappedIPv4, peerAuthority } from './peer-identity.js';
55
+ import { sendPeerUnavailable } from './owner-authority.js';
49
56
  import { setBrowserNetworkRule, localMarkerPatterns } from './browser-network-guard.js';
50
57
 
51
58
  /** The cookie's name without a port (tests, hosts that pass none); with one it is pageSecretCookieName(port). */
@@ -153,18 +160,57 @@ self.addEventListener('activate', (event) => { event.waitUntil(self.registration
153
160
 
154
161
  /**
155
162
  * @param {object} [o]
156
- * @param {{ refusal(req): string|null }} [o.peer] lib/peer-identity.js: why a request's peer process may not hold or
157
- * use the secret (null when it may, or when it could not be told)
163
+ * @param {{ supported?: boolean, refusal?(req): string|null }} [o.peer] lib/peer-identity.js. Its verdict on the
164
+ * request (req[PEER_VERDICT], read through peerAuthority) decides; `supported` (macOS, not off) makes a missing
165
+ * verdict on a request that hands out or carries the secret a failed lookup. A stand-in without verdicts may answer
166
+ * `refusal(req)` (a sentence: refused).
158
167
  */
159
168
  export function createPageSession({ secret = null, cookieName = null, port = null, secure = false, isGuest = null, peer = null, networkRule = setBrowserNetworkRule } = {}) {
160
169
  const value = typeof secret === 'string' && secret.length >= 32 ? secret : randomBytes(32).toString('hex');
161
170
  const expected = Buffer.from(value);
162
171
  const name = typeof cookieName === 'string' && cookieName ? cookieName : pageSecretCookieName(port);
163
172
  const guest = (req) => { try { return typeof isGuest === 'function' && isGuest(req) === true; } catch { return true; } };
164
- /** Why the peer lookup refuses this request the secret, or null (never asked, could not tell, or allowed). */
165
- const peerRefusal = (req) => { try { return typeof peer?.refusal === 'function' ? (peer.refusal(req) || null) : null; } catch { return null; } };
173
+ /** The lookup runs on this server (macOS, not off): where the secret is at stake, no verdict is no proof. */
174
+ const peerRequired = () => { try { return peer?.supported === true; } catch { return true; } };
175
+ /**
176
+ * What the peer lookup says of this request (peerAuthority's decision: before / allowed / refused / unavailable).
177
+ * `secretAtStake`: the request is handed the secret or carries it, so on a server whose lookup runs a missing verdict
178
+ * is a failed lookup. Never throws: on a server whose lookup runs a failure here is a failed lookup too.
179
+ */
180
+ function peerDecision(req, { secretAtStake = false } = {}) {
181
+ if (!peer) return { decision: 'before' };
182
+ try {
183
+ const verdict = req?.[PEER_VERDICT];
184
+ if (verdict != null) return peerAuthority(verdict);
185
+ if (typeof peer.refusal === 'function') {
186
+ const why = peer.refusal(req);
187
+ if (why) return { decision: 'refused', code: 'PEER_REFUSED', why: String(why), pid: null };
188
+ }
189
+ return secretAtStake && peerRequired() ? peerAuthority(failedPeerVerdict('the request was not identified')) : { decision: 'before' };
190
+ } catch (error) {
191
+ return peerRequired() ? peerAuthority(failedPeerVerdict(`the lookup failed (${error?.message || error})`)) : { decision: 'before' };
192
+ }
193
+ }
194
+ const refusedText = (auth) => (auth.gone || auth.pid == null ? auth.why : `${auth.why}: pid ${auth.pid} (${auth.name})`);
195
+ /** Why the peer lookup refuses this request the secret (a sentence), or null (never asked, not looked up here, or
196
+ * allowed). A failed lookup on macOS is a refusal too. */
197
+ const peerRefusal = (req) => {
198
+ const auth = peerDecision(req, { secretAtStake: true });
199
+ if (auth.decision === 'refused') return refusedText(auth);
200
+ if (auth.decision === 'unavailable') return `a request SynaBun could not identify (${auth.reason})`;
201
+ return null;
202
+ };
203
+ /** The request's peer could not be identified on macOS: { code: 'PEER_UNAVAILABLE', retryable, reason }, or null. */
204
+ const peerUnavailable = (req) => {
205
+ const auth = peerDecision(req, { secretAtStake: carriesSecret(req) });
206
+ return auth.decision === 'unavailable' ? auth : null;
207
+ };
166
208
  /** A request that may neither be handed the secret nor use it: a marker of the automation browser, or its peer. */
167
- const heldBack = (req) => hasWorkerMarker(req) || !!peerRefusal(req);
209
+ const heldBack = (req) => {
210
+ if (hasWorkerMarker(req)) return true;
211
+ const decision = peerDecision(req, { secretAtStake: true }).decision;
212
+ return decision === 'refused' || decision === 'unavailable';
213
+ };
168
214
 
169
215
  /** The Set-Cookie header value (HttpOnly, SameSite=Strict, the whole site). */
170
216
  function cookie() {
@@ -172,12 +218,13 @@ export function createPageSession({ secret = null, cookieName = null, port = nul
172
218
  }
173
219
  /**
174
220
  * Add the cookie to a response (once; a header already there is kept and this one appended). Never to a guest, a
175
- * request with the automation browser's marker or one whose peer is refused: `req` is the response's own request
176
- * (Express's res.req) unless given, so every caller that hands the page the secret asks the same questions.
221
+ * request with the automation browser's marker or one whose peer is refused or could not be identified: `req` is the
222
+ * response's own request (Express's res.req) unless given, so every caller that hands the page the secret asks the
223
+ * same questions (and with no request to ask, a server whose lookup runs hands out nothing).
177
224
  */
178
225
  function attach(res, req = res?.req) {
179
226
  if (!res || typeof res.getHeader !== 'function' || typeof res.setHeader !== 'function') return;
180
- if (req && (heldBack(req) || guest(req))) return;
227
+ if (req ? (heldBack(req) || guest(req)) : peerRequired()) return;
181
228
  const current = res.getHeader('Set-Cookie');
182
229
  const list = current === undefined ? [] : Array.isArray(current) ? [...current] : [String(current)];
183
230
  if (list.some((line) => String(line).startsWith(`${name}=`))) return;
@@ -191,10 +238,10 @@ export function createPageSession({ secret = null, cookieName = null, port = nul
191
238
  return !!got && got.length === expected.length && timingSafeEqual(got, expected);
192
239
  }
193
240
  /** Whether a request carries this boot's secret, and neither the automation browser's marker (cookie or header)
194
- * nor a peer the lookup refuses. */
241
+ * nor a peer the lookup refuses or (on macOS) could not identify. */
195
242
  function verify(req) {
196
- if (heldBack(req)) return false;
197
- return carriesSecret(req);
243
+ if (!carriesSecret(req)) return false;
244
+ return !heldBack(req);
198
245
  }
199
246
  /** Whether a request comes from a tab of SynaBun's automation browser (the marker cookie or the host-proof header). */
200
247
  function fromWorkerBrowser(req) {
@@ -230,14 +277,23 @@ export function createPageSession({ secret = null, cookieName = null, port = nul
230
277
  return false;
231
278
  }
232
279
  }
233
- /** Express middleware for an owner write: 403 PAGE_SECRET_REQUIRED without the secret. */
280
+ /** Answer 503 PEER_UNAVAILABLE for a request whose peer could not be identified (peerUnavailable(req)). */
281
+ function sendUnavailable(res, req, down = peerUnavailable(req)) {
282
+ return sendPeerUnavailable(res, req, down || { retryable: false, reason: 'the request was not identified' });
283
+ }
284
+ /** Express middleware for an owner write: 403 PAGE_SECRET_REQUIRED without the secret; 503 PEER_UNAVAILABLE when the
285
+ * request's peer could not be identified on macOS (the secret could not be handed out or taken: a reload, not a
286
+ * refresh, is what may cure it). */
234
287
  function require(req, res, next) {
235
288
  if (verify(req)) return next();
289
+ const down = peerUnavailable(req);
290
+ if (down) return sendUnavailable(res, req, down);
236
291
  res.status(403).json({ ok: false, code: 'PAGE_SECRET_REQUIRED', error: 'This change is made from SynaBun\'s own page. Reload the page and try again.' });
237
292
  }
238
293
  /** Express middleware that sets the cookie on the pages it belongs to (GET only, the app's shells; never a guest's
239
- * and never a request that carries the automation-browser marker or whose peer is refused — a marked tab, an
240
- * automation browser, an agent or a relay must never be handed the secret). */
294
+ * and never a request that carries the automation-browser marker or whose peer is refused or could not be
295
+ * identified — a marked tab, an automation browser, an agent, a relay or an unknown caller must never be handed the
296
+ * secret). The page itself still loads. */
241
297
  function pages(req, res, next) {
242
298
  if ((req.method === 'GET' || req.method === 'HEAD') && PAGE_SECRET_PATHS.includes(req.path) && !guest(req) && !heldBack(req)) attach(res, req);
243
299
  next();
@@ -247,21 +303,23 @@ export function createPageSession({ secret = null, cookieName = null, port = nul
247
303
  * after a restart). Answers { ok: true } with the cookie; a guest gets 403 and no cookie. A tab of SynaBun's
248
304
  * automation browser (the marker cookie or the host-proof header) is refused the secret too (403 WORKER_BROWSER),
249
305
  * as is a request whose peer process the lookup refuses (403 PEER_REFUSED: an automation browser, an agent's
250
- * process tree, a relay). Never cached.
306
+ * process tree, a relay). A request whose peer could not be identified on macOS gets 503 PEER_UNAVAILABLE and no
307
+ * cookie. Never cached.
251
308
  */
252
309
  function refresh(req, res) {
253
310
  res.setHeader('Cache-Control', 'no-store');
254
311
  if (guest(req)) return res.status(403).json({ ok: false, code: 'GUEST_FORBIDDEN', error: 'Available to the owner only.' });
255
312
  if (hasWorkerMarker(req)) return res.status(403).json({ ok: false, code: 'WORKER_BROWSER', error: 'SynaBun\'s automation browser does not hold the owner\'s page secret.' });
256
- const why = peerRefusal(req);
257
- if (why) return res.status(403).json({ ok: false, code: 'PEER_REFUSED', error: `SynaBun hands its page secret to the owner's own browser only; this request comes from ${why}.` });
313
+ const auth = peerDecision(req, { secretAtStake: true });
314
+ if (auth.decision === 'unavailable') return sendUnavailable(res, req, auth);
315
+ if (auth.decision === 'refused') return res.status(403).json({ ok: false, code: 'PEER_REFUSED', error: `SynaBun hands its page secret to the owner's own browser only; this request comes from ${refusedText(auth)}.` });
258
316
  attach(res, req);
259
317
  res.json({ ok: true });
260
318
  }
261
319
  /**
262
- * Express middleware for GET /sw.js: a browser that may not hold the secret (the automation browser's marker, or a
263
- * refused peer) gets SERVICE_WORKER_NOOP, so no service worker answers its requests out of the server's sight;
264
- * everyone else falls through to the real public/sw.js.
320
+ * Express middleware for GET /sw.js: a browser that may not hold the secret (the automation browser's marker, a
321
+ * refused peer, or on macOS one that could not be identified) gets SERVICE_WORKER_NOOP, so no service worker answers
322
+ * its requests out of the server's sight; everyone else falls through to the real public/sw.js.
265
323
  */
266
324
  function serviceWorker(req, res, next) {
267
325
  if ((req.method === 'GET' || req.method === 'HEAD') && req.path === SERVICE_WORKER_PATH && heldBack(req)) {
@@ -271,5 +329,5 @@ export function createPageSession({ secret = null, cookieName = null, port = nul
271
329
  }
272
330
  next();
273
331
  }
274
- return { cookieName: name, cookie, attach, carriesSecret, verify, require, pages, refresh, serviceWorker, fromWorkerBrowser, peerRefusal, markWorkerBrowserContext };
332
+ return { cookieName: name, cookie, attach, carriesSecret, verify, require, pages, refresh, serviceWorker, fromWorkerBrowser, peerRefusal, peerUnavailable, sendUnavailable, markWorkerBrowserContext };
275
333
  }