@pixelbyte-software/pixcode 1.54.9 → 1.54.11

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 (288) 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/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index-Bm6uAqKU.js → index-Bcqs_1vc.js} +114 -114
  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/features.html +133 -133
  19. package/dist/generate-icons.js +48 -48
  20. package/dist/humans.txt +15 -15
  21. package/dist/icons/codex-white.svg +3 -3
  22. package/dist/icons/codex.svg +3 -3
  23. package/dist/icons/cursor-white.svg +11 -11
  24. package/dist/icons/qwen-logo.svg +14 -14
  25. package/dist/index.html +58 -58
  26. package/dist/landing.html +268 -268
  27. package/dist/llms-full.txt +119 -119
  28. package/dist/llms.txt +53 -53
  29. package/dist/manifest.json +60 -60
  30. package/dist/openapi.yaml +1696 -1696
  31. package/dist/orchestration.html +125 -125
  32. package/dist/robots.txt +4 -4
  33. package/dist/site.css +692 -692
  34. package/dist/sitemap.xml +51 -51
  35. package/dist/sw.js +132 -132
  36. package/dist-server/server/cli.js +100 -100
  37. package/dist-server/server/daemon/manager.js +33 -33
  38. package/dist-server/server/daemon-manager.js +64 -64
  39. package/dist-server/server/index.js +13 -0
  40. package/dist-server/server/index.js.map +1 -1
  41. package/dist-server/server/routes/agent.js +10 -1
  42. package/dist-server/server/routes/agent.js.map +1 -1
  43. package/dist-server/server/routes/commands.js +25 -25
  44. package/dist-server/server/routes/git.js +17 -17
  45. package/dist-server/server/routes/live-view.js +46 -46
  46. package/dist-server/server/services/public-api-manifest.js +51 -51
  47. package/dist-server/server/sessionManager.js +5 -5
  48. package/dist-server/server/sessionManager.js.map +1 -1
  49. package/package.json +224 -224
  50. package/scripts/fix-node-pty.js +67 -67
  51. package/scripts/github/create-v1.38-issues.mjs +351 -351
  52. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  53. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  54. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  55. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  56. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  57. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  58. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  59. package/scripts/smoke/chat-session-state.mjs +19 -19
  60. package/scripts/smoke/code-editor-theme.mjs +55 -55
  61. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  62. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  63. package/scripts/smoke/command-center-non-git.mjs +46 -46
  64. package/scripts/smoke/context-packet.mjs +43 -43
  65. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  66. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  67. package/scripts/smoke/default-landing-routing.mjs +33 -33
  68. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  69. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  70. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  71. package/scripts/smoke/git-install-update.mjs +255 -255
  72. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  73. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  74. package/scripts/smoke/live-view-environment.mjs +92 -92
  75. package/scripts/smoke/live-view-integration.mjs +450 -450
  76. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  77. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  78. package/scripts/smoke/mobile-ux.mjs +76 -76
  79. package/scripts/smoke/model-registry.mjs +36 -36
  80. package/scripts/smoke/multi-project-ui.mjs +45 -45
  81. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  82. package/scripts/smoke/notification-center.mjs +87 -87
  83. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  84. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  85. package/scripts/smoke/orchestration-api.mjs +172 -172
  86. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  87. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  88. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  89. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  90. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  91. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  92. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  93. package/scripts/smoke/permission-policy.mjs +50 -50
  94. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  95. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  96. package/scripts/smoke/provider-rest-api.mjs +124 -124
  97. package/scripts/smoke/provider-selection-status.mjs +52 -52
  98. package/scripts/smoke/run-state-refresh.mjs +52 -52
  99. package/scripts/smoke/runtime-manager.mjs +99 -99
  100. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  101. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  102. package/scripts/smoke/static-root-routing.mjs +21 -21
  103. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  104. package/scripts/smoke/taskmaster-config.mjs +24 -24
  105. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  106. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  107. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  108. package/scripts/smoke/telegram-control.mjs +331 -331
  109. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  110. package/scripts/smoke/update-issue-progress.mjs +69 -69
  111. package/scripts/smoke/update-ux.mjs +55 -55
  112. package/scripts/smoke/v138-completion.mjs +132 -132
  113. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  114. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  115. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  116. package/scripts/smoke/v143-remote-control.mjs +76 -76
  117. package/scripts/smoke/v144-production-loop.mjs +47 -47
  118. package/scripts/smoke/v145-platformization.mjs +46 -46
  119. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  120. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  121. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  122. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  123. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  124. package/scripts/smoke/workflow-templates.mjs +43 -43
  125. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  126. package/scripts/update-git-install.mjs +298 -298
  127. package/server/claude-sdk.js +927 -927
  128. package/server/cli.js +1106 -1106
  129. package/server/constants/config.js +4 -4
  130. package/server/cursor-cli.js +344 -344
  131. package/server/daemon/manager.js +563 -563
  132. package/server/daemon-manager.js +964 -964
  133. package/server/database/db.js +988 -988
  134. package/server/database/json-store.js +197 -197
  135. package/server/gemini-cli.js +550 -550
  136. package/server/gemini-response-handler.js +79 -79
  137. package/server/index.js +5671 -5659
  138. package/server/load-env.js +35 -35
  139. package/server/middleware/account-lockout.js +112 -112
  140. package/server/middleware/auth.js +277 -277
  141. package/server/middleware/rate-limiter.js +87 -87
  142. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  143. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  144. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  145. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  146. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  147. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  148. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -60
  149. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -101
  150. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  151. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  152. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  153. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  154. package/server/modules/orchestration/a2a/bus.ts +46 -46
  155. package/server/modules/orchestration/a2a/routes.ts +586 -586
  156. package/server/modules/orchestration/a2a/task-dispatcher.ts +345 -345
  157. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  158. package/server/modules/orchestration/a2a/types.ts +126 -126
  159. package/server/modules/orchestration/a2a/validator.ts +113 -113
  160. package/server/modules/orchestration/index.ts +99 -99
  161. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  162. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  163. package/server/modules/orchestration/preview/types.ts +19 -19
  164. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  165. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  166. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +81 -81
  167. package/server/modules/orchestration/tasks/orchestration-task.service.ts +201 -201
  168. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  169. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  170. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  171. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  172. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  173. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  174. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  175. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  176. package/server/modules/orchestration/workflows/workflow-runner.ts +2062 -2062
  177. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  178. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  179. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  180. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  181. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  182. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  183. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  184. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  185. package/server/modules/orchestration/workspace/types.ts +52 -52
  186. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  187. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  188. package/server/modules/providers/index.ts +2 -2
  189. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  190. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  191. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  192. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  193. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  194. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  195. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  196. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  197. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  198. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  199. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  200. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  201. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  202. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  203. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  204. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  205. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  206. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  207. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  208. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  209. package/server/modules/providers/provider.registry.ts +40 -40
  210. package/server/modules/providers/provider.routes.ts +982 -982
  211. package/server/modules/providers/services/mcp.service.ts +86 -86
  212. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  213. package/server/modules/providers/services/sessions.service.ts +45 -45
  214. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  215. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  216. package/server/modules/providers/tests/mcp.test.ts +293 -293
  217. package/server/openai-codex.js +468 -468
  218. package/server/opencode-cli.js +491 -491
  219. package/server/opencode-response-handler.js +111 -111
  220. package/server/projects.js +3135 -3135
  221. package/server/qwen-code-cli.js +410 -410
  222. package/server/routes/agent.js +1462 -1451
  223. package/server/routes/auth.js +298 -298
  224. package/server/routes/codex.js +20 -20
  225. package/server/routes/commands.js +581 -581
  226. package/server/routes/cursor.js +61 -61
  227. package/server/routes/diagnostics.js +44 -44
  228. package/server/routes/gemini.js +25 -25
  229. package/server/routes/git.js +1822 -1822
  230. package/server/routes/live-view.js +434 -434
  231. package/server/routes/mcp-utils.js +13 -13
  232. package/server/routes/messages.js +97 -97
  233. package/server/routes/network.js +143 -143
  234. package/server/routes/platformization.js +231 -231
  235. package/server/routes/plugins.js +690 -690
  236. package/server/routes/production-agent-loop.js +90 -90
  237. package/server/routes/projects.js +918 -918
  238. package/server/routes/public-api.js +34 -34
  239. package/server/routes/qwen.js +27 -27
  240. package/server/routes/remote.js +56 -56
  241. package/server/routes/settings.js +321 -321
  242. package/server/routes/telegram.js +163 -163
  243. package/server/routes/user.js +125 -125
  244. package/server/routes/webhooks.js +63 -63
  245. package/server/services/control-room.js +102 -102
  246. package/server/services/diagnostics.js +165 -165
  247. package/server/services/external-access.js +403 -403
  248. package/server/services/install-jobs.js +715 -715
  249. package/server/services/live-view.js +956 -956
  250. package/server/services/managed-runtimes.js +493 -493
  251. package/server/services/model-registry.js +144 -144
  252. package/server/services/notification-orchestrator.js +365 -365
  253. package/server/services/notification-taxonomy.js +204 -204
  254. package/server/services/platformization.js +1052 -1052
  255. package/server/services/production-agent-loop.js +248 -248
  256. package/server/services/provider-cli-versions.js +149 -149
  257. package/server/services/provider-credentials.js +189 -189
  258. package/server/services/provider-models.js +396 -396
  259. package/server/services/public-api-manifest.js +181 -181
  260. package/server/services/qr-login.js +126 -126
  261. package/server/services/remote-connection.js +127 -127
  262. package/server/services/runtime-manager.js +323 -323
  263. package/server/services/startup-update.js +259 -259
  264. package/server/services/telegram/bot.js +393 -393
  265. package/server/services/telegram/control-center.js +2453 -2453
  266. package/server/services/telegram/telegram-gateway.js +314 -314
  267. package/server/services/telegram/telegram-http-client.js +201 -201
  268. package/server/services/telegram/translations.js +470 -470
  269. package/server/services/webhooks.js +216 -216
  270. package/server/sessionManager.js +225 -225
  271. package/server/setup-wizard.js +283 -283
  272. package/server/shared/interfaces.ts +54 -54
  273. package/server/shared/types.ts +172 -172
  274. package/server/shared/utils.ts +193 -193
  275. package/server/tsconfig.json +36 -36
  276. package/server/utils/colors.js +21 -21
  277. package/server/utils/commandParser.js +305 -305
  278. package/server/utils/frontmatter.js +18 -18
  279. package/server/utils/gitConfig.js +34 -34
  280. package/server/utils/plugin-loader.js +461 -461
  281. package/server/utils/plugin-process-manager.js +185 -185
  282. package/server/utils/port-access.js +227 -227
  283. package/server/utils/runtime-paths.js +37 -37
  284. package/server/utils/security-log.js +84 -84
  285. package/server/utils/url-detection.js +71 -71
  286. package/server/vite-daemon.js +79 -79
  287. package/shared/modelConstants.js +161 -161
  288. package/shared/networkHosts.js +22 -22
@@ -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
+ }