synabun 2.4.2 → 2.4.4

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 (220) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +83 -34
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -18
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +3 -1
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +11 -6
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  35. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  37. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-observe.js +113 -27
  39. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  40. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  41. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  42. package/mcp-server/dist/tools/browser-readers.js +17 -0
  43. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  44. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/remember.js +6 -2
  46. package/mcp-server/dist/tools/remember.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  48. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  50. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  52. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  54. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  56. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  57. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  58. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  59. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  60. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  61. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  62. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  64. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  65. package/mcp-server/package-lock.json +5 -5
  66. package/mcp-server/package.json +1 -1
  67. package/mcp-server/src/http.ts +8 -1
  68. package/mcp-server/src/services/identity.ts +5 -0
  69. package/mcp-server/src/services/memory-client.ts +32 -12
  70. package/mcp-server/src/services/memory-writer.ts +5 -2
  71. package/mcp-server/src/services/neural-interface.ts +66 -19
  72. package/mcp-server/src/services/typesafe-config.ts +268 -7
  73. package/mcp-server/src/tools/agents.ts +12 -6
  74. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  75. package/mcp-server/src/tools/browser-observe.ts +117 -28
  76. package/mcp-server/src/tools/browser-readers.ts +19 -0
  77. package/mcp-server/src/tools/remember.ts +6 -1
  78. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  79. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  80. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  81. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  82. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  83. package/neural-interface/i18n/en.json +189 -1
  84. package/neural-interface/i18n/pt-BR.json +196 -8
  85. package/neural-interface/lib/assistant-api.js +123 -0
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  88. package/neural-interface/lib/assistant-dispatch.js +302 -44
  89. package/neural-interface/lib/assistant-envelope.js +40 -0
  90. package/neural-interface/lib/assistant-memory.js +3 -1
  91. package/neural-interface/lib/assistant-persona.js +6 -0
  92. package/neural-interface/lib/assistant-router.js +18 -8
  93. package/neural-interface/lib/assistant-runtime.js +182 -11
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-extension-adapter.js +221 -17
  97. package/neural-interface/lib/browser-extension-archive.js +149 -0
  98. package/neural-interface/lib/browser-extension-bridge.js +46 -10
  99. package/neural-interface/lib/browser-extension-folder.js +635 -76
  100. package/neural-interface/lib/browser-extension-package.js +201 -0
  101. package/neural-interface/lib/browser-extension-pin.js +84 -0
  102. package/neural-interface/lib/browser-extension-pin.json +35 -0
  103. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
  104. package/neural-interface/lib/browser-extension-setup.js +108 -19
  105. package/neural-interface/lib/browser-extension-update.js +104 -0
  106. package/neural-interface/lib/browser-extraction.js +38 -14
  107. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  108. package/neural-interface/lib/claude-history.js +12 -1
  109. package/neural-interface/lib/cli-install.js +23 -3
  110. package/neural-interface/lib/cli-update-planner.js +67 -4
  111. package/neural-interface/lib/confined-fs.js +25 -0
  112. package/neural-interface/lib/coordination/operations.js +2 -0
  113. package/neural-interface/lib/db.js +39 -16
  114. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  115. package/neural-interface/lib/git-bash/manager.js +28 -3
  116. package/neural-interface/lib/git-status-runner.js +31 -3
  117. package/neural-interface/lib/loop-inventory.js +162 -0
  118. package/neural-interface/lib/loop-stall.js +74 -4
  119. package/neural-interface/lib/memory-session-capture.js +157 -66
  120. package/neural-interface/lib/native-loop-providers.js +82 -13
  121. package/neural-interface/lib/native-loop-runtime.js +23 -2
  122. package/neural-interface/lib/opencode-protocol.js +4 -2
  123. package/neural-interface/lib/opencode-shell-read.js +107 -0
  124. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  125. package/neural-interface/lib/opencode-turn-release.js +173 -0
  126. package/neural-interface/lib/opencode-v2-client.js +4 -1
  127. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  128. package/neural-interface/lib/opencode2-client.js +341 -6
  129. package/neural-interface/lib/opencode2-translate.js +161 -4
  130. package/neural-interface/lib/peer-identity.js +62 -16
  131. package/neural-interface/lib/session-cache-builder.js +66 -18
  132. package/neural-interface/lib/session-capture-gate.js +42 -0
  133. package/neural-interface/lib/session-indexer.js +28 -20
  134. package/neural-interface/lib/teams/scheduler.js +3 -2
  135. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  136. package/neural-interface/lib/ui-blob-api.js +14 -5
  137. package/neural-interface/lib/ui-blob-store.js +302 -39
  138. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  139. package/neural-interface/package-lock.json +5 -5
  140. package/neural-interface/package.json +1 -1
  141. package/neural-interface/public/extension-setup.html +6 -2
  142. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  143. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  144. package/neural-interface/public/shared/assistant/asst-api.js +67 -0
  145. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  146. package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
  147. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  148. package/neural-interface/public/shared/assistant/asst-render.js +343 -10
  149. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  150. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  151. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  152. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  153. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  154. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  155. package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
  156. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  157. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  158. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  159. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  160. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  161. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  162. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  163. package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
  164. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  165. package/neural-interface/public/shared/extension-update-view.js +34 -0
  166. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  167. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  168. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  169. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  170. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  171. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  172. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  173. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  174. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  175. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
  176. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  177. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  178. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  179. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  180. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  181. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  182. package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
  183. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  184. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  185. package/neural-interface/public/shared/styles.css +4 -0
  186. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  187. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  188. package/neural-interface/public/shared/ui-claude-panel.js +130 -1
  189. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  190. package/neural-interface/public/shared/ui-notifications.js +23 -4
  191. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  192. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  193. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  194. package/neural-interface/public/shared/worker-end.js +18 -0
  195. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  196. package/neural-interface/scripts/rebuild-pty.js +10 -0
  197. package/neural-interface/server.js +725 -308
  198. package/npm-shrinkwrap.json +5 -5
  199. package/package.json +1 -2
  200. package/browser-extension/content.js +0 -231
  201. package/browser-extension/engine.js +0 -658
  202. package/browser-extension/icons/icon-128.png +0 -0
  203. package/browser-extension/icons/icon-16.png +0 -0
  204. package/browser-extension/icons/icon-32.png +0 -0
  205. package/browser-extension/icons/icon-48.png +0 -0
  206. package/browser-extension/icons/status-off-16.png +0 -0
  207. package/browser-extension/icons/status-off-32.png +0 -0
  208. package/browser-extension/icons/status-off-48.png +0 -0
  209. package/browser-extension/icons/status-on-16.png +0 -0
  210. package/browser-extension/icons/status-on-32.png +0 -0
  211. package/browser-extension/icons/status-on-48.png +0 -0
  212. package/browser-extension/manifest.json +0 -58
  213. package/browser-extension/popup-strings.js +0 -250
  214. package/browser-extension/popup-view.js +0 -151
  215. package/browser-extension/popup.css +0 -166
  216. package/browser-extension/popup.html +0 -108
  217. package/browser-extension/popup.js +0 -359
  218. package/browser-extension/service-worker.js +0 -283
  219. package/browser-extension/setup-content.js +0 -36
  220. package/browser-extension/tokens.css +0 -326
@@ -1,23 +1,53 @@
1
- // The extension folder the owner loads in the browser ("Load unpacked"): a copy of the bundled browser-extension/ in
2
- // the owner's data home (DATA_HOME/browser-extension/unpacked), so an npm update or a moved checkout never breaks the
3
- // loaded extension. It is refreshed when the bundled copy changes and is not older than what is there; the browser
4
- // then needs the extension's Reload (the server tells the owner: status `reloadNeeded`).
1
+ // The extension folder the owner loads in the browser ("Load unpacked"): DATA_HOME/browser-extension/unpacked, in the
2
+ // owner's data home, so an npm update or a moved install never breaks the loaded extension. Its files come from the
3
+ // one package this app release pins (lib/browser-extension-pin.js), downloaded from synabun.ai and verified before a
4
+ // single byte is written here (lib/browser-extension-package.js); nothing of the extension is inside the app. When the
5
+ // folder's files change, the browser needs the extension's Reload (the server tells the owner: status `reloadNeeded`).
5
6
  //
