synabun 2.4.1 → 2.4.3

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 (345) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +46 -6
  4. package/lib/data-home-files.js +4 -2
  5. package/lib/first-launch-protection.js +8 -2
  6. package/lib/release-npm-ci.mjs +23 -1
  7. package/lib/update-snapshot.js +11 -4
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +25 -2
  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 +62 -17
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  15. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  16. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  18. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  19. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  20. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  21. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  22. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  23. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  24. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  25. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  26. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  27. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  28. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  29. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  30. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  31. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  32. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  33. package/mcp-server/dist/services/memory-schema.js +190 -13
  34. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  35. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  36. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  37. package/mcp-server/dist/services/memory-sessions.js +56 -20
  38. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  39. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-verification.js +8 -5
  41. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +19 -2
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  47. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  48. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  49. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  50. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  51. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  52. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  53. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  54. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  55. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  56. package/mcp-server/dist/services/sqlite-write.js +94 -0
  57. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  58. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  59. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  60. package/mcp-server/dist/services/sqlite.js +249 -8
  61. package/mcp-server/dist/services/sqlite.js.map +1 -1
  62. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  63. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  64. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  65. package/mcp-server/dist/services/typesafe-config.js +32 -10
  66. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  67. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  68. package/mcp-server/dist/services/typesafe.js +9 -7
  69. package/mcp-server/dist/services/typesafe.js.map +1 -1
  70. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  71. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  72. package/mcp-server/dist/services/vector-cache.js +161 -8
  73. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  74. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  75. package/mcp-server/dist/tools/agents.d.ts +11 -7
  76. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/agents.js +27 -9
  78. package/mcp-server/dist/tools/agents.js.map +1 -1
  79. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  80. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  82. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  83. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  84. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/browser-extension-setup.js +29 -0
  86. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  87. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/browser-interact.js +6 -1
  89. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  90. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  91. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  92. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  93. package/mcp-server/package-lock.json +5 -5
  94. package/mcp-server/package.json +1 -1
  95. package/mcp-server/src/http.ts +20 -2
  96. package/mcp-server/src/index.ts +59 -17
  97. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  98. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  99. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  100. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  101. package/mcp-server/src/services/memory-schema.ts +194 -12
  102. package/mcp-server/src/services/memory-sessions.ts +54 -21
  103. package/mcp-server/src/services/memory-verification.ts +7 -4
  104. package/mcp-server/src/services/neural-interface.ts +22 -2
  105. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  106. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  107. package/mcp-server/src/services/sqlite-write.ts +60 -0
  108. package/mcp-server/src/services/sqlite.ts +246 -8
  109. package/mcp-server/src/services/typesafe-config.ts +25 -6
  110. package/mcp-server/src/services/typesafe.ts +9 -7
  111. package/mcp-server/src/services/vector-cache.ts +154 -9
  112. package/mcp-server/src/tools/agents.ts +26 -9
  113. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  114. package/mcp-server/src/tools/browser-extension-setup.ts +36 -0
  115. package/mcp-server/src/tools/browser-interact.ts +5 -1
  116. package/neural-interface/i18n/en.json +313 -2
  117. package/neural-interface/i18n/pt-BR.json +321 -10
  118. package/neural-interface/lib/agents/split.js +32 -4
  119. package/neural-interface/lib/assistant-api.js +52 -8
  120. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  121. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  122. package/neural-interface/lib/assistant-catalog.js +2 -2
  123. package/neural-interface/lib/assistant-config.js +0 -7
  124. package/neural-interface/lib/assistant-dispatch.js +281 -95
  125. package/neural-interface/lib/assistant-envelope.js +40 -0
  126. package/neural-interface/lib/assistant-persona.js +16 -4
  127. package/neural-interface/lib/assistant-pricing.js +65 -14
  128. package/neural-interface/lib/assistant-router.js +131 -47
  129. package/neural-interface/lib/assistant-run-wait.js +45 -28
  130. package/neural-interface/lib/assistant-runtime.js +133 -42
  131. package/neural-interface/lib/backup-contents.js +158 -0
  132. package/neural-interface/lib/backup-crypto-io.js +330 -0
  133. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  134. package/neural-interface/lib/backup-crypto.js +525 -0
  135. package/neural-interface/lib/backup-download.js +268 -0
  136. package/neural-interface/lib/backup-encryption.js +318 -0
  137. package/neural-interface/lib/backup-groups.js +287 -0
  138. package/neural-interface/lib/backup-restore-session.js +176 -0
  139. package/neural-interface/lib/backup-restore-stage.js +60 -0
  140. package/neural-interface/lib/backup-service.js +788 -233
  141. package/neural-interface/lib/backup-zip-reader.js +30 -18
  142. package/neural-interface/lib/backup-zip-writer.js +34 -10
  143. package/neural-interface/lib/browser-extension-adapter.js +89 -15
  144. package/neural-interface/lib/browser-extension-archive.js +149 -0
  145. package/neural-interface/lib/browser-extension-bridge.js +24 -10
  146. package/neural-interface/lib/browser-extension-folder.js +596 -76
  147. package/neural-interface/lib/browser-extension-package.js +200 -0
  148. package/neural-interface/lib/browser-extension-pin.js +84 -0
  149. package/neural-interface/lib/browser-extension-pin.json +33 -0
  150. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +91 -6
  151. package/neural-interface/lib/browser-extension-setup.js +105 -18
  152. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  153. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  154. package/neural-interface/lib/cli-install.js +23 -3
  155. package/neural-interface/lib/cli-update-planner.js +171 -9
  156. package/neural-interface/lib/client-diagnostics.js +42 -0
  157. package/neural-interface/lib/confined-fs.js +7 -2
  158. package/neural-interface/lib/coordination/README.md +8 -2
  159. package/neural-interface/lib/coordination/contract.js +161 -0
  160. package/neural-interface/lib/coordination/database.js +999 -0
  161. package/neural-interface/lib/coordination/operations.js +436 -0
  162. package/neural-interface/lib/coordination/service.js +68 -537
  163. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  164. package/neural-interface/lib/coordination/store.js +219 -1111
  165. package/neural-interface/lib/db.js +70 -32
  166. package/neural-interface/lib/health-count.js +37 -0
  167. package/neural-interface/lib/loop-stall.js +139 -0
  168. package/neural-interface/lib/maritaca/client.js +2 -2
  169. package/neural-interface/lib/maritaca/models.js +12 -17
  170. package/neural-interface/lib/maritaca/opencode.js +4 -2
  171. package/neural-interface/lib/memory-api.js +9 -1
  172. package/neural-interface/lib/memory-session-capture.js +42 -10
  173. package/neural-interface/lib/memory-store-gate.js +313 -0
  174. package/neural-interface/lib/memory-store-migrate.js +65 -0
  175. package/neural-interface/lib/memory-timers.js +7 -7
  176. package/neural-interface/lib/native-loop-providers.js +23 -17
  177. package/neural-interface/lib/native-loop-runtime.js +48 -9
  178. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  179. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  180. package/neural-interface/lib/opencode-provider-view.js +14 -3
  181. package/neural-interface/lib/opencode-shell-read.js +107 -0
  182. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  183. package/neural-interface/lib/opencode-turn-release.js +173 -0
  184. package/neural-interface/lib/opencode-v2-client.js +4 -1
  185. package/neural-interface/lib/opencode-v2-ws-requests.js +65 -1
  186. package/neural-interface/lib/opencode2-client.js +343 -7
  187. package/neural-interface/lib/opencode2-translate.js +161 -4
  188. package/neural-interface/lib/recall-impact.js +122 -0
  189. package/neural-interface/lib/scratch-evidence.js +420 -0
  190. package/neural-interface/lib/scratch-process-guard.js +139 -0
  191. package/neural-interface/lib/scratch-references.js +279 -0
  192. package/neural-interface/lib/scratch-retention-core.js +385 -0
  193. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  194. package/neural-interface/lib/scratch-retention.js +151 -0
  195. package/neural-interface/lib/session-cache-builder.js +31 -43
  196. package/neural-interface/lib/session-cache-worker.js +157 -0
  197. package/neural-interface/lib/session-indexer.js +28 -21
  198. package/neural-interface/lib/session-search-index.js +85 -0
  199. package/neural-interface/lib/skills/creation.js +1 -1
  200. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  201. package/neural-interface/lib/style-guide/store.js +43 -3
  202. package/neural-interface/lib/system-restore.js +50 -0
  203. package/neural-interface/lib/teams/api.js +15 -6
  204. package/neural-interface/lib/teams/claims.js +67 -31
  205. package/neural-interface/lib/teams/index.js +7 -7
  206. package/neural-interface/lib/teams/integration.js +40 -40
  207. package/neural-interface/lib/teams/landing.js +6 -6
  208. package/neural-interface/lib/teams/recovery.js +24 -23
  209. package/neural-interface/lib/teams/scheduler.js +194 -95
  210. package/neural-interface/lib/teams/state.js +14 -14
  211. package/neural-interface/lib/teams/worktrees.js +27 -27
  212. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  213. package/neural-interface/lib/whatsapp/bridge.js +54 -7
  214. package/neural-interface/lib/worker-confinement.js +47 -2
  215. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  216. package/neural-interface/lib/worker-resume.js +5 -0
  217. package/neural-interface/lib/worker-stop.js +86 -0
  218. package/neural-interface/package-lock.json +5 -5
  219. package/neural-interface/package.json +1 -1
  220. package/neural-interface/public/extension-setup.html +5 -2
  221. package/neural-interface/public/index.html +233 -24
  222. package/neural-interface/public/onboarding.html +259 -34
  223. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  224. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  225. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  226. package/neural-interface/public/shared/agy/agy-panel.js +67 -20
  227. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  228. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  229. package/neural-interface/public/shared/api.js +1 -1
  230. package/neural-interface/public/shared/assistant/asst-api.js +28 -3
  231. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  232. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  233. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  234. package/neural-interface/public/shared/assistant/asst-panel.js +87 -3
  235. package/neural-interface/public/shared/assistant/asst-rack-styles.js +27 -0
  236. package/neural-interface/public/shared/assistant/asst-render.js +243 -44
  237. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  238. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  239. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  240. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  241. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  242. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  243. package/neural-interface/public/shared/assistant/asst-styles.js +11 -23
  244. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  245. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  246. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  247. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  248. package/neural-interface/public/shared/cdx/cdx-tabs.js +54 -9
  249. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  250. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  251. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  252. package/neural-interface/public/shared/effort-i18n.js +118 -0
  253. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  254. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  255. package/neural-interface/public/shared/html-shell.js +4 -52
  256. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  257. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  258. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  259. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  260. package/neural-interface/public/shared/mtc/mtc-panel.js +25 -3
  261. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +152 -8
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +53 -4
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +52 -6
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +22 -2
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +67 -93
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  278. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  279. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  280. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  281. package/neural-interface/public/shared/output-format.js +294 -0
  282. package/neural-interface/public/shared/provider-icons.js +6 -0
  283. package/neural-interface/public/shared/schedules-view.js +2 -1
  284. package/neural-interface/public/shared/server-presence.js +77 -0
  285. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  286. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  287. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  288. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  289. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  290. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  291. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  292. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  293. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  294. package/neural-interface/public/shared/studio-attention.js +6 -0
  295. package/neural-interface/public/shared/styles.css +341 -437
  296. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  297. package/neural-interface/public/shared/transcript-rows.js +28 -3
  298. package/neural-interface/public/shared/tray-auto-close.js +49 -6
  299. package/neural-interface/public/shared/ui-agents.js +1 -2
  300. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  301. package/neural-interface/public/shared/ui-claude-panel.js +62 -65
  302. package/neural-interface/public/shared/ui-loading.js +124 -17
  303. package/neural-interface/public/shared/ui-native-loop-router.js +52 -0
  304. package/neural-interface/public/shared/ui-navbar.js +2 -1
  305. package/neural-interface/public/shared/ui-output.js +533 -0
  306. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  307. package/neural-interface/public/shared/ui-scroll-follow.js +101 -6
  308. package/neural-interface/public/shared/ui-sessions.js +2 -2
  309. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  310. package/neural-interface/public/shared/ui-settings.js +224 -65
  311. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  312. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  313. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  314. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  315. package/neural-interface/public/shared/worker-end.js +9 -4
  316. package/neural-interface/public/variant/2d/main.js +5 -0
  317. package/neural-interface/public/variant/3d/app.js +10 -0
  318. package/neural-interface/public/variant/3d/main.js +5 -1
  319. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  320. package/neural-interface/server.js +725 -173
  321. package/npm-shrinkwrap.json +5 -5
  322. package/package.json +1 -2
  323. package/scripts/restore-data-home-from-backup.mjs +175 -8
  324. package/setup.js +18 -4
  325. package/browser-extension/content.js +0 -189
  326. package/browser-extension/engine.js +0 -508
  327. package/browser-extension/icons/icon-128.png +0 -0
  328. package/browser-extension/icons/icon-16.png +0 -0
  329. package/browser-extension/icons/icon-32.png +0 -0
  330. package/browser-extension/icons/icon-48.png +0 -0
  331. package/browser-extension/icons/status-off-16.png +0 -0
  332. package/browser-extension/icons/status-off-32.png +0 -0
  333. package/browser-extension/icons/status-off-48.png +0 -0
  334. package/browser-extension/icons/status-on-16.png +0 -0
  335. package/browser-extension/icons/status-on-32.png +0 -0
  336. package/browser-extension/icons/status-on-48.png +0 -0
  337. package/browser-extension/manifest.json +0 -56
  338. package/browser-extension/popup-strings.js +0 -250
  339. package/browser-extension/popup-view.js +0 -151
  340. package/browser-extension/popup.css +0 -166
  341. package/browser-extension/popup.html +0 -108
  342. package/browser-extension/popup.js +0 -359
  343. package/browser-extension/service-worker.js +0 -275
  344. package/browser-extension/setup-content.js +0 -36
  345. package/browser-extension/tokens.css +0 -326
