@pixelbyte-software/pixcode 1.54.10 → 1.55.0

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 (534) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +156 -156
  3. package/LICENSE +21 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +435 -418
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist-server/server/claude-sdk.js +1 -1
  13. package/dist-server/server/claude-sdk.js.map +1 -1
  14. package/dist-server/server/cli.js +100 -100
  15. package/dist-server/server/daemon/manager.js +33 -33
  16. package/dist-server/server/daemon-manager.js +64 -64
  17. package/dist-server/server/index.js +6 -11
  18. package/dist-server/server/index.js.map +1 -1
  19. package/dist-server/server/modules/security/permission-policy.js.map +1 -0
  20. package/dist-server/server/modules/tasks/git-worktree.js +98 -0
  21. package/dist-server/server/modules/tasks/git-worktree.js.map +1 -0
  22. package/dist-server/server/modules/tasks/index.js +8 -0
  23. package/dist-server/server/modules/tasks/index.js.map +1 -0
  24. package/dist-server/server/modules/tasks/prompt-builder.js +85 -0
  25. package/dist-server/server/modules/tasks/prompt-builder.js.map +1 -0
  26. package/dist-server/server/modules/tasks/role-presets.js +94 -0
  27. package/dist-server/server/modules/tasks/role-presets.js.map +1 -0
  28. package/dist-server/server/modules/tasks/runners/claude-runner.js +109 -0
  29. package/dist-server/server/modules/tasks/runners/claude-runner.js.map +1 -0
  30. package/dist-server/server/modules/tasks/runners/codex-runner.js +67 -0
  31. package/dist-server/server/modules/tasks/runners/codex-runner.js.map +1 -0
  32. package/dist-server/server/modules/tasks/runners/spawn-runner.js +111 -0
  33. package/dist-server/server/modules/tasks/runners/spawn-runner.js.map +1 -0
  34. package/dist-server/server/modules/tasks/runners/types.js +5 -0
  35. package/dist-server/server/modules/tasks/runners/types.js.map +1 -0
  36. package/dist-server/server/modules/tasks/scheduler.js +69 -0
  37. package/dist-server/server/modules/tasks/scheduler.js.map +1 -0
  38. package/dist-server/server/modules/tasks/task-queue.js +81 -0
  39. package/dist-server/server/modules/tasks/task-queue.js.map +1 -0
  40. package/dist-server/server/modules/tasks/task-routes.js +195 -0
  41. package/dist-server/server/modules/tasks/task-routes.js.map +1 -0
  42. package/dist-server/server/modules/tasks/task-runner.js +187 -0
  43. package/dist-server/server/modules/tasks/task-runner.js.map +1 -0
  44. package/dist-server/server/modules/tasks/task-store.js +196 -0
  45. package/dist-server/server/modules/tasks/task-store.js.map +1 -0
  46. package/dist-server/server/modules/tasks/task-types.js +5 -0
  47. package/dist-server/server/modules/tasks/task-types.js.map +1 -0
  48. package/dist-server/server/modules/tasks/user-interaction.js +73 -0
  49. package/dist-server/server/modules/tasks/user-interaction.js.map +1 -0
  50. package/dist-server/server/routes/commands.js +25 -25
  51. package/dist-server/server/routes/git.js +17 -17
  52. package/dist-server/server/routes/live-view.js +46 -46
  53. package/dist-server/server/services/control-room.js +9 -1
  54. package/dist-server/server/services/control-room.js.map +1 -1
  55. package/dist-server/server/services/public-api-manifest.js +54 -54
  56. package/dist-server/server/services/public-api-manifest.js.map +1 -1
  57. package/dist-server/server/services/telegram/control-center.js +10 -10
  58. package/dist-server/server/services/telegram/control-center.js.map +1 -1
  59. package/dist-server/server/services/telegram/telegram-gateway.js +2 -2
  60. package/dist-server/server/services/telegram/telegram-gateway.js.map +1 -1
  61. package/dist-server/server/services/telegram/translations.js +5 -5
  62. package/dist-server/server/services/telegram/translations.js.map +1 -1
  63. package/package.json +224 -224
  64. package/scripts/fix-node-pty.js +67 -67
  65. package/scripts/github/create-v1.38-issues.mjs +351 -351
  66. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  67. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  68. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  69. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  70. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  71. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  72. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  73. package/scripts/smoke/chat-session-state.mjs +19 -19
  74. package/scripts/smoke/code-editor-theme.mjs +55 -55
  75. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  76. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  77. package/scripts/smoke/command-center-non-git.mjs +46 -46
  78. package/scripts/smoke/context-packet.mjs +43 -43
  79. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  80. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  81. package/scripts/smoke/default-landing-routing.mjs +33 -33
  82. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  83. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  84. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  85. package/scripts/smoke/git-install-update.mjs +255 -255
  86. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  87. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  88. package/scripts/smoke/live-view-environment.mjs +92 -92
  89. package/scripts/smoke/live-view-integration.mjs +450 -450
  90. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  91. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  92. package/scripts/smoke/mobile-ux.mjs +76 -76
  93. package/scripts/smoke/model-registry.mjs +36 -36
  94. package/scripts/smoke/multi-project-ui.mjs +45 -45
  95. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  96. package/scripts/smoke/notification-center.mjs +87 -87
  97. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  98. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  99. package/scripts/smoke/orchestration-api.mjs +172 -172
  100. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  101. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  102. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  103. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  104. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  105. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  106. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  107. package/scripts/smoke/permission-policy.mjs +50 -50
  108. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  109. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  110. package/scripts/smoke/provider-rest-api.mjs +124 -124
  111. package/scripts/smoke/provider-selection-status.mjs +52 -52
  112. package/scripts/smoke/run-state-refresh.mjs +52 -52
  113. package/scripts/smoke/runtime-manager.mjs +99 -99
  114. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  115. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  116. package/scripts/smoke/static-root-routing.mjs +21 -21
  117. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  118. package/scripts/smoke/taskmaster-config.mjs +24 -24
  119. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  120. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  121. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  122. package/scripts/smoke/telegram-control.mjs +331 -331
  123. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  124. package/scripts/smoke/update-issue-progress.mjs +69 -69
  125. package/scripts/smoke/update-ux.mjs +55 -55
  126. package/scripts/smoke/v138-completion.mjs +132 -132
  127. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  128. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  129. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  130. package/scripts/smoke/v143-remote-control.mjs +76 -76
  131. package/scripts/smoke/v144-production-loop.mjs +47 -47
  132. package/scripts/smoke/v145-platformization.mjs +46 -46
  133. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  134. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  135. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  136. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  137. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  138. package/scripts/smoke/workflow-templates.mjs +43 -43
  139. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  140. package/scripts/update-git-install.mjs +298 -298
  141. package/server/claude-sdk.js +927 -927
  142. package/server/cli.js +1106 -1106
  143. package/server/constants/config.js +4 -4
  144. package/server/cursor-cli.js +344 -344
  145. package/server/daemon/manager.js +563 -563
  146. package/server/daemon-manager.js +964 -964
  147. package/server/database/db.js +988 -988
  148. package/server/database/json-store.js +197 -197
  149. package/server/gemini-cli.js +550 -550
  150. package/server/gemini-response-handler.js +79 -79
  151. package/server/index.js +5654 -5671
  152. package/server/load-env.js +35 -35
  153. package/server/middleware/account-lockout.js +112 -112
  154. package/server/middleware/auth.js +277 -277
  155. package/server/middleware/rate-limiter.js +87 -87
  156. package/server/modules/providers/index.ts +2 -2
  157. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  158. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  159. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  160. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  161. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  162. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  163. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  164. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  165. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  166. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  167. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  168. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  169. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  170. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  171. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  172. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  173. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  174. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  175. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  176. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  177. package/server/modules/providers/provider.registry.ts +40 -40
  178. package/server/modules/providers/provider.routes.ts +982 -982
  179. package/server/modules/providers/services/mcp.service.ts +86 -86
  180. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  181. package/server/modules/providers/services/sessions.service.ts +45 -45
  182. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  183. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  184. package/server/modules/providers/tests/mcp.test.ts +293 -293
  185. package/server/modules/{orchestration/security → security}/permission-policy.ts +401 -401
  186. package/server/modules/tasks/git-worktree.ts +102 -0
  187. package/server/modules/tasks/index.ts +9 -0
  188. package/server/modules/tasks/prompt-builder.ts +98 -0
  189. package/server/modules/tasks/role-presets.ts +113 -0
  190. package/server/modules/tasks/runners/claude-runner.ts +120 -0
  191. package/server/modules/tasks/runners/codex-runner.ts +80 -0
  192. package/server/modules/tasks/runners/spawn-runner.ts +122 -0
  193. package/server/modules/tasks/runners/types.ts +25 -0
  194. package/server/modules/tasks/scheduler.ts +75 -0
  195. package/server/modules/tasks/task-queue.ts +91 -0
  196. package/server/modules/tasks/task-routes.ts +245 -0
  197. package/server/modules/tasks/task-runner.ts +219 -0
  198. package/server/modules/tasks/task-store.ts +223 -0
  199. package/server/modules/tasks/task-types.ts +100 -0
  200. package/server/modules/tasks/user-interaction.ts +93 -0
  201. package/server/openai-codex.js +468 -468
  202. package/server/opencode-cli.js +491 -491
  203. package/server/opencode-response-handler.js +111 -111
  204. package/server/projects.js +3135 -3135
  205. package/server/qwen-code-cli.js +410 -410
  206. package/server/routes/agent.js +1462 -1462
  207. package/server/routes/auth.js +298 -298
  208. package/server/routes/codex.js +20 -20
  209. package/server/routes/commands.js +581 -581
  210. package/server/routes/cursor.js +61 -61
  211. package/server/routes/diagnostics.js +44 -44
  212. package/server/routes/gemini.js +25 -25
  213. package/server/routes/git.js +1822 -1822
  214. package/server/routes/live-view.js +434 -434
  215. package/server/routes/mcp-utils.js +13 -13
  216. package/server/routes/messages.js +97 -97
  217. package/server/routes/network.js +143 -143
  218. package/server/routes/platformization.js +231 -231
  219. package/server/routes/plugins.js +690 -690
  220. package/server/routes/production-agent-loop.js +90 -90
  221. package/server/routes/projects.js +918 -918
  222. package/server/routes/public-api.js +34 -34
  223. package/server/routes/qwen.js +27 -27
  224. package/server/routes/remote.js +56 -56
  225. package/server/routes/settings.js +321 -321
  226. package/server/routes/telegram.js +163 -163
  227. package/server/routes/user.js +125 -125
  228. package/server/routes/webhooks.js +63 -63
  229. package/server/services/control-room.js +111 -102
  230. package/server/services/diagnostics.js +165 -165
  231. package/server/services/external-access.js +403 -403
  232. package/server/services/install-jobs.js +715 -715
  233. package/server/services/live-view.js +956 -956
  234. package/server/services/managed-runtimes.js +493 -493
  235. package/server/services/model-registry.js +144 -144
  236. package/server/services/notification-orchestrator.js +365 -365
  237. package/server/services/notification-taxonomy.js +204 -204
  238. package/server/services/platformization.js +1052 -1052
  239. package/server/services/production-agent-loop.js +248 -248
  240. package/server/services/provider-cli-versions.js +149 -149
  241. package/server/services/provider-credentials.js +189 -189
  242. package/server/services/provider-models.js +396 -396
  243. package/server/services/public-api-manifest.js +181 -181
  244. package/server/services/qr-login.js +126 -126
  245. package/server/services/remote-connection.js +127 -127
  246. package/server/services/runtime-manager.js +323 -323
  247. package/server/services/startup-update.js +259 -259
  248. package/server/services/telegram/bot.js +393 -393
  249. package/server/services/telegram/control-center.js +2453 -2453
  250. package/server/services/telegram/telegram-gateway.js +314 -314
  251. package/server/services/telegram/telegram-http-client.js +201 -201
  252. package/server/services/telegram/translations.js +470 -470
  253. package/server/services/webhooks.js +216 -216
  254. package/server/sessionManager.js +225 -225
  255. package/server/setup-wizard.js +283 -283
  256. package/server/shared/interfaces.ts +54 -54
  257. package/server/shared/types.ts +172 -172
  258. package/server/shared/utils.ts +193 -193
  259. package/server/tsconfig.json +36 -36
  260. package/server/utils/colors.js +21 -21
  261. package/server/utils/commandParser.js +305 -305
  262. package/server/utils/frontmatter.js +18 -18
  263. package/server/utils/gitConfig.js +34 -34
  264. package/server/utils/plugin-loader.js +461 -461
  265. package/server/utils/plugin-process-manager.js +185 -185
  266. package/server/utils/port-access.js +227 -227
  267. package/server/utils/runtime-paths.js +37 -37
  268. package/server/utils/security-log.js +84 -84
  269. package/server/utils/url-detection.js +71 -71
  270. package/server/vite-daemon.js +79 -79
  271. package/shared/modelConstants.js +161 -161
  272. package/shared/networkHosts.js +22 -22
  273. package/dist/api-automation.html +0 -110
  274. package/dist/api-docs.html +0 -548
  275. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  276. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  277. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  278. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  279. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  280. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  281. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  282. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  283. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  284. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  285. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  286. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  287. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  288. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  289. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  290. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  291. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  292. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  293. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  294. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  295. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  296. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  297. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  298. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  299. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  300. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  301. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  302. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  303. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  304. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  305. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  306. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  307. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  308. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  309. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  310. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  311. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  312. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  313. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  314. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  315. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  316. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  317. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  318. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  319. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  320. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  321. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  322. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  323. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  324. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  325. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  326. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  327. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  328. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  329. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  330. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  331. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  332. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  333. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  334. package/dist/assets/index-DWOW_Jn0.js +0 -877
  335. package/dist/assets/index-Dz1luE0u.css +0 -32
  336. package/dist/assets/index-ak1p_4ew.js +0 -11
  337. package/dist/assets/localMonaco-DFIbtDNp.js +0 -1
  338. package/dist/assets/vendor-codemirror-CIYNS698.js +0 -41
  339. package/dist/assets/vendor-react-DB6V5Fl1.js +0 -59
  340. package/dist/assets/vendor-xterm-C7tpxJl7.js +0 -9
  341. package/dist/clear-cache.html +0 -85
  342. package/dist/convert-icons.md +0 -53
  343. package/dist/docs.html +0 -308
  344. package/dist/favicon.png +0 -0
  345. package/dist/favicon.svg +0 -8
  346. package/dist/features.html +0 -133
  347. package/dist/generate-icons.js +0 -49
  348. package/dist/humans.txt +0 -15
  349. package/dist/icons/claude-ai-icon.svg +0 -1
  350. package/dist/icons/codex-white.svg +0 -3
  351. package/dist/icons/codex.svg +0 -3
  352. package/dist/icons/cursor-white.svg +0 -12
  353. package/dist/icons/cursor.svg +0 -1
  354. package/dist/icons/gemini-ai-icon.svg +0 -1
  355. package/dist/icons/icon-128x128.png +0 -0
  356. package/dist/icons/icon-128x128.svg +0 -9
  357. package/dist/icons/icon-144x144.png +0 -0
  358. package/dist/icons/icon-144x144.svg +0 -9
  359. package/dist/icons/icon-152x152.png +0 -0
  360. package/dist/icons/icon-152x152.svg +0 -9
  361. package/dist/icons/icon-192x192.png +0 -0
  362. package/dist/icons/icon-192x192.svg +0 -9
  363. package/dist/icons/icon-384x384.png +0 -0
  364. package/dist/icons/icon-384x384.svg +0 -9
  365. package/dist/icons/icon-512x512.png +0 -0
  366. package/dist/icons/icon-512x512.svg +0 -9
  367. package/dist/icons/icon-72x72.png +0 -0
  368. package/dist/icons/icon-72x72.svg +0 -9
  369. package/dist/icons/icon-96x96.png +0 -0
  370. package/dist/icons/icon-96x96.svg +0 -9
  371. package/dist/icons/icon-template.svg +0 -9
  372. package/dist/icons/opencode-logo-dark.svg +0 -1
  373. package/dist/icons/opencode-logo-light.svg +0 -1
  374. package/dist/icons/qwen-ai-icon.png +0 -0
  375. package/dist/icons/qwen-logo.svg +0 -15
  376. package/dist/index.html +0 -62
  377. package/dist/landing.html +0 -268
  378. package/dist/llms-full.txt +0 -119
  379. package/dist/llms.txt +0 -53
  380. package/dist/logo-128.png +0 -0
  381. package/dist/logo-256.png +0 -0
  382. package/dist/logo-32.png +0 -0
  383. package/dist/logo-512.png +0 -0
  384. package/dist/logo-64.png +0 -0
  385. package/dist/logo.png +0 -0
  386. package/dist/logo.svg +0 -12
  387. package/dist/manifest.json +0 -61
  388. package/dist/openapi.yaml +0 -1696
  389. package/dist/orchestration.html +0 -125
  390. package/dist/robots.txt +0 -4
  391. package/dist/screenshots/cli-selection.png +0 -0
  392. package/dist/screenshots/desktop-main.png +0 -0
  393. package/dist/screenshots/mobile-chat.png +0 -0
  394. package/dist/screenshots/tools-modal.png +0 -0
  395. package/dist/site.css +0 -692
  396. package/dist/sitemap.xml +0 -51
  397. package/dist/sw.js +0 -132
  398. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js +0 -73
  399. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js.map +0 -1
  400. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js +0 -17
  401. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js.map +0 -1
  402. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js +0 -236
  403. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js.map +0 -1
  404. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js +0 -202
  405. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js.map +0 -1
  406. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js +0 -205
  407. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js.map +0 -1
  408. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js +0 -205
  409. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js.map +0 -1
  410. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js +0 -84
  411. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js.map +0 -1
  412. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js +0 -43
  413. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js.map +0 -1
  414. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js +0 -205
  415. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js.map +0 -1
  416. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js +0 -205
  417. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js.map +0 -1
  418. package/dist-server/server/modules/orchestration/a2a/agent-card.js +0 -50
  419. package/dist-server/server/modules/orchestration/a2a/agent-card.js.map +0 -1
  420. package/dist-server/server/modules/orchestration/a2a/auth.middleware.js +0 -25
  421. package/dist-server/server/modules/orchestration/a2a/auth.middleware.js.map +0 -1
  422. package/dist-server/server/modules/orchestration/a2a/bus.js +0 -34
  423. package/dist-server/server/modules/orchestration/a2a/bus.js.map +0 -1
  424. package/dist-server/server/modules/orchestration/a2a/routes.js +0 -502
  425. package/dist-server/server/modules/orchestration/a2a/routes.js.map +0 -1
  426. package/dist-server/server/modules/orchestration/a2a/task-dispatcher.js +0 -295
  427. package/dist-server/server/modules/orchestration/a2a/task-dispatcher.js.map +0 -1
  428. package/dist-server/server/modules/orchestration/a2a/task-store.js +0 -144
  429. package/dist-server/server/modules/orchestration/a2a/task-store.js.map +0 -1
  430. package/dist-server/server/modules/orchestration/a2a/types.js +0 -6
  431. package/dist-server/server/modules/orchestration/a2a/types.js.map +0 -1
  432. package/dist-server/server/modules/orchestration/a2a/validator.js +0 -101
  433. package/dist-server/server/modules/orchestration/a2a/validator.js.map +0 -1
  434. package/dist-server/server/modules/orchestration/index.js +0 -27
  435. package/dist-server/server/modules/orchestration/index.js.map +0 -1
  436. package/dist-server/server/modules/orchestration/preview/port-watcher.js +0 -90
  437. package/dist-server/server/modules/orchestration/preview/port-watcher.js.map +0 -1
  438. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +0 -58
  439. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +0 -1
  440. package/dist-server/server/modules/orchestration/preview/types.js +0 -2
  441. package/dist-server/server/modules/orchestration/preview/types.js.map +0 -1
  442. package/dist-server/server/modules/orchestration/security/permission-policy.js.map +0 -1
  443. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js +0 -34
  444. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js.map +0 -1
  445. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js +0 -70
  446. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js.map +0 -1
  447. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js +0 -181
  448. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js.map +0 -1
  449. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js +0 -2
  450. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js.map +0 -1
  451. package/dist-server/server/modules/orchestration/tasks/task-run-graph.js +0 -100
  452. package/dist-server/server/modules/orchestration/tasks/task-run-graph.js.map +0 -1
  453. package/dist-server/server/modules/orchestration/workflows/approval-queue.js +0 -72
  454. package/dist-server/server/modules/orchestration/workflows/approval-queue.js.map +0 -1
  455. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js +0 -126
  456. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js.map +0 -1
  457. package/dist-server/server/modules/orchestration/workflows/context-packet.js +0 -89
  458. package/dist-server/server/modules/orchestration/workflows/context-packet.js.map +0 -1
  459. package/dist-server/server/modules/orchestration/workflows/handoff-artifact.js +0 -123
  460. package/dist-server/server/modules/orchestration/workflows/handoff-artifact.js.map +0 -1
  461. package/dist-server/server/modules/orchestration/workflows/workflow-fallback-policy.js +0 -114
  462. package/dist-server/server/modules/orchestration/workflows/workflow-fallback-policy.js.map +0 -1
  463. package/dist-server/server/modules/orchestration/workflows/workflow-replay.js +0 -177
  464. package/dist-server/server/modules/orchestration/workflows/workflow-replay.js.map +0 -1
  465. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js +0 -1718
  466. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js.map +0 -1
  467. package/dist-server/server/modules/orchestration/workflows/workflow-store.js +0 -76
  468. package/dist-server/server/modules/orchestration/workflows/workflow-store.js.map +0 -1
  469. package/dist-server/server/modules/orchestration/workflows/workflow-templates.js +0 -242
  470. package/dist-server/server/modules/orchestration/workflows/workflow-templates.js.map +0 -1
  471. package/dist-server/server/modules/orchestration/workflows/workflow-trace.js +0 -388
  472. package/dist-server/server/modules/orchestration/workflows/workflow-trace.js.map +0 -1
  473. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js +0 -508
  474. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js.map +0 -1
  475. package/dist-server/server/modules/orchestration/workflows/workflow.types.js +0 -2
  476. package/dist-server/server/modules/orchestration/workflows/workflow.types.js.map +0 -1
  477. package/dist-server/server/modules/orchestration/workflows/workspace-target.js +0 -100
  478. package/dist-server/server/modules/orchestration/workflows/workspace-target.js.map +0 -1
  479. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js +0 -123
  480. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js.map +0 -1
  481. package/dist-server/server/modules/orchestration/workspace/path-safety.js +0 -48
  482. package/dist-server/server/modules/orchestration/workspace/path-safety.js.map +0 -1
  483. package/dist-server/server/modules/orchestration/workspace/types.js +0 -11
  484. package/dist-server/server/modules/orchestration/workspace/types.js.map +0 -1
  485. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js +0 -84
  486. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js.map +0 -1
  487. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js +0 -97
  488. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js.map +0 -1
  489. package/server/modules/orchestration/a2a/adapter-registry.ts +0 -108
  490. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +0 -63
  491. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +0 -286
  492. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +0 -244
  493. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +0 -249
  494. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +0 -248
  495. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +0 -60
  496. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +0 -101
  497. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +0 -248
  498. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +0 -248
  499. package/server/modules/orchestration/a2a/agent-card.ts +0 -55
  500. package/server/modules/orchestration/a2a/auth.middleware.ts +0 -29
  501. package/server/modules/orchestration/a2a/bus.ts +0 -46
  502. package/server/modules/orchestration/a2a/routes.ts +0 -586
  503. package/server/modules/orchestration/a2a/task-dispatcher.ts +0 -345
  504. package/server/modules/orchestration/a2a/task-store.ts +0 -178
  505. package/server/modules/orchestration/a2a/types.ts +0 -126
  506. package/server/modules/orchestration/a2a/validator.ts +0 -113
  507. package/server/modules/orchestration/index.ts +0 -99
  508. package/server/modules/orchestration/preview/port-watcher.ts +0 -112
  509. package/server/modules/orchestration/preview/preview-proxy.ts +0 -60
  510. package/server/modules/orchestration/preview/types.ts +0 -19
  511. package/server/modules/orchestration/tasks/orchestration-task-store.ts +0 -41
  512. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +0 -81
  513. package/server/modules/orchestration/tasks/orchestration-task.service.ts +0 -201
  514. package/server/modules/orchestration/tasks/orchestration-task.types.ts +0 -40
  515. package/server/modules/orchestration/tasks/task-run-graph.ts +0 -155
  516. package/server/modules/orchestration/workflows/approval-queue.ts +0 -106
  517. package/server/modules/orchestration/workflows/built-in-workflows.ts +0 -127
  518. package/server/modules/orchestration/workflows/context-packet.ts +0 -186
  519. package/server/modules/orchestration/workflows/handoff-artifact.ts +0 -175
  520. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +0 -161
  521. package/server/modules/orchestration/workflows/workflow-replay.ts +0 -254
  522. package/server/modules/orchestration/workflows/workflow-runner.ts +0 -2062
  523. package/server/modules/orchestration/workflows/workflow-store.ts +0 -97
  524. package/server/modules/orchestration/workflows/workflow-templates.ts +0 -272
  525. package/server/modules/orchestration/workflows/workflow-trace.ts +0 -424
  526. package/server/modules/orchestration/workflows/workflow.routes.ts +0 -586
  527. package/server/modules/orchestration/workflows/workflow.types.ts +0 -111
  528. package/server/modules/orchestration/workflows/workspace-target.ts +0 -122
  529. package/server/modules/orchestration/workspace/docker-workspace.ts +0 -136
  530. package/server/modules/orchestration/workspace/path-safety.ts +0 -55
  531. package/server/modules/orchestration/workspace/types.ts +0 -52
  532. package/server/modules/orchestration/workspace/workspace-manager.ts +0 -102
  533. package/server/modules/orchestration/workspace/worktree-workspace.ts +0 -126
  534. /package/dist-server/server/modules/{orchestration/security → security}/permission-policy.js +0 -0
