@pixelbyte-software/pixcode 1.51.7 → 1.51.9

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 (307) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +155 -155
  3. package/LICENSE +718 -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 +419 -419
  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/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index-BvQgSoyC.js → index-Gs7C4hZT.js} +70 -70
  15. package/dist/clear-cache.html +85 -85
  16. package/dist/convert-icons.md +52 -52
  17. package/dist/docs.html +308 -308
  18. package/dist/favicon.svg +8 -8
  19. package/dist/features.html +133 -133
  20. package/dist/generate-icons.js +48 -48
  21. package/dist/humans.txt +15 -15
  22. package/dist/icons/codex-white.svg +3 -3
  23. package/dist/icons/codex.svg +3 -3
  24. package/dist/icons/cursor-white.svg +11 -11
  25. package/dist/icons/icon-128x128.svg +9 -9
  26. package/dist/icons/icon-144x144.svg +9 -9
  27. package/dist/icons/icon-152x152.svg +9 -9
  28. package/dist/icons/icon-192x192.svg +9 -9
  29. package/dist/icons/icon-384x384.svg +9 -9
  30. package/dist/icons/icon-512x512.svg +9 -9
  31. package/dist/icons/icon-72x72.svg +9 -9
  32. package/dist/icons/icon-96x96.svg +9 -9
  33. package/dist/icons/icon-template.svg +9 -9
  34. package/dist/icons/qwen-logo.svg +14 -14
  35. package/dist/index.html +58 -58
  36. package/dist/landing.html +268 -268
  37. package/dist/llms-full.txt +119 -119
  38. package/dist/llms.txt +53 -53
  39. package/dist/logo.svg +12 -12
  40. package/dist/manifest.json +60 -60
  41. package/dist/openapi.yaml +1696 -1696
  42. package/dist/orchestration.html +125 -125
  43. package/dist/robots.txt +4 -4
  44. package/dist/site.css +692 -692
  45. package/dist/sitemap.xml +51 -51
  46. package/dist/sw.js +132 -132
  47. package/dist-server/server/cli.js +96 -96
  48. package/dist-server/server/daemon/manager.js +33 -33
  49. package/dist-server/server/daemon-manager.js +64 -64
  50. package/dist-server/server/index.js +91 -65
  51. package/dist-server/server/index.js.map +1 -1
  52. package/dist-server/server/routes/commands.js +25 -25
  53. package/dist-server/server/routes/git.js +17 -17
  54. package/dist-server/server/routes/live-view.js +46 -46
  55. package/dist-server/server/services/hermes-gateway.js +5 -5
  56. package/dist-server/server/services/public-api-manifest.js +51 -51
  57. package/package.json +222 -222
  58. package/scripts/fix-node-pty.js +67 -67
  59. package/scripts/github/create-v1.38-issues.mjs +351 -351
  60. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  61. package/scripts/hermes/configure-pixcode-mcp.mjs +165 -165
  62. package/scripts/hermes/pixcode-mcp-server.mjs +1009 -1009
  63. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  64. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  65. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  66. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  67. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  68. package/scripts/smoke/chat-session-state.mjs +19 -19
  69. package/scripts/smoke/code-editor-theme.mjs +55 -55
  70. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  71. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  72. package/scripts/smoke/command-center-non-git.mjs +46 -46
  73. package/scripts/smoke/context-packet.mjs +43 -43
  74. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  75. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  76. package/scripts/smoke/default-landing-routing.mjs +33 -33
  77. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  78. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  79. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  80. package/scripts/smoke/git-install-update.mjs +255 -255
  81. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  82. package/scripts/smoke/hermes-api-install.mjs +56 -56
  83. package/scripts/smoke/hermes-gateway-persistence.mjs +104 -104
  84. package/scripts/smoke/hermes-mcp-pixcode-roundtrip.mjs +426 -426
  85. package/scripts/smoke/hermes-rest-chat-api.mjs +162 -162
  86. package/scripts/smoke/hermes-rest-chat-live.mjs +45 -45
  87. package/scripts/smoke/hermes-rest-codex-launch.mjs +209 -209
  88. package/scripts/smoke/hermes-rest-gateway.mjs +79 -79
  89. package/scripts/smoke/hermes-rest-live.mjs +42 -42
  90. package/scripts/smoke/hermes-roundtrip.mjs +167 -167
  91. package/scripts/smoke/hermes-settings-commands.mjs +349 -349
  92. package/scripts/smoke/hermes-smoke-launcher-guard.mjs +34 -34
  93. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  94. package/scripts/smoke/live-view-environment.mjs +92 -92
  95. package/scripts/smoke/live-view-integration.mjs +450 -450
  96. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  97. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  98. package/scripts/smoke/model-registry.mjs +36 -36
  99. package/scripts/smoke/multi-project-ui.mjs +45 -45
  100. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  101. package/scripts/smoke/notification-center.mjs +87 -87
  102. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  103. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  104. package/scripts/smoke/orchestration-api.mjs +172 -172
  105. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  106. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  107. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  108. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  109. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  110. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  111. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  112. package/scripts/smoke/permission-policy.mjs +50 -50
  113. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  114. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  115. package/scripts/smoke/provider-rest-api.mjs +124 -124
  116. package/scripts/smoke/provider-selection-status.mjs +52 -52
  117. package/scripts/smoke/run-state-refresh.mjs +52 -52
  118. package/scripts/smoke/runtime-manager.mjs +99 -99
  119. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  120. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  121. package/scripts/smoke/static-root-routing.mjs +21 -21
  122. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  123. package/scripts/smoke/taskmaster-config.mjs +24 -24
  124. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  125. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  126. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  127. package/scripts/smoke/telegram-control.mjs +242 -242
  128. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  129. package/scripts/smoke/update-issue-progress.mjs +69 -69
  130. package/scripts/smoke/update-ux.mjs +55 -55
  131. package/scripts/smoke/v138-completion.mjs +132 -132
  132. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  133. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  134. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  135. package/scripts/smoke/v143-remote-control.mjs +76 -76
  136. package/scripts/smoke/v144-production-loop.mjs +47 -47
  137. package/scripts/smoke/v145-platformization.mjs +46 -46
  138. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  139. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  140. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  141. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  142. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  143. package/scripts/smoke/workflow-templates.mjs +43 -43
  144. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  145. package/scripts/update-git-install.mjs +283 -283
  146. package/server/claude-sdk.js +920 -920
  147. package/server/cli.js +1035 -1035
  148. package/server/constants/config.js +4 -4
  149. package/server/cursor-cli.js +344 -344
  150. package/server/daemon/manager.js +563 -563
  151. package/server/daemon-manager.js +964 -964
  152. package/server/database/db.js +895 -895
  153. package/server/database/json-store.js +197 -197
  154. package/server/gemini-cli.js +550 -550
  155. package/server/gemini-response-handler.js +79 -79
  156. package/server/index.js +111 -81
  157. package/server/load-env.js +35 -35
  158. package/server/middleware/auth.js +155 -155
  159. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  160. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  161. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  162. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  163. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  164. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  165. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +100 -100
  166. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  167. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  168. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  169. package/server/modules/orchestration/a2a/routes.ts +590 -590
  170. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  171. package/server/modules/orchestration/a2a/types.ts +126 -126
  172. package/server/modules/orchestration/a2a/validator.ts +113 -113
  173. package/server/modules/orchestration/hermes/hermes.routes.ts +642 -642
  174. package/server/modules/orchestration/index.ts +101 -101
  175. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  176. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  177. package/server/modules/orchestration/preview/types.ts +19 -19
  178. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  179. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  180. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +64 -64
  181. package/server/modules/orchestration/tasks/orchestration-task.service.ts +209 -209
  182. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  183. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  184. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  185. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  186. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  187. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  188. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  189. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  190. package/server/modules/orchestration/workflows/workflow-runner.ts +2070 -2070
  191. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  192. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  193. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  194. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  195. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  196. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  197. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  198. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  199. package/server/modules/orchestration/workspace/types.ts +52 -52
  200. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  201. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  202. package/server/modules/providers/index.ts +2 -2
  203. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  204. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  205. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  206. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  207. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  208. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  209. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  210. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  211. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  212. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  213. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  214. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  215. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  216. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  217. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  218. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  219. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  220. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  221. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  222. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  223. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  224. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  225. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  226. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  227. package/server/modules/providers/provider.registry.ts +40 -40
  228. package/server/modules/providers/provider.routes.ts +891 -891
  229. package/server/modules/providers/services/mcp.service.ts +86 -86
  230. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  231. package/server/modules/providers/services/sessions.service.ts +45 -45
  232. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  233. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  234. package/server/modules/providers/shared/provider-configs.ts +142 -142
  235. package/server/modules/providers/tests/mcp.test.ts +293 -293
  236. package/server/openai-codex.js +462 -462
  237. package/server/opencode-cli.js +491 -491
  238. package/server/opencode-response-handler.js +111 -111
  239. package/server/projects.js +3008 -3008
  240. package/server/qwen-code-cli.js +410 -410
  241. package/server/qwen-response-handler.js +73 -73
  242. package/server/routes/agent.js +1435 -1435
  243. package/server/routes/auth.js +142 -142
  244. package/server/routes/codex.js +20 -20
  245. package/server/routes/commands.js +538 -538
  246. package/server/routes/cursor.js +61 -61
  247. package/server/routes/diagnostics.js +41 -41
  248. package/server/routes/gemini.js +25 -25
  249. package/server/routes/git.js +1641 -1641
  250. package/server/routes/live-view.js +387 -387
  251. package/server/routes/mcp-utils.js +13 -13
  252. package/server/routes/messages.js +50 -50
  253. package/server/routes/network.js +117 -117
  254. package/server/routes/platformization.js +182 -182
  255. package/server/routes/plugins.js +320 -320
  256. package/server/routes/production-agent-loop.js +90 -90
  257. package/server/routes/projects.js +911 -911
  258. package/server/routes/public-api.js +34 -34
  259. package/server/routes/qwen.js +27 -27
  260. package/server/routes/remote.js +50 -50
  261. package/server/routes/settings.js +321 -321
  262. package/server/routes/telegram.js +140 -140
  263. package/server/routes/user.js +125 -125
  264. package/server/routes/webhooks.js +63 -63
  265. package/server/services/control-room.js +102 -102
  266. package/server/services/diagnostics.js +165 -165
  267. package/server/services/external-access.js +375 -375
  268. package/server/services/hermes-gateway.js +1562 -1562
  269. package/server/services/hermes-install-jobs.js +729 -729
  270. package/server/services/install-jobs.js +715 -715
  271. package/server/services/live-view.js +956 -956
  272. package/server/services/managed-runtimes.js +493 -493
  273. package/server/services/model-registry.js +144 -144
  274. package/server/services/notification-orchestrator.js +365 -365
  275. package/server/services/notification-taxonomy.js +204 -204
  276. package/server/services/platformization.js +773 -773
  277. package/server/services/production-agent-loop.js +248 -248
  278. package/server/services/provider-cli-versions.js +149 -149
  279. package/server/services/provider-credentials.js +189 -189
  280. package/server/services/provider-models.js +396 -396
  281. package/server/services/public-api-manifest.js +190 -190
  282. package/server/services/remote-connection.js +127 -127
  283. package/server/services/runtime-manager.js +323 -323
  284. package/server/services/startup-update.js +234 -234
  285. package/server/services/telegram/bot.js +331 -331
  286. package/server/services/telegram/control-center.js +979 -979
  287. package/server/services/telegram/telegram-http-client.js +151 -151
  288. package/server/services/telegram/translations.js +340 -340
  289. package/server/services/vapid-keys.js +36 -36
  290. package/server/services/webhooks.js +216 -216
  291. package/server/sessionManager.js +225 -225
  292. package/server/shared/interfaces.ts +54 -54
  293. package/server/shared/types.ts +172 -172
  294. package/server/shared/utils.ts +193 -193
  295. package/server/tsconfig.json +36 -36
  296. package/server/utils/colors.js +21 -21
  297. package/server/utils/commandParser.js +305 -305
  298. package/server/utils/frontmatter.js +18 -18
  299. package/server/utils/gitConfig.js +34 -34
  300. package/server/utils/plugin-loader.js +457 -457
  301. package/server/utils/plugin-process-manager.js +185 -185
  302. package/server/utils/port-access.js +209 -209
  303. package/server/utils/runtime-paths.js +37 -37
  304. package/server/utils/url-detection.js +71 -71
  305. package/server/vite-daemon.js +79 -79
  306. package/shared/modelConstants.js +161 -161
  307. package/shared/networkHosts.js +22 -22