6
- // The copy keeps the manifest's `key`, so the extension's ID is the same from this folder as from the bundled one
7
- // (lib/browser-extension-bridge.js EXTENSION_ID). Only the setup page's content script changes: its matches name this
7
+ // The folder keeps the manifest's `key`, so the extension's ID is the same from this folder as from any other
8
+ // (lib/browser-extension-pin.js EXTENSION_ID). Only the setup page's content script changes: its matches name this
8
9
  // server's own app port (127.0.0.1 and localhost), so the script runs on SynaBun's setup page and nowhere else.
9
10
  //
10
- // What is copied is an allowlist (the manifest, scripts, pages, styles, the icons), read as regular files only (a link
11
- // is never followed). The folder is replaced in one rename where the system allows it; where it does not (Windows,
12
- // a folder the browser holds open), the files are written in place. Nothing here is logged with a path.
11
+ // The extension has broad permissions, so the folder is held to the release, never to what a file in it says:
12
+ //
13
+ // current the folder holds exactly the files the pin lists (`files`: their SHA-256), byte for byte, and nothing
14
+ // else; the manifest may differ from the package's only in the setup content script, and only as
15
+ // folderManifest writes it for one port (inspectExtensionFolder). The marker (unpacked.json) is a record
16
+ // for an older SynaBun and for display; nothing decides on it.
17
+ // the root DATA_HOME (as resolved once) and DATA_HOME/browser-extension must be folders of this user that no one
18
+ // else can write, and the folder the browser loads a real folder (never a link). Anything else is
19
+ // EXTENSION_FOLDER_UNSAFE and nothing is read, recovered or written there.
20
+ // one writer every change, and the recovery before it, runs under one OS-held lock per data home (an empty SQLite
21
+ // file, lib/rulesets/lock.js: it goes away with a process that dies). Two servers on one data home take
22
+ // turns; nothing they do interleaves.
23
+ // a swap the new folder is written and synced beside the live one, a transaction record (transaction.json) is
24
+ // written and synced, then the live folder is renamed aside and the new one into its place: two renames,
25
+ // the same on every system, with a short moment between them where the path is empty (no program is
26
+ // started for this, and nothing but Node's own rename is used). A live folder that cannot be moved fails
27
+ // the first rename, so the update waits and the old folder stays whole. Live files are never overwritten
28
+ // one by one. The marker is written once the new folder is in place, then the old one and the record are
29
+ // removed. A process stopped at any step leaves the record, and the next locked step finishes it or takes
30
+ // it back (settle), by the folders' inodes.
31
+ // recovery only what a record names is ever moved back to the browser's path, and an old folder only when the
32
+ // record says it was the pinned extension. A leftover the record does not name is never promoted; the
33
+ // names SynaBun's own steps leave (staging folders, temporary files, old folders once the live one is
34
+ // there, a download nobody runs any more, and the swap-probe folders of an earlier build of this
35
+ // branch) are removed; nothing else is touched.
36
+ //
37
+ // Nothing here is logged with a path.
13
38
  import { createHash, randomBytes } from 'node:crypto';
14
- import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
15
- import { dirname, join } from 'node:path';
39
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, writeSync } from 'node:fs';
40
+ import { basename, join } from 'node:path';
41
+ import { EXTENSION_MAX_FILE_BYTES, EXTENSION_MAX_FILES, extensionFileAllowed, readExtensionSource, readExtensionZip } from './browser-extension-archive.js';
42
+ import { EXTENSION_PIN } from './browser-extension-pin.js';
43
+ import { createWriterLock } from './rulesets/lock.js';
16
44
 
17
45
  /** The path of the setup page, and the content-script file that reads its one-time pairing token. */
18
46
  export const SETUP_PAGE_PATH = '/extension-setup';
19
47
  export const SETUP_SCRIPT = 'setup-content.js';
20
- const FILE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(js|json|html|css|png)$/;
48
+ /** The port a manifest is set to before its SHA-256 is taken for the pin (the content script is the one part a folder changes). */
49
+ export const TEMPLATE_PORT = 1;
50
+ export const LOCK_TIMEOUT_MS = 15_000;
21
51
 
22
52
  /** The setup page's origins for an app port: the content script's matches, and what the service worker accepts. */
