synabun 2.4.0 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -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-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. package/setup.js +18 -4
@@ -0,0 +1,287 @@
1
+ // ═══════════════════════════════════════════
2
+ // BACKUP GROUPS — what a backup holds, by content
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // A full backup of the owner's data home was 9,389 MB on 2026-11-21 (151,584 entries). Read from that archive's own
6
+ // central directory and sorted into the groups below (MB in the archive / MB before compression):
7
+ //
8
+ // scratch 6,128 / 8,574 data/scratch: the working folders of dispatched runs (installers, build
9
+ // caches, whole checkouts with node_modules). Temporary, and 65% of the archive
10
+ // media 1,779 / 1,779 what creation runs generated, and screenshots
11
+ // memories 1,058 / 2,477 database/memory.db
12
+ // conversations 266 / 886 the Assistant's conversations, run tails, usage ledger
13
+ // settings 62 / 175 settings, schedules, agents, skills, plans, and every path no rule names
14
+ // caches 60 / 266 per-tab OpenCode configuration folders, the editor's completion serve, hook
15
+ // receipts, the link, map and session caches
16
+ // in no backup now 27 / 154 logs (a rotated server log of 50.6 MB among them) and runtime records
17
+ // the manifest 8 / 47
18
+ //
19
+ // What a backup never held (the updater's files, browser profile folders, the copies of memory.db that migrations
20
+ // leave) is not in an archive and was not measured here.
21
+ //
22
+ // So a backup is made of groups, and the owner chooses which go in (Settings → Backups, saved in
23
+ // DATA_HOME/data/backup-selection.json, the same choice for manual and scheduled backups). The default keeps
24
+ // everything that cannot be made again and leaves out what can.
25
+ //
26
+ // backupGroupOf(archivePath) the group of one file by its path in the archive, or null: in no backup at all
27
+ // normalizeBackupSelection(v) { id: boolean } for every group, defaults where nothing (valid) is said
28
+ // selectedBackupGroups(sel) the ids switched on, in BACKUP_GROUPS order
29
+ // manifestGroups(sel) what a manifest records: { version, included, excluded }
30
+ // readManifestGroups(manifest) what an archive holds, for any manifest (one from before groups is read from
31
+ // its file list): { recorded, included, excluded, complete, legacy }
32
+ // checkManifestGroups(manifest, entryNames, prefix) the problems of an archive against what its manifest says
33
+ // it holds; [] when it holds exactly that
34
+ //
35
+ // The rule that keeps this safe: a path no rule names belongs to `settings`, the group that is on by default and
36
+ // that the page warns about when it is switched off. A new feature's files are therefore in every default backup
37
+ // without anybody adding them here; only what is listed below as regenerable is ever left out by default.
38
+ // ═══════════════════════════════════════════
39
+
40
+ import { LOCK_FILE_NAME } from './rulesets/lock.js';
41
+
42
+ /** `kind`: irreplaceable (lost for good without a backup), regenerable (SynaBun makes it again), temporary (working files). */
43
+ export const BACKUP_GROUPS = Object.freeze([
44
+ Object.freeze({ id: 'memories', kind: 'irreplaceable', default: true }),
45
+ Object.freeze({ id: 'settings', kind: 'irreplaceable', default: true }),
46
+ Object.freeze({ id: 'conversations', kind: 'irreplaceable', default: true }),
47
+ Object.freeze({ id: 'media', kind: 'irreplaceable', default: true }),
48
+ Object.freeze({ id: 'caches', kind: 'regenerable', default: false }),
49
+ Object.freeze({ id: 'scratch', kind: 'temporary', default: false }),
50
+ ]);
51
+ export const BACKUP_GROUP_IDS = Object.freeze(BACKUP_GROUPS.map(group => group.id));
52
+ export const BACKUP_GROUPS_VERSION = 1;
53
+
54
+ const SQLITE_SIDE = ['', '-journal', '-wal', '-shm'];
55
+ // Operating-system locks kept as files: the rules installer's (lib/rulesets/lock.js) and the hooks' state lock
56
+ // (hooks/claude-code/state.mjs). Opening and closing one in this process can drop a lock this process holds on it.
57
+ const LOCK_FILES = [LOCK_FILE_NAME, 'hook-state-lock.sqlite'];
58
+ const isLockFile = (lower) => LOCK_FILES.some(file => SQLITE_SIDE.some(suffix => lower === `${file}${suffix}`));
59
+
60
+ /**
61
+ * True for a lock kept as a file (and the journal, WAL and shm names SQLite could put beside it), whatever the letter
62
+ * case. A backup never copies one and a restore never extracts one over the live file: archives from before
63
+ * 2026-11-21 hold data/hook-state-lock.sqlite.
64
+ */
65
+ export function isBackupLockFile(name) {
66
+ return isLockFile(String(name).toLowerCase());
67
+ }
68
+
69
+ /**
70
+ * The owner's backup-encryption key file in data/ (lib/backup-encryption.js): a public key, the private key wrapped by
71
+ * the backup password, and the authentication key. No archive holds it and no restore writes it: a restored backup would otherwise
72
+ * bring back the password (and the key pair) of the day it was made, or a crafted one somebody else's key.
73
+ */
74
+ export const BACKUP_ENCRYPTION_FILE = 'backup-encryption.json';
75
+
76
+ /** True for the backup-encryption key file, whatever the letter case. */
77
+ export function isBackupEncryptionFile(name) {
78
+ return String(name).toLowerCase() === BACKUP_ENCRYPTION_FILE;
79
+ }
80
+
81
+ // Records a running install rewrites about itself: restoring one would describe a process that is not there.
82
+ const RUNTIME_RECORDS = new Set([
83
+ 'server-stdout.log', 'server-stderr.log', 'restart-requested', 'opencode-managed.pid',
84
+ 'supervisor.json', 'start-launcher.lock', 'update-handoff.json',
85
+ ]);
86
+ // Folders of data/ no archive holds: the updater's own files, logs, bulk downloads a loop can fetch again, the
87
+ // automation browser's Chromium profiles (locked and rewritten while it runs, with its cookies and logins; a copy
88
+ // taken under a running browser is not a profile), and imports that were staged and never committed.
89
+ const NEVER_DATA_DIRS = new Set(['updater', 'logs', 'youtube-downloads', 'chrome-profile', 'chrome-attach', 'browser-profiles']);
90
+ const NEVER_DATA_PATHS = ['skills/staging'];
91
+
92
+ const SQLITE_JOURNAL_RE = /\.(?:db|bak)-journal$/i;
93
+
94
+ /**
95
+ * True for a path inside data/ or mcp-data/ (relative to it, forward slashes) that no archive of any kind holds.
96
+ * createVerifiedBackup, the upgrade snapshot and the size estimate all ask this one function.
97
+ */
98
+ export function isNeverBackedUp(relativePath) {
99
+ const normalized = String(relativePath).replace(/\\/g, '/');
100
+ const parts = normalized.split('/');
101
+ const name = parts.at(-1);
102
+ const lower = name.toLowerCase();
103
+ // A local browser profile's folder (data/local-profiles/<id>/…); its definitions (profiles.json) are a plain file.
104
+ if (parts[0] === 'local-profiles' && parts.length > 2) return true;
105
+ if (parts.length > 1 && NEVER_DATA_DIRS.has(parts[0])) return true;
106
+ if (NEVER_DATA_PATHS.some(path => normalized === path || normalized.startsWith(`${path}/`))) return true;
107
+ if (RUNTIME_RECORDS.has(name)) return true;
108
+ if (lower === BACKUP_ENCRYPTION_FILE) return true;
109
+ if (isLockFile(lower)) return true;
110
+ if (lower === '.ds_store' || lower === 'thumbs.db' || lower === 'desktop.ini') return true;
111
+ // Logs, the rotated ones too (server-stdout.log.1 was 50 MB of the archive): a log restored over a newer one is wrong.
112
+ if (/\.log(?:\.\d+)?$/i.test(name)) return true;
113
+ if (lower.endsWith('.tmp') || lower.endsWith('.pid')) return true;
114
+ if (/\.(?:db|sqlite|sqlite3)-(?:wal|shm)$/i.test(name)) return true;
115
+ if (SQLITE_JOURNAL_RE.test(name)) return true;
116
+ return false;
117
+ }
118
+
119
+ /** True for a folder of data/ (relative path) whose every file is never backed up: the walk does not enter it. */
120
+ export function isNeverBackedUpDir(relativePath) {
121
+ const normalized = String(relativePath).replace(/\\/g, '/');
122
+ const parts = normalized.split('/');
123
+ if (NEVER_DATA_DIRS.has(parts[0])) return true;
124
+ if (parts[0] === 'local-profiles' && parts.length >= 2) return true;
125
+ return NEVER_DATA_PATHS.some(path => normalized === path || normalized.startsWith(`${path}/`));
126
+ }
127
+
128
+ // data/<folder>/… by group. Anything not named here is `settings`.
129
+ const DATA_DIR_GROUPS = new Map([
130
+ ['scratch', 'scratch'],
131
+ ['media', 'media'], ['x-media', 'media'], ['x-showcase', 'media'], ['images', 'media'], ['extension-uploads', 'media'],
132
+ ['assistant', 'conversations'], ['assistant-usage', 'conversations'], ['run-tails', 'conversations'],
133
+ // Made again by what uses them: a tab's OpenCode configuration folder (with its node_modules), the editor's
134
+ // completion serve, the hooks' per-session receipts and flags.
135
+ ['sidepanel-configs', 'caches'], ['editor-complete', 'caches'], ['task-gate', 'caches'], ['memory-context', 'caches'],
136
+ ['pending-remember', 'caches'], ['pending-compact', 'caches'], ['precompact', 'caches'],
137
+ ]);
138
+ // data/<file> by group: the caches the server rebuilds from the memories and the transcripts, and its request journals.
139
+ const DATA_FILE_GROUPS = new Map([
140
+ ['assistant-dispatches.json', 'conversations'],
141
+ ['links-cache.json', 'caches'], ['memory-map.json', 'caches'], ['codex-request-journal.json', 'caches'],
142
+ ['ocp-trace.jsonl', 'caches'], ['last-session.json', 'caches'],
143
+ ]);
144
+ const SESSIONS_CACHE_RE = /^sessions-cache-.*\.json$/i;
145
+
146
+ /**
147
+ * The group of one file, by its path in the archive (`data/…`, `mcp-data/…`, `database/memory.db`, `env.bak`,
148
+ * `global-skills/…`, …). null: a file no backup holds (isNeverBackedUp).
149
+ */
150
+ export function backupGroupOf(archivePath) {
151
+ const path = String(archivePath).replace(/\\/g, '/');
152
+ if (path === 'database/memory.db') return 'memories';
153
+ const slash = path.indexOf('/');
154
+ const root = slash < 0 ? path : path.slice(0, slash);
155
+ const rel = slash < 0 ? '' : path.slice(slash + 1);
156
+ if (root === 'data' && rel) {
157
+ if (isNeverBackedUp(rel)) return null;
158
+ const parts = rel.split('/');
159
+ if (parts.length > 1) return DATA_DIR_GROUPS.get(parts[0]) || 'settings';
160
+ if (DATA_FILE_GROUPS.has(parts[0])) return DATA_FILE_GROUPS.get(parts[0]);
161
+ return SESSIONS_CACHE_RE.test(parts[0]) ? 'caches' : 'settings';
162
+ }
163
+ if (root === 'mcp-data' && rel) return isNeverBackedUp(rel) ? null : 'settings';
164
+ // Skills, agents, skins, ~/.claude/settings.json, the .env: a stray system file among them is still not data.
165
+ const name = path.split('/').at(-1).toLowerCase();
166
+ if (name === '.ds_store' || name === 'thumbs.db' || name === 'desktop.ini') return null;
167
+ return 'settings';
168
+ }
169
+
170
+ /** The folders of data/ a group owns outright (relative, one segment): a walk that leaves the group out skips them. */
171
+ export function dataDirsOfGroup(id) {
172
+ return [...DATA_DIR_GROUPS].filter(([, group]) => group === id).map(([dir]) => dir);
173
+ }
174
+
175
+ /** { id: boolean } for every group. Anything that is not a boolean for a known id is the group's default. */
176
+ export function normalizeBackupSelection(value) {
177
+ const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
178
+ const selection = {};
179
+ for (const group of BACKUP_GROUPS) selection[group.id] = typeof source[group.id] === 'boolean' ? source[group.id] : group.default;
180
+ return selection;
181
+ }
182
+
183
+ /** The ids switched on, in BACKUP_GROUPS order. `selection` null or undefined: every group (a backup of everything). */
184
+ export function selectedBackupGroups(selection) {
185
+ if (selection == null) return [...BACKUP_GROUP_IDS];
186
+ if (Array.isArray(selection)) return BACKUP_GROUP_IDS.filter(id => selection.includes(id));
187
+ const normalized = normalizeBackupSelection(selection);
188
+ return BACKUP_GROUP_IDS.filter(id => normalized[id]);
189
+ }
190
+
191
+ /** The irreplaceable groups a selection leaves out (what the page warns about). */
192
+ export function irreplaceableLeftOut(selection) {
193
+ const on = new Set(selectedBackupGroups(selection));
194
+ return BACKUP_GROUPS.filter(group => group.kind === 'irreplaceable' && !on.has(group.id)).map(group => group.id);
195
+ }
196
+
197
+ /** What a manifest records about its groups. */
198
+ export function manifestGroups(selection) {
199
+ const included = selectedBackupGroups(selection);
200
+ return { version: BACKUP_GROUPS_VERSION, included, excluded: BACKUP_GROUP_IDS.filter(id => !included.includes(id)) };
201
+ }
202
+
203
+ const cleanIds = (list) => [...new Set((Array.isArray(list) ? list : []).filter(id => typeof id === 'string' && /^[a-z][a-z0-9-]{0,39}$/.test(id)))];
204
+
205
+ /**
206
+ * What an archive holds, from its manifest.
207
+ * recorded the manifest says so itself (a backup made with groups)
208
+ * included / excluded group ids; for a manifest from before groups, `included` is read from its file list and
209
+ * `excluded` is the known groups it has no file of
210
+ * complete every group known to this version is in it
211
+ * legacy null | 'complete' | 'state-only' (an upgrade snapshot: state, without generated media)
212
+ */
213
+ export function readManifestGroups(manifest) {
214
+ const groups = manifest?.groups;
215
+ if (groups && typeof groups === 'object' && Array.isArray(groups.included)) {
216
+ const included = cleanIds(groups.included);
217
+ const excluded = cleanIds(groups.excluded).filter(id => !included.includes(id));
218
+ // A group this version knows and the manifest names nowhere (a backup from an older version): not in it.
219
+ for (const id of BACKUP_GROUP_IDS) if (!included.includes(id) && !excluded.includes(id)) excluded.push(id);
220
+ return { recorded: true, included, excluded, complete: BACKUP_GROUP_IDS.every(id => included.includes(id)), legacy: null };
221
+ }
222
+ const found = new Set();
223
+ if (manifest?.database || (Array.isArray(manifest?.files) && manifest.files.includes('database/memory.db'))) found.add('memories');
224
+ for (const file of Array.isArray(manifest?.files) ? manifest.files : []) {
225
+ const group = backupGroupOf(file);
226
+ if (group) found.add(group);
227
+ if (found.size === BACKUP_GROUP_IDS.length) break;
228
+ }
229
+ const included = BACKUP_GROUP_IDS.filter(id => found.has(id));
230
+ const legacy = manifest?.scope === 'state-only' ? 'state-only' : 'complete';
231
+ return { recorded: false, included, excluded: BACKUP_GROUP_IDS.filter(id => !found.has(id)), complete: legacy === 'complete', legacy };
232
+ }
233
+
234
+ /**
235
+ * Does the archive hold exactly what its manifest says? Returns the problems as sentences, [] for none. Only a
236
+ * manifest that records its groups is checked (one from before them promised nothing about groups):
237
+ * - every listed file belongs to an included group (a file of a group the manifest calls excluded is refused);
238
+ * - the memory database is there exactly when `memories` is included;
239
+ * - the archive has no entry the manifest does not list (nothing rides along unverified).
240
+ * @param {object} manifest
241
+ * @param {Iterable<string>} entryNames every file entry of the archive, as named in it
242
+ * @param {string} prefix the archive's folder (BACKUP_PREFIX)
243
+ */
244
+ export function checkManifestGroups(manifest, entryNames, prefix) {
245
+ const read = readManifestGroups(manifest);
246
+ if (!read.recorded) return [];
247
+ const problems = [];
248
+ const included = new Set(read.included);
249
+ const listed = new Set(Array.isArray(manifest.files) ? manifest.files : []);
250
+ for (const file of listed) {
251
+ const group = backupGroupOf(file);
252
+ if (group && !included.has(group)) { problems.push(`${file} belongs to "${group}", which this backup says it does not contain`); break; }
253
+ }
254
+ const hasDatabase = listed.has('database/memory.db');
255
+ // `absent`: the group was asked for and the data home had no memory database to give (a fresh install).
256
+ const absent = cleanIds(manifest.groups.absent);
257
+ if (included.has('memories') && !(hasDatabase && manifest.database) && !absent.includes('memories')) problems.push('the backup says it contains the memories, but the memory database is not in it');
258
+ if (!included.has('memories') && (hasDatabase || manifest.database)) problems.push('the backup says it does not contain the memories, but a memory database is in it');
259
+ const lead = prefix ? `${prefix}/` : '';
260
+ for (const name of entryNames) {
261
+ if (!name.startsWith(lead) || name.endsWith('/')) continue;
262
+ const rel = name.slice(lead.length);
263
+ if (rel === 'manifest.json') continue;
264
+ if (!listed.has(rel)) { problems.push(`${rel} is in the archive but not in its manifest`); break; }
265
+ }
266
+ return problems;
267
+ }
268
+
269
+ // ── Size estimates ──
270
+ // What a file takes in the archive, roughly, by what it is: stored as it is when already compressed, SQLite and text
271
+ // at the ratios measured on the 2026-11-21 archive (memory.db 0.43, JSON lines 0.31, mixed source trees 0.3 to 0.4).
272
+ const STORED = new Set(['.avif', '.gif', '.ico', '.jpeg', '.jpg', '.mov', '.mp3', '.mp4', '.ogg', '.png', '.webm', '.webp', '.woff', '.woff2', '.zip',
273
+ '.7z', '.gz', '.tgz', '.bz2', '.xz', '.zst', '.exe', '.dmg', '.pkg', '.msi', '.onnx', '.heic', '.m4a', '.m4v', '.mkv', '.pdf', '.wav']);
274
+ const TEXT = new Set(['.json', '.jsonl', '.md', '.txt', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.cts', '.mts', '.map', '.css', '.html',
275
+ '.yaml', '.yml', '.toml', '.svg', '.xml', '.csv', '.h', '.c', '.cc', '.cpp', '.py', '.sh', '.vue', '.svelte', '.mdx', '.bak', '.env']);
276
+
277
+ /** About how many bytes a file of `bytes` takes in the archive. An estimate for the page, never used to decide. */
278
+ export function estimateArchivedBytes(archivePath, bytes) {
279
+ const size = Math.max(0, Number(bytes) || 0);
280
+ const name = String(archivePath).toLowerCase();
281
+ const dot = name.lastIndexOf('.');
282
+ const ext = dot > name.lastIndexOf('/') ? name.slice(dot) : '';
283
+ if (STORED.has(ext)) return size;
284
+ if (ext === '.db' || ext === '.sqlite' || ext === '.sqlite3') return Math.round(size * 0.45);
285
+ if (TEXT.has(ext)) return Math.round(size * 0.33);
286
+ return Math.round(size * 0.7);
287
+ }
@@ -0,0 +1,176 @@
1
+ // ═══════════════════════════════════════════
2
+ // RESTORE — an encrypted backup, in three steps
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // A plain backup is uploaded with the request that restores it. An encrypted one cannot be: its password must not
6
+ // ride in a URL or a header, and typing it wrong must not cost another 10 GB upload. So the page uploads the file
7
+ // once (POST /api/system/restore/preview, which keeps it here instead of deleting it), then sends the password in a
8
+ // JSON body (unlock), reads what the backup holds, and asks for the restore (apply) or lets go (discard).
9
+ //
10
+ // createRestoreSessions({ stagingDir, limiter }) the one staged upload and, once unlocked, its file key
11
+ // encryptedRestoreHandlers({ sessions, preview, apply }) the three routes' handlers
12
+ //
13
+ // What is kept: the uploaded file, still encrypted, in the restore staging folder; after a right password, copies of
14
+ // that file's keys in memory. Never the password, never a plaintext copy of the archive: the ZIP inside is read
15
+ // through the decrypting reader (backup-crypto-io.js). One upload at a time; it is dropped when another arrives, when
16
+ // it is applied or discarded, after `ttlMs`, and at the next start of the server (the staging folder is emptied).
17
+ // A wrong password changes nothing and counts against the shared limiter (backup-encryption.js).
18
+
19
+ import { randomUUID } from 'node:crypto';
20
+ import { rmSync } from 'node:fs';
21
+ import { BackupEncryptionError, readBackupHeaderFile } from './backup-crypto.js';
22
+ import { BACKUP_ENCRYPTION_CAPABILITIES } from './backup-encryption.js';
23
+ import { openEncryptedBackupSource } from './backup-crypto-io.js';
24
+ import { openZipArchive } from './backup-zip-reader.js';
25
+
26
+ const gone = () => new BackupEncryptionError('RESTORE_UPLOAD_GONE', 'That backup is no longer waiting here. Choose the file again.', { status: 410 });
27
+
28
+ /**
29
+ * @param {object} [o]
30
+ * @param {{ check: () => void, fail: () => void, succeed: () => void }} o.limiter the password routes' shared limiter
31
+ * @param {number} [o.ttlMs] how long an upload waits for its password or its restore (30 minutes)
32
+ * @param {() => string|null} [o.currentKeyId] this installation's key id. A right password clears the count of wrong
33
+ * ones only for that key (or where there is none): anybody can craft a file with a password they know.
34
+ */
35
+ export function createRestoreSessions({ limiter, ttlMs = 30 * 60_000, currentKeyId = () => null, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
36
+ if (!limiter) throw new Error('limiter is required');
37
+ let current = null;
38
+
39
+ function drop() {
40
+ const session = current;
41
+ current = null;
42
+ if (!session) return;
43
+ clearTimer(session.timer);
44
+ wipeKeys(session);
45
+ try { rmSync(session.path, { force: true }); } catch { /* the start-up sweep removes it */ }
46
+ }
47
+
48
+ function wipeKeys(session) {
49
+ session.keys?.fileKey.fill(0);
50
+ session.keys?.authKey.fill(0);
51
+ session.keys = null;
52
+ }
53
+
54
+ function arm(session) {
55
+ clearTimer(session.timer);
56
+ session.expiresAt = now() + ttlMs;
57
+ session.timer = setTimer(() => { if (current === session) drop(); }, ttlMs);
58
+ session.timer?.unref?.();
59
+ }
60
+
61
+ const find = (id) => {
62
+ if (!current || typeof id !== 'string' || id !== current.id) throw gone();
63
+ return current;
64
+ };
65
+
66
+ return {
67
+ /** Keep an uploaded encrypted backup (system-restore.js saveRestoreUpload's { path, sizeBytes }). Returns what the page is told. */
68
+ async keep(upload) {
69
+ // What the header says without a key: which key pair. A file that is not a readable encrypted backup is
70
+ // refused here, and removed by the caller. The header's date is not told yet: until the password opened the
71
+ // file nothing has checked it (the unlock's answer carries it, authenticated).
72
+ const header = await readBackupHeaderFile(upload.path);
73
+ drop();
74
+ const session = { id: randomUUID(), path: upload.path, sizeBytes: upload.sizeBytes, keyId: header.recipient.keyId, keys: null, busy: false, timer: null, expiresAt: 0 };
75
+ current = session;
76
+ arm(session);
77
+ return {
78
+ uploadId: session.id,
79
+ sizeBytes: upload.sizeBytes,
80
+ keyId: header.recipient.keyId,
81
+ capabilities: [...BACKUP_ENCRYPTION_CAPABILITIES],
82
+ expiresInSeconds: Math.round(ttlMs / 1000),
83
+ };
84
+ },
85
+ /**
86
+ * Open the staged backup with `password`. Resolves the archive (backup-zip-reader.js), to be closed by the
87
+ * caller. WRONG_PASSWORD (401) leaves the upload waiting for another try; TOO_MANY_ATTEMPTS (429) while locked.
88
+ */
89
+ async unlock(id, password) {
90
+ const session = find(id);
91
+ if (session.busy) throw new BackupEncryptionError('RESTORE_RUNNING', 'This backup is already being restored.', { status: 409 });
92
+ limiter.check();
93
+ const own = currentKeyId();
94
+ const source = await limiter.attempt(() => openEncryptedBackupSource(session.path, { password }), { clears: !own || own === session.keyId });
95
+ if (current !== session || session.busy) {
96
+ await source.close();
97
+ if (current !== session) throw gone();
98
+ throw new BackupEncryptionError('RESTORE_RUNNING', 'This backup is already being restored.', { status: 409 });
99
+ }
100
+ wipeKeys(session);
101
+ session.keys = source.copyKeys();
102
+ arm(session);
103
+ return openZipArchive(session.path, { source });
104
+ },
105
+ /** The unlocked backup, for the restore itself. RESTORE_LOCKED (401) before a right password. One restore at a time. */
106
+ async open(id) {
107
+ const session = find(id);
108
+ if (!session.keys) throw new BackupEncryptionError('RESTORE_LOCKED', 'Enter the backup password first.', { status: 401 });
109
+ if (session.busy) throw new BackupEncryptionError('RESTORE_RUNNING', 'This backup is already being restored.', { status: 409 });
110
+ session.busy = true;
111
+ clearTimer(session.timer);
112
+ try { return await openZipArchive(session.path, { source: await openEncryptedBackupSource(session.path, { fileKey: session.keys.fileKey, authKey: session.keys.authKey }) }); }
113
+ catch (error) { session.busy = false; arm(session); throw error; }
114
+ },
115
+ /** Forget the staged backup: its file is removed and its key zeroed. True when there was one of that id. */
116
+ discard(id) {
117
+ if (!current || id !== current.id) return false;
118
+ drop();
119
+ return true;
120
+ },
121
+ /** For shutdown and tests. */
122
+ clear: drop,
123
+ waiting: () => (current ? { uploadId: current.id, unlocked: !!current.keys, expiresAt: current.expiresAt } : null),
124
+ };
125
+ }
126
+
127
+ /**
128
+ * The handlers of POST /api/system/restore/unlock { uploadId, password }, /apply-staged { uploadId, mode } and
129
+ * /discard { uploadId }. `preview(zip)` builds what the page shows before it asks (the same answer a plain backup's
130
+ * preview gives); `apply(zip, mode, res)` is the restore itself and answers the request. A failure is answered by
131
+ * its code and a sentence of this module's own; the password is read from the body and never repeated.
132
+ */
133
+ export function encryptedRestoreHandlers({ sessions, preview, apply }) {
134
+ const refuse = (res, error) => {
135
+ const known = error instanceof BackupEncryptionError;
136
+ if (error?.retryAfterSeconds) res.set('Retry-After', String(error.retryAfterSeconds));
137
+ return res.status(known ? error.status : 400).json({
138
+ ok: false,
139
+ code: known ? error.code : 'INVALID_BACKUP',
140
+ error: known ? error.message : String(error?.message || error),
141
+ ...(error?.retryAfterSeconds ? { retryAfterSeconds: error.retryAfterSeconds } : {}),
142
+ // The restore had begun writing (applyRestoreArchive): the page must not say that nothing was changed.
143
+ ...(res.locals?.restoreWriting ? { partial: true } : {}),
144
+ });
145
+ };
146
+ const text = (value) => (typeof value === 'string' ? value : '');
147
+ return {
148
+ async unlock(req, res) {
149
+ let zip = null;
150
+ try {
151
+ zip = await sessions.unlock(text(req.body?.uploadId), text(req.body?.password));
152
+ // `created`: when this file was written, from its header. The header's MAC held under the password's keys
153
+ // before anything was read, so this is the date the installation that made the backup wrote. It is what
154
+ // tells an older backup of the owner's from the latest one: both are genuine and both open.
155
+ res.json({ ...(await preview(zip)), encrypted: true, created: zip.source?.created || null, uploadId: text(req.body?.uploadId) });
156
+ } catch (error) { if (!res.headersSent) refuse(res, error); }
157
+ finally { await zip?.close().catch(() => {}); }
158
+ },
159
+ async apply(req, res) {
160
+ const id = text(req.body?.uploadId);
161
+ let zip = null;
162
+ try {
163
+ zip = await sessions.open(id);
164
+ await apply(zip, text(req.body?.mode) || 'full', res);
165
+ } catch (error) { if (!res.headersSent) refuse(res, error); }
166
+ finally {
167
+ await zip?.close().catch(() => {});
168
+ // Applied or failed part-way: the upload does not wait for a second try (the page uploads again).
169
+ if (zip) sessions.discard(id);
170
+ }
171
+ },
172
+ discard(req, res) {
173
+ res.json({ ok: true, discarded: sessions.discard(text(req.body?.uploadId)) });
174
+ },
175
+ };
176
+ }
@@ -0,0 +1,60 @@
1
+ // ═══════════════════════════════════════════
2
+ // RESTORE — the command line's private stage
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // `synabun restore-backup` extracts a backup into a sibling of the data home and swaps it in. Those files are the
6
+ // backup in plaintext, an encrypted backup's too, so the folder is private (0700) from its first moment, and a restore
7
+ // that was killed does not leave it behind: the next restore and the next server start remove it.
8
+ //
9
+ // No import from backup-service.js: the command-line restore loads this without the backup writer's dependencies.
10
+
11
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
12
+ import { basename, dirname, resolve } from 'node:path';
13
+
14
+ const STALE_STAGE_MS = 24 * 60 * 60 * 1000;
15
+
16
+ const stageNameOf = (target) => basename(resolve(target)).replace(/^\.+/, '') || 'synabun';
17
+
18
+ function pidIsGone(pid) {
19
+ try { process.kill(pid, 0); return false; }
20
+ catch (error) { return error?.code === 'ESRCH'; }
21
+ }
22
+
23
+ /** Where a restore of `target` stages its files: a sibling named after the data home, this process and this moment. */
24
+ export function restoreStagePath(target, { pid = process.pid, now = Date.now } = {}) {
25
+ return resolve(dirname(resolve(target)), `.${stageNameOf(target)}.restore-stage-${pid}-${now()}`);
26
+ }
27
+
28
+ /** Creates the stage, readable by its owner alone, whatever the umask says. It must not exist yet. */
29
+ export function makePrivateRestoreStage(stage) {
30
+ mkdirSync(stage, { mode: 0o700 });
31
+ if (process.platform !== 'win32') chmodSync(stage, 0o700);
32
+ return stage;
33
+ }
34
+
35
+ /**
36
+ * Removes the stages a killed restore of `target` left: those whose process is gone, and any older than a day (a
37
+ * process id can come back). Only real folders with exactly this data home's stage name are touched; a link is left
38
+ * alone. Returns the names removed.
39
+ */
40
+ export function sweepRestoreStages(target, { ownerGone = pidIsGone, now = Date.now, maxAgeMs = STALE_STAGE_MS } = {}) {
41
+ const parent = dirname(resolve(target));
42
+ const prefix = `.${stageNameOf(target)}.restore-stage-`;
43
+ const removed = [];
44
+ for (const name of readdirSync(parent)) {
45
+ if (!name.startsWith(prefix)) continue;
46
+ const match = name.slice(prefix.length).match(/^(\d+)-(\d+)$/);
47
+ if (!match) continue;
48
+ const path = resolve(parent, name);
49
+ try {
50
+ const stat = lstatSync(path);
51
+ if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
52
+ const owner = Number(match[1]);
53
+ const abandoned = owner !== process.pid && ownerGone(owner);
54
+ if (!abandoned && now() - stat.mtimeMs < maxAgeMs) continue;
55
+ rmSync(path, { recursive: true, force: true });
56
+ removed.push(name);
57
+ } catch { /* another process is removing it */ }
58
+ }
59
+ return removed;
60
+ }