@@ -2,121 +2,121 @@ import crypto from 'node:crypto';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
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';
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
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
-
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
120
  function compact(text, max = 120) {
121
121
  const value = String(text || '').replace(/\s+/g, ' ').trim();
122
122
  return value.length > max ? value.slice(0, max).replace(/[-_\s]+$/g, '') : value;
@@ -125,26 +125,26 @@ function compact(text, max = 120) {
125
125
  function compactProjectIdentifier(value) {
126
126
  return String(value || '').replace(/\s+/g, ' ').trim();
127
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
-
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
148
  function normalizeRole(role) {
149
149
  return TEAM_ROLES[role] ? role : 'viewer';
150
150
  }
@@ -271,201 +271,201 @@ export function filterProjectsForUser(projects = [], user) {
271
271
  if (isAdminUser(user)) return projects;
272
272
  return projects.filter((project) => userHasProjectAccess(user, project, 'viewFiles'));
273
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
-
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
469
  export function createProjectCollaborator(input = {}, actorId = null) {
470
470
  const projectName = compactProjectIdentifier(input.projectName || input.project || '');
471
471
  const projectPath = input.projectPath || null;
@@ -478,49 +478,49 @@ export function createProjectCollaborator(input = {}, actorId = null) {
478
478
  if (!targetUser) {
479
479
  throw new Error('Create the user account before assigning project access.');
480
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 = {
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
493
  id: crypto.randomUUID(),
494
494
  projectName,
495
495
  projectPath,
496
496
  userId: targetUser.id,
497
497
  userRef,
498
- role,
498
+ role,
499
499
  capabilities: {
500
500
  ...capabilities,
501
501
  ...(input.capabilities && typeof input.capabilities === 'object' ? input.capabilities : {}),
502
502
  },
503
503
  allowedRoots: normalizeAllowedRoots(input.allowedRoots || input.allowedFolders || ['.']),
504
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,
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
524
  capabilities: {
525
525
  ...collaborator.capabilities,
526
526
  ...(patch.capabilities && typeof patch.capabilities === 'object' ? patch.capabilities : {}),
@@ -529,280 +529,280 @@ export function updateProjectCollaborator(collaboratorId, patch = {}, actorId =
529
529
  ? normalizeAllowedRoots(patch.allowedRoots || patch.allowedFolders)
530
530
  : collaboratorAllowedRoots(collaborator),
531
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
-
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
806
  function normalizeAccessMode(mode) {
807
807
  return ['lan', 'tailscale', 'cloudflare_tunnel', 'custom_domain'].includes(mode) ? mode : 'lan';
808
808
  }
@@ -863,108 +863,108 @@ function runTailscaleCommand(command, args, options = {}) {
863
863
  });
864
864
  });
865
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
-
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
932
  export async function detectTailscaleStatus() {
933
933
  const installPlan = resolveTailscaleInstallPlan();
934
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,
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
947
  installUrl: 'https://tailscale.com/download',
948
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,
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
962
  installUrl: 'https://tailscale.com/download',
963
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.'),
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
968
  };
969
969
  }
970
970
  }
@@ -1007,46 +1007,46 @@ export async function loginTailscale(actorId = null) {
1007
1007
  tailscale: await detectTailscaleStatus(),
1008
1008
  };
1009
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
- }
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
+ }