23
53
  export function setupMatches(appPort) {
@@ -25,22 +55,7 @@ export function setupMatches(appPort) {
25
55
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw Object.assign(new Error('Invalid app port.'), { code: 'INVALID_MESSAGE' });
26
56
  return [`http://127.0.0.1:${port}${SETUP_PAGE_PATH}*`, `http://localhost:${port}${SETUP_PAGE_PATH}*`];
27
57
  }
28
- /** The bundled files, by path relative to the folder: regular files of the allowlist, one level of `icons/`. */
29
- export function bundledFiles(source) {
30
- const files = [];
31
- for (const [dir, prefix] of [[source, ''], [join(source, 'icons'), 'icons/']]) {
32
- let names = [];
33
- try { names = readdirSync(dir); } catch { continue; }
34
- for (const name of names.sort()) {
35
- if (!FILE.test(name)) continue;
36
- const path = join(dir, name);
37
- try { if (!lstatSync(path).isFile()) continue; } catch { continue; }
38
- files.push({ rel: prefix + name, path });
39
- }
40
- }
41
- return files;
42
- }
43
- /** The manifest the folder gets: the bundled one, with the setup content script set to `appPort`. */
58
+ /** The manifest the folder gets: the package's, with the setup content script set to `appPort`. */
44
59
  export function folderManifest(manifest, appPort) {
45
60
  const copy = structuredClone(manifest);
46
61
  copy.content_scripts = [{ matches: setupMatches(appPort), js: [SETUP_SCRIPT], run_at: 'document_idle', all_frames: false }];
@@ -52,65 +67,609 @@ export function compareVersions(a, b) {
52
67
  for (let i = 0; i < Math.max(pa.length, pb.length); i++) { const d = (pa[i] || 0) - (pb[i] || 0); if (d) return Math.sign(d); }
53
68
  return 0;
54
69
  }
55
- function contents(source, appPort) {
56
- const files = bundledFiles(source).map(f => ({ ...f, bytes: readFileSync(f.path) }));
57
- const manifestFile = files.find(f => f.rel === 'manifest.json');
58
- if (!manifestFile) throw Object.assign(new Error('The bundled extension has no manifest.'), { code: 'EXTENSION_FOLDER_FAILED' });
59
- const manifest = folderManifest(JSON.parse(manifestFile.bytes.toString('utf8')), appPort);
60
- manifestFile.bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
70
+
71
+ const ROOT = 'browser-extension', FOLDER = 'unpacked', MARKER = 'unpacked.json', JOURNAL = 'transaction.json', CACHE = 'package.zip', LOCK = 'install-lock.db';
72
+ /** The names SynaBun's own steps leave beside the folder (and only these are ever removed). */
73
+ export const STAGING_FOLDER = /^unpacked\.\d+\.[a-f0-9]{12}\.tmp$/;
74
+ export const RETIRED_FOLDER = /^unpacked\.[a-f0-9]{12}\.old$/;
75
+ const TEMPORARY_FILE = /^(unpacked\.json|transaction\.json|package\.zip)\.[a-f0-9]{12}\.tmp$/;
76
+ // A folder an earlier build of this branch made to test its file system, and left when it was stopped mid-test.
77
+ // Nothing makes one any more; the sweep still removes this exact name.
78
+ const SWAP_PROBE = /^swap-probe\.\d+\.[a-f0-9]{12}$/;
79
+ const DOWNLOAD_FILE = /^download\.(\d+)\.[a-f0-9]{12}\.tmp$/;
80
+ const STALE_DOWNLOAD_MS = 10 * 60 * 1000;
81
+ /** A name for a download's working file in the root (removed by the next locked step once nobody runs it). */
82
+ export const downloadWorkName = () => `download.${process.pid}.${hex()}.tmp`;
83
+
84
+ const hex = () => randomBytes(6).toString('hex');
85
+ const sha = bytes => createHash('sha256').update(bytes).digest('hex');
86
+ const byRel = (a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
87
+ const serialize = manifest => Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
88
+ const folderError = (code, message) => Object.assign(new Error(message), { code });
89
+ const failed = message => folderError('EXTENSION_FOLDER_FAILED', message);
90
+ const unsafe = (part, reason = 'it is a link, not a folder, another user\'s, or others can write to it') => Object.assign(folderError('EXTENSION_FOLDER_UNSAFE', `SynaBun did not use ${part}: ${reason}. Nothing was read or changed there.`), { reason });
91
+ const notPinned = message => folderError('EXTENSION_VERIFY_FAILED', message);
92
+ const KNOWN_CODES = new Set(['EXTENSION_FOLDER_FAILED', 'EXTENSION_FOLDER_UNSAFE', 'EXTENSION_VERIFY_FAILED']);
93
+ const asFolderError = error => (KNOWN_CODES.has(error?.code) ? error : Object.assign(failed('The extension folder could not be written.'), { cause: error }));
94
+ const WINDOWS = process.platform === 'win32';
95
+ const NOFOLLOW = constants.O_NOFOLLOW || 0, NONBLOCK = constants.O_NONBLOCK || 0;
96
+
97
+ // ── Files, inventories and the package ──
98
+
99
+ // A file is the folder's when it is the manifest set to a port, or anything else of the allowlist, byte for byte.
100
+ function manifestOf(bytes) {
101
+ let manifest;
102
+ try { manifest = JSON.parse(bytes.toString('utf8')); } catch { return null; }
103
+ return manifest && typeof manifest === 'object' && !Array.isArray(manifest) ? manifest : null;
104
+ }
105
+ /**
106
+ * The pin's `files` for a package's files ([{ rel, bytes }]): each file's SHA-256, the manifest's taken with its setup
107
+ * content script set to TEMPLATE_PORT. Throws EXTENSION_VERIFY_FAILED for files no extension folder may hold.
108
+ */
109
+ export function packageInventory(files) {
110
+ if (!Array.isArray(files) || !files.length || files.length > EXTENSION_MAX_FILES) throw notPinned('The extension has no files, or too many.');
111
+ const inventory = {}, seen = new Set();
112
+ for (const file of [...files].sort(byRel)) {
113
+ if (!extensionFileAllowed(file?.rel) || !Buffer.isBuffer(file.bytes) || seen.has(file.rel.toLowerCase())) throw notPinned('The extension holds a file that is not allowed.');
114
+ seen.add(file.rel.toLowerCase());
115
+ if (file.rel === 'manifest.json') {
116
+ const manifest = manifestOf(file.bytes);
117
+ if (!manifest) throw notPinned('The extension\'s manifest cannot be read.');
118
+ inventory[file.rel] = sha(serialize(folderManifest(manifest, TEMPLATE_PORT)));
119
+ } else inventory[file.rel] = sha(file.bytes);
120
+ }
121
+ if (!inventory['manifest.json']) throw notPinned('The extension has no manifest.');
122
+ return inventory;
123
+ }
124
+ const sameInventory = (a, b) => {
125
+ const names = Object.keys(a || {});
126
+ return names.length === Object.keys(b || {}).length && names.every(name => Object.hasOwn(b, name) && a[name] === b[name]);
127
+ };
128
+ /**
129
+ * The files of a package that is exactly the pinned one ([{ rel, bytes }]): its size and SHA-256 are the pin's, it is
130
+ * SynaBun's zip form, its manifest names the pinned version and key, and its files are the ones the pin lists. Throws
131
+ * EXTENSION_VERIFY_FAILED otherwise. Writes nothing.
132
+ */
133
+ export function verifiedPackageFiles(zip, pin = EXTENSION_PIN) {
134
+ if (!Buffer.isBuffer(zip) || zip.length !== pin.size || sha(zip) !== pin.sha256) throw notPinned('The download is not the file this SynaBun release expects.');
135
+ let files;
136
+ try { files = readExtensionZip(zip); } catch (error) { throw notPinned(error?.message || 'The package cannot be read.'); }
137
+ const manifest = manifestOf(files.find(f => f.rel === 'manifest.json').bytes);
138
+ if (!manifest) throw notPinned('The package\'s manifest cannot be read.');
139
+ if (manifest.version !== pin.version || manifest.key !== pin.key) throw notPinned('The package is not the extension this SynaBun release expects.');
140
+ if (!sameInventory(packageInventory(files), pin.files)) throw notPinned('The package\'s files are not the ones this SynaBun release lists.');
141
+ return files;
142
+ }
143
+ // The files as the folder holds them for `appPort` (the manifest set to it), the top level by name, then icons/: the
144
+ // order every folder was marked with since the first SynaBun that prepared one.
145
+ function folderFiles(files, appPort) {
146
+ const top = files.filter(f => !f.rel.includes('/')).sort(byRel), nested = files.filter(f => f.rel.includes('/')).sort(byRel);
147
+ return [...top, ...nested].map(f => (f.rel === 'manifest.json' ? { rel: f.rel, bytes: serialize(folderManifest(manifestOf(f.bytes), appPort)) } : { rel: f.rel, bytes: f.bytes }));
148
+ }
149
+ // The digest the marker has always carried (an older SynaBun reads it): every file's name and bytes in folder order.
150
+ function folderDigest(files) {
61
151
  const digest = createHash('sha256');
62
152
  for (const f of files) digest.update(f.rel).update('\0').update(f.bytes).update('\0');
63
- return { files, version: String(manifest.version || '0'), digest: digest.digest('hex') };
153
+ return digest.digest('hex');
64
154
  }
65
- function readMarker(path) {
66
- try { if (!lstatSync(path).isFile()) return null; const v = JSON.parse(readFileSync(path, 'utf8')); return v && typeof v === 'object' ? v : null; } catch { return null; }
155
+
156
+ // ── What is on disk, read without following a link ──
157
+
158
+ const POSIX = !WINDOWS && typeof process.getuid === 'function';
159
+ // What the ownership rule reads of the system: the platform, this process's user and group, and /etc/passwd and
160
+ // /etc/group (read as files, never through a program or NSS). `system` ({ platform, uid, gid, readFile }) replaces
161
+ // any part of it, for the tests; nothing else passes one.
162
+ function systemOf(given = null) {
163
+ const posix = typeof process.getuid === 'function' && typeof process.getgid === 'function';
164
+ return {
165
+ platform: given?.platform ?? process.platform,
166
+ uid: given?.uid ?? (posix ? process.getuid() : null),
167
+ gid: given?.gid ?? (posix ? process.getgid() : null),
168
+ readFile: given?.readFile ?? (path => readFileSync(path, 'utf8')),
169
+ };
170
+ }
171
+ const PRIVATE_GROUP_UNKNOWN = 'its group can write to it, and SynaBun could not confirm from /etc/passwd and /etc/group that this group is the user\'s own private group';
172
+ // Linux's user private groups (a umask of 002): a folder its group can write is still this user's alone when that group
173
+ // is the user's primary group, named after the user, with no other member, and nobody else's primary group. Anything
174
+ // that cannot be confirmed from the two files (a user or group from LDAP or another directory, a file that cannot be
175
+ // read, a line that cannot be parsed) is refused, with the reason.
176
+ function privateGroupVerdict(folderGid, system) {
177
+ const no = why => ({ ok: false, reason: `${PRIVATE_GROUP_UNKNOWN} (${why})` });
178
+ const lines = path => { try { return String(system.readFile(path)).split(/\r?\n/).filter(line => line.trim() && !line.startsWith('#')); } catch { return null; } };
179
+ const passwd = lines('/etc/passwd');
180
+ if (!passwd) return no('/etc/passwd could not be read');
181
+ const group = lines('/etc/group');
182
+ if (!group) return no('/etc/group could not be read');
183
+ if ([...passwd, ...group].some(line => line[0] === '+' || line[0] === '-')) return no('they pull in entries from a network directory (+ or -), which SynaBun does not read');
184
+ const id = text => (/^\d+$/.test(text) ? Number(text) : NaN);
185
+ const users = passwd.map(line => line.split(':')).map(f => ({ ok: f.length === 7 && !!f[0], name: f[0], uid: id(f[2]), gid: id(f[3]) }));
186
+ const groups = group.map(line => line.split(':')).map(f => ({ ok: f.length === 4 && !!f[0], name: f[0], gid: id(f[2]), members: (f[3] || '').split(',').map(m => m.trim()).filter(Boolean) }));
187
+ if (users.some(u => !u.ok || Number.isNaN(u.uid) || Number.isNaN(u.gid))) return no('a line of /etc/passwd cannot be read');
188
+ if (groups.some(g => !g.ok || Number.isNaN(g.gid))) return no('a line of /etc/group cannot be read');
189
+ const me = users.filter(u => u.uid === system.uid);
190
+ if (me.length !== 1) return no(me.length ? 'this user is listed in /etc/passwd more than once' : 'this user is not listed in /etc/passwd: an account from LDAP or another directory cannot be checked');
191
+ const [user] = me;
192
+ if (folderGid !== user.gid || folderGid !== system.gid) return no('the folder\'s group is not this user\'s primary group');
193
+ const entries = groups.filter(g => g.gid === folderGid);
194
+ if (!entries.length) return no('the group is not listed in /etc/group');
195
+ if (entries.length > 1) return no('/etc/group lists the group more than once');
196
+ if (entries[0].name !== user.name) return no('the group is not named after this user');
197
+ if (entries[0].members.some(m => m !== user.name)) return no('the group has other members');
198
+ if (users.some(u => u !== user && u.gid === folderGid)) return no('another account has it as its primary group');
199
+ return { ok: true };
200
+ }
201
+ /**
202
+ * Whether a folder or file (`info`: its lstat) is this user's and nobody else can write it: { ok } or { ok: false,
203
+ * reason } (a sentence without a path). Windows has no POSIX modes to check. Others' write is never accepted; the
204
+ * group's only on Linux, for the user's own private group (privateGroupVerdict). macOS keeps refusing it (`staff` is
205
+ * shared). `system`: see systemOf.
206
+ */
207
+ export function ownershipVerdict(info, given = null) {
208
+ const system = systemOf(given);
209
+ if (system.platform === 'win32' || system.uid === null) return { ok: true };
210
+ if (Number(info.uid) !== system.uid) return { ok: false, reason: 'it belongs to another user' };
211
+ const mode = Number(info.mode);
212
+ if (mode & 0o002) return { ok: false, reason: 'other users can write to it' };
213
+ if (!(mode & 0o020)) return { ok: true };
214
+ if (system.platform !== 'linux') return { ok: false, reason: 'its group can write to it' };
215
+ return privateGroupVerdict(Number(info.gid), system);
67
216
  }
68
- function writeFiles(folder, files) {
69
- mkdirSync(join(folder, 'icons'), { recursive: true, mode: 0o700 });
70
- for (const f of files) writeFileSync(join(folder, f.rel), f.bytes, { mode: 0o600 });
217
+ // A folder or file of this user that nobody else can write (a link is never one).
218
+ const ownedSafely = (info, system) => ownershipVerdict(info, system).ok;
219
+ function lstatOrNull(path) {
220
+ try { return lstatSync(path); } catch (error) { if (error?.code === 'ENOENT') return null; throw error; }
221
+ }
222
+ function list(dir) { try { return readdirSync(dir); } catch { return null; } }
223
+ // "<dev>:<ino>" of a real folder at `path` (never a link), or null.
224
+ function identity(path) {
225
+ if (!path) return null;
226
+ try { const info = lstatSync(path, { bigint: true }); return info.isDirectory() && !info.isSymbolicLink() ? `${info.dev}:${info.ino}` : null; } catch { return null; }
227
+ }
228
+ // The bytes of a regular file of at most `max` bytes, opened without following a link and without waiting on a pipe.
229
+ function readRegular(path, max = EXTENSION_MAX_FILE_BYTES) {
230
+ let fd = null;
231
+ try {
232
+ const before = lstatSync(path);
233
+ if (!before.isFile() || before.size > max) return null;
234
+ fd = openSync(path, constants.O_RDONLY | NOFOLLOW | NONBLOCK);
235
+ const info = fstatSync(fd);
236
+ if (!info.isFile() || info.size > max || (POSIX && (info.ino !== before.ino || info.dev !== before.dev))) return null;
237
+ const bytes = Buffer.alloc(info.size);
238
+ let at = 0;
239
+ while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
240
+ if (at !== bytes.length || readSync(fd, Buffer.alloc(1), 0, 1, at) !== 0) return null;
241
+ return bytes;
242
+ } catch { return null; } finally { if (fd !== null) try { closeSync(fd); } catch {} }
243
+ }
244
+ function readJson(path) {
245
+ const bytes = readRegular(path, 64 * 1024);
246
+ if (!bytes) return null;
247
+ try { const value = JSON.parse(bytes.toString('utf8')); return value && typeof value === 'object' && !Array.isArray(value) ? value : null; } catch { return null; }
248
+ }
249
+ function syncDir(dir) {
250
+ if (WINDOWS) return;
251
+ let fd = null;
252
+ try { fd = openSync(dir, constants.O_RDONLY); fsyncSync(fd); } finally { if (fd !== null) closeSync(fd); }
253
+ }
254
+ function writeNew(path, bytes) {
255
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o600);
256
+ try { let at = 0; while (at < bytes.length) at += writeSync(fd, bytes, at, bytes.length - at); fsyncSync(fd); } finally { closeSync(fd); }
257
+ }
258
+ // A file replaced in one rename, synced before and after (its temporary name is one the sweep knows).
259
+ function writeDurably(path, bytes, io) {
260
+ const temporary = `${path}.${hex()}.tmp`;
261
+ try { writeNew(temporary, bytes); io.rename(temporary, path); } catch (error) { rmSync(temporary, { force: true }); throw error; }
262
+ syncDir(join(path, '..'));
71
263
  }
72
264
 
73
265
  /**
74
- * Prepares or refreshes the owner's extension folder. `force` refreshes even when the bundled version is older than
75
- * what is there (never used at start). Returns { folder, version, changed, previousVersion, appPort }. Throws
76
- * EXTENSION_FOLDER_FAILED when the folder cannot be written.
266
+ * The install root of a data home, checked: DATA_HOME resolved once, then DATA_HOME/browser-extension, each a folder of
267
+ * this user that no one else can write (the root is never a link). Returns its paths, or null when the root is not
268
+ * there and `create` is not set. Throws EXTENSION_FOLDER_UNSAFE (its message says why, without a path), or
269
+ * EXTENSION_FOLDER_FAILED when it cannot be read. `system`: see systemOf.
77
270
  */
78
- export function prepareExtensionFolder({ source, home, appPort, now = Date.now, force = false }) {
79
- const root = join(home, 'browser-extension'), folder = join(root, 'unpacked'), markerPath = join(root, 'unpacked.json');
80
- const { files, version, digest } = contents(source, appPort);
81
- const marker = readMarker(markerPath);
82
- const present = (() => { try { return lstatSync(join(folder, 'manifest.json')).isFile(); } catch { return false; } })();
83
- const same = present && marker?.digest === digest;
84
- const older = present && marker?.version && compareVersions(version, marker.version) < 0;
85
- if (same || older && !force) return { folder, version: marker?.version || version, changed: false, previousVersion: marker?.version || null, appPort: marker?.appPort ?? Number(appPort), stale: !same };
271
+ function installRoot(home, { create = false, system = null } = {}) {
272
+ let base;
273
+ try { base = realpathSync(String(home)); } catch (error) {
274
+ if (error?.code === 'ENOENT' && !create) return null;
275
+ throw failed('The data folder cannot be found.');
276
+ }
277
+ // A part that is not a real folder (or file) of this user that nobody else can write: refused, with the reason.
278
+ const hold = (part, info, isKind) => {
279
+ if (info.isSymbolicLink() || !isKind(info)) throw unsafe(part, 'it is a link or not a folder');
280
+ const verdict = ownershipVerdict(info, system);
281
+ if (!verdict.ok) throw unsafe(part, verdict.reason);
282
+ };
283
+ let root;
86
284
  try {
87
- mkdirSync(root, { recursive: true, mode: 0o700 }); try { chmodSync(root, 0o700); } catch {}
88
- const staging = join(root, `unpacked.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
89
- try {
90
- writeFiles(staging, files);
91
- // One rename where the system allows it; else the files are written in place (a folder the browser holds open).
92
- const retired = `${folder}.${randomBytes(6).toString('hex')}.old`;
93
- let swapped = false;
94
- try {
95
- if (present || (() => { try { lstatSync(folder); return true; } catch { return false; } })()) renameSync(folder, retired);
96
- renameSync(staging, folder); swapped = true;
97
- } catch {
98
- try { lstatSync(folder); } catch { try { renameSync(retired, folder); } catch {} }
99
- }
100
- if (!swapped) writeFiles(folder, files);
101
- rmSync(retired, { recursive: true, force: true });
102
- } finally { rmSync(staging, { recursive: true, force: true }); }
103
- const record = { v: 1, version, digest, appPort: Number(appPort), preparedAt: now() };
104
- const temporary = `${markerPath}.${randomBytes(6).toString('hex')}.tmp`;
105
- writeFileSync(temporary, JSON.stringify(record), { mode: 0o600 }); renameSync(temporary, markerPath);
285
+ hold('the data folder', lstatSync(base), info => info.isDirectory());
286
+ root = join(base, ROOT);
287
+ let info = lstatOrNull(root);
288
+ if (!info) {
289
+ if (!create) return null;
290
+ try { mkdirSync(root, { mode: 0o700 }); } catch (error) { if (error?.code !== 'EEXIST') throw error; }
291
+ info = lstatSync(root);
292
+ }
293
+ hold('its extension folder (browser-extension)', info, i => i.isDirectory());
294
+ const lock = lstatOrNull(join(root, LOCK));
295
+ if (lock) hold('the extension folder\'s lock file', lock, i => i.isFile());
296
+ } catch (error) { throw asFolderError(error); }
297
+ return { base, root, folder: join(root, FOLDER), marker: join(root, MARKER), journal: join(root, JOURNAL), cache: join(root, CACHE), lock: join(root, LOCK), system };
298
+ }
299
+ // One writer per data home: everything that changes the root, and the recovery before it, runs inside.
300
+ function withLock(paths, fn, timeoutMs = LOCK_TIMEOUT_MS) {
301
+ const lock = createWriterLock(paths.lock, { timeoutMs });
302
+ try { lock.enter(); } catch (error) {
303
+ lock.close();
304
+ throw Object.assign(failed(error?.code === 'BUSY' ? 'Another SynaBun is changing the extension folder right now. Try again in a moment.' : 'The extension folder\'s lock cannot be used.'), { cause: error });
305
+ }
306
+ try { return fn(); } finally { lock.leave(); lock.close(); }
307
+ }
308
+
309
+ // What the folder at `folder` holds, held to the pin: missing, unsafe (a link, not a folder, another user's), other
310
+ // (anything but the pinned files) or pinned, with the port its manifest names and the files as they are.
311
+ function inspectTree(folder, pin, system = null) {
312
+ let info;
313
+ try { info = lstatOrNull(folder); } catch { return { state: 'other', version: null }; }
314
+ if (!info) return { state: 'missing' };
315
+ if (info.isSymbolicLink() || !info.isDirectory() || !ownedSafely(info, system)) return { state: 'unsafe' };
316
+ const other = () => ({ state: 'other', version: shownVersion(folder) });
317
+ const wanted = Object.keys(pin.files);
318
+ const top = new Set(wanted.filter(rel => !rel.includes('/'))), icons = new Set(wanted.filter(rel => rel.startsWith('icons/')).map(rel => rel.slice(6)));
319
+ if (icons.size) top.add('icons');
320
+ const same = (names, set) => !!names && names.length === set.size && names.every(name => set.has(name));
321
+ if (!same(list(folder), top)) return other();
322
+ if (icons.size) {
323
+ let iconInfo;
324
+ try { iconInfo = lstatSync(join(folder, 'icons')); } catch { return other(); }
325
+ if (iconInfo.isSymbolicLink() || !iconInfo.isDirectory() || !ownedSafely(iconInfo, system) || !same(list(join(folder, 'icons')), icons)) return other();
326
+ }
327
+ const files = [];
328
+ for (const rel of wanted) {
329
+ const bytes = readRegular(join(folder, ...rel.split('/')));
330
+ if (!bytes) return other();
331
+ if (rel !== 'manifest.json' && sha(bytes) !== pin.files[rel]) return other();
332
+ files.push({ rel, bytes });
333
+ }
334
+ const manifestBytes = files.find(f => f.rel === 'manifest.json').bytes, manifest = manifestOf(manifestBytes);
335
+ const port = Number(/^http:\/\/127\.0\.0\.1:(\d{1,5})\/extension-setup\*$/.exec(manifest?.content_scripts?.[0]?.matches?.[0] || '')?.[1]);
336
+ if (!manifest || !(port >= 1 && port <= 65535)) return other();
337
+ // Set to that port exactly as folderManifest writes it, and otherwise the pinned manifest.
338
+ if (!serialize(folderManifest(manifest, port)).equals(manifestBytes) || sha(serialize(folderManifest(manifest, TEMPLATE_PORT))) !== pin.files['manifest.json']) return other();
339
+ return { state: 'pinned', port, files, version: pin.version };
340
+ }
341
+ // The version a folder's manifest names, for display only (never trusted).
342
+ function shownVersion(folder) {
343
+ const manifest = manifestOf(readRegular(join(folder, 'manifest.json'), 256 * 1024) || Buffer.alloc(0));
344
+ return typeof manifest?.version === 'string' && /^\d+(\.\d+){0,3}$/.test(manifest.version) ? manifest.version : null;
345
+ }
346
+
347
+ // ── The transaction ──
348
+
349
+ // 'place': no live folder, one rename. 'renames': the live folder aside, then the new one into its place.
350
+ // 'exchange' is only ever read: a record an earlier build of this branch wrote, settled by its folders' identities
351
+ // like any other (settle never needs to know how the folders were moved), and never written again.
352
+ const JOURNAL_MODES = new Set(['place', 'renames', 'exchange']);
353
+ const IDENTITY = /^\d+:\d+$/;
354
+ function readJournal(paths) {
355
+ let info;
356
+ try { info = lstatOrNull(paths.journal); } catch { return null; }
357
+ if (!info) return null;
358
+ const j = info.isFile() ? readJson(paths.journal) : null;
359
+ const valid = j && j.v === 1 && JOURNAL_MODES.has(j.mode) && typeof j.staging === 'string' && STAGING_FOLDER.test(j.staging)
360
+ && (j.mode === 'renames' ? typeof j.retired === 'string' && RETIRED_FOLDER.test(j.retired) : j.retired === null)
361
+ && typeof j.next === 'string' && IDENTITY.test(j.next) && (j.mode === 'place' ? j.previous === null : typeof j.previous === 'string' && IDENTITY.test(j.previous))
362
+ && j.marker && typeof j.marker === 'object' && typeof j.marker.version === 'string';
363
+ // A record SynaBun did not write whole names nothing that can be trusted: it is removed, and nothing it says is done.
364
+ if (!valid) { rmSync(paths.journal, { force: true }); return null; }
365
+ return j;
366
+ }
367
+ /**
368
+ * Finishes or takes back the transaction a record describes, by the folders' identities (never by their names alone).
369
+ * `prefer`: 'forward' (a restart: the new folder, verified before it was staged, goes into place when the path is
370
+ * empty) or 'back' (this process just failed a step: the old folder goes back). An old folder is put back by a restart
371
+ * only when the record says it was the pinned extension. Removes the record last.
372
+ */
373
+ function settle(paths, j, io, { prefer = 'forward' } = {}) {
374
+ const at = name => (name ? join(paths.root, name) : null);
375
+ const same = (a, b) => a !== null && b !== null && a === b;
376
+ let live = identity(paths.folder);
377
+ if (live === null) {
378
+ if (prefer === 'forward' && same(identity(at(j.staging)), j.next)) { io.rename(at(j.staging), paths.folder); syncDir(paths.root); }
379
+ else if (j.mode === 'renames' && same(identity(at(j.retired)), j.previous) && (prefer === 'back' || j.previousVerified === true)) { io.rename(at(j.retired), paths.folder); syncDir(paths.root); }
380
+ live = identity(paths.folder);
381
+ }
382
+ if (same(live, j.next)) {
383
+ writeDurably(paths.marker, Buffer.from(JSON.stringify(j.marker)), io);
384
+ io.step('marked');
385
+ // The old folder: where the first rename put it (or, for an earlier build's exchange record, the staging name).
386
+ for (const name of [j.staging, j.retired]) if (name && same(identity(at(name)), j.previous)) rmSync(at(name), { recursive: true, force: true });
387
+ } else if (same(identity(at(j.staging)), j.next)) {
388
+ rmSync(at(j.staging), { recursive: true, force: true });
389
+ }
390
+ syncDir(paths.root);
391
+ rmSync(paths.journal, { force: true });
392
+ syncDir(paths.root);
393
+ io.step('settled');
394
+ }
395
+ const pidAlive = pid => { try { process.kill(pid, 0); return true; } catch (error) { return error?.code === 'EPERM'; } };
396
+ // What SynaBun's own steps left beside the folder: removed under the lock, once no record names it. A download's
397
+ // working file only once its process is gone or it is old; an old folder only while the live one is there.
398
+ function sweep(paths, now) {
399
+ const live = identity(paths.folder) !== null;
400
+ for (const name of list(paths.root) || []) {
401
+ const path = join(paths.root, name), download = DOWNLOAD_FILE.exec(name);
402
+ let remove = STAGING_FOLDER.test(name) || TEMPORARY_FILE.test(name) || SWAP_PROBE.test(name) || (live && RETIRED_FOLDER.test(name));
403
+ if (download) { try { remove = !pidAlive(Number(download[1])) || now - lstatSync(path).mtimeMs > STALE_DOWNLOAD_MS; } catch { remove = false; } }
404
+ if (remove) try { rmSync(path, { recursive: true, force: true }); } catch { /* the next locked step tries again */ }
405
+ }
406
+ }
407
+ // Inside the lock, before anything else: a stopped transaction finished or taken back, then the leftovers removed.
408
+ function recover(paths, io, now) {
409
+ const j = readJournal(paths);
410
+ if (j) settle(paths, j, io, { prefer: 'forward' });
411
+ sweep(paths, now);
412
+ }
413
+ function writeTree(dir, files) {
414
+ mkdirSync(dir, { mode: 0o700 });
415
+ if (files.some(f => f.rel.startsWith('icons/'))) mkdirSync(join(dir, 'icons'), { mode: 0o700 });
416
+ for (const f of files) writeNew(join(dir, ...f.rel.split('/')), f.bytes);
417
+ if (files.some(f => f.rel.startsWith('icons/'))) syncDir(join(dir, 'icons'));
418
+ syncDir(dir);
419
+ }
420
+ // Recognize an ordinary upgrade for the reload prompt only. Installation always verifies against the NEW pin.
421
+ // If the old manifest, contents or recorded installation disagree, keep the manual repair confirmation.
422
+ function previousInstall(paths, marker, previous, pin) {
423
+ if (!previous?.version || previous.version !== marker?.version || compareVersions(previous.version, pin.version) >= 0) return null;
424
+ const names = list(paths.folder);
425
+ if (!names || names.length > EXTENSION_MAX_FILES) return null;
426
+ const pathsInOrder = names.filter(name => name !== 'icons').sort();
427
+ if (names.includes('icons')) {
428
+ const icons = join(paths.folder, 'icons');
429
+ let info;
430
+ try { info = lstatOrNull(icons); } catch { return null; }
431
+ if (!info?.isDirectory() || !ownedSafely(info, paths.system)) return null;
432
+ const children = list(icons);
433
+ if (!children || children.length + pathsInOrder.length > EXTENSION_MAX_FILES) return null;
434
+ pathsInOrder.push(...children.sort().map(name => `icons/${name}`));
435
+ }
436
+ const digest = createHash('sha256');
437
+ for (const rel of pathsInOrder) {
438
+ if (!extensionFileAllowed(rel)) return null;
439
+ const bytes = readRegular(join(paths.folder, rel));
440
+ if (!bytes || (rel === 'manifest.json' && manifestOf(bytes)?.key !== pin.key)) return null;
441
+ digest.update(rel).update('\0').update(bytes).update('\0');
442
+ }
443
+ return digest.digest('hex') === marker.digest ? previous.version : null;
444
+ }
445
+ // The Reload the marker asks for after a replacement (`reload`), until the setup page sees the extension running again
446
+ // (confirmExtensionReload), the new version authenticates (confirmExtensionVersion), or the owner confirms a repair.
447
+ // `repair`: the folder held files that were not the pinned extension (changed, added or
448
+ // deleted, or an unrecognized version) and they were replaced: the browser may still run them, at any version. `fromPort`: the
449
+ // same extension on another port, whose old manifest the browser keeps until a Reload. A Reload asked for before and
450
+ // not yet seen is kept (a repair stays a repair). A first install (no folder) asks for none.
451
+ function reloadAfter(pending, previous, port, fromVersion) {
452
+ const kept = pending && typeof pending === 'object' && !Array.isArray(pending) ? pending : null;
453
+ if (fromVersion && !kept?.repair) return { reload: { fromVersion } };
454
+ const repair = previous?.state === 'other' || kept?.repair === true;
455
+ const fromPort = previous?.state === 'pinned' && previous.port !== port ? previous.port : Number.isInteger(kept?.fromPort) ? kept.fromPort : null;
456
+ if (!repair && fromPort === null && !kept) return {};
457
+ return { reload: { ...(fromPort !== null ? { fromPort } : {}), ...(repair ? { repair: true } : {}),
458
+ ...(!repair && kept?.fromVersion ? { fromVersion: kept.fromVersion } : {}) } };
459
+ }
460
+ const reloadReasonOf = reload => (!reload ? null : reload.repair === true ? 'repair' : reload.fromVersion ? 'version' : 'port');
461
+ // The verified files into the browser's path for `port`, as one transaction. `previous`: what inspectTree said of the
462
+ // folder that is there. Returns the marker written.
463
+ function place(paths, { files, port, pin, now, io, previous }) {
464
+ const wanted = folderFiles(files, port);
465
+ const staging = join(paths.root, `unpacked.${process.pid}.${hex()}.tmp`);
466
+ // Until the record is written nothing names the staged folder: a failure here removes it at once.
467
+ const unstage = error => { rmSync(staging, { recursive: true, force: true }); throw error; };
468
+ try { writeTree(staging, wanted); } catch (error) { unstage(error); }
469
+ io.step('staged');
470
+ const live = identity(paths.folder);
471
+ const mode = live ? 'renames' : 'place';
472
+ const oldMarker = readJson(paths.marker);
473
+ const fromVersion = previous?.state === 'other' ? previousInstall(paths, oldMarker, previous, pin) : null;
474
+ const marker = { v: 1, version: pin.version, digest: folderDigest(wanted), appPort: port, preparedAt: now(), package: pin.sha256,
475
+ ...reloadAfter(oldMarker?.reload, previous, port, fromVersion) };
476
+ const j = { v: 1, mode, staging: basename(staging), retired: mode === 'renames' ? `unpacked.${hex()}.old` : null, next: identity(staging), previous: live,
477
+ previousVerified: previous?.state === 'pinned', marker };
478
+ try { writeDurably(paths.journal, Buffer.from(JSON.stringify(j)), io); } catch (error) { unstage(error); }
479
+ io.step('journaled');
480
+ try {
481
+ if (mode === 'renames') {
482
+ // A folder that cannot be moved (Windows, a folder the browser holds open) fails here: nothing has moved yet.
483
+ io.rename(paths.folder, join(paths.root, j.retired));
484
+ // Between these two renames the browser's path is empty for a moment; the record says how to finish or take it back.
485
+ io.step('retired');
486
+ io.rename(staging, paths.folder);
487
+ } else io.rename(staging, paths.folder);
488
+ syncDir(paths.root);
489
+ io.step('swapped');
106
490
  } catch (error) {
107
- if (error?.code === 'EXTENSION_FOLDER_FAILED') throw error;
108
- throw Object.assign(new Error('The extension folder could not be written.'), { code: 'EXTENSION_FOLDER_FAILED' });
491
+ try { settle(paths, j, io, { prefer: 'back' }); } catch { /* the record stays: the next locked step settles it */ }
492
+ throw error;
109
493
  }
110
- return { folder, version, changed: true, previousVersion: marker?.version || null, appPort: Number(appPort), stale: false };
494
+ settle(paths, j, io);
495
+ return marker;
496
+ }
497
+ function ioOf(io = {}) { return { rename: io.rename || renameSync, step: io.step || (() => {}) }; }
498
+ const markerShape = marker => (marker ? { version: marker.version || null, appPort: marker.appPort ?? null, preparedAt: marker.preparedAt ?? null, package: typeof marker.package === 'string' ? marker.package : null } : null);
499
+ // A folder that holds the pinned files for `port` with a marker that says otherwise: the marker follows the files.
500
+ function reconcileMarker(paths, files, port, pin, now, io) {
501
+ const marker = readJson(paths.marker), digest = folderDigest(folderFiles(files, port));
502
+ // A marker from before downloads names no package: left as it is (an older SynaBun reads it the same way).
503
+ if (marker && marker.version === pin.version && marker.digest === digest && marker.appPort === port && (marker.package == null || marker.package === pin.sha256)) return false;
504
+ const record = { v: 1, version: pin.version, digest, appPort: port, preparedAt: marker?.preparedAt ?? now(), package: pin.sha256, ...(marker?.reload ? { reload: marker.reload } : {}) };
505
+ writeDurably(paths.marker, Buffer.from(JSON.stringify(record)), io);
506
+ return true;
507
+ }
508
+ function readCache(paths, pin) {
509
+ const bytes = readRegular(paths.cache, pin.size);
510
+ if (!bytes) return null;
511
+ try { return verifiedPackageFiles(bytes, pin); } catch { return null; }
512
+ }
513
+
514
+ // ── What the server calls ──
515
+
516
+ /**
517
+ * What the folder holds now, read-only and without a lock: { state, folder, version, port }. `state`: 'missing' (no
518
+ * folder), 'unsafe' (its root or the folder is a link, not a folder, another user's or writable by others), 'current'
519
+ * (exactly the pinned extension, set to `appPort`), 'retarget' (exactly the pinned extension, set to another port:
520
+ * no download needed) or 'other' (anything else: an older or newer version, a changed, added or deleted file).
521
+ */
522
+ export function inspectExtensionFolder({ home, appPort, pin = EXTENSION_PIN, system = null }) {
523
+ const folder = join(home, ROOT, FOLDER);
524
+ let paths;
525
+ try { paths = installRoot(home, { system }); } catch (error) { return error?.code === 'EXTENSION_FOLDER_UNSAFE' ? { state: 'unsafe', folder, version: null, port: null, reason: error.reason } : { state: 'other', folder, version: null, port: null }; }
526
+ if (!paths) return { state: 'missing', folder, version: null, port: null };
527
+ const look = inspectTree(paths.folder, pin, paths.system);
528
+ if (look.state === 'pinned') return { state: look.port === Number(appPort) ? 'current' : 'retarget', folder, version: pin.version, port: look.port };
529
+ return { state: look.state, folder, version: look.version ?? null, port: null };
530
+ }
531
+
532
+ /**
533
+ * Puts the pinned extension into the owner's folder, set to `appPort`. `files` ([{ rel, bytes }]: a verified package's;
534
+ * or, with `source`, a folder's own, read through the allowlist) must be exactly the files the pin lists, else
535
+ * EXTENSION_VERIFY_FAILED and nothing is written. `zip`: the verified package itself, kept for a repair with no network.
536
+ * Nothing is written when the folder already holds exactly these files for this port (its marker is brought in line).
537
+ * Returns { folder, version, changed, previousVersion, appPort, stale }; throws EXTENSION_FOLDER_FAILED (the folder and
538
+ * its marker are as they were, or the record of a stopped step is left for the next one) or EXTENSION_FOLDER_UNSAFE.
539
+ * `io` ({ rename, step }) is for the tests of those failures.
540
+ */
541
+ export function prepareExtensionFolder({ files, source, zip = null, home, appPort, pin = EXTENSION_PIN, now = Date.now, io: given = {}, lockTimeoutMs = LOCK_TIMEOUT_MS, system = null }) {
542
+ const port = Number(appPort);
543
+ setupMatches(port);
544
+ const io = ioOf(given);
545
+ const offered = source ? readExtensionSource(source) : files;
546
+ if (!sameInventory(packageInventory(offered), pin.files)) throw notPinned('These are not the extension files this SynaBun release pins.');
547
+ const shown = join(home, ROOT, FOLDER);
548
+ const paths = installRoot(home, { create: true, system });
549
+ try {
550
+ return withLock(paths, () => {
551
+ recover(paths, io, now());
552
+ if (zip) { try { if (verifiedPackageFiles(zip, pin) && !readRegular(paths.cache, pin.size)?.equals(zip)) writeDurably(paths.cache, zip, io); } catch { /* a repair then downloads it again */ } }
553
+ const before = inspectTree(paths.folder, pin, paths.system), marker = markerShape(readJson(paths.marker));
554
+ if (before.state === 'unsafe') throw unsafe('the extension folder (unpacked)');
555
+ if (before.state === 'pinned' && before.port === port) {
556
+ reconcileMarker(paths, before.files, port, pin, now, io);
557
+ return { folder: shown, version: pin.version, changed: false, previousVersion: pin.version, appPort: port, stale: false };
558
+ }
559
+ place(paths, { files: offered, port, pin, now, io, previous: before });
560
+ const after = inspectTree(paths.folder, pin, paths.system);
561
+ if (after.state !== 'pinned' || after.port !== port) throw failed('The extension folder does not hold what was written.');
562
+ return { folder: shown, version: pin.version, changed: true, previousVersion: before.state === 'pinned' ? pin.version : marker?.version || before.version || null, appPort: port, stale: false };
563
+ }, lockTimeoutMs);
564
+ } catch (error) { throw asFolderError(error); }
565
+ }
566
+
567
+ /**
568
+ * At start-up and before a setup uses the folder (no network): under the lock, a stopped transaction is settled and
569
+ * leftovers removed; then the folder is held to the pin. The pinned extension on another port is rewritten for
570
+ * `appPort` from its own verified files; anything else is repaired from the verified package this data home keeps,
571
+ * when it has one (else it waits for a download: `state` 'other'). Returns { folder, version, changed, state, reason }
572
+ * (`reason`: 'port' or 'repair' when something was written). A data home with no extension folder is not touched.
573
+ * Throws EXTENSION_FOLDER_UNSAFE or EXTENSION_FOLDER_FAILED (a port that could not be set is a failure, never `unchanged`).
574
+ */
575
+ export function retargetExtensionFolder({ home, appPort, pin = EXTENSION_PIN, now = Date.now, io: given = {}, lockTimeoutMs = LOCK_TIMEOUT_MS, system = null }) {
576
+ const port = Number(appPort);
577
+ setupMatches(port);
578
+ const io = ioOf(given), shown = join(home, ROOT, FOLDER);
579
+ const paths = installRoot(home, { system });
580
+ if (!paths) return { folder: shown, version: null, changed: false, state: 'missing', reason: null };
581
+ try {
582
+ return withLock(paths, () => {
583
+ recover(paths, io, now());
584
+ const look = inspectTree(paths.folder, pin, paths.system);
585
+ if (look.state === 'unsafe') throw unsafe('the extension folder (unpacked)');
586
+ if (look.state === 'missing') return { folder: shown, version: null, changed: false, state: 'missing', reason: null };
587
+ let files = null, reason = null;
588
+ if (look.state === 'pinned') {
589
+ if (look.port === port) { reconcileMarker(paths, look.files, port, pin, now, io); return { folder: shown, version: pin.version, changed: false, state: 'current', reason: null }; }
590
+ files = look.files; reason = 'port';
591
+ } else {
592
+ files = readCache(paths, pin); reason = 'repair';
593
+ if (!files) return { folder: shown, version: look.version ?? null, changed: false, state: 'other', reason: null };
594
+ }
595
+ place(paths, { files, port, pin, now, io, previous: look });
596
+ const after = inspectTree(paths.folder, pin, paths.system);
597
+ if (after.state !== 'pinned' || after.port !== port) throw failed('The extension folder does not hold what was written.');
598
+ return { folder: shown, version: pin.version, changed: true, state: 'current', reason };
599
+ }, lockTimeoutMs);
600
+ } catch (error) { throw asFolderError(error); }
601
+ }
602
+
603
+ /**
604
+ * The verified package this data home keeps (written after a download), or null: read and checked against the pin
605
+ * like a download, so a changed or foreign file is simply not used.
606
+ */
607
+ export function cachedExtensionPackage({ home, pin = EXTENSION_PIN }) {
608
+ try { const paths = installRoot(home); return paths ? readCache(paths, pin) : null; } catch { return null; }
609
+ }
610
+ /** The root a download's working file goes into, checked (created when missing). Throws EXTENSION_FOLDER_UNSAFE / _FAILED. */
611
+ export function extensionWorkDir(home) { return installRoot(home, { create: true }).root; }
612
+
613
+ // The marker's pending Reload removed under the lock, when `clears(reload, marker)` says so. Returns whether it was.
614
+ function clearReload(home, io, clears, remaining = () => null) {
615
+ let paths;
616
+ try { paths = installRoot(home); } catch { return false; }
617
+ if (!paths) return false;
618
+ try {
619
+ return withLock(paths, () => {
620
+ const marker = readJson(paths.marker);
621
+ if (!marker?.reload || !clears(marker.reload, marker)) return false;
622
+ const { reload, ...rest } = marker;
623
+ const pending = remaining(reload);
624
+ if (pending) rest.reload = pending;
625
+ writeDurably(paths.marker, Buffer.from(JSON.stringify(rest)), io);
626
+ return true;
627
+ });
628
+ } catch { return false; }
111
629
  }
112
- /** What the folder holds now, without writing: { folder, version, prepared }. */
630
+
631
+ /**
632
+ * The setup page saw the extension's content script on `appPort` (POST …/setup/seen, the one caller): the browser
633
+ * runs the folder's manifest for this port, so the Reload a port change asked for is done. Returns whether a pending
634
+ * Reload was cleared. A repair's Reload is never cleared here: the copy the browser still runs (changed code included)
635
+ * has the same matches and version, so it answers the setup page just the same; only the owner's confirmation clears
636
+ * it (confirmExtensionRepairReload). A port change while a repair is pending keeps the repair (reloadAfter). Nothing
637
+ * else clears either: a restart, a same-version start or a background refresh keeps the marker's `reload`
638
+ * (reconcileMarker carries it).
639
+ */
640
+ export function confirmExtensionReload({ home, appPort, io: given = {} }) {
641
+ return clearReload(home, ioOf(given), (reload, marker) => !reload.fromVersion && reload.repair !== true && marker.appPort === Number(appPort));
642
+ }
643
+
644
+ // A newly authenticated browser reported the installed version. This clears only an ordinary version upgrade.
645
+ export function confirmExtensionVersion({ home, version, io: given = {} }) {
646
+ // A same-version port change after this upgrade still needs the content script on the new port.
647
+ return clearReload(home, ioOf(given), (reload, marker) => !!reload.fromVersion && !reload.repair && marker.version === version,
648
+ reload => Number.isInteger(reload.fromPort) ? { fromPort: reload.fromPort } : null);
649
+ }
650
+
651
+ /**
652
+ * The owner said, in Settings, that they reloaded the extension after a repair (POST …/reload/confirm, the one caller:
653
+ * a deliberate click, never a page load, a poll, the setup page or the extension bridge). Clears a pending repair's
654
+ * Reload (and a port change pending with it); a port change alone keeps its own rule (confirmExtensionReload). Returns
655
+ * whether something was cleared.
656
+ */
657
+ export function confirmExtensionRepairReload({ home, io: given = {} }) {
658
+ return clearReload(home, ioOf(given), reload => reload.repair === true);
659
+ }
660
+
661
+ /**
662
+ * What the folder's marker says, without writing or verifying: { folder, version, prepared, present, appPort,
663
+ * preparedAt, package, reloadPending, reloadReason, fromVersion? }. `reloadReason`: 'version' for an upgrade from an
664
+ * intact recorded installation, 'repair' (files that were not the pinned
665
+ * extension were replaced) or 'port' (only the setup port changed), while a Reload is pending; else null. For display
666
+ * only: whether the folder is the pinned extension is inspectExtensionFolder's answer, never this one.
667
+ */
113
668
  export function extensionFolderState(home) {
114
- const root = join(home, 'browser-extension'), marker = readMarker(join(root, 'unpacked.json'));
115
- return { folder: join(root, 'unpacked'), version: marker?.version || null, prepared: !!marker, appPort: marker?.appPort ?? null, preparedAt: marker?.preparedAt ?? null, root: dirname(join(root, 'unpacked')) };
669
+ const root = join(home, ROOT), folder = join(root, FOLDER), marker = readJson(join(root, MARKER));
670
+ let present = false;
671
+ try { const info = lstatSync(folder); present = info.isDirectory() && !info.isSymbolicLink() && lstatSync(join(folder, 'manifest.json')).isFile(); } catch { present = false; }
672
+ return { folder, version: typeof marker?.version === 'string' ? marker.version : null, prepared: !!marker, present, appPort: marker?.appPort ?? null,
673
+ preparedAt: marker?.preparedAt ?? null, package: typeof marker?.package === 'string' ? marker.package : null, reloadPending: !!marker?.reload,
674
+ reloadReason: reloadReasonOf(marker?.reload), ...(marker?.reload?.fromVersion ? { fromVersion: marker.reload.fromVersion } : {}), root };
116
675
  }