@@ -0,0 +1,545 @@
1
+ // ═══════════════════════════════════════════
2
+ // SETTINGS — Password protection of backups
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // Settings → Memory & backups → Backups → Password protection, the list of recent backups, and the password step of a
6
+ // restore (Settings and onboarding.html). The server decides (lib/backup-encryption.js, lib/backup-restore-session.js);
7
+ // this module says what its answers mean and sends the requests. Pure: no DOM and no import, so node runs it
8
+ // (tests/settings-backup-encryption.test.mjs); settings-backup-encryption-pane.js draws.
9
+ //
10
+ // A password lives in the form's input and in the one request that uses it: never in a model, a URL or a message.
11
+ //
12
+ // readEncryptionResponse({ status, body, error }) what the server answered → a reading
13
+ // validatePasswordForm(mode, values, minLength) what is wrong with a form, before anything is sent
14
+ // describeBackupEncryption(model, { tx }) the row as the pane draws it
15
+ // describeBackupHistory(reading, { tx }) the list of recent backups
16
+ // formatHistorySize(bytes) a backup's size in a unit that says something
17
+ // describeRestoreCreated(manifest, { tx }) when and where a backup was made, for the restore's question
18
+ // createBackupEncryptionController({ fetch, … }) load, open a form, submit it
19
+ // unlock / apply / discardEncryptedRestore(fetch, …) the three steps of an encrypted restore
20
+ // restoreCanUnlock(preview), describeEncryptedRestore(preview) may the password be sent; when the backup was made
21
+ // restoreErrorMessage(body, { tx }) a refused restore in the owner's words
22
+ // previewErrorMessage(body, { tx, fallback }) a refused upload (the restore's first step) in the owner's words
23
+ // restoreCatalogueUrl({ search, saved, languages }) which strings onboarding's restore reads, by the app's locale rules
24
+ // restoreNeedsNewFile(code) a refusal no other password can cure: the file is chosen again
25
+ // restorePartialCodes(body) a 200 that could not do all of it: its problems, worst first (null: none)
26
+ // describeRestoreOutcome(outcome, { tx }) those problems and the way forward, in the owner's words
27
+ // save / read / clearRestoreOutcome(…) the short-lived page record that outlives a reload or a restart
28
+ // describeWait(seconds, { tx }) the rate limiter's wait, "30 seconds" / "3 minutes"
29
+ //
30
+ // Every refusal is told by its `code`, never by the server's English sentence (which can hold a path): a code with
31
+ // no text here, or no code at all, is the generic sentence (with the code beside it when it is a plain identifier).
32
+ // docs/backup-encryption.md → Refusals lists each code, its status and where it is shown.
33
+
34
+ const K = 'settings.redesign.server';
35
+
36
+ export const BACKUP_ENCRYPTION_URL = '/api/system/backup/encryption';
37
+ export const BACKUP_HISTORY_URL = '/api/system/backup/history';
38
+ const DEFAULT_MIN_LENGTH = 8;
39
+ const MAX_LENGTH = 1024;
40
+ /**
41
+ * What a server must list (lib/backup-encryption.js BACKUP_ENCRYPTION_CAPABILITIES) before this page turns encryption
42
+ * on or sends it a backup's password. A page is read from disk at any time and the server's code only at a start, so
43
+ * this page can meet a server from before the authentication key: one whose encrypted backups anybody holding one
44
+ * could forge, and whose key file the finished code cannot use. That server answers without the list, and the page
45
+ * then says a restart is missing instead of acting.
46
+ */
47
+ export const REQUIRED_CAPABILITY = 'auth-key';
48
+ export const serverCanEncrypt = (body) => Array.isArray(body?.capabilities) && body.capabilities.includes(REQUIRED_CAPABILITY);
49
+
50
+ const clean = (value, max = 400) => {
51
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
52
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
53
+ };
54
+
55
+ /** A code as support can read it: an identifier, never a sentence or a path. */
56
+ const CODE_PATTERN = /^[A-Z][A-Z0-9_]{1,63}$/;
57
+ export const stableCode = (code) => (typeof code === 'string' && CODE_PATTERN.test(code) ? code : null);
58
+
59
+ /**
60
+ * Refusals that come from the gates in front of every owner route (lib/http-guards.js, lib/page-session.js,
61
+ * lib/owner-authority.js), not from backup encryption: the page was not accepted as SynaBun's own, or the caller is a guest.
62
+ */
63
+ const REFUSED_CODES = new Set(['PAGE_SECRET_REQUIRED', 'BAD_HOST', 'BAD_ORIGIN', 'ORIGIN_REQUIRED', 'CROSS_SITE', 'PEER_REFUSED', 'PEER_UNAVAILABLE', 'WORKER_BROWSER']);
64
+ const guardKeyOf = (code) => (REFUSED_CODES.has(code) ? `${K}.backupEncErrRefused` : code === 'GUEST_FORBIDDEN' ? `${K}.backupEncErrOwnerOnly` : null);
65
+
66
+ /** The limiter's wait as the owner reads it: whole seconds up to two minutes, then minutes (rounded up, as the server's own sentence does). null when there is none. */
67
+ export function describeWait(seconds, { tx } = {}) {
68
+ const wait = Math.ceil(Number(seconds));
69
+ if (!Number.isFinite(wait) || wait < 1) return null;
70
+ if (wait >= 120) return tx(`${K}.backupEncWaitMinutes`, { n: Math.ceil(wait / 60) });
71
+ return wait === 1 ? tx(`${K}.backupEncWaitSecond`) : tx(`${K}.backupEncWaitSeconds`, { n: wait });
72
+ }
73
+ const lockedMessage = (body) => {
74
+ const wait = Number(body?.retryAfterSeconds);
75
+ return Number.isFinite(wait) && wait >= 1 ? { key: `${K}.backupEncErrLocked`, params: { wait: { wait } } } : { key: `${K}.backupEncErrLockedNoWait` };
76
+ };
77
+ /** A refusal this page has no sentence for: the generic one, with the code when it is a plain identifier. */
78
+ const unknownMessage = (key, code) => (stableCode(code) ? { key, code: stableCode(code) } : { key });
79
+
80
+ /** The length the server counts: characters of the normalized password. */
81
+ export const passwordLength = (value) => [...String(value ?? '').normalize('NFKC')].length;
82
+
83
+ /**
84
+ * What the server answered:
85
+ * on { keyId, changedAt, minLength }
86
+ * off { minLength }
87
+ * broken the key file is there and cannot be used: backups are stopped until it is repaired ({ code }).
88
+ * The server's own sentence about it is English and names the file by its path: it is for the
89
+ * server's log and is not kept here, so no page can show it.
90
+ * unavailable a server started before these routes (404), or before the authentication key (no `auth-key`
91
+ * among its capabilities): a restart is missing, and nothing is sent to it
92
+ * error { code, status }: what could not be read; the owner is told in words of this page, never the server's
93
+ */
94
+ export function readEncryptionResponse({ status, body, error } = {}) {
95
+ if (error) return { state: 'error', code: null, status: null };
96
+ if (status === 404) return { state: 'unavailable' };
97
+ if (!(status >= 200 && status < 300) || !body || body.ok !== true) return { state: 'error', code: stableCode(body?.code), status: Number(status) || null };
98
+ if (!serverCanEncrypt(body)) return { state: 'unavailable' };
99
+ const minLength = Number.isInteger(body.minPasswordLength) && body.minPasswordLength > 0 ? body.minPasswordLength : DEFAULT_MIN_LENGTH;
100
+ if (body.enabled && body.usable === false) return { state: 'broken', code: stableCode(body.code), minLength };
101
+ if (body.enabled) return { state: 'on', keyId: body.keyId || null, changedAt: body.changedAt || null, minLength };
102
+ return { state: 'off', minLength };
103
+ }
104
+
105
+ /**
106
+ * The first thing wrong with a form, or null. `mode`: enable | repair | change | disable (`repair` is `enable` for a
107
+ * key file that cannot be used: the same fields, the same request). `values`: { current, password, confirm,
108
+ * acknowledged }. Returns { field, key, params }: never a value that was typed.
109
+ */
110
+ export function validatePasswordForm(mode, values = {}, minLength = DEFAULT_MIN_LENGTH) {
111
+ const { current = '', password = '', confirm = '', acknowledged = false } = values;
112
+ if ((mode === 'change' || mode === 'disable') && !current) return { field: 'current', key: `${K}.backupEncErrRequired` };
113
+ if (mode === 'disable') return null;
114
+ if (!password) return { field: 'password', key: `${K}.backupEncErrRequired` };
115
+ if (passwordLength(password) < minLength) return { field: 'password', key: `${K}.backupEncErrShort`, params: { min: minLength } };
116
+ if (password !== confirm) return { field: 'confirm', key: `${K}.backupEncErrMismatch` };
117
+ if ((mode === 'enable' || mode === 'repair') && acknowledged !== true) return { field: 'acknowledged', key: `${K}.backupEncErrAck` };
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * A refused password request as { field?, key, params?, code?, reload? }: words of this page, by the refusal's `code`.
123
+ * `field` puts it under that field; without one it is the form's own line. `reload` says the page's reading of the
124
+ * state was out of date (it is read again). `mode` is the form that was sent (a refusal of a password names no field
125
+ * by itself; the form says which one that was) and `minLength` what the server said it asks for.
126
+ */
127
+ export function encryptionErrorOf(body, status, { mode = null, minLength = DEFAULT_MIN_LENGTH } = {}) {
128
+ const code = stableCode(body?.code);
129
+ const typed = mode === 'enable' || mode === 'repair' ? 'password' : mode === 'disable' ? 'current' : null;
130
+ switch (code) {
131
+ case 'WRONG_PASSWORD': return { field: 'current', key: `${K}.backupEncErrWrong` };
132
+ case 'TOO_MANY_ATTEMPTS': return lockedMessage(body);
133
+ case 'PASSWORD_TOO_SHORT': return { field: 'password', key: `${K}.backupEncErrShort`, params: { min: minLength } };
134
+ case 'PASSWORD_TOO_LONG': return { ...(typed ? { field: typed } : {}), key: `${K}.backupEncErrTooLong`, params: { max: MAX_LENGTH } };
135
+ case 'PASSWORD_REQUIRED': return { ...(typed ? { field: typed } : {}), key: `${K}.backupEncErrRequired` };
136
+ case 'ACKNOWLEDGE_REQUIRED': return { field: 'acknowledged', key: `${K}.backupEncErrAck` };
137
+ case 'ALREADY_ENABLED': return { key: `${K}.backupEncErrAlreadyOn`, reload: true };
138
+ case 'NOT_ENABLED': return { key: `${K}.backupEncErrNotOn`, reload: true };
139
+ case 'BACKUP_ENC_KEY_UNREADABLE': return { key: `${K}.backupEncErrKeyUnreadable`, reload: true };
140
+ // The server's own "something unexpected": nothing was written, and its sentence is withheld on purpose.
141
+ case 'ENCRYPTION_FAILED': return { key: `${K}.backupEncErrFailed` };
142
+ default: break;
143
+ }
144
+ const guard = guardKeyOf(code);
145
+ if (guard) return { key: guard };
146
+ if (status === 404 && !code) return { key: `${K}.backupEncNeedsRestart` };
147
+ return unknownMessage(`${K}.backupEncErrFailed`, code);
148
+ }
149
+
150
+ const NOTICE = { enable: `${K}.backupEncEnabledDone`, repair: `${K}.backupEncRepairedDone`, change: `${K}.backupEncChangedDone`, disable: `${K}.backupEncDisabledDone` };
151
+
152
+ /**
153
+ * A form's words, by what it does. Its title and its submit button name the action that opened it: the form of
154
+ * "Set a new password" is not the form of "Turn on", although both send the same request.
155
+ */
156
+ export const BACKUP_ENCRYPTION_FORMS = Object.freeze({
157
+ enable: Object.freeze({ title: `${K}.backupEncEnableTitle`, submit: `${K}.backupEncEnable`, note: null, password: `${K}.backupEncPassword`, confirm: `${K}.backupEncPasswordConfirm`, fields: Object.freeze(['password', 'confirm', 'acknowledged']) }),
158
+ repair: Object.freeze({ title: `${K}.backupEncRepair`, submit: `${K}.backupEncRepair`, note: `${K}.backupEncRepairNote`, password: `${K}.backupEncNew`, confirm: `${K}.backupEncNewConfirm`, fields: Object.freeze(['password', 'confirm', 'acknowledged']) }),
159
+ change: Object.freeze({ title: `${K}.backupEncChange`, submit: `${K}.backupEncChange`, note: `${K}.backupEncChangeNote`, password: `${K}.backupEncNew`, confirm: `${K}.backupEncNewConfirm`, fields: Object.freeze(['current', 'password', 'confirm']) }),
160
+ disable: Object.freeze({ title: `${K}.backupEncDisableTitle`, submit: `${K}.backupEncDisable`, note: `${K}.backupEncDisableNote`, password: `${K}.backupEncPassword`, confirm: `${K}.backupEncPasswordConfirm`, fields: Object.freeze(['current']) }),
161
+ });
162
+
163
+ /** A message as text. A parameter that is `{ wait }` (seconds) is the wait as a phrase; `code` is added as the plain identifier. */
164
+ const textOf = (message, tx) => {
165
+ if (!message?.key) return '';
166
+ const params = {};
167
+ for (const [name, value] of Object.entries(message.params || {})) {
168
+ params[name] = value && typeof value === 'object' && 'wait' in value ? (describeWait(value.wait, { tx }) ?? '') : value;
169
+ }
170
+ const text = tx(message.key, params);
171
+ return message.code ? `${text} ${tx(`${K}.backupEncCodeNote`, { code: message.code })}` : text;
172
+ };
173
+
174
+ /** The status row's line when the state could not be read: by the refusal's code, never the server's sentence. */
175
+ function unreadableMessage(reading) {
176
+ const guard = guardKeyOf(reading?.code);
177
+ if (guard) return { key: guard };
178
+ // ENCRYPTION_FAILED is the server's own catch-all: its code says nothing a person could use.
179
+ return unknownMessage(`${K}.backupEncUnreadable`, reading?.code === 'ENCRYPTION_FAILED' ? null : reading?.code);
180
+ }
181
+
182
+ /**
183
+ * The row: { available, on, canToggle, pill: { text, state }, status, form, error, fieldError, errorField, notice,
184
+ * busy }. A refusal that names a field is `fieldError`, shown next to the field `errorField`; one that names none is
185
+ * `error`, the form's own line.
186
+ */
187
+ export function describeBackupEncryption(model, { tx, formatDate = (value) => new Date(value).toLocaleString() } = {}) {
188
+ const reading = model?.reading || { state: 'loading' };
189
+ const state = reading.state;
190
+ const on = state === 'on' || state === 'broken';
191
+ const pill = state === 'on' ? { text: tx(`${K}.backupEncOn`), state: 'ok' }
192
+ : state === 'broken' ? { text: tx(`${K}.backupEncBroken`), state: 'err' }
193
+ : state === 'off' ? { text: tx(`${K}.backupEncOff`), state: 'off' }
194
+ : { text: '', state: 'off' };
195
+ let status = '';
196
+ if (state === 'off') status = tx(`${K}.backupEncStatusOff`);
197
+ else if (state === 'on') status = reading.changedAt ? tx(`${K}.backupEncStatusOn`, { date: formatDate(reading.changedAt) }) : tx(`${K}.backupEncStatusOnNoDate`);
198
+ // In the owner's language, from the state alone: every code the server has for it means the same to the owner.
199
+ else if (state === 'broken') status = tx(`${K}.backupEncStatusBroken`);
200
+ else if (state === 'unavailable') status = tx(`${K}.backupEncNeedsRestart`);
201
+ else if (state === 'error') status = textOf(unreadableMessage(reading), tx);
202
+ return {
203
+ available: state === 'on' || state === 'off' || state === 'broken',
204
+ on,
205
+ canToggle: (state === 'on' || state === 'off') && !model?.busy,
206
+ canChange: state === 'on' && !model?.busy && !model?.form,
207
+ // A key file that cannot be used stops every backup: a new password is the way out.
208
+ canRepair: state === 'broken' && !model?.busy && !model?.form,
209
+ pill,
210
+ status,
211
+ form: model?.form || null,
212
+ busy: !!model?.busy,
213
+ error: model?.error?.field ? '' : textOf(model?.error, tx),
214
+ fieldError: model?.error?.field ? textOf(model.error, tx) : '',
215
+ errorField: model?.error?.field || null,
216
+ notice: textOf(model?.notice, tx),
217
+ minLength: reading.minLength || DEFAULT_MIN_LENGTH,
218
+ };
219
+ }
220
+
221
+ /**
222
+ * A backup's size as the list shows it. From a tenth of a megabyte up it reads as the line under "Download full
223
+ * backup" does (MB with one decimal, GB with two); below that, where that line would say "0.0 MB", in KB or bytes.
224
+ * '' for what is not a size.
225
+ */
226
+ export function formatHistorySize(bytes) {
227
+ const size = Number(bytes);
228
+ if (bytes == null || bytes === '' || !Number.isFinite(size) || size < 0) return '';
229
+ const MB = 1024 * 1024;
230
+ if (size >= 1024 * MB) return `${(size / (1024 * MB)).toFixed(2)} GB`;
231
+ if (size >= 0.05 * MB) return `${(size / MB).toFixed(1)} MB`;
232
+ if (size >= 1024) return `${Math.round(size / 1024)} KB`;
233
+ return `${Math.round(size)} B`;
234
+ }
235
+
236
+ /** `body` of GET /api/system/backup/history → { available, rows: [{ name, when, size, encrypted, badge }], note }. */
237
+ export function describeBackupHistory({ status, body, error } = {}, { tx, formatDate = (value) => new Date(value).toLocaleString(), formatSize = formatHistorySize } = {}) {
238
+ if (error || status === 404 || !body?.ok || !Array.isArray(body.backups)) return { available: false, rows: [], note: '' };
239
+ const rows = body.backups.map((item) => ({
240
+ name: clean(item.name, 200),
241
+ when: item.createdAt ? formatDate(item.createdAt) : '',
242
+ size: Number.isFinite(item.sizeBytes) ? formatSize(item.sizeBytes) : '',
243
+ encrypted: item.encrypted === true,
244
+ badge: { text: tx(item.encrypted === true ? `${K}.backupHistoryEncrypted` : `${K}.backupHistoryPlain`), state: item.encrypted === true ? 'ok' : 'off' },
245
+ }));
246
+ const total = Number(body.total) || rows.length;
247
+ return {
248
+ available: true,
249
+ rows,
250
+ note: !rows.length ? tx(`${K}.backupHistoryEmpty`) : total > rows.length ? tx(`${K}.backupHistoryMore`, { shown: rows.length, total }) : '',
251
+ };
252
+ }
253
+
254
+ async function postJson(fetchFn, url, body) {
255
+ const res = await fetchFn(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SynaBun-UI': '1' }, body: JSON.stringify(body) });
256
+ let answer = null;
257
+ try { answer = await res.json(); } catch { /* a page or an empty answer */ }
258
+ return { status: res.status, ok: res.ok, body: answer };
259
+ }
260
+
261
+ /**
262
+ * The Password protection row's state. `render(model)` is called on every change. The values of a form are passed to
263
+ * `submit` and go no further than its one request.
264
+ */
265
+ export function createBackupEncryptionController({ fetch: fetchFn, render, alive = () => true } = {}) {
266
+ let model = { reading: null, form: null, busy: false, error: null, notice: null };
267
+ const draw = () => { if (alive()) render({ ...model }); };
268
+ const set = (patch) => { model = { ...model, ...patch }; draw(); };
269
+
270
+ async function load() {
271
+ try {
272
+ const res = await fetchFn(BACKUP_ENCRYPTION_URL);
273
+ let body = null;
274
+ try { body = await res.json(); } catch { /* below */ }
275
+ set({ reading: readEncryptionResponse({ status: res.status, body }) });
276
+ } catch (error) {
277
+ set({ reading: readEncryptionResponse({ error }) });
278
+ }
279
+ return model.reading;
280
+ }
281
+
282
+ return {
283
+ load,
284
+ open(mode) { if (!model.busy && Object.hasOwn(BACKUP_ENCRYPTION_FORMS, mode)) set({ form: mode, error: null, notice: null }); },
285
+ close() { if (!model.busy) set({ form: null, error: null }); },
286
+ /** Resolves true when the server did it; the caller clears the inputs either way. */
287
+ async submit(values) {
288
+ const mode = model.form;
289
+ if (!mode || model.busy) return false;
290
+ // Only a server that said it can: the last check before a password leaves the page.
291
+ if (!['on', 'off', 'broken'].includes(model.reading?.state)) { set({ form: null, error: null }); return false; }
292
+ const problem = validatePasswordForm(mode, values, model.reading?.minLength);
293
+ if (problem) { set({ error: problem, notice: null }); return false; }
294
+ const request = mode === 'enable' || mode === 'repair'
295
+ ? { url: `${BACKUP_ENCRYPTION_URL}/enable`, body: { password: values.password, acknowledged: true } }
296
+ : mode === 'change'
297
+ ? { url: `${BACKUP_ENCRYPTION_URL}/change`, body: { currentPassword: values.current, newPassword: values.password } }
298
+ : { url: `${BACKUP_ENCRYPTION_URL}/disable`, body: { currentPassword: values.current } };
299
+ set({ busy: true, error: null, notice: null });
300
+ try {
301
+ const answer = await postJson(fetchFn, request.url, request.body);
302
+ if (answer.ok && answer.body?.ok) {
303
+ set({ busy: false, form: null, reading: readEncryptionResponse({ status: answer.status, body: answer.body }), notice: { key: NOTICE[mode] } });
304
+ return true;
305
+ }
306
+ const error = encryptionErrorOf(answer.body, answer.status, { mode, minLength: model.reading?.minLength });
307
+ set({ busy: false, error });
308
+ // The page's reading was behind the server's (turned on or off elsewhere, a key file that went bad): read it again.
309
+ if (error.reload) await load();
310
+ } catch {
311
+ set({ busy: false, error: { key: `${K}.backupEncErrFailed` } });
312
+ }
313
+ return false;
314
+ },
315
+ };
316
+ }
317
+
318
+ /**
319
+ * True when the preview's answer for an encrypted upload came from a server this page may send the password to
320
+ * (REQUIRED_CAPABILITY). False: the upload is discarded and the owner is told to restart SynaBun.
321
+ */
322
+ export const restoreCanUnlock = (preview) => serverCanEncrypt(preview);
323
+
324
+ /** When an unlocked encrypted backup was made, for the restore's question: the header's authenticated date. */
325
+ export function describeEncryptedRestore(preview, { tx, formatDate = (value) => new Date(value).toLocaleString() } = {}) {
326
+ if (!preview?.encrypted) return '';
327
+ const when = typeof preview.created === 'string' && !Number.isNaN(Date.parse(preview.created)) ? preview.created : null;
328
+ return when ? tx(`${K}.restoreEncMade`, { date: formatDate(when) }) : tx(`${K}.restoreEncMadeUnknown`);
329
+ }
330
+
331
+ /**
332
+ * The restore's question: when the backup was made and, when its manifest says so, on which computer. A backup
333
+ * that names no computer gets the date alone, never a word for "unknown". '' when it says neither.
334
+ */
335
+ export function describeRestoreCreated(manifest, { tx, formatDate = (value) => new Date(value).toLocaleString() } = {}) {
336
+ const host = clean(manifest?.hostname, 120);
337
+ const when = manifest?.created != null && !Number.isNaN(new Date(manifest.created).getTime()) ? formatDate(manifest.created) : '';
338
+ if (when && host) return tx(`${K}.restoreCreatedOn`, { date: when, host });
339
+ if (when) return tx(`${K}.restoreCreated`, { date: when });
340
+ return host ? tx(`${K}.restoreCreatedHost`, { host }) : '';
341
+ }
342
+
343
+ /** POST unlock: { ok, status, body } with the same preview a plain backup gets when the password opened it. */
344
+ export const unlockEncryptedRestore = (fetchFn, uploadId, password) => postJson(fetchFn, '/api/system/restore/unlock', { uploadId, password });
345
+ /** POST apply-staged: answers as POST /api/system/restore does. */
346
+ export const applyEncryptedRestore = (fetchFn, uploadId, mode = 'full') => postJson(fetchFn, '/api/system/restore/apply-staged', { uploadId, mode });
347
+ /** Forget the staged upload. Never throws: the server drops it by itself after 30 minutes. */
348
+ export async function discardEncryptedRestore(fetchFn, uploadId) {
349
+ try { await postJson(fetchFn, '/api/system/restore/discard', { uploadId }); } catch { /* it expires */ }
350
+ }
351
+
352
+ /** The refusals of the restore's steps that no other password can cure: the staged file is gone, damaged, not one this SynaBun reads, or not a backup. */
353
+ const RESTORE_DEAD_ENDS = new Set(['RESTORE_UPLOAD_GONE', 'BACKUP_ENC_DAMAGED', 'BACKUP_ENC_UNSUPPORTED', 'BACKUP_NOT_ENCRYPTED', 'INVALID_BACKUP']);
354
+ export const restoreNeedsNewFile = (code) => RESTORE_DEAD_ENDS.has(code);
355
+
356
+ const RESTORE_KEYS = {
357
+ WRONG_PASSWORD: 'restoreEncWrong',
358
+ BACKUP_ENC_DAMAGED: 'restoreEncDamaged',
359
+ BACKUP_ENC_UNSUPPORTED: 'restoreEncUnsupported',
360
+ BACKUP_NOT_ENCRYPTED: 'restoreEncNotEncrypted',
361
+ RESTORE_UPLOAD_GONE: 'restoreEncGone',
362
+ RESTORE_RUNNING: 'restoreEncRunning',
363
+ RESTORE_LOCKED: 'restoreEncLocked',
364
+ BACKUP_PASSWORD_REQUIRED: 'restoreEncLocked',
365
+ BACKUP_ENC_READ: 'restoreEncRead',
366
+ INVALID_BACKUP: 'restoreEncInvalid',
367
+ PASSWORD_REQUIRED: 'backupEncErrRequired',
368
+ // The plain refusals of the upload, the preview and the restore (lib/system-restore.js RESTORE_FAILURE_CODES).
369
+ RESTORE_EMPTY_UPLOAD: 'restoreErrEmpty',
370
+ RESTORE_ZIP_INVALID: 'restoreErrZip',
371
+ RESTORE_ZIP_UNSUPPORTED: 'restoreErrZipUnsupported',
372
+ RESTORE_MANIFEST_MISSING: 'restoreErrNoManifest',
373
+ RESTORE_MANIFEST_UNREADABLE: 'restoreErrManifest',
374
+ RESTORE_UNSUPPORTED_VERSION: 'restoreErrVersion',
375
+ RESTORE_UNSAFE_PATH: 'restoreErrUnsafePath',
376
+ BACKUP_GROUPS_MISMATCH: 'restoreEncDamaged',
377
+ RESTORE_CHECKSUM_MISMATCH: 'restoreEncDamaged',
378
+ RESTORE_ENTRY_MISSING: 'restoreEncDamaged',
379
+ RESTORE_ENTRY_UNREADABLE: 'restoreEncDamaged',
380
+ BACKUP_ENCRYPTED: 'restoreErrEncrypted',
381
+ RESTORE_WRITE_FAILED: 'restoreErrPartial',
382
+ RESTORE_FAILED: 'restoreEncFailed',
383
+ RESTORE_DB_FAILED: 'restoreWarnDatabase',
384
+ RESTORE_QDRANT_FORMAT: 'restoreWarnQdrant',
385
+ RESTORE_KEY_NOT_KEPT: 'restoreWarnKey',
386
+ RESTORE_MCP_BUILD_FAILED: 'restoreWarnBuild',
387
+ // A system error keeps its own code in the upload's answer (it always did).
388
+ Z_DATA_ERROR: 'restoreErrZip',
389
+ Z_BUF_ERROR: 'restoreErrZip',
390
+ ENOSPC: 'restoreErrDiskFull',
391
+ EDQUOT: 'restoreErrDiskFull',
392
+ EACCES: 'restoreErrNoAccess',
393
+ EPERM: 'restoreErrNoAccess',
394
+ EROFS: 'restoreErrNoAccess',
395
+ };
396
+
397
+ /**
398
+ * A refused unlock, apply or upload, in the owner's words: by `body.code`, never by the server's sentence. A code with
399
+ * no text here and a body with no code are the generic sentence (with the code beside it when there is a plain one).
400
+ * Without `tx` (a page whose strings did not load) it is an English generic sentence: still not the server's.
401
+ */
402
+ export function restoreErrorMessage(body, { tx = null } = {}) {
403
+ // Whatever its code: the restore had begun writing, so no sentence that says nothing was changed may stand.
404
+ if (body?.partial === true) return tx ? tx(`${K}.restoreErrPartial`) : 'The restore stopped while writing files, so some may already have been replaced. Restore a complete backup again.';
405
+ if (!tx) return 'The backup could not be opened.';
406
+ const code = stableCode(body?.code);
407
+ if (code === 'TOO_MANY_ATTEMPTS') return textOf(lockedMessage(body), tx);
408
+ if (code === 'PASSWORD_TOO_LONG') return tx(`${K}.backupEncErrTooLong`, { max: MAX_LENGTH });
409
+ if (code && Object.hasOwn(RESTORE_KEYS, code)) return tx(`${K}.${RESTORE_KEYS[code]}`);
410
+ const guard = guardKeyOf(code);
411
+ if (guard) return tx(guard);
412
+ return textOf(unknownMessage(`${K}.restoreEncFailed`, code), tx);
413
+ }
414
+
415
+ /**
416
+ * A refused upload (POST /api/system/restore/preview), which a plain backup meets too: a code this page knows is told
417
+ * as restoreErrorMessage tells it; anything else is `fallback` (the page's own "Invalid backup"), not the server's text.
418
+ */
419
+ export function previewErrorMessage(body, { tx = null, fallback = '' } = {}) {
420
+ const code = stableCode(body?.code);
421
+ const known = code && (Object.hasOwn(RESTORE_KEYS, code) || code === 'TOO_MANY_ATTEMPTS' || guardKeyOf(code));
422
+ return tx && known ? restoreErrorMessage(body, { tx }) : fallback;
423
+ }
424
+
425
+ // ── A restore that answered 200 and could not do all of it ──
426
+ // The server keeps its sentences in `results.errors` and, from dd14b42c on, one code per sentence in
427
+ // `results.errorCodes` (lib/system-restore.js PARTIAL_FAILURES). A page is read from disk at any time and the server's
428
+ // code only at a start, so an answer may have sentences and no codes. A sentence is never shown: it can hold a path.
429
+
430
+ /** The generic problem: an answer with no code, a code this page has no words for, or a 200 that says nothing readable. */
431
+ const RESTORE_PARTIAL_GENERIC = 'RESTORE_FAILED';
432
+ /** The codes with their own words, most serious first: the memories did not come back, then what is left to repair. */
433
+ export const RESTORE_PARTIAL_CODES = Object.freeze(['RESTORE_DB_FAILED', 'RESTORE_QDRANT_FORMAT', 'RESTORE_KEY_NOT_KEPT', 'RESTORE_MCP_BUILD_FAILED']);
434
+ const RESTORE_PARTIAL_ORDER = [...RESTORE_PARTIAL_CODES, RESTORE_PARTIAL_GENERIC];
435
+ /** With these, what the owner came for is not there: trying another copy is the first way forward. */
436
+ const RESTORE_RETRY_FIRST = new Set(['RESTORE_DB_FAILED', 'RESTORE_QDRANT_FORMAT', RESTORE_PARTIAL_GENERIC]);
437
+
438
+ const partialList = (codes) => {
439
+ const found = new Set(codes.map((code) => (RESTORE_PARTIAL_CODES.includes(code) ? code : RESTORE_PARTIAL_GENERIC)));
440
+ return RESTORE_PARTIAL_ORDER.filter((code) => found.has(code));
441
+ };
442
+
443
+ /**
444
+ * What a 200 from POST /api/system/restore or /apply-staged could not do: its codes, deduplicated, worst first, with
445
+ * the generic one for anything without words here. null only for a restore that says it did all of it.
446
+ */
447
+ export function restorePartialCodes(body) {
448
+ if (body === null || typeof body !== 'object' || body.ok !== true || body.partial === true) return [RESTORE_PARTIAL_GENERIC];
449
+ const listed = (value) => (Array.isArray(value) ? value : value ? [value] : []);
450
+ const sentences = listed(body.results?.errors);
451
+ const codes = listed(body.results?.errorCodes);
452
+ const count = Math.max(sentences.length, codes.length);
453
+ if (!count) return null;
454
+ return partialList(Array.from({ length: count }, (_, index) => codes[index]));
455
+ }
456
+
457
+ /** The English of the outcome's strings, for a page whose catalogue could not be read. Equal to i18n/en.json (tested). */
458
+ export const RESTORE_OUTCOME_COPY = Object.freeze({
459
+ restorePartialTitle: 'The restore finished with problems',
460
+ restoreWarnDatabase: 'The files were restored, but your memories were not. Restore the backup again, or try another copy.',
461
+ restoreWarnQdrant: 'This backup holds its memories in an old format, so they were not restored. Convert it with the migration script, then restore it again.',
462
+ restoreWarnKey: 'The files were restored, but password protection was not kept, so new backups may not be encrypted. Turn it on again in Settings → Backups.',
463
+ restoreWarnBuild: 'The files were restored, but the MCP server could not be rebuilt. Restart SynaBun, and reinstall it if the problem stays.',
464
+ restoreWarnGeneric: 'Part of this restore did not work, so some of your data may be missing. Restore the backup again, or try another copy.',
465
+ restorePartialRestarting: 'SynaBun is restarting. This message will still be here when it is back.',
466
+ restorePartialReload: 'Reload SynaBun',
467
+ restorePartialClose: 'Close',
468
+ restorePartialTryAnother: 'Try another backup',
469
+ restorePartialContinue: 'Continue anyway',
470
+ restorePartialContinuing: 'Finishing setup…',
471
+ restorePartialContinueFailed: 'SynaBun could not finish setup yet. Try again in a moment.',
472
+ });
473
+
474
+ /** The outcome as a surface draws it. `restarting`: the server is going away right now and the page will come back. */
475
+ export function describeRestoreOutcome(outcome, { tx = null, restarting = false } = {}) {
476
+ const word = (name) => {
477
+ const key = `${K}.${name}`;
478
+ const text = tx ? tx(key) : key;
479
+ return text && text !== key ? text : RESTORE_OUTCOME_COPY[name];
480
+ };
481
+ const codes = partialList(Array.isArray(outcome?.codes) && outcome.codes.length ? outcome.codes : [RESTORE_PARTIAL_GENERIC]);
482
+ return {
483
+ title: word('restorePartialTitle'),
484
+ messages: codes.map((code) => word(code === RESTORE_PARTIAL_GENERIC ? 'restoreWarnGeneric' : RESTORE_KEYS[code])),
485
+ note: restarting ? word('restorePartialRestarting') : '',
486
+ retryFirst: codes.some((code) => RESTORE_RETRY_FIRST.has(code)),
487
+ reload: word('restorePartialReload'),
488
+ close: word('restorePartialClose'),
489
+ tryAnother: word('restorePartialTryAnother'),
490
+ continueAnyway: word('restorePartialContinue'),
491
+ continuing: word('restorePartialContinuing'),
492
+ continueFailed: word('restorePartialContinueFailed'),
493
+ };
494
+ }
495
+
496
+ // The record that keeps the outcome on screen through what follows a restore: the reload a restart forces, a page
497
+ // refreshed by hand, onboarding sent to the app because the restored settings say setup is complete. This tab only,
498
+ // for an hour, and only codes from the list above: no sentence, path, name or secret of the server's.
499
+ /** ui-settings-entry.js holds the same name, so the boot reads it without loading this module. */
500
+ export const RESTORE_OUTCOME_KEY = 'synabun-restore-outcome';
501
+ export const RESTORE_OUTCOME_TTL_MS = 60 * 60 * 1000;
502
+ const tabStorage = () => { try { return globalThis.sessionStorage ?? null; } catch { return null; } };
503
+
504
+ export function saveRestoreOutcome(outcome, { storage = tabStorage(), now = Date.now() } = {}) {
505
+ try {
506
+ storage?.setItem(RESTORE_OUTCOME_KEY, JSON.stringify({ v: 1, at: now, codes: partialList(outcome?.codes || []), restart: outcome?.restart === true }));
507
+ return !!storage;
508
+ } catch { return false; }
509
+ }
510
+
511
+ export function clearRestoreOutcome({ storage = tabStorage() } = {}) {
512
+ try { storage?.removeItem(RESTORE_OUTCOME_KEY); } catch { /* nothing to keep */ }
513
+ }
514
+
515
+ /** The kept outcome, or null. A record that is old, from a later clock or not one of ours is removed. */
516
+ export function readRestoreOutcome({ storage = tabStorage(), now = Date.now() } = {}) {
517
+ let raw = null;
518
+ try { raw = storage?.getItem(RESTORE_OUTCOME_KEY) ?? null; } catch { return null; }
519
+ if (raw === null) return null;
520
+ try {
521
+ const record = JSON.parse(raw);
522
+ const age = now - record?.at;
523
+ if (record?.v === 1 && Number.isFinite(age) && age >= -60_000 && age <= RESTORE_OUTCOME_TTL_MS && Array.isArray(record.codes) && record.codes.length && record.codes.length <= RESTORE_PARTIAL_ORDER.length) {
524
+ return { codes: partialList(record.codes), restart: record.restart === true };
525
+ }
526
+ } catch { /* not ours */ }
527
+ clearRestoreOutcome({ storage });
528
+ return null;
529
+ }
530
+
531
+ /**
532
+ * Which strings onboarding's restore reads: the wizard runs without the app's i18n and storage, so this is i18n.js's
533
+ * order over what the page can see (`?lang=`, the stored choice, the browser's languages), and English otherwise.
534
+ */
535
+ export function restoreCatalogueUrl({ search = '', saved = null, languages = [] } = {}) {
536
+ const pick = (tag) => {
537
+ const wanted = String(tag || '').trim().toLowerCase();
538
+ if (wanted === 'en' || wanted.startsWith('en-')) return 'en';
539
+ return wanted === 'pt' || wanted.startsWith('pt-') ? 'pt-BR' : null;
540
+ };
541
+ let address = null;
542
+ try { address = new URLSearchParams(search).get('lang'); } catch { /* no usable address */ }
543
+ const locale = pick(address) || pick(saved) || languages.map(pick).find(Boolean) || 'en';
544
+ return `/i18n/${locale}.json`;
545
+ }