@@ -1,1052 +1,1052 @@
1
- import crypto from 'node:crypto';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { execFile, spawn } from 'node:child_process';
5
- import { promisify } from 'node:util';
6
-
7
- import bcrypt from 'bcryptjs';
8
-
9
- import { appConfigDb, userDb } from '../database/db.js';
10
-
11
- const CONFIG_KEY = 'platformization';
12
- const execFileAsync = promisify(execFile);
13
-
14
- export const TEAM_ROLES = {
15
- owner: [
16
- 'team:manage',
17
- 'project:admin',
18
- 'run:approve',
19
- 'secret:manage',
20
- 'marketplace:manage',
21
- 'eval:run',
22
- 'usage:view',
23
- 'security:audit',
24
- ],
25
- admin: [
26
- 'project:admin',
27
- 'run:approve',
28
- 'secret:manage',
29
- 'marketplace:manage',
30
- 'eval:run',
31
- 'usage:view',
32
- 'security:audit',
33
- ],
34
- member: [
35
- 'project:write',
36
- 'run:create',
37
- 'secret:use',
38
- 'eval:run',
39
- 'usage:view',
40
- ],
41
- project_partner: [
42
- 'project:write',
43
- 'run:create',
44
- 'run:approve',
45
- 'review:manage',
46
- 'usage:view',
47
- ],
48
- project_worker: [
49
- 'project:write',
50
- 'run:create',
51
- 'review:update',
52
- ],
53
- project_reviewer: [
54
- 'project:read',
55
- 'review:manage',
56
- 'usage:view',
57
- ],
58
- viewer: [
59
- 'project:read',
60
- 'usage:view',
61
- ],
62
- };
63
-
64
- export const SECRET_SCOPES = ['global', 'provider', 'project', 'workflow', 'telegram', 'api'];
65
-
66
- export const MARKETPLACE_PLUGIN_TYPES = ['mcp-server', 'workflow-template', 'provider-adapter', 'notification-channel'];
67
-
68
- export const SECURITY_AUDIT_CHECKS = [
69
- 'dependency_audit',
70
- 'secret_scan',
71
- 'permission_audit',
72
- 'agent_output_leak_detection',
73
- ];
74
-
75
- function nowIso() {
76
- return new Date().toISOString();
77
- }
78
-
79
- function emptyStore() {
80
- return {
81
- teamMembers: [],
82
- secrets: [],
83
- marketplacePlugins: [],
84
- evaluationSuites: [],
85
- evaluationRuns: [],
86
- usageEvents: [],
87
- securityAuditRuns: [],
88
- projectCollaborators: [],
89
- remoteAccessConfigs: [],
90
- auditLog: [],
91
- };
92
- }
93
-
94
- function readStore() {
95
- const raw = appConfigDb.get(CONFIG_KEY);
96
- if (!raw) return emptyStore();
97
- try {
98
- const parsed = JSON.parse(raw);
99
- return {
100
- teamMembers: Array.isArray(parsed.teamMembers) ? parsed.teamMembers : [],
101
- secrets: Array.isArray(parsed.secrets) ? parsed.secrets : [],
102
- marketplacePlugins: Array.isArray(parsed.marketplacePlugins) ? parsed.marketplacePlugins : [],
103
- evaluationSuites: Array.isArray(parsed.evaluationSuites) ? parsed.evaluationSuites : [],
104
- evaluationRuns: Array.isArray(parsed.evaluationRuns) ? parsed.evaluationRuns : [],
105
- usageEvents: Array.isArray(parsed.usageEvents) ? parsed.usageEvents : [],
106
- securityAuditRuns: Array.isArray(parsed.securityAuditRuns) ? parsed.securityAuditRuns : [],
107
- projectCollaborators: Array.isArray(parsed.projectCollaborators) ? parsed.projectCollaborators : [],
108
- remoteAccessConfigs: Array.isArray(parsed.remoteAccessConfigs) ? parsed.remoteAccessConfigs : [],
109
- auditLog: Array.isArray(parsed.auditLog) ? parsed.auditLog : [],
110
- };
111
- } catch {
112
- return emptyStore();
113
- }
114
- }
115
-
116
- function writeStore(store) {
117
- appConfigDb.set(CONFIG_KEY, JSON.stringify(store));
118
- }
119
-
120
- function compact(text, max = 120) {
121
- const value = String(text || '').replace(/\s+/g, ' ').trim();
122
- return value.length > max ? value.slice(0, max).replace(/[-_\s]+$/g, '') : value;
123
- }
124
-
125
- function compactProjectIdentifier(value) {
126
- return String(value || '').replace(/\s+/g, ' ').trim();
127
- }
128
-
129
- function slugify(value) {
130
- const slug = compact(value, 72)
131
- .toLowerCase()
132
- .replace(/[^a-z0-9]+/g, '-')
133
- .replace(/^-+|-+$/g, '');
134
- return slug || crypto.randomUUID();
135
- }
136
-
137
- function addAudit(store, action, actorId, details = {}) {
138
- store.auditLog.unshift({
139
- id: crypto.randomUUID(),
140
- action,
141
- actorId: actorId || null,
142
- createdAt: nowIso(),
143
- details,
144
- });
145
- store.auditLog = store.auditLog.slice(0, 250);
146
- }
147
-
148
- function normalizeRole(role) {
149
- return TEAM_ROLES[role] ? role : 'viewer';
150
- }
151
-
152
- export function isAdminUser(user = {}) {
153
- return user?.role === 'admin' || user?.role === 'owner';
154
- }
155
-
156
- function resolveUser(input = {}) {
157
- const users = userDb.listUsers();
158
- const userId = Number(input.userId);
159
- if (Number.isFinite(userId)) {
160
- return users.find((user) => user.id === userId && user.is_active) || null;
161
- }
162
-
163
- const userRef = compact(input.userRef || input.email || input.username || '').toLowerCase();
164
- if (!userRef) return null;
165
- return users.find((user) => user.is_active && String(user.username).toLowerCase() === userRef) || null;
166
- }
167
-
168
- function projectMatches(collaborator, project = {}) {
169
- const projectName = compactProjectIdentifier(project.name || project.projectName || project);
170
- const projectPath = compactProjectIdentifier(project.fullPath || project.path || project.projectPath || '');
171
-
172
- return Boolean(
173
- (projectName && collaborator.projectName === projectName) ||
174
- (projectPath && collaborator.projectPath === projectPath)
175
- );
176
- }
177
-
178
- function isPathInside(basePath, targetPath) {
179
- const relative = path.relative(path.resolve(basePath), path.resolve(targetPath));
180
- return relative === '' || (relative && !relative.startsWith('..') && !path.isAbsolute(relative));
181
- }
182
-
183
- function normalizeAllowedRoots(input) {
184
- const roots = Array.isArray(input) ? input : [];
185
- const normalized = roots
186
- .filter((entry) => typeof entry === 'string')
187
- .map((entry) => entry.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/g, ''))
188
- .map((entry) => entry || '.')
189
- .filter((entry) => !entry.includes('..'));
190
- return Array.from(new Set(normalized.length > 0 ? normalized : ['.']));
191
- }
192
-
193
- function collaboratorAllowedRoots(collaborator) {
194
- return normalizeAllowedRoots(collaborator.allowedRoots || collaborator.allowedFolders || ['.']);
195
- }
196
-
197
- export function userHasProjectAccess(user, project, capability = 'viewFiles') {
198
- if (isAdminUser(user)) return true;
199
- if (!user?.id && !user?.userId) return false;
200
-
201
- const userId = Number(user.id ?? user.userId);
202
- const username = String(user.username || '').toLowerCase();
203
- const store = readStore();
204
-
205
- return store.projectCollaborators.some((collaborator) => {
206
- if (collaborator.status === 'disabled') return false;
207
- if (!projectMatches(collaborator, project)) return false;
208
-
209
- const sameUser = Number(collaborator.userId) === userId ||
210
- String(collaborator.userRef || '').toLowerCase() === username;
211
- if (!sameUser) return false;
212
-
213
- if (capability === 'viewFiles') {
214
- return collaborator.capabilities?.viewFiles !== false;
215
- }
216
-
217
- return collaborator.capabilities?.[capability] === true;
218
- });
219
- }
220
-
221
- export function getProjectAccessForUser(user, project, capability = 'viewFiles') {
222
- if (isAdminUser(user)) {
223
- return { unrestricted: true, allowedRoots: ['.'] };
224
- }
225
- if (!user?.id && !user?.userId) return { unrestricted: false, allowedRoots: [] };
226
-
227
- const userId = Number(user.id ?? user.userId);
228
- const username = String(user.username || '').toLowerCase();
229
- const store = readStore();
230
- const allowedRoots = [];
231
-
232
- for (const collaborator of store.projectCollaborators) {
233
- if (collaborator.status === 'disabled') continue;
234
- if (!projectMatches(collaborator, project)) continue;
235
- const sameUser = Number(collaborator.userId) === userId ||
236
- String(collaborator.userRef || '').toLowerCase() === username;
237
- if (!sameUser) continue;
238
- const capabilityAllowed = capability === 'viewFiles'
239
- ? collaborator.capabilities?.viewFiles !== false
240
- : collaborator.capabilities?.[capability] === true;
241
- if (!capabilityAllowed) continue;
242
- allowedRoots.push(...collaboratorAllowedRoots(collaborator));
243
- }
244
-
245
- return { unrestricted: false, allowedRoots: Array.from(new Set(allowedRoots)) };
246
- }
247
-
248
- export function userHasProjectPathAccess(user, project, targetPath, capability = 'viewFiles') {
249
- if (isAdminUser(user)) return true;
250
- const projectPath = project?.fullPath || project?.path || project?.projectPath;
251
- if (!projectPath || !targetPath) return false;
252
- const access = getProjectAccessForUser(user, project, capability);
253
- return access.allowedRoots.some((root) => {
254
- const allowedPath = root === '.' ? projectPath : path.resolve(projectPath, root);
255
- return isPathInside(allowedPath, targetPath);
256
- });
257
- }
258
-
259
- export function filterFileTreeForUser(files = [], user, project, capability = 'viewFiles') {
260
- if (isAdminUser(user)) return files;
261
- const projectPath = project?.fullPath || project?.path || project?.projectPath;
262
- if (!projectPath) return [];
263
- return files.filter((entry) => {
264
- const entryPath = entry?.path || entry?.fullPath || entry?.relativePath || '';
265
- const absoluteEntryPath = path.isAbsolute(entryPath) ? entryPath : path.resolve(projectPath, entryPath);
266
- return userHasProjectPathAccess(user, { ...project, fullPath: projectPath }, absoluteEntryPath, capability);
267
- });
268
- }
269
-
270
- export function filterProjectsForUser(projects = [], user) {
271
- if (isAdminUser(user)) return projects;
272
- return projects.filter((project) => userHasProjectAccess(user, project, 'viewFiles'));
273
- }
274
-
275
- function normalizeScope(scope) {
276
- return SECRET_SCOPES.includes(scope) ? scope : 'project';
277
- }
278
-
279
- function vaultKey() {
280
- const material = process.env.PIXCODE_SECRET_KEY || process.env.JWT_SECRET || appConfigDb.getOrCreateJwtSecret();
281
- return crypto.createHash('sha256').update(material).digest();
282
- }
283
-
284
- function sealSecret(value) {
285
- const iv = crypto.randomBytes(12);
286
- const cipher = crypto.createCipheriv('aes-256-gcm', vaultKey(), iv);
287
- const encrypted = Buffer.concat([cipher.update(String(value || ''), 'utf8'), cipher.final()]);
288
- return {
289
- algorithm: 'aes-256-gcm',
290
- iv: iv.toString('base64'),
291
- tag: cipher.getAuthTag().toString('base64'),
292
- ciphertext: encrypted.toString('base64'),
293
- };
294
- }
295
-
296
- function openSecret(sealed) {
297
- const decipher = crypto.createDecipheriv('aes-256-gcm', vaultKey(), Buffer.from(sealed.iv, 'base64'));
298
- decipher.setAuthTag(Buffer.from(sealed.tag, 'base64'));
299
- return Buffer.concat([
300
- decipher.update(Buffer.from(sealed.ciphertext, 'base64')),
301
- decipher.final(),
302
- ]).toString('utf8');
303
- }
304
-
305
- function redactSecret(secret) {
306
- return {
307
- ...secret,
308
- sealedValue: undefined,
309
- redacted: '********',
310
- };
311
- }
312
-
313
- function scopeMatches(secret, input = {}) {
314
- if (secret.scope === 'global') return true;
315
- if (secret.scope === 'provider') return !input.provider || secret.target === input.provider;
316
- if (secret.scope === 'project') return !input.projectPath || secret.target === input.projectPath || secret.target === input.projectName;
317
- if (secret.scope === 'workflow') return !input.workflowId || secret.target === input.workflowId;
318
- if (secret.scope === 'telegram') return input.channel === 'telegram';
319
- if (secret.scope === 'api') return input.channel === 'api';
320
- return false;
321
- }
322
-
323
- export function getPlatformizationState() {
324
- const store = readStore();
325
- return {
326
- roles: TEAM_ROLES,
327
- secretScopes: SECRET_SCOPES,
328
- marketplacePluginTypes: MARKETPLACE_PLUGIN_TYPES,
329
- securityAuditChecks: SECURITY_AUDIT_CHECKS,
330
- teamMembers: store.teamMembers,
331
- secrets: store.secrets.map(redactSecret),
332
- marketplacePlugins: store.marketplacePlugins,
333
- evaluationSuites: store.evaluationSuites,
334
- evaluationRuns: store.evaluationRuns,
335
- usageSummary: summarizeUsageEvents(store.usageEvents),
336
- securityAuditRuns: store.securityAuditRuns,
337
- adminUsers: listAdminUsers(),
338
- projectCollaborators: store.projectCollaborators,
339
- remoteAccessConfigs: store.remoteAccessConfigs,
340
- auditLog: store.auditLog,
341
- };
342
- }
343
-
344
- export function createTeamMember(input = {}, actorId = null) {
345
- const email = compact(input.email || input.username || '');
346
- if (!email) throw new Error('Team member email or username is required.');
347
- const store = readStore();
348
- const member = {
349
- id: crypto.randomUUID(),
350
- email,
351
- displayName: compact(input.displayName || email, 80),
352
- role: normalizeRole(input.role || 'viewer'),
353
- projectScopes: Array.isArray(input.projectScopes) ? input.projectScopes : [],
354
- status: input.status || 'active',
355
- createdAt: nowIso(),
356
- updatedAt: nowIso(),
357
- };
358
- member.permissions = TEAM_ROLES[member.role];
359
- store.teamMembers.unshift(member);
360
- addAudit(store, 'team.member.created', actorId, { memberId: member.id, role: member.role });
361
- writeStore(store);
362
- return member;
363
- }
364
-
365
- export function updateTeamMember(memberId, patch = {}, actorId = null) {
366
- const store = readStore();
367
- let updated = null;
368
- store.teamMembers = store.teamMembers.map((member) => {
369
- if (member.id !== memberId) return member;
370
- updated = {
371
- ...member,
372
- ...patch,
373
- id: member.id,
374
- role: normalizeRole(patch.role || member.role),
375
- updatedAt: nowIso(),
376
- };
377
- updated.permissions = TEAM_ROLES[updated.role];
378
- return updated;
379
- });
380
- if (updated) {
381
- addAudit(store, 'team.member.updated', actorId, { memberId, role: updated.role });
382
- writeStore(store);
383
- }
384
- return updated;
385
- }
386
-
387
- export function listAdminUsers() {
388
- return userDb.listUsers().map((user) => ({
389
- id: user.id,
390
- username: user.username,
391
- role: user.role || 'member',
392
- status: user.is_active ? 'active' : 'disabled',
393
- isActive: Boolean(user.is_active),
394
- createdAt: user.created_at,
395
- lastLogin: user.last_login,
396
- }));
397
- }
398
-
399
- export async function createAdminUser(input = {}, actorId = null) {
400
- const username = compact(input.username || input.email || '');
401
- const password = String(input.password || '');
402
- if (!username || password.length < 6) {
403
- throw new Error('Admin user creation requires a username and a password with at least 6 characters.');
404
- }
405
-
406
- const role = normalizeRole(input.role || 'member');
407
- const passwordHash = await bcrypt.hash(password, 12);
408
- const user = userDb.createManagedUser(username, passwordHash, {
409
- role,
410
- is_active: input.status !== 'disabled',
411
- });
412
-
413
- const store = readStore();
414
- const member = {
415
- id: crypto.randomUUID(),
416
- userId: user.id,
417
- email: input.email || username,
418
- displayName: compact(input.displayName || username, 80),
419
- role,
420
- projectScopes: Array.isArray(input.projectScopes) ? input.projectScopes : [],
421
- status: input.status || 'active',
422
- createdAt: nowIso(),
423
- updatedAt: nowIso(),
424
- permissions: TEAM_ROLES[role],
425
- };
426
- store.teamMembers.unshift(member);
427
- addAudit(store, 'admin.user.created', actorId, { userId: user.id, username, role });
428
- writeStore(store);
429
- return {
430
- ...user,
431
- status: member.status,
432
- permissions: member.permissions,
433
- };
434
- }
435
-
436
- export function updateAdminUser(userId, patch = {}, actorId = null) {
437
- const numericUserId = Number(userId);
438
- const role = patch.role ? normalizeRole(patch.role) : undefined;
439
- const isActive = patch.status === 'disabled' ? false : patch.status === 'active' ? true : undefined;
440
- const user = userDb.updateUser(numericUserId, {
441
- username: patch.username,
442
- role,
443
- is_active: isActive,
444
- });
445
- if (!user) return null;
446
-
447
- const store = readStore();
448
- store.teamMembers = store.teamMembers.map((member) => {
449
- if (member.userId !== numericUserId) return member;
450
- const nextRole = role || member.role;
451
- const nextStatus = patch.status || member.status;
452
- return {
453
- ...member,
454
- role: nextRole,
455
- status: nextStatus,
456
- permissions: TEAM_ROLES[nextRole] || TEAM_ROLES.viewer,
457
- updatedAt: nowIso(),
458
- };
459
- });
460
- addAudit(store, 'admin.user.updated', actorId, { userId: numericUserId, role: role || user.role, status: patch.status });
461
- writeStore(store);
462
- return {
463
- ...user,
464
- role: role || user.role || 'member',
465
- status: user.is_active ? 'active' : 'disabled',
466
- };
467
- }
468
-
469
- export function createProjectCollaborator(input = {}, actorId = null) {
470
- const projectName = compactProjectIdentifier(input.projectName || input.project || '');
471
- const projectPath = input.projectPath || null;
472
- const targetUser = resolveUser(input);
473
- const userRef = compact(input.userRef || input.email || input.username || targetUser?.username || '');
474
- if (!projectName || !userRef) {
475
- throw new Error('Project collaborator requires a project name and user reference.');
476
- }
477
-
478
- if (!targetUser) {
479
- throw new Error('Create the user account before assigning project access.');
480
- }
481
-
482
- const role = ['partner', 'worker', 'reviewer', 'viewer'].includes(input.role) ? input.role : 'worker';
483
- const capabilities = {
484
- chatAgents: input.capabilities?.chatAgents !== false,
485
- viewFiles: true,
486
- editFiles: role === 'partner' || role === 'worker',
487
- useShell: role === 'partner',
488
- approveActions: role === 'partner' || role === 'reviewer',
489
- manageSecrets: role === 'partner',
490
- manageProjectSettings: role === 'partner',
491
- };
492
- const collaborator = {
493
- id: crypto.randomUUID(),
494
- projectName,
495
- projectPath,
496
- userId: targetUser.id,
497
- userRef,
498
- role,
499
- capabilities: {
500
- ...capabilities,
501
- ...(input.capabilities && typeof input.capabilities === 'object' ? input.capabilities : {}),
502
- },
503
- allowedRoots: normalizeAllowedRoots(input.allowedRoots || input.allowedFolders || ['.']),
504
- status: input.status || 'active',
505
- createdAt: nowIso(),
506
- updatedAt: nowIso(),
507
- };
508
- const store = readStore();
509
- store.projectCollaborators.unshift(collaborator);
510
- addAudit(store, 'project.collaborator.created', actorId, { collaboratorId: collaborator.id, projectName, userRef, role });
511
- writeStore(store);
512
- return collaborator;
513
- }
514
-
515
- export function updateProjectCollaborator(collaboratorId, patch = {}, actorId = null) {
516
- const store = readStore();
517
- let updated = null;
518
- store.projectCollaborators = store.projectCollaborators.map((collaborator) => {
519
- if (collaborator.id !== collaboratorId) return collaborator;
520
- updated = {
521
- ...collaborator,
522
- ...patch,
523
- id: collaborator.id,
524
- capabilities: {
525
- ...collaborator.capabilities,
526
- ...(patch.capabilities && typeof patch.capabilities === 'object' ? patch.capabilities : {}),
527
- },
528
- allowedRoots: patch.allowedRoots || patch.allowedFolders
529
- ? normalizeAllowedRoots(patch.allowedRoots || patch.allowedFolders)
530
- : collaboratorAllowedRoots(collaborator),
531
- updatedAt: nowIso(),
532
- };
533
- return updated;
534
- });
535
- if (updated) {
536
- addAudit(store, 'project.collaborator.updated', actorId, { collaboratorId, role: updated.role, status: updated.status });
537
- writeStore(store);
538
- }
539
- return updated;
540
- }
541
-
542
- export function createSecret(input = {}, actorId = null) {
543
- const name = compact(input.name || input.envName || '');
544
- const value = input.value;
545
- if (!name || typeof value !== 'string') throw new Error('Secret name and string value are required.');
546
- const scope = normalizeScope(input.scope || 'project');
547
- const store = readStore();
548
- const secret = {
549
- id: crypto.randomUUID(),
550
- name,
551
- envName: compact(input.envName || name).replace(/[^A-Z0-9_]/gi, '_').toUpperCase(),
552
- scope,
553
- target: input.target || input.projectPath || input.provider || null,
554
- createdAt: nowIso(),
555
- updatedAt: nowIso(),
556
- fingerprint: crypto.createHash('sha256').update(value).digest('hex').slice(0, 12),
557
- sealedValue: sealSecret(value),
558
- };
559
- store.secrets = store.secrets.filter((existing) => !(existing.envName === secret.envName && existing.scope === secret.scope && existing.target === secret.target));
560
- store.secrets.unshift(secret);
561
- addAudit(store, 'secret.created', actorId, { secretId: secret.id, scope: secret.scope, envName: secret.envName });
562
- writeStore(store);
563
- return redactSecret(secret);
564
- }
565
-
566
- export function listSecrets() {
567
- return readStore().secrets.map(redactSecret);
568
- }
569
-
570
- export function materializeScopedEnv(input = {}, options = {}) {
571
- const store = readStore();
572
- const env = {};
573
- const included = [];
574
- for (const secret of store.secrets) {
575
- if (!scopeMatches(secret, input)) continue;
576
- included.push({
577
- id: secret.id,
578
- envName: secret.envName,
579
- scope: secret.scope,
580
- target: secret.target,
581
- redacted: '********',
582
- });
583
- if (options.reveal === true) {
584
- env[secret.envName] = openSecret(secret.sealedValue);
585
- }
586
- }
587
- return { env, included };
588
- }
589
-
590
- export function upsertMarketplacePlugin(input = {}, actorId = null) {
591
- const pluginId = input.id || slugify(input.name || input.packageName || 'plugin');
592
- const store = readStore();
593
- const existing = store.marketplacePlugins.find((plugin) => plugin.id === pluginId);
594
- const plugin = {
595
- id: pluginId,
596
- name: compact(input.name || pluginId, 100),
597
- type: MARKETPLACE_PLUGIN_TYPES.includes(input.type) ? input.type : 'mcp-server',
598
- source: input.source || input.packageName || input.repository || null,
599
- permissionScopes: Array.isArray(input.permissionScopes) ? input.permissionScopes : [],
600
- installCommand: input.installCommand || null,
601
- status: input.status || existing?.status || 'available',
602
- health: input.health || existing?.health || { status: 'unknown', checkedAt: null },
603
- updatedAt: nowIso(),
604
- createdAt: existing?.createdAt || nowIso(),
605
- };
606
- store.marketplacePlugins = [plugin, ...store.marketplacePlugins.filter((item) => item.id !== pluginId)];
607
- addAudit(store, 'marketplace.plugin.upserted', actorId, { pluginId, type: plugin.type });
608
- writeStore(store);
609
- return plugin;
610
- }
611
-
612
- export function updateMarketplacePluginHealth(pluginId, health = {}, actorId = null) {
613
- const store = readStore();
614
- let updated = null;
615
- store.marketplacePlugins = store.marketplacePlugins.map((plugin) => {
616
- if (plugin.id !== pluginId) return plugin;
617
- updated = {
618
- ...plugin,
619
- health: {
620
- status: health.status || 'unknown',
621
- message: health.message || '',
622
- checkedAt: nowIso(),
623
- },
624
- updatedAt: nowIso(),
625
- };
626
- return updated;
627
- });
628
- if (updated) {
629
- addAudit(store, 'marketplace.plugin.health_checked', actorId, { pluginId, status: updated.health.status });
630
- writeStore(store);
631
- }
632
- return updated;
633
- }
634
-
635
- export function createEvaluationSuite(input = {}, actorId = null) {
636
- const tasks = Array.isArray(input.tasks) ? input.tasks : [];
637
- const suite = {
638
- id: input.id || slugify(input.name || 'evaluation-suite'),
639
- name: compact(input.name || 'Evaluation suite', 100),
640
- description: compact(input.description || '', 240),
641
- tasks: tasks.map((task, index) => ({
642
- id: task.id || `task-${index + 1}`,
643
- title: compact(task.title || `Task ${index + 1}`, 120),
644
- acceptanceCriteria: Array.isArray(task.acceptanceCriteria) ? task.acceptanceCriteria : [],
645
- projectPath: task.projectPath || null,
646
- })),
647
- createdAt: nowIso(),
648
- updatedAt: nowIso(),
649
- };
650
- const store = readStore();
651
- store.evaluationSuites = [suite, ...store.evaluationSuites.filter((item) => item.id !== suite.id)];
652
- addAudit(store, 'eval.suite.upserted', actorId, { suiteId: suite.id, tasks: suite.tasks.length });
653
- writeStore(store);
654
- return suite;
655
- }
656
-
657
- export function createEvaluationRun(input = {}, actorId = null) {
658
- const results = Array.isArray(input.results) ? input.results : [];
659
- const passed = results.filter((result) => result.status === 'passed').length;
660
- const run = {
661
- id: crypto.randomUUID(),
662
- suiteId: input.suiteId || null,
663
- provider: input.provider || null,
664
- model: input.model || null,
665
- status: input.status || 'completed',
666
- createdAt: nowIso(),
667
- results,
668
- summary: {
669
- total: results.length,
670
- passed,
671
- failed: results.filter((result) => result.status === 'failed').length,
672
- passRate: results.length ? Math.round((passed / results.length) * 1000) / 10 : 0,
673
- averageLatencyMs: average(results.map((result) => Number(result.latencyMs || 0)).filter(Boolean)),
674
- },
675
- };
676
- const store = readStore();
677
- store.evaluationRuns.unshift(run);
678
- addAudit(store, 'eval.run.created', actorId, { runId: run.id, suiteId: run.suiteId, passRate: run.summary.passRate });
679
- writeStore(store);
680
- return run;
681
- }
682
-
683
- function average(values) {
684
- if (!values.length) return 0;
685
- return Math.round(values.reduce((sum, value) => sum + value, 0) / values.length);
686
- }
687
-
688
- export function recordUsageEvent(input = {}, actorId = null) {
689
- const event = {
690
- id: crypto.randomUUID(),
691
- createdAt: input.createdAt || nowIso(),
692
- provider: input.provider || 'unknown',
693
- model: input.model || 'unknown',
694
- workflow: input.workflow || input.source || 'manual',
695
- inputTokens: Number(input.inputTokens || 0),
696
- outputTokens: Number(input.outputTokens || 0),
697
- costUsd: Number(input.costUsd || 0),
698
- latencyMs: Number(input.latencyMs || 0),
699
- status: input.status || 'ok',
700
- };
701
- const store = readStore();
702
- store.usageEvents.unshift(event);
703
- store.usageEvents = store.usageEvents.slice(0, 2000);
704
- addAudit(store, 'usage.event.recorded', actorId, { provider: event.provider, model: event.model, status: event.status });
705
- writeStore(store);
706
- return event;
707
- }
708
-
709
- export function summarizeUsageEvents(events = readStore().usageEvents) {
710
- const groups = new Map();
711
- for (const event of events) {
712
- const key = `${event.provider}:${event.model}:${event.workflow}`;
713
- const current = groups.get(key) || {
714
- provider: event.provider,
715
- model: event.model,
716
- workflow: event.workflow,
717
- runs: 0,
718
- errors: 0,
719
- inputTokens: 0,
720
- outputTokens: 0,
721
- totalTokens: 0,
722
- costUsd: 0,
723
- latencyMs: 0,
724
- };
725
- current.runs += 1;
726
- current.errors += event.status === 'error' ? 1 : 0;
727
- current.inputTokens += event.inputTokens;
728
- current.outputTokens += event.outputTokens;
729
- current.totalTokens += event.inputTokens + event.outputTokens;
730
- current.costUsd += event.costUsd;
731
- current.latencyMs += event.latencyMs;
732
- groups.set(key, current);
733
- }
734
- return Array.from(groups.values()).map((group) => ({
735
- ...group,
736
- costUsd: Math.round(group.costUsd * 10000) / 10000,
737
- averageLatencyMs: group.runs ? Math.round(group.latencyMs / group.runs) : 0,
738
- errorRate: group.runs ? Math.round((group.errors / group.runs) * 1000) / 10 : 0,
739
- latencyMs: undefined,
740
- }));
741
- }
742
-
743
- export function createSecurityAuditRun(input = {}, actorId = null) {
744
- const checks = Array.isArray(input.checks) && input.checks.length
745
- ? input.checks.filter((check) => SECURITY_AUDIT_CHECKS.includes(check))
746
- : SECURITY_AUDIT_CHECKS;
747
- const findings = Array.isArray(input.findings) ? input.findings : [];
748
- const run = {
749
- id: crypto.randomUUID(),
750
- protocol: 'pixcode.security-audit.v1',
751
- status: input.status || 'queued',
752
- projectName: input.projectName || null,
753
- projectPath: input.projectPath || null,
754
- checks,
755
- createdAt: nowIso(),
756
- findings: findings.map((finding, index) => ({
757
- id: finding.id || `finding-${index + 1}`,
758
- severity: finding.severity || 'medium',
759
- title: compact(finding.title || 'Security finding', 140),
760
- file: finding.file || null,
761
- recommendation: finding.recommendation || null,
762
- })),
763
- checklist: checks.map((check) => ({
764
- check,
765
- status: 'pending',
766
- })),
767
- };
768
- const store = readStore();
769
- store.securityAuditRuns.unshift(run);
770
- addAudit(store, 'security.audit.created', actorId, { runId: run.id, checks });
771
- writeStore(store);
772
- return run;
773
- }
774
-
775
- export function getAuditLog(filters = {}) {
776
- const store = readStore();
777
- let entries = store.auditLog;
778
- if (filters.userId) {
779
- entries = entries.filter((entry) => String(entry.actorId) === String(filters.userId));
780
- }
781
- if (filters.eventType) {
782
- entries = entries.filter((entry) => entry.action === filters.eventType || entry.action.includes(filters.eventType));
783
- }
784
- if (filters.projectName) {
785
- entries = entries.filter((entry) => entry.details?.projectName === filters.projectName);
786
- }
787
- if (filters.severity) {
788
- entries = entries.filter((entry) => entry.details?.severity === filters.severity);
789
- }
790
- return entries.slice(0, Number(filters.limit || 200));
791
- }
792
-
793
- export function exportAuditLog(format = 'json', filters = {}) {
794
- const entries = getAuditLog(filters);
795
- if (format === 'csv') {
796
- const header = ['id', 'createdAt', 'actorId', 'action', 'details'];
797
- const lines = entries.map((entry) => header.map((field) => {
798
- const value = field === 'details' ? JSON.stringify(entry.details || {}) : entry[field];
799
- return `"${String(value ?? '').replace(/"/g, '""')}"`;
800
- }).join(','));
801
- return [header.join(','), ...lines].join('\n');
802
- }
803
- return JSON.stringify(entries, null, 2);
804
- }
805
-
806
- function normalizeAccessMode(mode) {
807
- return ['lan', 'tailscale', 'cloudflare_tunnel', 'custom_domain'].includes(mode) ? mode : 'lan';
808
- }
809
-
810
- function resolveTailscaleInstallPlan() {
811
- const platform = os.platform();
812
- if (platform === 'darwin') {
813
- return {
814
- platform,
815
- command: 'brew',
816
- args: ['install', 'tailscale'],
817
- displayCommand: 'brew install tailscale',
818
- docsUrl: 'https://tailscale.com/download/mac',
819
- note: 'If Homebrew is not installed, open the download page and install the macOS app.',
820
- };
821
- }
822
- if (platform === 'win32') {
823
- return {
824
- platform,
825
- command: 'winget',
826
- args: ['install', '--id', 'Tailscale.Tailscale', '-e', '--silent'],
827
- displayCommand: 'winget install --id Tailscale.Tailscale -e --silent',
828
- docsUrl: 'https://tailscale.com/download/windows',
829
- note: 'If winget is unavailable, install from the Tailscale download page.',
830
- };
831
- }
832
- return {
833
- platform,
834
- command: 'sh',
835
- args: ['-c', 'curl -fsSL https://tailscale.com/install.sh | sh'],
836
- displayCommand: 'curl -fsSL https://tailscale.com/install.sh | sh',
837
- docsUrl: 'https://tailscale.com/download/linux',
838
- note: 'Linux install may require root privileges. If this fails, run the command with sudo in a terminal.',
839
- };
840
- }
841
-
842
- function extractFirstUrl(text = '') {
843
- return String(text).match(/https?:\/\/[^\s]+/i)?.[0] || null;
844
- }
845
-
846
- function runTailscaleCommand(command, args, options = {}) {
847
- return new Promise((resolve) => {
848
- const child = spawn(command, args, {
849
- shell: false,
850
- windowsHide: true,
851
- env: process.env,
852
- ...options,
853
- });
854
- let stdout = '';
855
- let stderr = '';
856
- child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
857
- child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
858
- child.on('error', (error) => {
859
- resolve({ ok: false, code: null, stdout, stderr, error: error.message });
860
- });
861
- child.on('close', (code) => {
862
- resolve({ ok: code === 0, code, stdout, stderr, error: code === 0 ? null : `${command} exited with code ${code}` });
863
- });
864
- });
865
- }
866
-
867
- function normalizePublicUrl(value) {
868
- const raw = typeof value === 'string' ? value.trim() : '';
869
- if (!raw) return null;
870
- const url = new URL(raw);
871
- if (!['http:', 'https:'].includes(url.protocol)) {
872
- throw new Error('Remote access URL must use http or https.');
873
- }
874
- url.pathname = url.pathname.replace(/\/+$/, '');
875
- url.search = '';
876
- url.hash = '';
877
- return url.toString().replace(/\/$/, '');
878
- }
879
-
880
- export function saveRemoteAccessConfig(input = {}, actorId = null) {
881
- const mode = normalizeAccessMode(input.mode);
882
- const id = input.id || mode;
883
- const config = {
884
- id,
885
- mode,
886
- label: compact(input.label || mode.replace(/_/g, ' '), 80),
887
- url: input.url ? normalizePublicUrl(input.url) : null,
888
- targetPort: Number(input.targetPort || process.env.SERVER_PORT || 3001),
889
- public: mode === 'cloudflare_tunnel' || mode === 'custom_domain',
890
- tlsRequired: mode === 'cloudflare_tunnel' || mode === 'custom_domain',
891
- privateOnly: mode === 'tailscale' || mode === 'lan',
892
- status: input.status || 'configured',
893
- notes: compact(input.notes || '', 240),
894
- updatedAt: nowIso(),
895
- createdAt: input.createdAt || nowIso(),
896
- lastHealth: input.lastHealth || null,
897
- };
898
- const store = readStore();
899
- store.remoteAccessConfigs = [config, ...store.remoteAccessConfigs.filter((item) => item.id !== id)];
900
- addAudit(store, 'remote.access.configured', actorId, { mode, url: config.url, public: config.public });
901
- writeStore(store);
902
- return config;
903
- }
904
-
905
- export function getRemoteAccessState() {
906
- const store = readStore();
907
- return {
908
- host: os.hostname(),
909
- platform: os.platform(),
910
- localUrl: `http://127.0.0.1:${process.env.SERVER_PORT || 3001}`,
911
- configs: store.remoteAccessConfigs,
912
- recommendations: [
913
- {
914
- mode: 'tailscale',
915
- label: 'Tailscale private network',
916
- recommendedWhen: 'No stable domain, no public IP, private team access.',
917
- },
918
- {
919
- mode: 'cloudflare_tunnel',
920
- label: 'Cloudflare Tunnel',
921
- recommendedWhen: 'Stable public HTTPS URL without opening inbound ports.',
922
- },
923
- {
924
- mode: 'custom_domain',
925
- label: 'Custom domain / reverse proxy',
926
- recommendedWhen: 'Existing domain, reverse proxy, and TLS termination.',
927
- },
928
- ],
929
- };
930
- }
931
-
932
- export async function detectTailscaleStatus() {
933
- const installPlan = resolveTailscaleInstallPlan();
934
- try {
935
- const { stdout } = await execFileAsync('tailscale', ['status', '--json'], { timeout: 5000 });
936
- const status = JSON.parse(stdout || '{}');
937
- const self = status.Self || {};
938
- const tailscaleIps = Array.isArray(self.TailscaleIPs) ? self.TailscaleIPs : [];
939
- return {
940
- installed: true,
941
- loggedIn: Boolean(self.ID || self.DNSName || tailscaleIps.length),
942
- backendState: status.BackendState || null,
943
- deviceName: self.HostName || os.hostname(),
944
- magicDnsName: self.DNSName || null,
945
- tailscaleIp: tailscaleIps[0] || null,
946
- pixcodeUrl: tailscaleIps[0] ? `http://${tailscaleIps[0]}:${process.env.SERVER_PORT || 3001}` : null,
947
- installUrl: 'https://tailscale.com/download',
948
- installPlan,
949
- checkedAt: nowIso(),
950
- message: tailscaleIps[0] ? 'Tailscale is ready for private Pixcode access.' : 'Tailscale CLI is installed but no device IP was detected.',
951
- };
952
- } catch (error) {
953
- const isMissing = error?.code === 'ENOENT';
954
- return {
955
- installed: false,
956
- loggedIn: false,
957
- backendState: 'missing',
958
- deviceName: os.hostname(),
959
- magicDnsName: null,
960
- tailscaleIp: null,
961
- pixcodeUrl: null,
962
- installUrl: 'https://tailscale.com/download',
963
- installPlan,
964
- checkedAt: nowIso(),
965
- message: isMissing
966
- ? 'Tailscale is optional. Use the LAN links now, or install Tailscale from Settings > Access for private team access without a public domain.'
967
- : (error?.message || 'Tailscale status could not be read.'),
968
- };
969
- }
970
- }
971
-
972
- export async function installTailscale(actorId = null) {
973
- const plan = resolveTailscaleInstallPlan();
974
- const result = await runTailscaleCommand(plan.command, plan.args);
975
- const store = readStore();
976
- addAudit(store, 'remote.access.tailscale.install', actorId, {
977
- platform: plan.platform,
978
- ok: result.ok,
979
- command: plan.displayCommand,
980
- });
981
- writeStore(store);
982
- return {
983
- ...result,
984
- plan,
985
- message: result.ok
986
- ? 'Tailscale install command completed. Run login/connect next.'
987
- : `Install command failed. ${plan.note}`,
988
- };
989
- }
990
-
991
- export async function loginTailscale(actorId = null) {
992
- const result = await runTailscaleCommand('tailscale', ['up']);
993
- const combinedOutput = `${result.stdout || ''}\n${result.stderr || ''}`;
994
- const authUrl = extractFirstUrl(combinedOutput);
995
- const store = readStore();
996
- addAudit(store, 'remote.access.tailscale.login', actorId, {
997
- ok: result.ok,
998
- authUrl: Boolean(authUrl),
999
- });
1000
- writeStore(store);
1001
- return {
1002
- ...result,
1003
- authUrl,
1004
- message: result.ok
1005
- ? 'Tailscale is connected.'
1006
- : (authUrl ? 'Open the login URL to finish connecting this device.' : 'Tailscale login command failed.'),
1007
- tailscale: await detectTailscaleStatus(),
1008
- };
1009
- }
1010
-
1011
- export async function checkRemoteAccessHealth(input = {}, actorId = null) {
1012
- const url = normalizePublicUrl(input.url || input.remoteUrl || '');
1013
- const checkedAt = nowIso();
1014
- if (!url) {
1015
- throw new Error('Remote access health check requires a URL.');
1016
- }
1017
- const parsed = new URL(url);
1018
- const controller = new AbortController();
1019
- const timeout = setTimeout(() => controller.abort(), Number(input.timeoutMs || 5000));
1020
- try {
1021
- const response = await fetch(`${url}/api/auth/status`, { signal: controller.signal });
1022
- const health = {
1023
- url,
1024
- reachable: response.ok,
1025
- checkedAt,
1026
- statusCode: response.status,
1027
- https: parsed.protocol === 'https:',
1028
- websocketExpected: true,
1029
- message: response.ok ? 'Pixcode auth endpoint is reachable.' : `Pixcode returned HTTP ${response.status}.`,
1030
- };
1031
- const store = readStore();
1032
- addAudit(store, 'remote.access.health_checked', actorId, { url, reachable: health.reachable, https: health.https });
1033
- writeStore(store);
1034
- return health;
1035
- } catch (error) {
1036
- const health = {
1037
- url,
1038
- reachable: false,
1039
- checkedAt,
1040
- statusCode: null,
1041
- https: parsed.protocol === 'https:',
1042
- websocketExpected: true,
1043
- message: error?.name === 'AbortError' ? 'Health check timed out.' : (error?.message || 'Remote access URL is unreachable.'),
1044
- };
1045
- const store = readStore();
1046
- addAudit(store, 'remote.access.health_checked', actorId, { url, reachable: false, https: health.https });
1047
- writeStore(store);
1048
- return health;
1049
- } finally {
1050
- clearTimeout(timeout);
1051
- }
1052
- }
1
+ import crypto from 'node:crypto';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+
7
+ import bcrypt from 'bcryptjs';
8
+
9
+ import { appConfigDb, userDb } from '../database/db.js';
10
+
11
+ const CONFIG_KEY = 'platformization';
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ export const TEAM_ROLES = {
15
+ owner: [
16
+ 'team:manage',
17
+ 'project:admin',
18
+ 'run:approve',
19
+ 'secret:manage',
20
+ 'marketplace:manage',
21
+ 'eval:run',
22
+ 'usage:view',
23
+ 'security:audit',
24
+ ],
25
+ admin: [
26
+ 'project:admin',
27
+ 'run:approve',
28
+ 'secret:manage',
29
+ 'marketplace:manage',
30
+ 'eval:run',
31
+ 'usage:view',
32
+ 'security:audit',
33
+ ],
34
+ member: [
35
+ 'project:write',
36
+ 'run:create',
37
+ 'secret:use',
38
+ 'eval:run',
39
+ 'usage:view',
40
+ ],
41
+ project_partner: [
42
+ 'project:write',
43
+ 'run:create',
44
+ 'run:approve',
45
+ 'review:manage',
46
+ 'usage:view',
47
+ ],
48
+ project_worker: [
49
+ 'project:write',
50
+ 'run:create',
51
+ 'review:update',
52
+ ],
53
+ project_reviewer: [
54
+ 'project:read',
55
+ 'review:manage',
56
+ 'usage:view',
57
+ ],
58
+ viewer: [
59
+ 'project:read',
60
+ 'usage:view',
61
+ ],
62
+ };
63
+
64
+ export const SECRET_SCOPES = ['global', 'provider', 'project', 'workflow', 'telegram', 'api'];
65
+
66
+ export const MARKETPLACE_PLUGIN_TYPES = ['mcp-server', 'workflow-template', 'provider-adapter', 'notification-channel'];
67
+
68
+ export const SECURITY_AUDIT_CHECKS = [
69
+ 'dependency_audit',
70
+ 'secret_scan',
71
+ 'permission_audit',
72
+ 'agent_output_leak_detection',
73
+ ];
74
+
75
+ function nowIso() {
76
+ return new Date().toISOString();
77
+ }
78
+
79
+ function emptyStore() {
80
+ return {
81
+ teamMembers: [],
82
+ secrets: [],
83
+ marketplacePlugins: [],
84
+ evaluationSuites: [],
85
+ evaluationRuns: [],
86
+ usageEvents: [],
87
+ securityAuditRuns: [],
88
+ projectCollaborators: [],
89
+ remoteAccessConfigs: [],
90
+ auditLog: [],
91
+ };
92
+ }
93
+
94
+ function readStore() {
95
+ const raw = appConfigDb.get(CONFIG_KEY);
96
+ if (!raw) return emptyStore();
97
+ try {
98
+ const parsed = JSON.parse(raw);
99
+ return {
100
+ teamMembers: Array.isArray(parsed.teamMembers) ? parsed.teamMembers : [],
101
+ secrets: Array.isArray(parsed.secrets) ? parsed.secrets : [],
102
+ marketplacePlugins: Array.isArray(parsed.marketplacePlugins) ? parsed.marketplacePlugins : [],
103
+ evaluationSuites: Array.isArray(parsed.evaluationSuites) ? parsed.evaluationSuites : [],
104
+ evaluationRuns: Array.isArray(parsed.evaluationRuns) ? parsed.evaluationRuns : [],
105
+ usageEvents: Array.isArray(parsed.usageEvents) ? parsed.usageEvents : [],
106
+ securityAuditRuns: Array.isArray(parsed.securityAuditRuns) ? parsed.securityAuditRuns : [],
107
+ projectCollaborators: Array.isArray(parsed.projectCollaborators) ? parsed.projectCollaborators : [],
108
+ remoteAccessConfigs: Array.isArray(parsed.remoteAccessConfigs) ? parsed.remoteAccessConfigs : [],
109
+ auditLog: Array.isArray(parsed.auditLog) ? parsed.auditLog : [],
110
+ };
111
+ } catch {
112
+ return emptyStore();
113
+ }
114
+ }
115
+
116
+ function writeStore(store) {
117
+ appConfigDb.set(CONFIG_KEY, JSON.stringify(store));
118
+ }
119
+
120
+ function compact(text, max = 120) {
121
+ const value = String(text || '').replace(/\s+/g, ' ').trim();
122
+ return value.length > max ? value.slice(0, max).replace(/[-_\s]+$/g, '') : value;
123
+ }
124
+
125
+ function compactProjectIdentifier(value) {
126
+ return String(value || '').replace(/\s+/g, ' ').trim();
127
+ }
128
+
129
+ function slugify(value) {
130
+ const slug = compact(value, 72)
131
+ .toLowerCase()
132
+ .replace(/[^a-z0-9]+/g, '-')
133
+ .replace(/^-+|-+$/g, '');
134
+ return slug || crypto.randomUUID();
135
+ }
136
+
137
+ function addAudit(store, action, actorId, details = {}) {
138
+ store.auditLog.unshift({
139
+ id: crypto.randomUUID(),
140
+ action,
141
+ actorId: actorId || null,
142
+ createdAt: nowIso(),
143
+ details,
144
+ });
145
+ store.auditLog = store.auditLog.slice(0, 250);
146
+ }
147
+
148
+ function normalizeRole(role) {
149
+ return TEAM_ROLES[role] ? role : 'viewer';
150
+ }
151
+
152
+ export function isAdminUser(user = {}) {
153
+ return user?.role === 'admin' || user?.role === 'owner';
154
+ }
155
+
156
+ function resolveUser(input = {}) {
157
+ const users = userDb.listUsers();
158
+ const userId = Number(input.userId);
159
+ if (Number.isFinite(userId)) {
160
+ return users.find((user) => user.id === userId && user.is_active) || null;
161
+ }
162
+
163
+ const userRef = compact(input.userRef || input.email || input.username || '').toLowerCase();
164
+ if (!userRef) return null;
165
+ return users.find((user) => user.is_active && String(user.username).toLowerCase() === userRef) || null;
166
+ }
167
+
168
+ function projectMatches(collaborator, project = {}) {
169
+ const projectName = compactProjectIdentifier(project.name || project.projectName || project);
170
+ const projectPath = compactProjectIdentifier(project.fullPath || project.path || project.projectPath || '');
171
+
172
+ return Boolean(
173
+ (projectName && collaborator.projectName === projectName) ||
174
+ (projectPath && collaborator.projectPath === projectPath)
175
+ );
176
+ }
177
+
178
+ function isPathInside(basePath, targetPath) {
179
+ const relative = path.relative(path.resolve(basePath), path.resolve(targetPath));
180
+ return relative === '' || (relative && !relative.startsWith('..') && !path.isAbsolute(relative));
181
+ }
182
+
183
+ function normalizeAllowedRoots(input) {
184
+ const roots = Array.isArray(input) ? input : [];
185
+ const normalized = roots
186
+ .filter((entry) => typeof entry === 'string')
187
+ .map((entry) => entry.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/g, ''))
188
+ .map((entry) => entry || '.')
189
+ .filter((entry) => !entry.includes('..'));
190
+ return Array.from(new Set(normalized.length > 0 ? normalized : ['.']));
191
+ }
192
+
193
+ function collaboratorAllowedRoots(collaborator) {
194
+ return normalizeAllowedRoots(collaborator.allowedRoots || collaborator.allowedFolders || ['.']);
195
+ }
196
+
197
+ export function userHasProjectAccess(user, project, capability = 'viewFiles') {
198
+ if (isAdminUser(user)) return true;
199
+ if (!user?.id && !user?.userId) return false;
200
+
201
+ const userId = Number(user.id ?? user.userId);
202
+ const username = String(user.username || '').toLowerCase();
203
+ const store = readStore();
204
+
205
+ return store.projectCollaborators.some((collaborator) => {
206
+ if (collaborator.status === 'disabled') return false;
207
+ if (!projectMatches(collaborator, project)) return false;
208
+
209
+ const sameUser = Number(collaborator.userId) === userId ||
210
+ String(collaborator.userRef || '').toLowerCase() === username;
211
+ if (!sameUser) return false;
212
+
213
+ if (capability === 'viewFiles') {
214
+ return collaborator.capabilities?.viewFiles !== false;
215
+ }
216
+
217
+ return collaborator.capabilities?.[capability] === true;
218
+ });
219
+ }
220
+
221
+ export function getProjectAccessForUser(user, project, capability = 'viewFiles') {
222
+ if (isAdminUser(user)) {
223
+ return { unrestricted: true, allowedRoots: ['.'] };
224
+ }
225
+ if (!user?.id && !user?.userId) return { unrestricted: false, allowedRoots: [] };
226
+
227
+ const userId = Number(user.id ?? user.userId);
228
+ const username = String(user.username || '').toLowerCase();
229
+ const store = readStore();
230
+ const allowedRoots = [];
231
+
232
+ for (const collaborator of store.projectCollaborators) {
233
+ if (collaborator.status === 'disabled') continue;
234
+ if (!projectMatches(collaborator, project)) continue;
235
+ const sameUser = Number(collaborator.userId) === userId ||
236
+ String(collaborator.userRef || '').toLowerCase() === username;
237
+ if (!sameUser) continue;
238
+ const capabilityAllowed = capability === 'viewFiles'
239
+ ? collaborator.capabilities?.viewFiles !== false
240
+ : collaborator.capabilities?.[capability] === true;
241
+ if (!capabilityAllowed) continue;
242
+ allowedRoots.push(...collaboratorAllowedRoots(collaborator));
243
+ }
244
+
245
+ return { unrestricted: false, allowedRoots: Array.from(new Set(allowedRoots)) };
246
+ }
247
+
248
+ export function userHasProjectPathAccess(user, project, targetPath, capability = 'viewFiles') {
249
+ if (isAdminUser(user)) return true;
250
+ const projectPath = project?.fullPath || project?.path || project?.projectPath;
251
+ if (!projectPath || !targetPath) return false;
252
+ const access = getProjectAccessForUser(user, project, capability);
253
+ return access.allowedRoots.some((root) => {
254
+ const allowedPath = root === '.' ? projectPath : path.resolve(projectPath, root);
255
+ return isPathInside(allowedPath, targetPath);
256
+ });
257
+ }
258
+
259
+ export function filterFileTreeForUser(files = [], user, project, capability = 'viewFiles') {
260
+ if (isAdminUser(user)) return files;
261
+ const projectPath = project?.fullPath || project?.path || project?.projectPath;
262
+ if (!projectPath) return [];
263
+ return files.filter((entry) => {
264
+ const entryPath = entry?.path || entry?.fullPath || entry?.relativePath || '';
265
+ const absoluteEntryPath = path.isAbsolute(entryPath) ? entryPath : path.resolve(projectPath, entryPath);
266
+ return userHasProjectPathAccess(user, { ...project, fullPath: projectPath }, absoluteEntryPath, capability);
267
+ });
268
+ }
269
+
270
+ export function filterProjectsForUser(projects = [], user) {
271
+ if (isAdminUser(user)) return projects;
272
+ return projects.filter((project) => userHasProjectAccess(user, project, 'viewFiles'));
273
+ }
274
+
275
+ function normalizeScope(scope) {
276
+ return SECRET_SCOPES.includes(scope) ? scope : 'project';
277
+ }
278
+
279
+ function vaultKey() {
280
+ const material = process.env.PIXCODE_SECRET_KEY || process.env.JWT_SECRET || appConfigDb.getOrCreateJwtSecret();
281
+ return crypto.createHash('sha256').update(material).digest();
282
+ }
283
+
284
+ function sealSecret(value) {
285
+ const iv = crypto.randomBytes(12);
286
+ const cipher = crypto.createCipheriv('aes-256-gcm', vaultKey(), iv);
287
+ const encrypted = Buffer.concat([cipher.update(String(value || ''), 'utf8'), cipher.final()]);
288
+ return {
289
+ algorithm: 'aes-256-gcm',
290
+ iv: iv.toString('base64'),
291
+ tag: cipher.getAuthTag().toString('base64'),
292
+ ciphertext: encrypted.toString('base64'),
293
+ };
294
+ }
295
+
296
+ function openSecret(sealed) {
297
+ const decipher = crypto.createDecipheriv('aes-256-gcm', vaultKey(), Buffer.from(sealed.iv, 'base64'));
298
+ decipher.setAuthTag(Buffer.from(sealed.tag, 'base64'));
299
+ return Buffer.concat([
300
+ decipher.update(Buffer.from(sealed.ciphertext, 'base64')),
301
+ decipher.final(),
302
+ ]).toString('utf8');
303
+ }
304
+
305
+ function redactSecret(secret) {
306
+ return {
307
+ ...secret,
308
+ sealedValue: undefined,
309
+ redacted: '********',
310
+ };
311
+ }
312
+
313
+ function scopeMatches(secret, input = {}) {
314
+ if (secret.scope === 'global') return true;
315
+ if (secret.scope === 'provider') return !input.provider || secret.target === input.provider;
316
+ if (secret.scope === 'project') return !input.projectPath || secret.target === input.projectPath || secret.target === input.projectName;
317
+ if (secret.scope === 'workflow') return !input.workflowId || secret.target === input.workflowId;
318
+ if (secret.scope === 'telegram') return input.channel === 'telegram';
319
+ if (secret.scope === 'api') return input.channel === 'api';
320
+ return false;
321
+ }
322
+
323
+ export function getPlatformizationState() {
324
+ const store = readStore();
325
+ return {
326
+ roles: TEAM_ROLES,
327
+ secretScopes: SECRET_SCOPES,
328
+ marketplacePluginTypes: MARKETPLACE_PLUGIN_TYPES,
329
+ securityAuditChecks: SECURITY_AUDIT_CHECKS,
330
+ teamMembers: store.teamMembers,
331
+ secrets: store.secrets.map(redactSecret),
332
+ marketplacePlugins: store.marketplacePlugins,
333
+ evaluationSuites: store.evaluationSuites,
334
+ evaluationRuns: store.evaluationRuns,
335
+ usageSummary: summarizeUsageEvents(store.usageEvents),
336
+ securityAuditRuns: store.securityAuditRuns,
337
+ adminUsers: listAdminUsers(),
338
+ projectCollaborators: store.projectCollaborators,
339
+ remoteAccessConfigs: store.remoteAccessConfigs,
340
+ auditLog: store.auditLog,
341
+ };
342
+ }
343
+
344
+ export function createTeamMember(input = {}, actorId = null) {
345
+ const email = compact(input.email || input.username || '');
346
+ if (!email) throw new Error('Team member email or username is required.');
347
+ const store = readStore();
348
+ const member = {
349
+ id: crypto.randomUUID(),
350
+ email,
351
+ displayName: compact(input.displayName || email, 80),
352
+ role: normalizeRole(input.role || 'viewer'),
353
+ projectScopes: Array.isArray(input.projectScopes) ? input.projectScopes : [],
354
+ status: input.status || 'active',
355
+ createdAt: nowIso(),
356
+ updatedAt: nowIso(),
357
+ };
358
+ member.permissions = TEAM_ROLES[member.role];
359
+ store.teamMembers.unshift(member);
360
+ addAudit(store, 'team.member.created', actorId, { memberId: member.id, role: member.role });
361
+ writeStore(store);
362
+ return member;
363
+ }
364
+
365
+ export function updateTeamMember(memberId, patch = {}, actorId = null) {
366
+ const store = readStore();
367
+ let updated = null;
368
+ store.teamMembers = store.teamMembers.map((member) => {
369
+ if (member.id !== memberId) return member;
370
+ updated = {
371
+ ...member,
372
+ ...patch,
373
+ id: member.id,
374
+ role: normalizeRole(patch.role || member.role),
375
+ updatedAt: nowIso(),
376
+ };
377
+ updated.permissions = TEAM_ROLES[updated.role];
378
+ return updated;
379
+ });
380
+ if (updated) {
381
+ addAudit(store, 'team.member.updated', actorId, { memberId, role: updated.role });
382
+ writeStore(store);
383
+ }
384
+ return updated;
385
+ }
386
+
387
+ export function listAdminUsers() {
388
+ return userDb.listUsers().map((user) => ({
389
+ id: user.id,
390
+ username: user.username,
391
+ role: user.role || 'member',
392
+ status: user.is_active ? 'active' : 'disabled',
393
+ isActive: Boolean(user.is_active),
394
+ createdAt: user.created_at,
395
+ lastLogin: user.last_login,
396
+ }));
397
+ }
398
+
399
+ export async function createAdminUser(input = {}, actorId = null) {
400
+ const username = compact(input.username || input.email || '');
401
+ const password = String(input.password || '');
402
+ if (!username || password.length < 6) {
403
+ throw new Error('Admin user creation requires a username and a password with at least 6 characters.');
404
+ }
405
+
406
+ const role = normalizeRole(input.role || 'member');
407
+ const passwordHash = await bcrypt.hash(password, 12);
408
+ const user = userDb.createManagedUser(username, passwordHash, {
409
+ role,
410
+ is_active: input.status !== 'disabled',
411
+ });
412
+
413
+ const store = readStore();
414
+ const member = {
415
+ id: crypto.randomUUID(),
416
+ userId: user.id,
417
+ email: input.email || username,
418
+ displayName: compact(input.displayName || username, 80),
419
+ role,
420
+ projectScopes: Array.isArray(input.projectScopes) ? input.projectScopes : [],
421
+ status: input.status || 'active',
422
+ createdAt: nowIso(),
423
+ updatedAt: nowIso(),
424
+ permissions: TEAM_ROLES[role],
425
+ };
426
+ store.teamMembers.unshift(member);
427
+ addAudit(store, 'admin.user.created', actorId, { userId: user.id, username, role });
428
+ writeStore(store);
429
+ return {
430
+ ...user,
431
+ status: member.status,
432
+ permissions: member.permissions,
433
+ };
434
+ }
435
+
436
+ export function updateAdminUser(userId, patch = {}, actorId = null) {
437
+ const numericUserId = Number(userId);
438
+ const role = patch.role ? normalizeRole(patch.role) : undefined;
439
+ const isActive = patch.status === 'disabled' ? false : patch.status === 'active' ? true : undefined;
440
+ const user = userDb.updateUser(numericUserId, {
441
+ username: patch.username,
442
+ role,
443
+ is_active: isActive,
444
+ });
445
+ if (!user) return null;
446
+
447
+ const store = readStore();
448
+ store.teamMembers = store.teamMembers.map((member) => {
449
+ if (member.userId !== numericUserId) return member;
450
+ const nextRole = role || member.role;
451
+ const nextStatus = patch.status || member.status;
452
+ return {
453
+ ...member,
454
+ role: nextRole,
455
+ status: nextStatus,
456
+ permissions: TEAM_ROLES[nextRole] || TEAM_ROLES.viewer,
457
+ updatedAt: nowIso(),
458
+ };
459
+ });
460
+ addAudit(store, 'admin.user.updated', actorId, { userId: numericUserId, role: role || user.role, status: patch.status });
461
+ writeStore(store);
462
+ return {
463
+ ...user,
464
+ role: role || user.role || 'member',
465
+ status: user.is_active ? 'active' : 'disabled',
466
+ };
467
+ }
468
+
469
+ export function createProjectCollaborator(input = {}, actorId = null) {
470
+ const projectName = compactProjectIdentifier(input.projectName || input.project || '');
471
+ const projectPath = input.projectPath || null;
472
+ const targetUser = resolveUser(input);
473
+ const userRef = compact(input.userRef || input.email || input.username || targetUser?.username || '');
474
+ if (!projectName || !userRef) {
475
+ throw new Error('Project collaborator requires a project name and user reference.');
476
+ }
477
+
478
+ if (!targetUser) {
479
+ throw new Error('Create the user account before assigning project access.');
480
+ }
481
+
482
+ const role = ['partner', 'worker', 'reviewer', 'viewer'].includes(input.role) ? input.role : 'worker';
483
+ const capabilities = {
484
+ chatAgents: input.capabilities?.chatAgents !== false,
485
+ viewFiles: true,
486
+ editFiles: role === 'partner' || role === 'worker',
487
+ useShell: role === 'partner',
488
+ approveActions: role === 'partner' || role === 'reviewer',
489
+ manageSecrets: role === 'partner',
490
+ manageProjectSettings: role === 'partner',
491
+ };
492
+ const collaborator = {
493
+ id: crypto.randomUUID(),
494
+ projectName,
495
+ projectPath,
496
+ userId: targetUser.id,
497
+ userRef,
498
+ role,
499
+ capabilities: {
500
+ ...capabilities,
501
+ ...(input.capabilities && typeof input.capabilities === 'object' ? input.capabilities : {}),
502
+ },
503
+ allowedRoots: normalizeAllowedRoots(input.allowedRoots || input.allowedFolders || ['.']),
504
+ status: input.status || 'active',
505
+ createdAt: nowIso(),
506
+ updatedAt: nowIso(),
507
+ };
508
+ const store = readStore();
509
+ store.projectCollaborators.unshift(collaborator);
510
+ addAudit(store, 'project.collaborator.created', actorId, { collaboratorId: collaborator.id, projectName, userRef, role });
511
+ writeStore(store);
512
+ return collaborator;
513
+ }
514
+
515
+ export function updateProjectCollaborator(collaboratorId, patch = {}, actorId = null) {
516
+ const store = readStore();
517
+ let updated = null;
518
+ store.projectCollaborators = store.projectCollaborators.map((collaborator) => {
519
+ if (collaborator.id !== collaboratorId) return collaborator;
520
+ updated = {
521
+ ...collaborator,
522
+ ...patch,
523
+ id: collaborator.id,
524
+ capabilities: {
525
+ ...collaborator.capabilities,
526
+ ...(patch.capabilities && typeof patch.capabilities === 'object' ? patch.capabilities : {}),
527
+ },
528
+ allowedRoots: patch.allowedRoots || patch.allowedFolders
529
+ ? normalizeAllowedRoots(patch.allowedRoots || patch.allowedFolders)
530
+ : collaboratorAllowedRoots(collaborator),
531
+ updatedAt: nowIso(),
532
+ };
533
+ return updated;
534
+ });
535
+ if (updated) {
536
+ addAudit(store, 'project.collaborator.updated', actorId, { collaboratorId, role: updated.role, status: updated.status });
537
+ writeStore(store);
538
+ }
539
+ return updated;
540
+ }
541
+
542
+ export function createSecret(input = {}, actorId = null) {
543
+ const name = compact(input.name || input.envName || '');
544
+ const value = input.value;
545
+ if (!name || typeof value !== 'string') throw new Error('Secret name and string value are required.');
546
+ const scope = normalizeScope(input.scope || 'project');
547
+ const store = readStore();
548
+ const secret = {
549
+ id: crypto.randomUUID(),
550
+ name,
551
+ envName: compact(input.envName || name).replace(/[^A-Z0-9_]/gi, '_').toUpperCase(),
552
+ scope,
553
+ target: input.target || input.projectPath || input.provider || null,
554
+ createdAt: nowIso(),
555
+ updatedAt: nowIso(),
556
+ fingerprint: crypto.createHash('sha256').update(value).digest('hex').slice(0, 12),
557
+ sealedValue: sealSecret(value),
558
+ };
559
+ store.secrets = store.secrets.filter((existing) => !(existing.envName === secret.envName && existing.scope === secret.scope && existing.target === secret.target));
560
+ store.secrets.unshift(secret);
561
+ addAudit(store, 'secret.created', actorId, { secretId: secret.id, scope: secret.scope, envName: secret.envName });
562
+ writeStore(store);
563
+ return redactSecret(secret);
564
+ }
565
+
566
+ export function listSecrets() {
567
+ return readStore().secrets.map(redactSecret);
568
+ }
569
+
570
+ export function materializeScopedEnv(input = {}, options = {}) {
571
+ const store = readStore();
572
+ const env = {};
573
+ const included = [];
574
+ for (const secret of store.secrets) {
575
+ if (!scopeMatches(secret, input)) continue;
576
+ included.push({
577
+ id: secret.id,
578
+ envName: secret.envName,
579
+ scope: secret.scope,
580
+ target: secret.target,
581
+ redacted: '********',
582
+ });
583
+ if (options.reveal === true) {
584
+ env[secret.envName] = openSecret(secret.sealedValue);
585
+ }
586
+ }
587
+ return { env, included };
588
+ }
589
+
590
+ export function upsertMarketplacePlugin(input = {}, actorId = null) {
591
+ const pluginId = input.id || slugify(input.name || input.packageName || 'plugin');
592
+ const store = readStore();
593
+ const existing = store.marketplacePlugins.find((plugin) => plugin.id === pluginId);
594
+ const plugin = {
595
+ id: pluginId,
596
+ name: compact(input.name || pluginId, 100),
597
+ type: MARKETPLACE_PLUGIN_TYPES.includes(input.type) ? input.type : 'mcp-server',
598
+ source: input.source || input.packageName || input.repository || null,
599
+ permissionScopes: Array.isArray(input.permissionScopes) ? input.permissionScopes : [],
600
+ installCommand: input.installCommand || null,
601
+ status: input.status || existing?.status || 'available',
602
+ health: input.health || existing?.health || { status: 'unknown', checkedAt: null },
603
+ updatedAt: nowIso(),
604
+ createdAt: existing?.createdAt || nowIso(),
605
+ };
606
+ store.marketplacePlugins = [plugin, ...store.marketplacePlugins.filter((item) => item.id !== pluginId)];
607
+ addAudit(store, 'marketplace.plugin.upserted', actorId, { pluginId, type: plugin.type });
608
+ writeStore(store);
609
+ return plugin;
610
+ }
611
+
612
+ export function updateMarketplacePluginHealth(pluginId, health = {}, actorId = null) {
613
+ const store = readStore();
614
+ let updated = null;
615
+ store.marketplacePlugins = store.marketplacePlugins.map((plugin) => {
616
+ if (plugin.id !== pluginId) return plugin;
617
+ updated = {
618
+ ...plugin,
619
+ health: {
620
+ status: health.status || 'unknown',
621
+ message: health.message || '',
622
+ checkedAt: nowIso(),
623
+ },
624
+ updatedAt: nowIso(),
625
+ };
626
+ return updated;
627
+ });
628
+ if (updated) {
629
+ addAudit(store, 'marketplace.plugin.health_checked', actorId, { pluginId, status: updated.health.status });
630
+ writeStore(store);
631
+ }
632
+ return updated;
633
+ }
634
+
635
+ export function createEvaluationSuite(input = {}, actorId = null) {
636
+ const tasks = Array.isArray(input.tasks) ? input.tasks : [];
637
+ const suite = {
638
+ id: input.id || slugify(input.name || 'evaluation-suite'),
639
+ name: compact(input.name || 'Evaluation suite', 100),
640
+ description: compact(input.description || '', 240),
641
+ tasks: tasks.map((task, index) => ({
642
+ id: task.id || `task-${index + 1}`,
643
+ title: compact(task.title || `Task ${index + 1}`, 120),
644
+ acceptanceCriteria: Array.isArray(task.acceptanceCriteria) ? task.acceptanceCriteria : [],
645
+ projectPath: task.projectPath || null,
646
+ })),
647
+ createdAt: nowIso(),
648
+ updatedAt: nowIso(),
649
+ };
650
+ const store = readStore();
651
+ store.evaluationSuites = [suite, ...store.evaluationSuites.filter((item) => item.id !== suite.id)];
652
+ addAudit(store, 'eval.suite.upserted', actorId, { suiteId: suite.id, tasks: suite.tasks.length });
653
+ writeStore(store);
654
+ return suite;
655
+ }
656
+
657
+ export function createEvaluationRun(input = {}, actorId = null) {
658
+ const results = Array.isArray(input.results) ? input.results : [];
659
+ const passed = results.filter((result) => result.status === 'passed').length;
660
+ const run = {
661
+ id: crypto.randomUUID(),
662
+ suiteId: input.suiteId || null,
663
+ provider: input.provider || null,
664
+ model: input.model || null,
665
+ status: input.status || 'completed',
666
+ createdAt: nowIso(),
667
+ results,
668
+ summary: {
669
+ total: results.length,
670
+ passed,
671
+ failed: results.filter((result) => result.status === 'failed').length,
672
+ passRate: results.length ? Math.round((passed / results.length) * 1000) / 10 : 0,
673
+ averageLatencyMs: average(results.map((result) => Number(result.latencyMs || 0)).filter(Boolean)),
674
+ },
675
+ };
676
+ const store = readStore();
677
+ store.evaluationRuns.unshift(run);
678
+ addAudit(store, 'eval.run.created', actorId, { runId: run.id, suiteId: run.suiteId, passRate: run.summary.passRate });
679
+ writeStore(store);
680
+ return run;
681
+ }
682
+
683
+ function average(values) {
684
+ if (!values.length) return 0;
685
+ return Math.round(values.reduce((sum, value) => sum + value, 0) / values.length);
686
+ }
687
+
688
+ export function recordUsageEvent(input = {}, actorId = null) {
689
+ const event = {
690
+ id: crypto.randomUUID(),
691
+ createdAt: input.createdAt || nowIso(),
692
+ provider: input.provider || 'unknown',
693
+ model: input.model || 'unknown',
694
+ workflow: input.workflow || input.source || 'manual',
695
+ inputTokens: Number(input.inputTokens || 0),
696
+ outputTokens: Number(input.outputTokens || 0),
697
+ costUsd: Number(input.costUsd || 0),
698
+ latencyMs: Number(input.latencyMs || 0),
699
+ status: input.status || 'ok',
700
+ };
701
+ const store = readStore();
702
+ store.usageEvents.unshift(event);
703
+ store.usageEvents = store.usageEvents.slice(0, 2000);
704
+ addAudit(store, 'usage.event.recorded', actorId, { provider: event.provider, model: event.model, status: event.status });
705
+ writeStore(store);
706
+ return event;
707
+ }
708
+
709
+ export function summarizeUsageEvents(events = readStore().usageEvents) {
710
+ const groups = new Map();
711
+ for (const event of events) {
712
+ const key = `${event.provider}:${event.model}:${event.workflow}`;
713
+ const current = groups.get(key) || {
714
+ provider: event.provider,
715
+ model: event.model,
716
+ workflow: event.workflow,
717
+ runs: 0,
718
+ errors: 0,
719
+ inputTokens: 0,
720
+ outputTokens: 0,
721
+ totalTokens: 0,
722
+ costUsd: 0,
723
+ latencyMs: 0,
724
+ };
725
+ current.runs += 1;
726
+ current.errors += event.status === 'error' ? 1 : 0;
727
+ current.inputTokens += event.inputTokens;
728
+ current.outputTokens += event.outputTokens;
729
+ current.totalTokens += event.inputTokens + event.outputTokens;
730
+ current.costUsd += event.costUsd;
731
+ current.latencyMs += event.latencyMs;
732
+ groups.set(key, current);
733
+ }
734
+ return Array.from(groups.values()).map((group) => ({
735
+ ...group,
736
+ costUsd: Math.round(group.costUsd * 10000) / 10000,
737
+ averageLatencyMs: group.runs ? Math.round(group.latencyMs / group.runs) : 0,
738
+ errorRate: group.runs ? Math.round((group.errors / group.runs) * 1000) / 10 : 0,
739
+ latencyMs: undefined,
740
+ }));
741
+ }
742
+
743
+ export function createSecurityAuditRun(input = {}, actorId = null) {
744
+ const checks = Array.isArray(input.checks) && input.checks.length
745
+ ? input.checks.filter((check) => SECURITY_AUDIT_CHECKS.includes(check))
746
+ : SECURITY_AUDIT_CHECKS;
747
+ const findings = Array.isArray(input.findings) ? input.findings : [];
748
+ const run = {
749
+ id: crypto.randomUUID(),
750
+ protocol: 'pixcode.security-audit.v1',
751
+ status: input.status || 'queued',
752
+ projectName: input.projectName || null,
753
+ projectPath: input.projectPath || null,
754
+ checks,
755
+ createdAt: nowIso(),
756
+ findings: findings.map((finding, index) => ({
757
+ id: finding.id || `finding-${index + 1}`,
758
+ severity: finding.severity || 'medium',
759
+ title: compact(finding.title || 'Security finding', 140),
760
+ file: finding.file || null,
761
+ recommendation: finding.recommendation || null,
762
+ })),
763
+ checklist: checks.map((check) => ({
764
+ check,
765
+ status: 'pending',
766
+ })),
767
+ };
768
+ const store = readStore();
769
+ store.securityAuditRuns.unshift(run);
770
+ addAudit(store, 'security.audit.created', actorId, { runId: run.id, checks });
771
+ writeStore(store);
772
+ return run;
773
+ }
774
+
775
+ export function getAuditLog(filters = {}) {
776
+ const store = readStore();
777
+ let entries = store.auditLog;
778
+ if (filters.userId) {
779
+ entries = entries.filter((entry) => String(entry.actorId) === String(filters.userId));
780
+ }
781
+ if (filters.eventType) {
782
+ entries = entries.filter((entry) => entry.action === filters.eventType || entry.action.includes(filters.eventType));
783
+ }
784
+ if (filters.projectName) {
785
+ entries = entries.filter((entry) => entry.details?.projectName === filters.projectName);
786
+ }
787
+ if (filters.severity) {
788
+ entries = entries.filter((entry) => entry.details?.severity === filters.severity);
789
+ }
790
+ return entries.slice(0, Number(filters.limit || 200));
791
+ }
792
+
793
+ export function exportAuditLog(format = 'json', filters = {}) {
794
+ const entries = getAuditLog(filters);
795
+ if (format === 'csv') {
796
+ const header = ['id', 'createdAt', 'actorId', 'action', 'details'];
797
+ const lines = entries.map((entry) => header.map((field) => {
798
+ const value = field === 'details' ? JSON.stringify(entry.details || {}) : entry[field];
799
+ return `"${String(value ?? '').replace(/"/g, '""')}"`;
800
+ }).join(','));
801
+ return [header.join(','), ...lines].join('\n');
802
+ }
803
+ return JSON.stringify(entries, null, 2);
804
+ }
805
+
806
+ function normalizeAccessMode(mode) {
807
+ return ['lan', 'tailscale', 'cloudflare_tunnel', 'custom_domain'].includes(mode) ? mode : 'lan';
808
+ }
809
+
810
+ function resolveTailscaleInstallPlan() {
811
+ const platform = os.platform();
812
+ if (platform === 'darwin') {
813
+ return {
814
+ platform,
815
+ command: 'brew',
816
+ args: ['install', 'tailscale'],
817
+ displayCommand: 'brew install tailscale',
818
+ docsUrl: 'https://tailscale.com/download/mac',
819
+ note: 'If Homebrew is not installed, open the download page and install the macOS app.',
820
+ };
821
+ }
822
+ if (platform === 'win32') {
823
+ return {
824
+ platform,
825
+ command: 'winget',
826
+ args: ['install', '--id', 'Tailscale.Tailscale', '-e', '--silent'],
827
+ displayCommand: 'winget install --id Tailscale.Tailscale -e --silent',
828
+ docsUrl: 'https://tailscale.com/download/windows',
829
+ note: 'If winget is unavailable, install from the Tailscale download page.',
830
+ };
831
+ }
832
+ return {
833
+ platform,
834
+ command: 'sh',
835
+ args: ['-c', 'curl -fsSL https://tailscale.com/install.sh | sh'],
836
+ displayCommand: 'curl -fsSL https://tailscale.com/install.sh | sh',
837
+ docsUrl: 'https://tailscale.com/download/linux',
838
+ note: 'Linux install may require root privileges. If this fails, run the command with sudo in a terminal.',
839
+ };
840
+ }
841
+
842
+ function extractFirstUrl(text = '') {
843
+ return String(text).match(/https?:\/\/[^\s]+/i)?.[0] || null;
844
+ }
845
+
846
+ function runTailscaleCommand(command, args, options = {}) {
847
+ return new Promise((resolve) => {
848
+ const child = spawn(command, args, {
849
+ shell: false,
850
+ windowsHide: true,
851
+ env: process.env,
852
+ ...options,
853
+ });
854
+ let stdout = '';
855
+ let stderr = '';
856
+ child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
857
+ child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
858
+ child.on('error', (error) => {
859
+ resolve({ ok: false, code: null, stdout, stderr, error: error.message });
860
+ });
861
+ child.on('close', (code) => {
862
+ resolve({ ok: code === 0, code, stdout, stderr, error: code === 0 ? null : `${command} exited with code ${code}` });
863
+ });
864
+ });
865
+ }
866
+
867
+ function normalizePublicUrl(value) {
868
+ const raw = typeof value === 'string' ? value.trim() : '';
869
+ if (!raw) return null;
870
+ const url = new URL(raw);
871
+ if (!['http:', 'https:'].includes(url.protocol)) {
872
+ throw new Error('Remote access URL must use http or https.');
873
+ }
874
+ url.pathname = url.pathname.replace(/\/+$/, '');
875
+ url.search = '';
876
+ url.hash = '';
877
+ return url.toString().replace(/\/$/, '');
878
+ }
879
+
880
+ export function saveRemoteAccessConfig(input = {}, actorId = null) {
881
+ const mode = normalizeAccessMode(input.mode);
882
+ const id = input.id || mode;
883
+ const config = {
884
+ id,
885
+ mode,
886
+ label: compact(input.label || mode.replace(/_/g, ' '), 80),
887
+ url: input.url ? normalizePublicUrl(input.url) : null,
888
+ targetPort: Number(input.targetPort || process.env.SERVER_PORT || 3001),
889
+ public: mode === 'cloudflare_tunnel' || mode === 'custom_domain',
890
+ tlsRequired: mode === 'cloudflare_tunnel' || mode === 'custom_domain',
891
+ privateOnly: mode === 'tailscale' || mode === 'lan',
892
+ status: input.status || 'configured',
893
+ notes: compact(input.notes || '', 240),
894
+ updatedAt: nowIso(),
895
+ createdAt: input.createdAt || nowIso(),
896
+ lastHealth: input.lastHealth || null,
897
+ };
898
+ const store = readStore();
899
+ store.remoteAccessConfigs = [config, ...store.remoteAccessConfigs.filter((item) => item.id !== id)];
900
+ addAudit(store, 'remote.access.configured', actorId, { mode, url: config.url, public: config.public });
901
+ writeStore(store);
902
+ return config;
903
+ }
904
+
905
+ export function getRemoteAccessState() {
906
+ const store = readStore();
907
+ return {
908
+ host: os.hostname(),
909
+ platform: os.platform(),
910
+ localUrl: `http://127.0.0.1:${process.env.SERVER_PORT || 3001}`,
911
+ configs: store.remoteAccessConfigs,
912
+ recommendations: [
913
+ {
914
+ mode: 'tailscale',
915
+ label: 'Tailscale private network',
916
+ recommendedWhen: 'No stable domain, no public IP, private team access.',
917
+ },
918
+ {
919
+ mode: 'cloudflare_tunnel',
920
+ label: 'Cloudflare Tunnel',
921
+ recommendedWhen: 'Stable public HTTPS URL without opening inbound ports.',
922
+ },
923
+ {
924
+ mode: 'custom_domain',
925
+ label: 'Custom domain / reverse proxy',
926
+ recommendedWhen: 'Existing domain, reverse proxy, and TLS termination.',
927
+ },
928
+ ],
929
+ };
930
+ }
931
+
932
+ export async function detectTailscaleStatus() {
933
+ const installPlan = resolveTailscaleInstallPlan();
934
+ try {
935
+ const { stdout } = await execFileAsync('tailscale', ['status', '--json'], { timeout: 5000 });
936
+ const status = JSON.parse(stdout || '{}');
937
+ const self = status.Self || {};
938
+ const tailscaleIps = Array.isArray(self.TailscaleIPs) ? self.TailscaleIPs : [];
939
+ return {
940
+ installed: true,
941
+ loggedIn: Boolean(self.ID || self.DNSName || tailscaleIps.length),
942
+ backendState: status.BackendState || null,
943
+ deviceName: self.HostName || os.hostname(),
944
+ magicDnsName: self.DNSName || null,
945
+ tailscaleIp: tailscaleIps[0] || null,
946
+ pixcodeUrl: tailscaleIps[0] ? `http://${tailscaleIps[0]}:${process.env.SERVER_PORT || 3001}` : null,
947
+ installUrl: 'https://tailscale.com/download',
948
+ installPlan,
949
+ checkedAt: nowIso(),
950
+ message: tailscaleIps[0] ? 'Tailscale is ready for private Pixcode access.' : 'Tailscale CLI is installed but no device IP was detected.',
951
+ };
952
+ } catch (error) {
953
+ const isMissing = error?.code === 'ENOENT';
954
+ return {
955
+ installed: false,
956
+ loggedIn: false,
957
+ backendState: 'missing',
958
+ deviceName: os.hostname(),
959
+ magicDnsName: null,
960
+ tailscaleIp: null,
961
+ pixcodeUrl: null,
962
+ installUrl: 'https://tailscale.com/download',
963
+ installPlan,
964
+ checkedAt: nowIso(),
965
+ message: isMissing
966
+ ? 'Tailscale is optional. Use the LAN links now, or install Tailscale from Settings > Access for private team access without a public domain.'
967
+ : (error?.message || 'Tailscale status could not be read.'),
968
+ };
969
+ }
970
+ }
971
+
972
+ export async function installTailscale(actorId = null) {
973
+ const plan = resolveTailscaleInstallPlan();
974
+ const result = await runTailscaleCommand(plan.command, plan.args);
975
+ const store = readStore();
976
+ addAudit(store, 'remote.access.tailscale.install', actorId, {
977
+ platform: plan.platform,
978
+ ok: result.ok,
979
+ command: plan.displayCommand,
980
+ });
981
+ writeStore(store);
982
+ return {
983
+ ...result,
984
+ plan,
985
+ message: result.ok
986
+ ? 'Tailscale install command completed. Run login/connect next.'
987
+ : `Install command failed. ${plan.note}`,
988
+ };
989
+ }
990
+
991
+ export async function loginTailscale(actorId = null) {
992
+ const result = await runTailscaleCommand('tailscale', ['up']);
993
+ const combinedOutput = `${result.stdout || ''}\n${result.stderr || ''}`;
994
+ const authUrl = extractFirstUrl(combinedOutput);
995
+ const store = readStore();
996
+ addAudit(store, 'remote.access.tailscale.login', actorId, {
997
+ ok: result.ok,
998
+ authUrl: Boolean(authUrl),
999
+ });
1000
+ writeStore(store);
1001
+ return {
1002
+ ...result,
1003
+ authUrl,
1004
+ message: result.ok
1005
+ ? 'Tailscale is connected.'
1006
+ : (authUrl ? 'Open the login URL to finish connecting this device.' : 'Tailscale login command failed.'),
1007
+ tailscale: await detectTailscaleStatus(),
1008
+ };
1009
+ }
1010
+
1011
+ export async function checkRemoteAccessHealth(input = {}, actorId = null) {
1012
+ const url = normalizePublicUrl(input.url || input.remoteUrl || '');
1013
+ const checkedAt = nowIso();
1014
+ if (!url) {
1015
+ throw new Error('Remote access health check requires a URL.');
1016
+ }
1017
+ const parsed = new URL(url);
1018
+ const controller = new AbortController();
1019
+ const timeout = setTimeout(() => controller.abort(), Number(input.timeoutMs || 5000));
1020
+ try {
1021
+ const response = await fetch(`${url}/api/auth/status`, { signal: controller.signal });
1022
+ const health = {
1023
+ url,
1024
+ reachable: response.ok,
1025
+ checkedAt,
1026
+ statusCode: response.status,
1027
+ https: parsed.protocol === 'https:',
1028
+ websocketExpected: true,
1029
+ message: response.ok ? 'Pixcode auth endpoint is reachable.' : `Pixcode returned HTTP ${response.status}.`,
1030
+ };
1031
+ const store = readStore();
1032
+ addAudit(store, 'remote.access.health_checked', actorId, { url, reachable: health.reachable, https: health.https });
1033
+ writeStore(store);
1034
+ return health;
1035
+ } catch (error) {
1036
+ const health = {
1037
+ url,
1038
+ reachable: false,
1039
+ checkedAt,
1040
+ statusCode: null,
1041
+ https: parsed.protocol === 'https:',
1042
+ websocketExpected: true,
1043
+ message: error?.name === 'AbortError' ? 'Health check timed out.' : (error?.message || 'Remote access URL is unreachable.'),
1044
+ };
1045
+ const store = readStore();
1046
+ addAudit(store, 'remote.access.health_checked', actorId, { url, reachable: false, https: health.https });
1047
+ writeStore(store);
1048
+ return health;
1049
+ } finally {
1050
+ clearTimeout(timeout);
1051
+ }
1052
+ }