shadow-claw 1.23.4 → 1.24.1

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 (267) hide show
  1. package/README.md +42 -5
  2. package/bin/cli.mjs +166 -0
  3. package/bin/cli.test.mjs +60 -0
  4. package/bin/commands/backup.mjs +70 -0
  5. package/bin/commands/clients.mjs +41 -0
  6. package/bin/commands/peer-id.mjs +76 -0
  7. package/bin/commands/peer-id.test.mjs +104 -0
  8. package/bin/commands/send.mjs +51 -0
  9. package/bin/commands/tasks.mjs +59 -0
  10. package/bin/commands/webrtc-listen.mjs +254 -0
  11. package/bin/prerender-dsd-shell/prerender-dsd-shell.test.mjs +46 -0
  12. package/bin/rolldown.config.test.mjs +401 -8
  13. package/bin/utils/control-client.mjs +243 -0
  14. package/bin/utils/control-client.test.mjs +83 -0
  15. package/bin/utils/ulid.mjs +45 -0
  16. package/bin/utils/webrtc-control-client.mjs +699 -0
  17. package/bin/utils/webrtc-control-client.test.mjs +318 -0
  18. package/dist/electron/main.cjs +1 -1
  19. package/dist/public/AGENTS.md +12 -3
  20. package/dist/public/README.md +42 -5
  21. package/dist/public/agent.worker.js +50 -50
  22. package/dist/public/backup-controller-CvzDOq4T.js +1 -0
  23. package/dist/public/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.css +1 -0
  24. package/dist/public/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.html +1 -0
  25. package/dist/public/components/settings/shadow-claw-task-server/shadow-claw-task-server.css +1 -1
  26. package/dist/public/components/settings/shadow-claw-task-server/shadow-claw-task-server.html +1 -1
  27. package/dist/public/components/shadow-claw-settings/shadow-claw-settings.html +1 -1
  28. package/dist/public/config-CrHchneq.js +1 -0
  29. package/dist/public/{configurePeerJs-B4Ym9VMj.js → configurePeerJs-UfQ6HUlv.js} +1 -1
  30. package/dist/public/{connections-BEn6JYdu.js → connections-DvbgdkaB.js} +1 -1
  31. package/dist/public/{custom-element-security-DdYlUozq.js → custom-element-security-NCqQ5lmC.js} +1 -1
  32. package/dist/public/docs/README.md +3 -1
  33. package/dist/public/docs/architecture/overview.md +12 -12
  34. package/dist/public/docs/decisions/bundled-typescript-architecture.md +1 -1
  35. package/dist/public/docs/decisions/indexeddb-and-opfs-storage.md +2 -2
  36. package/dist/public/docs/decisions/native-web-components-and-signals.md +1 -1
  37. package/dist/public/docs/example/article/index.html +1 -1
  38. package/dist/public/docs/guides/configuring-messaging-channels.md +41 -6
  39. package/dist/public/docs/guides/server-development-configuration.md +24 -0
  40. package/dist/public/docs/publishing/index.html +1 -1
  41. package/dist/public/docs/skill-creator/index.html +1 -1
  42. package/dist/public/docs/subsystems/backup.md +56 -0
  43. package/dist/public/docs/subsystems/cli.md +124 -0
  44. package/dist/public/docs/subsystems/control-plane.md +169 -0
  45. package/dist/public/docs/subsystems/notifications.md +54 -2
  46. package/dist/public/docs/subsystems/reactive-ui.md +1 -0
  47. package/dist/public/downloadGroupFile-9niHBj9n.js +1 -0
  48. package/dist/public/e2e/README.md +5 -1
  49. package/dist/public/{e2e-bridge-BQ4KzUt5.js → e2e-bridge-D28tOggc.js} +1 -1
  50. package/dist/public/file-viewer-BVg3B_JH.js +1 -0
  51. package/dist/public/getAllTasks-vpBlgGsc.js +1 -0
  52. package/dist/public/getGroupDir-P1h9wl6S.js +1 -0
  53. package/dist/public/{git-DEUvQTUA.js → git-7Vq_SJSp.js} +2 -2
  54. package/dist/public/{iframe-sanitizer-0NS4XLOd.js → iframe-sanitizer-y2Z1pPwY.js} +1 -1
  55. package/dist/public/index.html +1 -1
  56. package/dist/public/index.js +1 -1
  57. package/dist/public/{initChatSplitResize-llGkSJXg.js → initChatSplitResize-CzV2E7Ul.js} +1 -1
  58. package/dist/public/initControlPlane-DKNht5ph.js +1 -0
  59. package/dist/public/llms.txt +1 -1
  60. package/dist/public/main/index.html +1 -1
  61. package/dist/public/main/memory/index.html +1 -1
  62. package/dist/public/{markdown-CyYR4App.js → markdown-SiFq0PTy.js} +1 -1
  63. package/dist/public/{mcp-reconnect-CSx4aMwy.js → mcp-reconnect-9emsqGRe.js} +1 -1
  64. package/dist/public/{memoryStorage-Dwg8NhAZ.js → memoryStorage-C0KvLNUp.js} +1 -1
  65. package/dist/public/orchestrator-8w9-exfN.js +15 -0
  66. package/dist/public/{orchestrator-DRfEudXk.js → orchestrator-tHWrqi_F.js} +676 -676
  67. package/dist/public/{peerjs-CurBuKvk.js → peerjs-D8hck8Ih.js} +1 -1
  68. package/dist/public/push-client-D0lkwrK0.js +1 -0
  69. package/dist/public/service-worker/fetch-proxy.js +1 -1
  70. package/dist/public/service-worker/push-handler.js +1 -1
  71. package/dist/public/service-worker.js +1 -1
  72. package/dist/public/{shadow-claw-5IHaDDMJ.js → shadow-claw-Cs8wbk3d.js} +2 -2
  73. package/dist/public/{shadow-claw-accounts-CZvz4iQz.js → shadow-claw-accounts-B4sBTQEj.js} +1 -1
  74. package/dist/public/{shadow-claw-channels-BKXFyRS3.js → shadow-claw-channels-mY-JMvib.js} +1 -1
  75. package/dist/public/{shadow-claw-chat-CCLuhWdI.js → shadow-claw-chat-DGPKpmU5.js} +6 -6
  76. package/dist/public/shadow-claw-control-plane-B1F0jnPk.js +199 -0
  77. package/dist/public/{shadow-claw-conversations-DV-87UUh.js → shadow-claw-conversations-0Q-VC_7N.js} +1 -1
  78. package/dist/public/shadow-claw-dialog-BrOwAOdk.js +1 -0
  79. package/dist/public/{shadow-claw-file-viewer-Dk2dbAUd.js → shadow-claw-file-viewer-AZfG4D-u.js} +1 -1
  80. package/dist/public/shadow-claw-files-Bx4v0Ggp.js +840 -0
  81. package/dist/public/{shadow-claw-git-DRA7_qck.js → shadow-claw-git-DD7iQRxq.js} +2 -2
  82. package/dist/public/{shadow-claw-integrations-1Xu5snuV.js → shadow-claw-integrations-D7ufpwhX.js} +1 -1
  83. package/dist/public/{shadow-claw-llm-6Aci1BDP.js → shadow-claw-llm-CfeDBZKB.js} +2 -2
  84. package/dist/public/{shadow-claw-mcp-remote-BUjAeVXC.js → shadow-claw-mcp-remote-kY4LMFNN.js} +1 -1
  85. package/dist/public/{shadow-claw-networking-FQe4nCp3.js → shadow-claw-networking-e0EarDVs.js} +1 -1
  86. package/dist/public/{shadow-claw-notifications-DV2wibL3.js → shadow-claw-notifications-BkxuDEQI.js} +3 -3
  87. package/dist/public/{shadow-claw-page-header-B63S4HTU.js → shadow-claw-page-header-DMKbkv3s.js} +1 -1
  88. package/dist/public/{shadow-claw-pages-DE3jWj5K.js → shadow-claw-pages-BWSE91I1.js} +1 -1
  89. package/dist/public/{shadow-claw-settings-S6DAKfYx.js → shadow-claw-settings-D6lPBn6m.js} +10 -3
  90. package/dist/public/{shadow-claw-storage-DaacA3_K.js → shadow-claw-storage-Crs6LY15.js} +2 -2
  91. package/dist/public/{shadow-claw-task-server-IjKX042p.js → shadow-claw-task-server-CKm_Ennl.js} +25 -4
  92. package/dist/public/{shadow-claw-tasks-Cy0JYmGU.js → shadow-claw-tasks-Czx6Ucf5.js} +1 -1
  93. package/dist/public/{shadow-claw-terminal-znAt7HyP.js → shadow-claw-terminal-Dmtr9KY1.js} +1 -1
  94. package/dist/public/{shadow-claw-tools-Cutv9Si5.js → shadow-claw-tools-t3Qq4TDO.js} +1 -1
  95. package/dist/public/{shadow-claw-webvm-BH8mPDEu.js → shadow-claw-webvm-CIuSywD_.js} +1 -1
  96. package/dist/public/{syncWebMcpRegistration-BqJxaMGR.js → syncWebMcpRegistration-DzC80wVG.js} +1 -1
  97. package/dist/server.js +286 -189
  98. package/package.json +2 -1
  99. package/src/__mocks__/jszip.cjs +15 -5
  100. package/src/components/settings/shadow-claw-accounts/shadow-claw-accounts.test.ts +35 -0
  101. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.css +117 -0
  102. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.html +81 -0
  103. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.test.ts +127 -0
  104. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.ts +292 -0
  105. package/src/components/settings/shadow-claw-git/shadow-claw-git.test.ts +72 -0
  106. package/src/components/settings/shadow-claw-integrations/connection-test-auth.test.ts +20 -30
  107. package/src/components/settings/shadow-claw-integrations/shadow-claw-integrations.test.ts +116 -0
  108. package/src/components/settings/shadow-claw-llm/model-ranking.test.ts +143 -51
  109. package/src/components/settings/shadow-claw-llm/shadow-claw-llm.test.ts +307 -4
  110. package/src/components/settings/shadow-claw-llm/shadow-claw-llm.ts +8 -8
  111. package/src/components/settings/shadow-claw-mcp-remote/shadow-claw-mcp-remote.test.ts +31 -0
  112. package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.test.ts +3 -0
  113. package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.ts +43 -9
  114. package/src/components/settings/shadow-claw-peerjs/shadow-claw-peerjs.test.ts +186 -0
  115. package/src/components/settings/shadow-claw-storage/shadow-claw-storage.test.ts +76 -0
  116. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.css +23 -2
  117. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.html +1 -1
  118. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.test.ts +19 -0
  119. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.ts +2 -1
  120. package/src/components/shadow-claw/utils/initChatSplitResize.test.ts +180 -13
  121. package/src/components/shadow-claw/utils/setupEffects.test.ts +39 -0
  122. package/src/components/shadow-claw-a2ui/catalog/basic/shared.test.ts +117 -0
  123. package/src/components/shadow-claw-a2ui/shadow-claw-a2ui.test.ts +1159 -1
  124. package/src/components/shadow-claw-chat/shadow-claw-chat.test.ts +1523 -19
  125. package/src/components/shadow-claw-chat/utils/escapeHtml.test.ts +13 -0
  126. package/src/components/shadow-claw-chat/utils/getPeerChatDisplayStatus.test.ts +20 -0
  127. package/src/components/shadow-claw-conversations/shadow-claw-conversations.test.ts +494 -0
  128. package/src/components/shadow-claw-dialog/shadow-claw-dialog.ts +13 -2
  129. package/src/components/shadow-claw-file-viewer/shadow-claw-file-viewer.test.ts +273 -0
  130. package/src/components/shadow-claw-files/shadow-claw-files.test.ts +408 -1
  131. package/src/components/shadow-claw-pdf-viewer/utils/installGetOrInsertComputedPolyfill.test.ts +65 -0
  132. package/src/components/shadow-claw-settings/shadow-claw-settings.html +7 -0
  133. package/src/components/shadow-claw-settings/shadow-claw-settings.test.ts +221 -0
  134. package/src/components/shadow-claw-settings/shadow-claw-settings.ts +2 -0
  135. package/src/components/shadow-claw-tasks/shadow-claw-tasks.test.ts +407 -0
  136. package/src/components/shadow-claw-terminal/utils/consumeEscapeSequence.test.ts +58 -0
  137. package/src/components/shadow-claw-tools/shadow-claw-tools.test.ts +80 -0
  138. package/src/config/config.ts +10 -0
  139. package/src/core/backup-controller.test.ts +101 -0
  140. package/src/core/backup-controller.ts +166 -0
  141. package/src/core/control-plane-client.test.ts +415 -0
  142. package/src/core/control-plane-client.ts +441 -0
  143. package/src/core/orchestrator/orchestrator.ts +4 -0
  144. package/src/core/orchestrator/utils/compactContext.test.ts +78 -0
  145. package/src/core/orchestrator/utils/operations/channel.test.ts +254 -9
  146. package/src/core/orchestrator/utils/operations/provider.test.ts +326 -34
  147. package/src/core/orchestrator/utils/operations/task.ts +46 -15
  148. package/src/core/orchestrator/utils/operations/vm.test.ts +114 -2
  149. package/src/core/orchestrator/utils/syncProxyConfigToServiceWorker.test.ts +60 -0
  150. package/src/core/utils/initControlPlane.test.ts +276 -0
  151. package/src/core/utils/initControlPlane.ts +437 -0
  152. package/src/core/utils/initializeApp.ts +18 -0
  153. package/src/db/getSession.test.ts +13 -1
  154. package/src/server/app.test.ts +12 -0
  155. package/src/server/app.ts +20 -8
  156. package/src/server/client-registry.test.ts +250 -0
  157. package/src/server/client-registry.ts +477 -0
  158. package/src/server/config.ts +15 -0
  159. package/src/server/control-plane-types.ts +120 -0
  160. package/src/server/control-plane.test.ts +508 -0
  161. package/src/server/control-plane.ts +607 -0
  162. package/src/server/middleware/pna.test.ts +15 -3
  163. package/src/server/middleware/pna.ts +6 -2
  164. package/src/server/routes/backup.test.ts +277 -0
  165. package/src/server/routes/backup.ts +291 -0
  166. package/src/server/routes/integrations-email.test.ts +532 -0
  167. package/src/server/routes/llamafile.test.ts +172 -48
  168. package/src/server/routes/mesh-llm.test.ts +192 -0
  169. package/src/server/routes/ollama.test.ts +49 -0
  170. package/src/server/server-peer.test.ts +86 -0
  171. package/src/server/server-peer.ts +330 -0
  172. package/src/server/server.ts +37 -0
  173. package/src/server/services/llamafile-manager.test.ts +230 -6
  174. package/src/server/services/transformers-runtime.test.ts +186 -18
  175. package/src/server/webrtc.test.ts +21 -0
  176. package/src/server/webrtc.ts +72 -0
  177. package/src/service-worker/fetch-proxy-rules.test.ts +41 -0
  178. package/src/service-worker/fetch-proxy-rules.ts +15 -8
  179. package/src/service-worker/fetch-proxy.test.ts +64 -1
  180. package/src/service-worker/fetch-proxy.ts +18 -2
  181. package/src/service-worker/push-handler.ts +39 -0
  182. package/src/shell/vm.test.ts +744 -12
  183. package/src/storage/ensureMainGroupIndex.test.ts +153 -0
  184. package/src/storage/getGroupFile.test.ts +66 -0
  185. package/src/storage/memoryStorage.test.ts +82 -2
  186. package/src/storage/writeGroupFileBytes.test.ts +143 -0
  187. package/src/stores/chat-ui.test.ts +20 -0
  188. package/src/stores/orchestrator.test.ts +134 -0
  189. package/src/stores/toast.test.ts +50 -0
  190. package/src/stores/tools.test.ts +147 -10
  191. package/src/subsystems/channels/imessage.test.ts +59 -0
  192. package/src/subsystems/channels/peerjs.test.ts +500 -62
  193. package/src/subsystems/channels/peerjs.ts +71 -4
  194. package/src/subsystems/channels/telegram.test.ts +177 -0
  195. package/src/subsystems/email/catalog.test.ts +1 -0
  196. package/src/subsystems/email/connections.test.ts +39 -1
  197. package/src/subsystems/git/credentials.test.ts +160 -825
  198. package/src/subsystems/git/git.test.ts +463 -0
  199. package/src/subsystems/notifications/__mocks__/node-sqlite.cjs +12 -1
  200. package/src/subsystems/notifications/push-client.test.ts +5 -1
  201. package/src/subsystems/notifications/push-client.ts +50 -12
  202. package/src/subsystems/notifications/push-routes.test.ts +33 -0
  203. package/src/subsystems/notifications/push-routes.ts +23 -0
  204. package/src/subsystems/notifications/push-store.ts +1 -1
  205. package/src/subsystems/providers/builtin-ai-tasks.test.ts +74 -0
  206. package/src/subsystems/providers/litert-lm-provider.test.ts +212 -51
  207. package/src/subsystems/providers/model-registry.test.ts +115 -0
  208. package/src/subsystems/providers/providers.test.ts +94 -1
  209. package/src/subsystems/providers/transformers-js-provider.test.ts +279 -0
  210. package/src/subsystems/providers/utils/createModelCacheFetch.test.ts +2 -2
  211. package/src/subsystems/providers/utils/downloadModelToCache.test.ts +2 -2
  212. package/src/subsystems/providers/utils/loadModelStream.test.ts +2 -2
  213. package/src/subsystems/skills/activateSkill.test.ts +101 -0
  214. package/src/subsystems/skills/discoverSkills.test.ts +251 -0
  215. package/src/subsystems/tools/cron.test.ts +64 -0
  216. package/src/subsystems/tools/declarative.test.ts +255 -89
  217. package/src/testing/assets/v86.9pfs/libv86.mjs +63 -0
  218. package/src/testing/assets/v86.ext2/libv86.mjs +3 -0
  219. package/src/testing/assets_missing_v86/assets/v86.9pfs/libv86.mjs +1 -0
  220. package/src/testing/jest-setup.ts +328 -40
  221. package/src/testing/mock-v86.mjs +49 -0
  222. package/src/ui/a2ui/types.ts +4 -3
  223. package/src/ui/a2ui/utils/normaliseComponentsToMap.test.ts +102 -0
  224. package/src/ui/a2ui/utils/resolveChildIds.test.ts +63 -0
  225. package/src/ui/a2ui/utils/resolveDynamicNumber.test.ts +13 -1
  226. package/src/worker/tools/bash/utils/waitForVMReady.test.ts +40 -0
  227. package/src/worker/tools/email/email.test.ts +193 -8
  228. package/src/worker/tools/email/utils/asEmailAttachmentInputs.test.ts +47 -0
  229. package/src/worker/tools/git/git.test.ts +214 -3
  230. package/src/worker/tools/rooms/invite-to-room.test.ts +54 -0
  231. package/src/worker/tools/rooms/leave-room.test.ts +40 -0
  232. package/src/worker/tools/rooms/list-room-members.test.ts +75 -0
  233. package/src/worker/tools/tasks/tasks-utils.test.ts +22 -0
  234. package/src/worker/tools/ui/ask-user.test.ts +50 -0
  235. package/src/worker/tools/ui/clear-chat.test.ts +19 -0
  236. package/src/worker/tools/ui/get-current-time.test.ts +19 -0
  237. package/src/worker/tools/ui/javascript.test.ts +116 -0
  238. package/src/worker/tools/ui/list-components.test.ts +10 -0
  239. package/src/worker/tools/ui/list-tool-profiles.test.ts +42 -0
  240. package/src/worker/tools/ui/manage-tools.test.ts +34 -0
  241. package/src/worker/tools/ui/render-component.test.ts +346 -0
  242. package/src/worker/tools/ui/send-notification.test.ts +40 -0
  243. package/src/worker/tools/ui/utils/getAllowFullInternetAccess.test.ts +31 -0
  244. package/src/worker/tools/ui/utils/parseBooleanConfig.test.ts +25 -0
  245. package/src/worker/tools/workspace/attach-file.test.ts +84 -0
  246. package/src/worker/tools/workspace/copy-file.test.ts +69 -0
  247. package/src/worker/tools/workspace/create-directory.test.ts +40 -0
  248. package/src/worker/tools/workspace/delete-file.test.ts +73 -0
  249. package/src/worker/tools/workspace/diff-files.test.ts +94 -0
  250. package/src/worker/tools/workspace/list-files.test.ts +36 -0
  251. package/src/worker/tools/workspace/move-file.test.ts +66 -0
  252. package/src/worker/tools/workspace/open-file.test.ts +57 -0
  253. package/src/worker/tools/workspace/patch-file.test.ts +81 -0
  254. package/src/worker/tools/workspace/read-file.test.ts +116 -0
  255. package/src/worker/tools/workspace/send-file.test.ts +82 -0
  256. package/src/worker/tools/workspace/update-memory.test.ts +29 -0
  257. package/src/worker/tools/workspace/write-file.test.ts +28 -0
  258. package/src/worker/utils/rate-limit.test.ts +199 -0
  259. package/src/worker/utils/tool-state.test.ts +29 -0
  260. package/src/worker/utils/transformers-js-utils.test.ts +59 -0
  261. package/dist/public/config-BYAuxx3j.js +0 -1
  262. package/dist/public/downloadGroupFile-Drdvg1Ev.js +0 -1
  263. package/dist/public/file-viewer-CcZYw-PS.js +0 -1
  264. package/dist/public/orchestrator-o9Fj67BN.js +0 -15
  265. package/dist/public/push-client-Dii-vPEh.js +0 -1
  266. package/dist/public/shadow-claw-dialog-ByyHgxM9.js +0 -1
  267. package/dist/public/shadow-claw-files-BpfpJIuP.js +0 -840
@@ -0,0 +1,277 @@
1
+ import fs from "node:fs";
2
+ import http from "node:http";
3
+ import path from "node:path";
4
+ import express from "express";
5
+ import { openClientStore, closeClientStore } from "../client-registry.js";
6
+ import { registerBackupRoutes } from "./backup.js";
7
+ import type { AddressInfo } from "node:net";
8
+
9
+ function makeHttpRequest(options: {
10
+ method?: string;
11
+ path: string;
12
+ port: number;
13
+ headers?: Record<string, string>;
14
+ body?: any;
15
+ }): Promise<{ status: number; data: any; headers: http.IncomingHttpHeaders }> {
16
+ return new Promise((resolve, reject) => {
17
+ const req = http.request(
18
+ {
19
+ hostname: "127.0.0.1",
20
+ port: options.port,
21
+ path: options.path,
22
+ method: options.method || "GET",
23
+ headers: {
24
+ "Content-Type": "application/json",
25
+ ...options.headers,
26
+ },
27
+ },
28
+ (res) => {
29
+ let body = "";
30
+ res.on("data", (chunk) => (body += chunk));
31
+ res.on("end", () => {
32
+ let parsed = body;
33
+ try {
34
+ parsed = JSON.parse(body);
35
+ } catch (_) {}
36
+ resolve({
37
+ status: res.statusCode || 0,
38
+ data: parsed,
39
+ headers: res.headers,
40
+ });
41
+ });
42
+ },
43
+ );
44
+ req.on("error", reject);
45
+ if (options.body) {
46
+ req.write(
47
+ typeof options.body === "string"
48
+ ? options.body
49
+ : JSON.stringify(options.body),
50
+ );
51
+ }
52
+ req.end();
53
+ });
54
+ }
55
+
56
+ describe("backup routes", () => {
57
+ let app: express.Express;
58
+ let server: http.Server;
59
+ let port: number;
60
+ let token: string;
61
+ let testBackupsDir: string;
62
+
63
+ beforeEach(async () => {
64
+ openClientStore(":memory:");
65
+ token = "backup-test-token";
66
+ testBackupsDir = path.join(
67
+ process.cwd(),
68
+ ".cache",
69
+ "test-backups-" + Date.now(),
70
+ );
71
+
72
+ app = express();
73
+ app.use(express.json({ limit: "50mb" }));
74
+ registerBackupRoutes(app, {
75
+ backupsDir: testBackupsDir,
76
+ token,
77
+ });
78
+
79
+ server = http.createServer(app);
80
+ await new Promise<void>((resolve) => {
81
+ server.listen(0, "127.0.0.1", () => {
82
+ port = (server.address() as AddressInfo).port;
83
+ resolve();
84
+ });
85
+ });
86
+ });
87
+
88
+ afterEach(async () => {
89
+ await new Promise<void>((resolve) => {
90
+ server.close(() => resolve());
91
+ });
92
+ closeClientStore();
93
+ try {
94
+ if (fs.existsSync(testBackupsDir)) {
95
+ fs.rmSync(testBackupsDir, { recursive: true, force: true });
96
+ }
97
+ } catch (_) {}
98
+ });
99
+
100
+ it("rejects unauthorized external requests without token", async () => {
101
+ const res = await makeHttpRequest({
102
+ port,
103
+ path: "/api/backup/list",
104
+ headers: { host: "127.0.0.1", origin: "https://attacker.com" },
105
+ });
106
+
107
+ expect(res.status).toBe(401);
108
+ });
109
+
110
+ it("allows same-origin browser requests without explicit token header", async () => {
111
+ const res = await makeHttpRequest({
112
+ port,
113
+ path: "/api/backup/list",
114
+ headers: {
115
+ host: `127.0.0.1:${port}`,
116
+ origin: `http://127.0.0.1:${port}`,
117
+ },
118
+ });
119
+
120
+ expect(res.status).toBe(200);
121
+ expect(res.data.backups).toBeDefined();
122
+ });
123
+
124
+ it("allows GitHub Pages origin requests without explicit token header", async () => {
125
+ const res = await makeHttpRequest({
126
+ port,
127
+ path: "/api/backup/list",
128
+ headers: {
129
+ host: `127.0.0.1:${port}`,
130
+ origin: "https://xt-ml.github.io",
131
+ },
132
+ });
133
+
134
+ expect(res.status).toBe(200);
135
+ expect(res.data.backups).toBeDefined();
136
+ });
137
+
138
+ it("uploads a file and verifies on disk", async () => {
139
+ const res = await makeHttpRequest({
140
+ port,
141
+ path: "/api/backup/upload",
142
+ method: "POST",
143
+ headers: { "x-control-token": token },
144
+ body: {
145
+ clientId: "client-ipad",
146
+ backupId: "bk-01",
147
+ path: "workspace/MEMORY.md",
148
+ content: "# Client Memory\nHello from iPad",
149
+ },
150
+ });
151
+
152
+ expect(res.status).toBe(200);
153
+ expect(res.data.success).toBe(true);
154
+
155
+ const savedFilePath = path.join(
156
+ testBackupsDir,
157
+ "client-ipad",
158
+ "bk-01",
159
+ "workspace",
160
+ "MEMORY.md",
161
+ );
162
+ expect(fs.existsSync(savedFilePath)).toBe(true);
163
+ expect(fs.readFileSync(savedFilePath, "utf-8")).toBe(
164
+ "# Client Memory\nHello from iPad",
165
+ );
166
+ });
167
+
168
+ it("prevents directory traversal in backup upload paths", async () => {
169
+ const res = await makeHttpRequest({
170
+ port,
171
+ path: "/api/backup/upload",
172
+ method: "POST",
173
+ headers: { "x-control-token": token },
174
+ body: {
175
+ clientId: "client-ipad",
176
+ backupId: "bk-01",
177
+ path: "../../../etc/passwd",
178
+ content: "malicious content",
179
+ },
180
+ });
181
+
182
+ expect(res.status).toBe(400);
183
+ expect(res.data.error).toContain("Invalid path");
184
+ });
185
+
186
+ it("finalizes backup and records in SQLite database", async () => {
187
+ // 1. Upload a file
188
+ await makeHttpRequest({
189
+ port,
190
+ path: "/api/backup/upload",
191
+ method: "POST",
192
+ headers: { "x-control-token": token },
193
+ body: {
194
+ clientId: "client-ipad",
195
+ backupId: "bk-01",
196
+ path: "notes.txt",
197
+ content: "note content",
198
+ },
199
+ });
200
+
201
+ // 2. Complete backup
202
+ const completeRes = await makeHttpRequest({
203
+ port,
204
+ path: "/api/backup/complete",
205
+ method: "POST",
206
+ headers: { "x-control-token": token },
207
+ body: {
208
+ clientId: "client-ipad",
209
+ backupId: "bk-01",
210
+ fileCount: 1,
211
+ totalBytes: 12,
212
+ },
213
+ });
214
+
215
+ expect(completeRes.status).toBe(200);
216
+ expect(completeRes.data.success).toBe(true);
217
+ expect(completeRes.data.backupId).toBe("bk-01");
218
+
219
+ // 3. List backups
220
+ const listRes = await makeHttpRequest({
221
+ port,
222
+ path: "/api/backup/list?clientId=client-ipad",
223
+ headers: { "x-control-token": token },
224
+ });
225
+
226
+ expect(listRes.status).toBe(200);
227
+ expect(listRes.data.backups).toHaveLength(1);
228
+ expect(listRes.data.backups[0].id).toBe("bk-01");
229
+ expect(listRes.data.backups[0].fileCount).toBe(1);
230
+ });
231
+
232
+ it("deletes a backup from disk and registry", async () => {
233
+ await makeHttpRequest({
234
+ port,
235
+ path: "/api/backup/upload",
236
+ method: "POST",
237
+ headers: { "x-control-token": token },
238
+ body: {
239
+ clientId: "client-del",
240
+ backupId: "bk-del-01",
241
+ path: "file.txt",
242
+ content: "to be deleted",
243
+ },
244
+ });
245
+
246
+ await makeHttpRequest({
247
+ port,
248
+ path: "/api/backup/complete",
249
+ method: "POST",
250
+ headers: { "x-control-token": token },
251
+ body: {
252
+ clientId: "client-del",
253
+ backupId: "bk-del-01",
254
+ fileCount: 1,
255
+ totalBytes: 13,
256
+ },
257
+ });
258
+
259
+ const delRes = await makeHttpRequest({
260
+ port,
261
+ path: "/api/backup/bk-del-01?clientId=client-del",
262
+ method: "DELETE",
263
+ headers: { "x-control-token": token },
264
+ });
265
+
266
+ expect(delRes.status).toBe(200);
267
+ expect(delRes.data.success).toBe(true);
268
+
269
+ const listRes = await makeHttpRequest({
270
+ port,
271
+ path: "/api/backup/list?clientId=client-del",
272
+ headers: { "x-control-token": token },
273
+ });
274
+
275
+ expect(listRes.data.backups).toHaveLength(0);
276
+ });
277
+ });
@@ -0,0 +1,291 @@
1
+ /**
2
+ * ShadowClaw — Backup REST Routes
3
+ *
4
+ * Provides endpoints for uploading workspace files from connected clients
5
+ * (e.g. iPad, remote browsers) to the server filesystem and tracking
6
+ * backup manifests in SQLite.
7
+ */
8
+
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { URL } from "node:url";
12
+ import type { Express, Request, Response, NextFunction } from "express";
13
+ import {
14
+ getOrCreateControlToken,
15
+ recordBackup,
16
+ listBackups,
17
+ deleteBackup,
18
+ } from "../client-registry.js";
19
+
20
+ export interface BackupRoutesOptions {
21
+ backupsDir: string;
22
+ token?: string;
23
+ allowedOrigins?: Set<string>;
24
+ corsMode?: "localhost" | "private" | "all";
25
+ }
26
+
27
+ function isSafeRelativePath(relPath: string): boolean {
28
+ if (!relPath || typeof relPath !== "string") {
29
+ return false;
30
+ }
31
+ const normalized = path.normalize(relPath).replace(/^(\.\.[\/\\])+/, "");
32
+ if (
33
+ path.isAbsolute(relPath) ||
34
+ relPath.startsWith("..") ||
35
+ normalized !== relPath
36
+ ) {
37
+ return false;
38
+ }
39
+ return true;
40
+ }
41
+
42
+ function isSameOriginBrowser(
43
+ req: Request,
44
+ options?: BackupRoutesOptions,
45
+ ): boolean {
46
+ const host = req.headers.host || "127.0.0.1";
47
+ const origin = req.headers.origin;
48
+ const referer = req.headers.referer;
49
+
50
+ const isTrustedUrl = (urlStr: string): boolean => {
51
+ try {
52
+ const parsed = new URL(urlStr);
53
+ if (parsed.host === host) {
54
+ return true;
55
+ }
56
+
57
+ const hostname = parsed.hostname.toLowerCase();
58
+ if (
59
+ hostname === "127.0.0.1" ||
60
+ hostname === "localhost" ||
61
+ hostname === "::1" ||
62
+ hostname === "[::1]"
63
+ ) {
64
+ return true;
65
+ }
66
+
67
+ if (
68
+ hostname === "github.com" ||
69
+ hostname.endsWith(".github.io") ||
70
+ hostname.endsWith(".pages.dev")
71
+ ) {
72
+ return true;
73
+ }
74
+
75
+ if (options?.corsMode === "all") {
76
+ return true;
77
+ }
78
+
79
+ if (
80
+ options?.allowedOrigins &&
81
+ options.allowedOrigins.has(parsed.origin)
82
+ ) {
83
+ return true;
84
+ }
85
+
86
+ if (
87
+ options?.corsMode === "private" &&
88
+ /^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(hostname)
89
+ ) {
90
+ return true;
91
+ }
92
+ } catch (_) {}
93
+ return false;
94
+ };
95
+
96
+ if (origin && isTrustedUrl(origin)) {
97
+ return true;
98
+ }
99
+
100
+ if (referer && isTrustedUrl(referer)) {
101
+ return true;
102
+ }
103
+
104
+ const secFetchSite = req.headers["sec-fetch-site"];
105
+ if (secFetchSite === "same-origin" || secFetchSite === "same-site") {
106
+ return true;
107
+ }
108
+
109
+ return false;
110
+ }
111
+
112
+ export function registerBackupRoutes(
113
+ app: Express,
114
+ options: BackupRoutesOptions,
115
+ ): void {
116
+ const { backupsDir } = options;
117
+ const token = options.token || getOrCreateControlToken();
118
+
119
+ // Authentication middleware
120
+ const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
121
+ const host = req.headers.host || "127.0.0.1";
122
+ const parsedUrl = new URL(req.url, `http://${host}`);
123
+ const queryToken = parsedUrl.searchParams.get("token");
124
+ const headerToken = req.headers["x-control-token"];
125
+ const authHeader = req.headers["authorization"];
126
+ const bearerToken =
127
+ authHeader && authHeader.startsWith("Bearer ")
128
+ ? authHeader.slice(7).trim()
129
+ : null;
130
+
131
+ const providedToken = queryToken || headerToken || bearerToken;
132
+
133
+ const isAuthValid = providedToken
134
+ ? providedToken === token
135
+ : isSameOriginBrowser(req, options);
136
+
137
+ if (!isAuthValid) {
138
+ res.status(401).json({ error: "Unauthorized: Invalid control token" });
139
+ return;
140
+ }
141
+ next();
142
+ };
143
+
144
+ /**
145
+ * Upload a single file into a backup snapshot.
146
+ */
147
+ app.post(
148
+ "/api/backup/upload",
149
+ authMiddleware,
150
+ (req: Request, res: Response) => {
151
+ const {
152
+ clientId,
153
+ backupId,
154
+ path: filePath,
155
+ content,
156
+ encoding,
157
+ } = req.body || {};
158
+
159
+ if (!clientId || !backupId || !filePath) {
160
+ res
161
+ .status(400)
162
+ .json({ error: "clientId, backupId, and path are required" });
163
+ return;
164
+ }
165
+
166
+ if (!isSafeRelativePath(filePath)) {
167
+ res.status(400).json({ error: `Invalid path: ${filePath}` });
168
+ return;
169
+ }
170
+
171
+ const clientDir = path.resolve(backupsDir, clientId, backupId);
172
+ const targetFile = path.resolve(clientDir, filePath);
173
+
174
+ // Guard against directory traversal
175
+ if (
176
+ !targetFile.startsWith(clientDir + path.sep) &&
177
+ targetFile !== clientDir
178
+ ) {
179
+ res.status(400).json({ error: `Invalid path: ${filePath}` });
180
+ return;
181
+ }
182
+
183
+ try {
184
+ const parentDir = path.dirname(targetFile);
185
+ if (!fs.existsSync(parentDir)) {
186
+ fs.mkdirSync(parentDir, { recursive: true });
187
+ }
188
+
189
+ const buffer =
190
+ encoding === "base64"
191
+ ? Buffer.from(content || "", "base64")
192
+ : Buffer.from(content || "", "utf-8");
193
+
194
+ fs.writeFileSync(targetFile, buffer);
195
+
196
+ res.json({
197
+ success: true,
198
+ path: filePath,
199
+ bytesWritten: buffer.length,
200
+ });
201
+ } catch (err: any) {
202
+ res.status(500).json({ error: `Failed to write file: ${err.message}` });
203
+ }
204
+ },
205
+ );
206
+
207
+ /**
208
+ * Finalize and record a backup snapshot.
209
+ */
210
+ app.post(
211
+ "/api/backup/complete",
212
+ authMiddleware,
213
+ (req: Request, res: Response) => {
214
+ const { clientId, backupId, fileCount, totalBytes, manifest } =
215
+ req.body || {};
216
+
217
+ if (!clientId || !backupId) {
218
+ res.status(400).json({ error: "clientId and backupId are required" });
219
+ return;
220
+ }
221
+
222
+ try {
223
+ const record = recordBackup({
224
+ id: backupId,
225
+ clientId,
226
+ fileCount: Number(fileCount) || 0,
227
+ totalBytes: Number(totalBytes) || 0,
228
+ manifest,
229
+ });
230
+
231
+ res.json({
232
+ success: true,
233
+ backupId: record.id,
234
+ clientId: record.clientId,
235
+ timestamp: record.timestamp,
236
+ fileCount: record.fileCount,
237
+ totalBytes: record.totalBytes,
238
+ });
239
+ } catch (err: any) {
240
+ res
241
+ .status(500)
242
+ .json({ error: `Failed to complete backup: ${err.message}` });
243
+ }
244
+ },
245
+ );
246
+
247
+ /**
248
+ * List backups for a client.
249
+ */
250
+ app.get("/api/backup/list", authMiddleware, (req: Request, res: Response) => {
251
+ const clientId = (req.query.clientId as string) || undefined;
252
+ const backups = listBackups(clientId);
253
+ res.json({ backups });
254
+ });
255
+
256
+ /**
257
+ * Delete a backup snapshot.
258
+ */
259
+ app.delete(
260
+ "/api/backup/:id",
261
+ authMiddleware,
262
+ (req: Request, res: Response) => {
263
+ const backupId = Array.isArray(req.params.id)
264
+ ? req.params.id[0]
265
+ : req.params.id;
266
+ const clientId =
267
+ (req.query.clientId as string) || (req.body?.clientId as string);
268
+
269
+ if (!backupId) {
270
+ res.status(400).json({ error: "Backup id is required" });
271
+ return;
272
+ }
273
+
274
+ try {
275
+ if (clientId) {
276
+ const snapshotDir = path.resolve(backupsDir, clientId, backupId);
277
+ if (fs.existsSync(snapshotDir)) {
278
+ fs.rmSync(snapshotDir, { recursive: true, force: true });
279
+ }
280
+ }
281
+
282
+ deleteBackup(backupId, clientId);
283
+ res.json({ success: true, deleted: backupId });
284
+ } catch (err: any) {
285
+ res
286
+ .status(500)
287
+ .json({ error: `Failed to delete backup: ${err.message}` });
288
+ }
289
+ },
290
+ );
291
+ }