@pixelbyte-software/pixcode 1.35.2 → 1.35.4

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 (228) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/index-BwmhA_le.css +32 -0
  11. package/dist/assets/{index-D1-AIL_5.js → index-CyxRiNt0.js} +182 -182
  12. package/dist/clear-cache.html +85 -85
  13. package/dist/convert-icons.md +52 -52
  14. package/dist/favicon.svg +8 -8
  15. package/dist/generate-icons.js +48 -48
  16. package/dist/icons/codex-white.svg +3 -3
  17. package/dist/icons/codex.svg +3 -3
  18. package/dist/icons/cursor-white.svg +11 -11
  19. package/dist/icons/icon-128x128.svg +9 -9
  20. package/dist/icons/icon-144x144.svg +9 -9
  21. package/dist/icons/icon-152x152.svg +9 -9
  22. package/dist/icons/icon-192x192.svg +9 -9
  23. package/dist/icons/icon-384x384.svg +9 -9
  24. package/dist/icons/icon-512x512.svg +9 -9
  25. package/dist/icons/icon-72x72.svg +9 -9
  26. package/dist/icons/icon-96x96.svg +9 -9
  27. package/dist/icons/icon-template.svg +9 -9
  28. package/dist/icons/qwen-logo.svg +14 -14
  29. package/dist/index.html +59 -59
  30. package/dist/logo.svg +12 -12
  31. package/dist/manifest.json +60 -60
  32. package/dist/openapi.yaml +1693 -1693
  33. package/dist/sw.js +124 -124
  34. package/dist-server/server/cli.js +96 -96
  35. package/dist-server/server/cli.js.map +1 -1
  36. package/dist-server/server/cursor-cli.js.map +1 -1
  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/gemini-cli.js +4 -4
  40. package/dist-server/server/gemini-cli.js.map +1 -1
  41. package/dist-server/server/index.js +11 -11
  42. package/dist-server/server/index.js.map +1 -1
  43. package/dist-server/server/load-env.js.map +1 -1
  44. package/dist-server/server/middleware/auth.js.map +1 -1
  45. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js.map +1 -1
  46. package/dist-server/server/modules/providers/list/claude/claude-auth.provider.js +1 -1
  47. package/dist-server/server/modules/providers/list/claude/claude-auth.provider.js.map +1 -1
  48. package/dist-server/server/modules/providers/list/codex/codex-auth.provider.js +1 -1
  49. package/dist-server/server/modules/providers/list/codex/codex-auth.provider.js.map +1 -1
  50. package/dist-server/server/modules/providers/list/gemini/gemini-auth.provider.js +1 -1
  51. package/dist-server/server/modules/providers/list/gemini/gemini-auth.provider.js.map +1 -1
  52. package/dist-server/server/modules/providers/list/opencode/opencode-auth.provider.js +1 -1
  53. package/dist-server/server/modules/providers/list/opencode/opencode-auth.provider.js.map +1 -1
  54. package/dist-server/server/modules/providers/list/qwen/qwen-auth.provider.js +1 -1
  55. package/dist-server/server/modules/providers/list/qwen/qwen-auth.provider.js.map +1 -1
  56. package/dist-server/server/modules/providers/provider.routes.js +3 -6
  57. package/dist-server/server/modules/providers/provider.routes.js.map +1 -1
  58. package/dist-server/server/opencode-cli.js +1 -1
  59. package/dist-server/server/opencode-cli.js.map +1 -1
  60. package/dist-server/server/projects.js +2 -3
  61. package/dist-server/server/projects.js.map +1 -1
  62. package/dist-server/server/qwen-code-cli.js +1 -1
  63. package/dist-server/server/qwen-code-cli.js.map +1 -1
  64. package/dist-server/server/routes/agent.js +3 -3
  65. package/dist-server/server/routes/agent.js.map +1 -1
  66. package/dist-server/server/routes/auth.js.map +1 -1
  67. package/dist-server/server/routes/codex.js.map +1 -1
  68. package/dist-server/server/routes/commands.js +26 -26
  69. package/dist-server/server/routes/commands.js.map +1 -1
  70. package/dist-server/server/routes/cursor.js +1 -1
  71. package/dist-server/server/routes/cursor.js.map +1 -1
  72. package/dist-server/server/routes/gemini.js.map +1 -1
  73. package/dist-server/server/routes/git.js +18 -18
  74. package/dist-server/server/routes/git.js.map +1 -1
  75. package/dist-server/server/routes/mcp-utils.js.map +1 -1
  76. package/dist-server/server/routes/messages.js.map +1 -1
  77. package/dist-server/server/routes/network.js +1 -1
  78. package/dist-server/server/routes/network.js.map +1 -1
  79. package/dist-server/server/routes/plugins.js +2 -2
  80. package/dist-server/server/routes/plugins.js.map +1 -1
  81. package/dist-server/server/routes/projects.js +1 -1
  82. package/dist-server/server/routes/projects.js.map +1 -1
  83. package/dist-server/server/routes/settings.js.map +1 -1
  84. package/dist-server/server/routes/taskmaster.js +423 -424
  85. package/dist-server/server/routes/taskmaster.js.map +1 -1
  86. package/dist-server/server/routes/user.js +1 -1
  87. package/dist-server/server/routes/user.js.map +1 -1
  88. package/dist-server/server/services/external-access.js +0 -1
  89. package/dist-server/server/services/external-access.js.map +1 -1
  90. package/dist-server/server/services/notification-orchestrator.js.map +1 -1
  91. package/dist-server/server/utils/commandParser.js.map +1 -1
  92. package/dist-server/server/utils/plugin-process-manager.js.map +1 -1
  93. package/dist-server/server/vite-daemon.js.map +1 -1
  94. package/package.json +180 -180
  95. package/scripts/fix-node-pty.js +67 -67
  96. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  97. package/scripts/smoke/orchestration-api.mjs +172 -172
  98. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  99. package/server/claude-sdk.js +898 -898
  100. package/server/cli.js +936 -935
  101. package/server/constants/config.js +4 -4
  102. package/server/cursor-cli.js +344 -342
  103. package/server/daemon/manager.js +564 -564
  104. package/server/daemon-manager.js +959 -959
  105. package/server/database/db.js +794 -794
  106. package/server/database/json-store.js +197 -197
  107. package/server/gemini-cli.js +536 -535
  108. package/server/gemini-response-handler.js +79 -79
  109. package/server/index.js +3138 -3135
  110. package/server/load-env.js +35 -34
  111. package/server/middleware/auth.js +174 -173
  112. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  113. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  114. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  115. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  116. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  117. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  118. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  119. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  120. package/server/modules/orchestration/a2a/routes.ts +577 -577
  121. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  122. package/server/modules/orchestration/a2a/types.ts +125 -125
  123. package/server/modules/orchestration/a2a/validator.ts +113 -113
  124. package/server/modules/orchestration/index.ts +66 -66
  125. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  126. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  127. package/server/modules/orchestration/preview/types.ts +19 -19
  128. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  129. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +74 -73
  130. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  131. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  132. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  133. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  134. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  135. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  136. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  137. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  138. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  139. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  140. package/server/modules/orchestration/workspace/types.ts +52 -52
  141. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  142. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  143. package/server/modules/providers/index.ts +2 -2
  144. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -145
  145. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  146. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  147. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  148. package/server/modules/providers/list/codex/codex-auth.provider.ts +116 -115
  149. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  150. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  151. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  152. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  153. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  154. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  155. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  156. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +164 -163
  157. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  158. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  159. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  160. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -130
  161. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  162. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  163. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  164. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -145
  165. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  166. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  167. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  168. package/server/modules/providers/provider.registry.ts +40 -40
  169. package/server/modules/providers/provider.routes.ts +822 -819
  170. package/server/modules/providers/services/mcp.service.ts +86 -86
  171. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  172. package/server/modules/providers/services/sessions.service.ts +45 -45
  173. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  174. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  175. package/server/modules/providers/shared/provider-configs.ts +142 -142
  176. package/server/modules/providers/tests/mcp.test.ts +293 -293
  177. package/server/openai-codex.js +462 -462
  178. package/server/opencode-cli.js +460 -459
  179. package/server/opencode-response-handler.js +107 -107
  180. package/server/projects.js +3106 -3105
  181. package/server/qwen-code-cli.js +396 -395
  182. package/server/qwen-response-handler.js +73 -73
  183. package/server/routes/agent.js +1367 -1365
  184. package/server/routes/auth.js +139 -138
  185. package/server/routes/codex.js +20 -19
  186. package/server/routes/commands.js +556 -554
  187. package/server/routes/cursor.js +54 -52
  188. package/server/routes/gemini.js +25 -24
  189. package/server/routes/git.js +1490 -1488
  190. package/server/routes/mcp-utils.js +32 -31
  191. package/server/routes/messages.js +62 -61
  192. package/server/routes/network.js +121 -120
  193. package/server/routes/plugins.js +320 -318
  194. package/server/routes/projects.js +917 -915
  195. package/server/routes/qwen.js +27 -27
  196. package/server/routes/settings.js +287 -286
  197. package/server/routes/taskmaster.js +1498 -1496
  198. package/server/routes/telegram.js +125 -125
  199. package/server/routes/user.js +125 -123
  200. package/server/services/external-access.js +171 -171
  201. package/server/services/install-jobs.js +571 -571
  202. package/server/services/notification-orchestrator.js +244 -242
  203. package/server/services/provider-credentials.js +189 -189
  204. package/server/services/provider-models.js +381 -381
  205. package/server/services/telegram/bot.js +279 -279
  206. package/server/services/telegram/telegram-http-client.js +130 -130
  207. package/server/services/telegram/translations.js +170 -170
  208. package/server/services/vapid-keys.js +36 -36
  209. package/server/sessionManager.js +225 -225
  210. package/server/shared/interfaces.ts +54 -54
  211. package/server/shared/types.ts +172 -172
  212. package/server/shared/utils.ts +193 -193
  213. package/server/tsconfig.json +36 -36
  214. package/server/utils/colors.js +21 -21
  215. package/server/utils/commandParser.js +305 -303
  216. package/server/utils/frontmatter.js +18 -18
  217. package/server/utils/gitConfig.js +34 -34
  218. package/server/utils/mcp-detector.js +147 -147
  219. package/server/utils/plugin-loader.js +457 -457
  220. package/server/utils/plugin-process-manager.js +185 -184
  221. package/server/utils/port-access.js +209 -209
  222. package/server/utils/runtime-paths.js +37 -37
  223. package/server/utils/taskmaster-websocket.js +128 -128
  224. package/server/utils/url-detection.js +71 -71
  225. package/server/vite-daemon.js +79 -78
  226. package/shared/modelConstants.js +162 -162
  227. package/shared/networkHosts.js +22 -22
  228. package/dist/assets/index-B8w57E1r.css +0 -32
@@ -1,794 +1,794 @@
1
- import crypto from 'node:crypto';
2
- import fs from 'node:fs';
3
- import { createRequire } from 'node:module';
4
- import path from 'node:path';
5
-
6
- import { findAppRoot, getModuleDir } from '../utils/runtime-paths.js';
7
-
8
- import { JsonStore, nowIso } from './json-store.js';
9
-
10
- // CommonJS `require` shim — we only reach for it once, during the
11
- // legacy-to-JSON migration below, to dynamically import better-sqlite3
12
- // only when an old auth.db is actually present on disk.
13
- const require = createRequire(import.meta.url);
14
-
15
- const __dirname = getModuleDir(import.meta.url);
16
- // The compiled backend lives under dist-server/server/database, but the install root we log
17
- // should still point at the project/app root. Resolving it here avoids build-layout drift.
18
- const APP_ROOT = findAppRoot(__dirname);
19
-
20
- // ANSI color codes for terminal output
21
- const colors = {
22
- reset: '\x1b[0m',
23
- bright: '\x1b[1m',
24
- cyan: '\x1b[36m',
25
- dim: '\x1b[2m',
26
- };
27
-
28
- const c = {
29
- info: (text) => `${colors.cyan}${text}${colors.reset}`,
30
- bright: (text) => `${colors.bright}${text}${colors.reset}`,
31
- dim: (text) => `${colors.dim}${text}${colors.reset}`,
32
- };
33
-
34
- // DATABASE_PATH keeps its historical meaning (user override), but points
35
- // at a `.json` file now. If the user's env var still names a `.db`
36
- // extension, we swap to the corresponding `.json` sibling — the auth
37
- // store moved off SQLite in v1.33.0.
38
- const rawDbPath = process.env.DATABASE_PATH || path.join(__dirname, 'auth.db');
39
- const JSON_PATH = rawDbPath.endsWith('.db')
40
- ? rawDbPath.replace(/\.db$/, '.json')
41
- : (rawDbPath.endsWith('.json') ? rawDbPath : `${rawDbPath}.json`);
42
- const LEGACY_SQLITE_PATH = rawDbPath.endsWith('.db')
43
- ? rawDbPath
44
- : rawDbPath.replace(/\.json$/, '.db');
45
-
46
- // Ensure parent dir exists before migration / initial write.
47
- {
48
- const dir = path.dirname(JSON_PATH);
49
- if (!fs.existsSync(dir)) {
50
- try { fs.mkdirSync(dir, { recursive: true }); }
51
- catch (err) {
52
- console.error(`Failed to create database directory ${dir}:`, err.message);
53
- throw err;
54
- }
55
- }
56
- }
57
-
58
- /**
59
- * One-time migration from the previous better-sqlite3 auth.db to the
60
- * new JSON format. Triggered only when:
61
- * - The legacy .db exists
62
- * - AND no .json has been created yet
63
- * The legacy file is kept in place as `<name>.db.migrated-<timestamp>`
64
- * so a user can roll back by moving it into place and reinstalling
65
- * better-sqlite3 if they hit a showstopper. Runs synchronously because
66
- * all downstream modules (auth.js, vapid-keys.js) import `db` at module
67
- * load and can't wait for async startup.
68
- */
69
- function migrateSqliteIfPresent() {
70
- if (fs.existsSync(JSON_PATH)) return; // Already migrated or fresh install.
71
- if (!fs.existsSync(LEGACY_SQLITE_PATH)) return; // Nothing to migrate.
72
-
73
- console.log(`${c.info('[MIGRATION]')} Converting ${c.bright(LEGACY_SQLITE_PATH)} → ${c.bright(JSON_PATH)} (JSON auth store, v1.33.0)`);
74
-
75
- let Database;
76
- try {
77
- const mod = require('better-sqlite3');
78
- Database = mod.default || mod;
79
- } catch {
80
- // Auto-install path fell through — the user has a legacy file but
81
- // better-sqlite3 isn't present (they may have a trimmed dep tree).
82
- // Surface a clear error; we'd rather fail startup than silently
83
- // skip migration and strand the user's saved credentials.
84
- console.error('[MIGRATION] Legacy auth.db present but better-sqlite3 not installed.');
85
- console.error('[MIGRATION] Install it once to migrate: `npm install better-sqlite3` in your pixcode install dir, then restart.');
86
- throw new Error('Auth DB migration requires better-sqlite3 (legacy file detected).');
87
- }
88
-
89
- const legacy = new Database(LEGACY_SQLITE_PATH, { readonly: true });
90
- const store = new JsonStore(JSON_PATH);
91
-
92
- // Pull every table, skipping silently when it doesn't exist (old
93
- // installs that never ran some migrations). We rely on `IF NOT EXISTS`
94
- // patterns from the old schema.js — missing tables throw a SQLite
95
- // error which we catch per-table.
96
- const safeAll = (sql) => {
97
- try { return legacy.prepare(sql).all(); } catch { return []; }
98
- };
99
-
100
- const users = safeAll('SELECT id, username, password_hash, created_at, last_login, is_active, git_name, git_email, has_completed_onboarding FROM users');
101
- for (const u of users) {
102
- store.raw.users.push({
103
- id: u.id,
104
- username: u.username,
105
- password_hash: u.password_hash,
106
- created_at: u.created_at || nowIso(),
107
- last_login: u.last_login || null,
108
- is_active: u.is_active !== 0,
109
- git_name: u.git_name || null,
110
- git_email: u.git_email || null,
111
- has_completed_onboarding: u.has_completed_onboarding === 1,
112
- });
113
- store.raw._sequences.users = Math.max(store.raw._sequences.users, u.id);
114
- }
115
-
116
- const apiKeys = safeAll('SELECT id, user_id, key_name, api_key, created_at, last_used, is_active FROM api_keys');
117
- for (const k of apiKeys) {
118
- store.raw.api_keys.push({
119
- id: k.id,
120
- user_id: k.user_id,
121
- key_name: k.key_name,
122
- api_key: k.api_key,
123
- created_at: k.created_at || nowIso(),
124
- last_used: k.last_used || null,
125
- is_active: k.is_active !== 0,
126
- });
127
- store.raw._sequences.api_keys = Math.max(store.raw._sequences.api_keys, k.id);
128
- }
129
-
130
- const credentials = safeAll('SELECT id, user_id, credential_name, credential_type, credential_value, description, created_at, is_active FROM user_credentials');
131
- for (const cr of credentials) {
132
- store.raw.user_credentials.push({
133
- id: cr.id,
134
- user_id: cr.user_id,
135
- credential_name: cr.credential_name,
136
- credential_type: cr.credential_type,
137
- credential_value: cr.credential_value,
138
- description: cr.description || null,
139
- created_at: cr.created_at || nowIso(),
140
- is_active: cr.is_active !== 0,
141
- });
142
- store.raw._sequences.user_credentials = Math.max(store.raw._sequences.user_credentials, cr.id);
143
- }
144
-
145
- const prefs = safeAll('SELECT user_id, preferences_json, updated_at FROM user_notification_preferences');
146
- for (const p of prefs) {
147
- store.raw.user_notification_preferences.push({
148
- user_id: p.user_id,
149
- preferences_json: p.preferences_json,
150
- updated_at: p.updated_at || nowIso(),
151
- });
152
- }
153
-
154
- const vapid = safeAll('SELECT id, public_key, private_key, created_at FROM vapid_keys');
155
- for (const v of vapid) {
156
- store.raw.vapid_keys.push({
157
- id: v.id,
158
- public_key: v.public_key,
159
- private_key: v.private_key,
160
- created_at: v.created_at || nowIso(),
161
- });
162
- store.raw._sequences.vapid_keys = Math.max(store.raw._sequences.vapid_keys, v.id);
163
- }
164
-
165
- const pushSubs = safeAll('SELECT id, user_id, endpoint, keys_p256dh, keys_auth, created_at FROM push_subscriptions');
166
- for (const s of pushSubs) {
167
- store.raw.push_subscriptions.push({
168
- id: s.id,
169
- user_id: s.user_id,
170
- endpoint: s.endpoint,
171
- keys_p256dh: s.keys_p256dh,
172
- keys_auth: s.keys_auth,
173
- created_at: s.created_at || nowIso(),
174
- });
175
- store.raw._sequences.push_subscriptions = Math.max(store.raw._sequences.push_subscriptions, s.id);
176
- }
177
-
178
- const sessionNames = safeAll('SELECT session_id, provider, custom_name, created_at, updated_at FROM session_names');
179
- for (const sn of sessionNames) {
180
- store.raw.session_names.push({
181
- session_id: sn.session_id,
182
- provider: sn.provider,
183
- custom_name: sn.custom_name,
184
- created_at: sn.created_at || nowIso(),
185
- updated_at: sn.updated_at || nowIso(),
186
- });
187
- }
188
-
189
- const appConfig = safeAll('SELECT key, value, created_at FROM app_config');
190
- for (const a of appConfig) {
191
- store.raw.app_config.push({
192
- key: a.key,
193
- value: a.value,
194
- created_at: a.created_at || nowIso(),
195
- });
196
- }
197
-
198
- const telegramConfig = safeAll('SELECT id, bot_token, bot_username, updated_at FROM telegram_config');
199
- for (const t of telegramConfig) {
200
- store.raw.telegram_config.push({
201
- id: 1,
202
- bot_token: t.bot_token,
203
- bot_username: t.bot_username || null,
204
- updated_at: t.updated_at || nowIso(),
205
- });
206
- }
207
-
208
- const telegramLinks = safeAll('SELECT user_id, chat_id, telegram_username, language, pairing_code, pairing_code_expires_at, verified_at, notifications_enabled, bridge_enabled, updated_at FROM telegram_links');
209
- for (const tl of telegramLinks) {
210
- store.raw.telegram_links.push({
211
- user_id: tl.user_id,
212
- chat_id: tl.chat_id || null,
213
- telegram_username: tl.telegram_username || null,
214
- language: tl.language || 'en',
215
- pairing_code: tl.pairing_code || null,
216
- pairing_code_expires_at: tl.pairing_code_expires_at || null,
217
- verified_at: tl.verified_at || null,
218
- notifications_enabled: tl.notifications_enabled !== 0,
219
- bridge_enabled: tl.bridge_enabled !== 0,
220
- updated_at: tl.updated_at || nowIso(),
221
- });
222
- }
223
-
224
- store.save();
225
- legacy.close();
226
-
227
- // Rename the old .db out of the way so we never migrate it twice.
228
- // Keep it (not delete) so the user can roll back if needed.
229
- const backup = `${LEGACY_SQLITE_PATH}.migrated-${Date.now()}`;
230
- try {
231
- fs.renameSync(LEGACY_SQLITE_PATH, backup);
232
- for (const suffix of ['-wal', '-shm']) {
233
- if (fs.existsSync(LEGACY_SQLITE_PATH + suffix)) {
234
- try { fs.renameSync(LEGACY_SQLITE_PATH + suffix, backup + suffix); } catch { /* noop */ }
235
- }
236
- }
237
- } catch (err) {
238
- console.warn(`[MIGRATION] Migration succeeded but could not rename old DB: ${err.message}`);
239
- }
240
-
241
- console.log(`${c.info('[MIGRATION]')} Migration complete. Old DB preserved as ${c.dim(backup)}.`);
242
- }
243
-
244
- // Module-load order matters — auth middleware imports `db` and reads the
245
- // JWT secret before anything else gets to boot. So the store has to be
246
- // ready synchronously at the first `import { db } from './db.js'`.
247
- migrateSqliteIfPresent();
248
-
249
- const store = new JsonStore(JSON_PATH);
250
-
251
- console.log('');
252
- console.log(c.dim('═'.repeat(60)));
253
- console.log(`${c.info('[INFO]')} App Installation: ${c.bright(APP_ROOT)}`);
254
- console.log(`${c.info('[INFO]')} Auth store: ${c.dim(path.relative(APP_ROOT, JSON_PATH))}`);
255
- if (process.env.DATABASE_PATH) {
256
- console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
257
- }
258
- console.log(c.dim('═'.repeat(60)));
259
- console.log('');
260
-
261
- // initializeDatabase used to run `CREATE TABLE IF NOT EXISTS` + migrations.
262
- // The JSON store always has its shape pre-baked, so this is a no-op —
263
- // keeping the export preserves the server boot sequence.
264
- const initializeDatabase = async () => { /* schema lives in code, not in file */ };
265
-
266
- // ---------------------------------------------------------------------------
267
- // Back-compat `db` shim — a few modules outside database/db.js imported `db`
268
- // and called `db.prepare(sql)` directly. Most of those uses were for trivial
269
- // transaction markers (BEGIN/COMMIT/ROLLBACK — no-op under our JSON store)
270
- // or very specific SELECTs we've wrapped in explicit helpers. This shim
271
- // lets those call sites keep working without a bigger refactor.
272
- // ---------------------------------------------------------------------------
273
- const db = {
274
- prepare(sql) {
275
- const normalized = sql.trim().toUpperCase();
276
- // Transaction markers — our store writes atomically per op, so
277
- // there's no real transaction to start. No-op + success result.
278
- if (normalized === 'BEGIN' || normalized === 'COMMIT' || normalized === 'ROLLBACK') {
279
- return {
280
- run: () => ({ changes: 0, lastInsertRowid: 0 }),
281
- };
282
- }
283
-
284
- // Specific query routed through the new helpers — used by
285
- // server/routes/projects.js to fetch a single github credential.
286
- if (/FROM USER_CREDENTIALS\s+WHERE ID = \?\s+AND USER_ID = \?\s+AND CREDENTIAL_TYPE = \?\s+AND IS_ACTIVE = 1/.test(normalized)) {
287
- return {
288
- get: (id, userId, credentialType) =>
289
- store.findWhere('user_credentials',
290
- (r) => r.id === id && r.user_id === userId && r.credential_type === credentialType && r.is_active)
291
- || undefined,
292
- };
293
- }
294
-
295
- throw new Error(
296
- `db.prepare: unsupported SQL passed through the compat shim: ${sql.slice(0, 80)}`
297
- + '\nExtend server/database/db.js or use a dedicated helper (userDb, credentialsDb, …).',
298
- );
299
- },
300
- };
301
-
302
- // ---------------------------------------------------------------------------
303
- // User operations
304
- // ---------------------------------------------------------------------------
305
- const userDb = {
306
- hasUsers: () => store.count('users', (r) => r.is_active) > 0,
307
-
308
- createUser: (username, passwordHash) => {
309
- const row = store.insert('users', {
310
- username,
311
- password_hash: passwordHash,
312
- created_at: nowIso(),
313
- last_login: null,
314
- is_active: true,
315
- git_name: null,
316
- git_email: null,
317
- has_completed_onboarding: false,
318
- });
319
- return { id: row.id, username: row.username };
320
- },
321
-
322
- getUserByUsername: (username) =>
323
- store.findWhere('users', (r) => r.username === username && r.is_active) || undefined,
324
-
325
- updateLastLogin: (userId) => {
326
- try {
327
- store.updateWhere('users', (r) => r.id === userId, { last_login: nowIso() });
328
- } catch (err) {
329
- console.warn('Failed to update last login:', err.message);
330
- }
331
- },
332
-
333
- getUserById: (userId) => {
334
- const row = store.findWhere('users', (r) => r.id === userId && r.is_active);
335
- if (!row) return undefined;
336
- return {
337
- id: row.id,
338
- username: row.username,
339
- created_at: row.created_at,
340
- last_login: row.last_login,
341
- };
342
- },
343
-
344
- getFirstUser: () => {
345
- const row = store.raw.users.find((r) => r.is_active);
346
- if (!row) return undefined;
347
- return {
348
- id: row.id,
349
- username: row.username,
350
- created_at: row.created_at,
351
- last_login: row.last_login,
352
- };
353
- },
354
-
355
- updateGitConfig: (userId, gitName, gitEmail) => {
356
- store.updateWhere('users', (r) => r.id === userId, { git_name: gitName, git_email: gitEmail });
357
- },
358
-
359
- getGitConfig: (userId) => {
360
- const row = store.findWhere('users', (r) => r.id === userId);
361
- if (!row) return undefined;
362
- return { git_name: row.git_name || null, git_email: row.git_email || null };
363
- },
364
-
365
- completeOnboarding: (userId) => {
366
- store.updateWhere('users', (r) => r.id === userId, { has_completed_onboarding: true });
367
- },
368
-
369
- hasCompletedOnboarding: (userId) => {
370
- const row = store.findWhere('users', (r) => r.id === userId);
371
- return Boolean(row?.has_completed_onboarding);
372
- },
373
- };
374
-
375
- // ---------------------------------------------------------------------------
376
- // API key operations
377
- // ---------------------------------------------------------------------------
378
- const apiKeysDb = {
379
- generateApiKey: () => 'ck_' + crypto.randomBytes(32).toString('hex'),
380
-
381
- createApiKey: (userId, keyName) => {
382
- const apiKey = apiKeysDb.generateApiKey();
383
- const row = store.insert('api_keys', {
384
- user_id: userId,
385
- key_name: keyName,
386
- api_key: apiKey,
387
- created_at: nowIso(),
388
- last_used: null,
389
- is_active: true,
390
- });
391
- return { id: row.id, keyName, apiKey };
392
- },
393
-
394
- getApiKeys: (userId) => {
395
- const rows = store.filterWhere('api_keys', (r) => r.user_id === userId);
396
- // Match the old ORDER BY created_at DESC behaviour.
397
- return rows
398
- .slice()
399
- .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
400
- .map((r) => ({
401
- id: r.id,
402
- key_name: r.key_name,
403
- api_key: r.api_key,
404
- created_at: r.created_at,
405
- last_used: r.last_used,
406
- is_active: r.is_active ? 1 : 0,
407
- }));
408
- },
409
-
410
- validateApiKey: (apiKey) => {
411
- const key = store.findWhere('api_keys', (r) => r.api_key === apiKey && r.is_active);
412
- if (!key) return undefined;
413
- const user = store.findWhere('users', (r) => r.id === key.user_id && r.is_active);
414
- if (!user) return undefined;
415
- // Mirror the SQL-era side effect: stamp last_used. Only relevant
416
- // for the "which key was used last" display in the UI.
417
- store.updateWhere('api_keys', (r) => r.id === key.id, { last_used: nowIso() });
418
- return {
419
- id: user.id,
420
- username: user.username,
421
- api_key_id: key.id,
422
- };
423
- },
424
-
425
- deleteApiKey: (userId, apiKeyId) =>
426
- store.deleteWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId) > 0,
427
-
428
- toggleApiKey: (userId, apiKeyId, isActive) =>
429
- store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
430
- };
431
-
432
- // ---------------------------------------------------------------------------
433
- // Credentials (GitHub tokens, etc.) operations
434
- // ---------------------------------------------------------------------------
435
- const credentialsDb = {
436
- createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
437
- const row = store.insert('user_credentials', {
438
- user_id: userId,
439
- credential_name: credentialName,
440
- credential_type: credentialType,
441
- credential_value: credentialValue,
442
- description,
443
- created_at: nowIso(),
444
- is_active: true,
445
- });
446
- return { id: row.id, credentialName, credentialType };
447
- },
448
-
449
- getCredentials: (userId, credentialType = null) => {
450
- const rows = store.filterWhere('user_credentials', (r) =>
451
- r.user_id === userId && (credentialType == null || r.credential_type === credentialType),
452
- );
453
- return rows
454
- .slice()
455
- .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
456
- .map((r) => ({
457
- id: r.id,
458
- credential_name: r.credential_name,
459
- credential_type: r.credential_type,
460
- description: r.description,
461
- created_at: r.created_at,
462
- is_active: r.is_active ? 1 : 0,
463
- }));
464
- },
465
-
466
- getActiveCredential: (userId, credentialType) => {
467
- const rows = store.filterWhere('user_credentials', (r) =>
468
- r.user_id === userId && r.credential_type === credentialType && r.is_active,
469
- );
470
- if (rows.length === 0) return null;
471
- // "Most recent active" — mirror ORDER BY created_at DESC LIMIT 1
472
- rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
473
- return rows[0].credential_value;
474
- },
475
-
476
- getCredentialById: (userId, credentialId, credentialType = null) => {
477
- const row = store.findWhere('user_credentials', (r) =>
478
- r.id === credentialId && r.user_id === userId && r.is_active
479
- && (credentialType == null || r.credential_type === credentialType),
480
- );
481
- return row || undefined;
482
- },
483
-
484
- deleteCredential: (userId, credentialId) =>
485
- store.deleteWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId) > 0,
486
-
487
- toggleCredential: (userId, credentialId, isActive) =>
488
- store.updateWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
489
- };
490
-
491
- // ---------------------------------------------------------------------------
492
- // Notification preferences
493
- // ---------------------------------------------------------------------------
494
- const DEFAULT_NOTIFICATION_PREFERENCES = {
495
- channels: { inApp: false, webPush: false },
496
- events: { actionRequired: true, stop: true, error: true },
497
- };
498
-
499
- const normalizeNotificationPreferences = (value) => {
500
- const source = value && typeof value === 'object' ? value : {};
501
- return {
502
- channels: {
503
- inApp: source.channels?.inApp === true,
504
- webPush: source.channels?.webPush === true,
505
- },
506
- events: {
507
- actionRequired: source.events?.actionRequired !== false,
508
- stop: source.events?.stop !== false,
509
- error: source.events?.error !== false,
510
- },
511
- };
512
- };
513
-
514
- const notificationPreferencesDb = {
515
- getPreferences: (userId) => {
516
- const row = store.findWhere('user_notification_preferences', (r) => r.user_id === userId);
517
- if (!row) {
518
- const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
519
- store.insert('user_notification_preferences', {
520
- user_id: userId,
521
- preferences_json: JSON.stringify(defaults),
522
- updated_at: nowIso(),
523
- }, { autoId: false });
524
- return defaults;
525
- }
526
- try {
527
- return normalizeNotificationPreferences(JSON.parse(row.preferences_json));
528
- } catch {
529
- return normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
530
- }
531
- },
532
-
533
- updatePreferences: (userId, preferences) => {
534
- const normalized = normalizeNotificationPreferences(preferences);
535
- store.upsertWhere(
536
- 'user_notification_preferences',
537
- (r) => r.user_id === userId,
538
- { user_id: userId, preferences_json: JSON.stringify(normalized), updated_at: nowIso() },
539
- );
540
- return normalized;
541
- },
542
- };
543
-
544
- // ---------------------------------------------------------------------------
545
- // Push subscriptions
546
- // ---------------------------------------------------------------------------
547
- const pushSubscriptionsDb = {
548
- saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
549
- // The old SQL path upserted on `endpoint`, updating user_id as
550
- // well. Preserve that exact behaviour.
551
- const existing = store.findWhere('push_subscriptions', (r) => r.endpoint === endpoint);
552
- if (existing) {
553
- store.updateWhere('push_subscriptions', (r) => r.endpoint === endpoint, {
554
- user_id: userId,
555
- keys_p256dh: keysP256dh,
556
- keys_auth: keysAuth,
557
- });
558
- return;
559
- }
560
- store.insert('push_subscriptions', {
561
- user_id: userId,
562
- endpoint,
563
- keys_p256dh: keysP256dh,
564
- keys_auth: keysAuth,
565
- created_at: nowIso(),
566
- });
567
- },
568
-
569
- getSubscriptions: (userId) =>
570
- store.filterWhere('push_subscriptions', (r) => r.user_id === userId).map((r) => ({
571
- endpoint: r.endpoint,
572
- keys_p256dh: r.keys_p256dh,
573
- keys_auth: r.keys_auth,
574
- })),
575
-
576
- removeSubscription: (endpoint) => {
577
- store.deleteWhere('push_subscriptions', (r) => r.endpoint === endpoint);
578
- },
579
-
580
- removeAllForUser: (userId) => {
581
- store.deleteWhere('push_subscriptions', (r) => r.user_id === userId);
582
- },
583
- };
584
-
585
- // ---------------------------------------------------------------------------
586
- // VAPID key storage (for web push)
587
- // ---------------------------------------------------------------------------
588
- const vapidKeysDb = {
589
- getLatest: () => {
590
- if (store.raw.vapid_keys.length === 0) return null;
591
- // Mirror ORDER BY id DESC LIMIT 1 — take the newest row.
592
- const rows = store.raw.vapid_keys.slice().sort((a, b) => b.id - a.id);
593
- return { public_key: rows[0].public_key, private_key: rows[0].private_key };
594
- },
595
- insert: (publicKey, privateKey) => {
596
- store.insert('vapid_keys', {
597
- public_key: publicKey,
598
- private_key: privateKey,
599
- created_at: nowIso(),
600
- });
601
- },
602
- };
603
-
604
- // ---------------------------------------------------------------------------
605
- // Session custom names
606
- // ---------------------------------------------------------------------------
607
- const sessionNamesDb = {
608
- setName: (sessionId, provider, customName) => {
609
- store.upsertWhere(
610
- 'session_names',
611
- (r) => r.session_id === sessionId && r.provider === provider,
612
- { session_id: sessionId, provider, custom_name: customName, updated_at: nowIso(), created_at: nowIso() },
613
- );
614
- },
615
-
616
- getName: (sessionId, provider) => {
617
- const row = store.findWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider);
618
- return row?.custom_name || null;
619
- },
620
-
621
- getNames: (sessionIds, provider) => {
622
- if (!sessionIds.length) return new Map();
623
- const lookup = new Set(sessionIds);
624
- const matches = store.filterWhere('session_names',
625
- (r) => r.provider === provider && lookup.has(r.session_id));
626
- return new Map(matches.map((r) => [r.session_id, r.custom_name]));
627
- },
628
-
629
- deleteName: (sessionId, provider) =>
630
- store.deleteWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider) > 0,
631
- };
632
-
633
- function applyCustomSessionNames(sessions, provider) {
634
- if (!sessions?.length) return;
635
- try {
636
- const ids = sessions.map((s) => s.id);
637
- const customNames = sessionNamesDb.getNames(ids, provider);
638
- for (const session of sessions) {
639
- const custom = customNames.get(session.id);
640
- if (custom) session.summary = custom;
641
- }
642
- } catch (error) {
643
- console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
644
- }
645
- }
646
-
647
- // ---------------------------------------------------------------------------
648
- // App config (key/value)
649
- // ---------------------------------------------------------------------------
650
- const appConfigDb = {
651
- get: (key) => {
652
- const row = store.findWhere('app_config', (r) => r.key === key);
653
- return row?.value || null;
654
- },
655
-
656
- set: (key, value) => {
657
- store.upsertWhere('app_config', (r) => r.key === key,
658
- { key, value, created_at: nowIso() });
659
- },
660
-
661
- getOrCreateJwtSecret: () => {
662
- let secret = appConfigDb.get('jwt_secret');
663
- if (!secret) {
664
- secret = crypto.randomBytes(64).toString('hex');
665
- appConfigDb.set('jwt_secret', secret);
666
- }
667
- return secret;
668
- },
669
- };
670
-
671
- // ---------------------------------------------------------------------------
672
- // Telegram — singleton config + per-user links
673
- // ---------------------------------------------------------------------------
674
- const telegramConfigDb = {
675
- get: () => {
676
- const row = store.raw.telegram_config[0];
677
- if (!row) return null;
678
- return { bot_token: row.bot_token, bot_username: row.bot_username, updated_at: row.updated_at };
679
- },
680
- set: (botToken, botUsername = null) => {
681
- store.raw.telegram_config = [{
682
- id: 1,
683
- bot_token: botToken,
684
- bot_username: botUsername,
685
- updated_at: nowIso(),
686
- }];
687
- store.save();
688
- },
689
- clear: () => {
690
- store.raw.telegram_config = [];
691
- store.save();
692
- },
693
- };
694
-
695
- const telegramLinksDb = {
696
- setPairingCode: (userId, code, expiresAt, language) => {
697
- store.upsertWhere('telegram_links', (r) => r.user_id === userId, {
698
- user_id: userId,
699
- pairing_code: code,
700
- pairing_code_expires_at: expiresAt,
701
- language,
702
- chat_id: null,
703
- telegram_username: null,
704
- verified_at: null,
705
- notifications_enabled: true,
706
- bridge_enabled: true,
707
- updated_at: nowIso(),
708
- });
709
- },
710
- findByPairingCode: (code) => {
711
- const row = store.findWhere('telegram_links', (r) => r.pairing_code === code);
712
- if (!row) return null;
713
- return {
714
- user_id: row.user_id,
715
- pairing_code: row.pairing_code,
716
- pairing_code_expires_at: row.pairing_code_expires_at,
717
- language: row.language,
718
- };
719
- },
720
- verify: (userId, chatId, telegramUsername) => {
721
- store.updateWhere('telegram_links', (r) => r.user_id === userId, {
722
- chat_id: chatId,
723
- telegram_username: telegramUsername,
724
- verified_at: nowIso(),
725
- pairing_code: null,
726
- pairing_code_expires_at: null,
727
- updated_at: nowIso(),
728
- });
729
- },
730
- getByUserId: (userId) => {
731
- const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
732
- return row ? { ...row } : null;
733
- },
734
- getByChatId: (chatId) => {
735
- const row = store.findWhere('telegram_links', (r) => r.chat_id === chatId);
736
- if (!row) return null;
737
- return {
738
- user_id: row.user_id,
739
- chat_id: row.chat_id,
740
- telegram_username: row.telegram_username,
741
- language: row.language,
742
- notifications_enabled: row.notifications_enabled,
743
- bridge_enabled: row.bridge_enabled,
744
- };
745
- },
746
- listVerified: () =>
747
- store.filterWhere('telegram_links', (r) => r.chat_id && r.verified_at).map((r) => ({
748
- user_id: r.user_id,
749
- chat_id: r.chat_id,
750
- telegram_username: r.telegram_username,
751
- language: r.language,
752
- notifications_enabled: r.notifications_enabled,
753
- bridge_enabled: r.bridge_enabled,
754
- })),
755
- updatePreferences: (userId, { language, notificationsEnabled, bridgeEnabled }) => {
756
- const patch = { updated_at: nowIso() };
757
- if (language !== undefined) patch.language = language;
758
- if (notificationsEnabled !== undefined) patch.notifications_enabled = Boolean(notificationsEnabled);
759
- if (bridgeEnabled !== undefined) patch.bridge_enabled = Boolean(bridgeEnabled);
760
- if (Object.keys(patch).length === 1) return; // only updated_at → no real change
761
- store.updateWhere('telegram_links', (r) => r.user_id === userId, patch);
762
- },
763
- unlink: (userId) => {
764
- store.deleteWhere('telegram_links', (r) => r.user_id === userId);
765
- },
766
- };
767
-
768
- // Back-compat surface — older callers used `githubTokensDb.*`; internally
769
- // they always delegated to credentialsDb with `credential_type='github_token'`.
770
- const githubTokensDb = {
771
- createGithubToken: (userId, tokenName, githubToken, description = null) =>
772
- credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description),
773
- getGithubTokens: (userId) => credentialsDb.getCredentials(userId, 'github_token'),
774
- getActiveGithubToken: (userId) => credentialsDb.getActiveCredential(userId, 'github_token'),
775
- deleteGithubToken: (userId, tokenId) => credentialsDb.deleteCredential(userId, tokenId),
776
- toggleGithubToken: (userId, tokenId, isActive) => credentialsDb.toggleCredential(userId, tokenId, isActive),
777
- };
778
-
779
- export {
780
- db,
781
- initializeDatabase,
782
- userDb,
783
- apiKeysDb,
784
- credentialsDb,
785
- notificationPreferencesDb,
786
- pushSubscriptionsDb,
787
- vapidKeysDb,
788
- sessionNamesDb,
789
- applyCustomSessionNames,
790
- appConfigDb,
791
- telegramConfigDb,
792
- telegramLinksDb,
793
- githubTokensDb,
794
- };
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+
6
+ import { findAppRoot, getModuleDir } from '../utils/runtime-paths.js';
7
+
8
+ import { JsonStore, nowIso } from './json-store.js';
9
+
10
+ // CommonJS `require` shim — we only reach for it once, during the
11
+ // legacy-to-JSON migration below, to dynamically import better-sqlite3
12
+ // only when an old auth.db is actually present on disk.
13
+ const require = createRequire(import.meta.url);
14
+
15
+ const __dirname = getModuleDir(import.meta.url);
16
+ // The compiled backend lives under dist-server/server/database, but the install root we log
17
+ // should still point at the project/app root. Resolving it here avoids build-layout drift.
18
+ const APP_ROOT = findAppRoot(__dirname);
19
+
20
+ // ANSI color codes for terminal output
21
+ const colors = {
22
+ reset: '\x1b[0m',
23
+ bright: '\x1b[1m',
24
+ cyan: '\x1b[36m',
25
+ dim: '\x1b[2m',
26
+ };
27
+
28
+ const c = {
29
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
30
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
31
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
32
+ };
33
+
34
+ // DATABASE_PATH keeps its historical meaning (user override), but points
35
+ // at a `.json` file now. If the user's env var still names a `.db`
36
+ // extension, we swap to the corresponding `.json` sibling — the auth
37
+ // store moved off SQLite in v1.33.0.
38
+ const rawDbPath = process.env.DATABASE_PATH || path.join(__dirname, 'auth.db');
39
+ const JSON_PATH = rawDbPath.endsWith('.db')
40
+ ? rawDbPath.replace(/\.db$/, '.json')
41
+ : (rawDbPath.endsWith('.json') ? rawDbPath : `${rawDbPath}.json`);
42
+ const LEGACY_SQLITE_PATH = rawDbPath.endsWith('.db')
43
+ ? rawDbPath
44
+ : rawDbPath.replace(/\.json$/, '.db');
45
+
46
+ // Ensure parent dir exists before migration / initial write.
47
+ {
48
+ const dir = path.dirname(JSON_PATH);
49
+ if (!fs.existsSync(dir)) {
50
+ try { fs.mkdirSync(dir, { recursive: true }); }
51
+ catch (err) {
52
+ console.error(`Failed to create database directory ${dir}:`, err.message);
53
+ throw err;
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * One-time migration from the previous better-sqlite3 auth.db to the
60
+ * new JSON format. Triggered only when:
61
+ * - The legacy .db exists
62
+ * - AND no .json has been created yet
63
+ * The legacy file is kept in place as `<name>.db.migrated-<timestamp>`
64
+ * so a user can roll back by moving it into place and reinstalling
65
+ * better-sqlite3 if they hit a showstopper. Runs synchronously because
66
+ * all downstream modules (auth.js, vapid-keys.js) import `db` at module
67
+ * load and can't wait for async startup.
68
+ */
69
+ function migrateSqliteIfPresent() {
70
+ if (fs.existsSync(JSON_PATH)) return; // Already migrated or fresh install.
71
+ if (!fs.existsSync(LEGACY_SQLITE_PATH)) return; // Nothing to migrate.
72
+
73
+ console.log(`${c.info('[MIGRATION]')} Converting ${c.bright(LEGACY_SQLITE_PATH)} → ${c.bright(JSON_PATH)} (JSON auth store, v1.33.0)`);
74
+
75
+ let Database;
76
+ try {
77
+ const mod = require('better-sqlite3');
78
+ Database = mod.default || mod;
79
+ } catch {
80
+ // Auto-install path fell through — the user has a legacy file but
81
+ // better-sqlite3 isn't present (they may have a trimmed dep tree).
82
+ // Surface a clear error; we'd rather fail startup than silently
83
+ // skip migration and strand the user's saved credentials.
84
+ console.error('[MIGRATION] Legacy auth.db present but better-sqlite3 not installed.');
85
+ console.error('[MIGRATION] Install it once to migrate: `npm install better-sqlite3` in your pixcode install dir, then restart.');
86
+ throw new Error('Auth DB migration requires better-sqlite3 (legacy file detected).');
87
+ }
88
+
89
+ const legacy = new Database(LEGACY_SQLITE_PATH, { readonly: true });
90
+ const store = new JsonStore(JSON_PATH);
91
+
92
+ // Pull every table, skipping silently when it doesn't exist (old
93
+ // installs that never ran some migrations). We rely on `IF NOT EXISTS`
94
+ // patterns from the old schema.js — missing tables throw a SQLite
95
+ // error which we catch per-table.
96
+ const safeAll = (sql) => {
97
+ try { return legacy.prepare(sql).all(); } catch { return []; }
98
+ };
99
+
100
+ const users = safeAll('SELECT id, username, password_hash, created_at, last_login, is_active, git_name, git_email, has_completed_onboarding FROM users');
101
+ for (const u of users) {
102
+ store.raw.users.push({
103
+ id: u.id,
104
+ username: u.username,
105
+ password_hash: u.password_hash,
106
+ created_at: u.created_at || nowIso(),
107
+ last_login: u.last_login || null,
108
+ is_active: u.is_active !== 0,
109
+ git_name: u.git_name || null,
110
+ git_email: u.git_email || null,
111
+ has_completed_onboarding: u.has_completed_onboarding === 1,
112
+ });
113
+ store.raw._sequences.users = Math.max(store.raw._sequences.users, u.id);
114
+ }
115
+
116
+ const apiKeys = safeAll('SELECT id, user_id, key_name, api_key, created_at, last_used, is_active FROM api_keys');
117
+ for (const k of apiKeys) {
118
+ store.raw.api_keys.push({
119
+ id: k.id,
120
+ user_id: k.user_id,
121
+ key_name: k.key_name,
122
+ api_key: k.api_key,
123
+ created_at: k.created_at || nowIso(),
124
+ last_used: k.last_used || null,
125
+ is_active: k.is_active !== 0,
126
+ });
127
+ store.raw._sequences.api_keys = Math.max(store.raw._sequences.api_keys, k.id);
128
+ }
129
+
130
+ const credentials = safeAll('SELECT id, user_id, credential_name, credential_type, credential_value, description, created_at, is_active FROM user_credentials');
131
+ for (const cr of credentials) {
132
+ store.raw.user_credentials.push({
133
+ id: cr.id,
134
+ user_id: cr.user_id,
135
+ credential_name: cr.credential_name,
136
+ credential_type: cr.credential_type,
137
+ credential_value: cr.credential_value,
138
+ description: cr.description || null,
139
+ created_at: cr.created_at || nowIso(),
140
+ is_active: cr.is_active !== 0,
141
+ });
142
+ store.raw._sequences.user_credentials = Math.max(store.raw._sequences.user_credentials, cr.id);
143
+ }
144
+
145
+ const prefs = safeAll('SELECT user_id, preferences_json, updated_at FROM user_notification_preferences');
146
+ for (const p of prefs) {
147
+ store.raw.user_notification_preferences.push({
148
+ user_id: p.user_id,
149
+ preferences_json: p.preferences_json,
150
+ updated_at: p.updated_at || nowIso(),
151
+ });
152
+ }
153
+
154
+ const vapid = safeAll('SELECT id, public_key, private_key, created_at FROM vapid_keys');
155
+ for (const v of vapid) {
156
+ store.raw.vapid_keys.push({
157
+ id: v.id,
158
+ public_key: v.public_key,
159
+ private_key: v.private_key,
160
+ created_at: v.created_at || nowIso(),
161
+ });
162
+ store.raw._sequences.vapid_keys = Math.max(store.raw._sequences.vapid_keys, v.id);
163
+ }
164
+
165
+ const pushSubs = safeAll('SELECT id, user_id, endpoint, keys_p256dh, keys_auth, created_at FROM push_subscriptions');
166
+ for (const s of pushSubs) {
167
+ store.raw.push_subscriptions.push({
168
+ id: s.id,
169
+ user_id: s.user_id,
170
+ endpoint: s.endpoint,
171
+ keys_p256dh: s.keys_p256dh,
172
+ keys_auth: s.keys_auth,
173
+ created_at: s.created_at || nowIso(),
174
+ });
175
+ store.raw._sequences.push_subscriptions = Math.max(store.raw._sequences.push_subscriptions, s.id);
176
+ }
177
+
178
+ const sessionNames = safeAll('SELECT session_id, provider, custom_name, created_at, updated_at FROM session_names');
179
+ for (const sn of sessionNames) {
180
+ store.raw.session_names.push({
181
+ session_id: sn.session_id,
182
+ provider: sn.provider,
183
+ custom_name: sn.custom_name,
184
+ created_at: sn.created_at || nowIso(),
185
+ updated_at: sn.updated_at || nowIso(),
186
+ });
187
+ }
188
+
189
+ const appConfig = safeAll('SELECT key, value, created_at FROM app_config');
190
+ for (const a of appConfig) {
191
+ store.raw.app_config.push({
192
+ key: a.key,
193
+ value: a.value,
194
+ created_at: a.created_at || nowIso(),
195
+ });
196
+ }
197
+
198
+ const telegramConfig = safeAll('SELECT id, bot_token, bot_username, updated_at FROM telegram_config');
199
+ for (const t of telegramConfig) {
200
+ store.raw.telegram_config.push({
201
+ id: 1,
202
+ bot_token: t.bot_token,
203
+ bot_username: t.bot_username || null,
204
+ updated_at: t.updated_at || nowIso(),
205
+ });
206
+ }
207
+
208
+ const telegramLinks = safeAll('SELECT user_id, chat_id, telegram_username, language, pairing_code, pairing_code_expires_at, verified_at, notifications_enabled, bridge_enabled, updated_at FROM telegram_links');
209
+ for (const tl of telegramLinks) {
210
+ store.raw.telegram_links.push({
211
+ user_id: tl.user_id,
212
+ chat_id: tl.chat_id || null,
213
+ telegram_username: tl.telegram_username || null,
214
+ language: tl.language || 'en',
215
+ pairing_code: tl.pairing_code || null,
216
+ pairing_code_expires_at: tl.pairing_code_expires_at || null,
217
+ verified_at: tl.verified_at || null,
218
+ notifications_enabled: tl.notifications_enabled !== 0,
219
+ bridge_enabled: tl.bridge_enabled !== 0,
220
+ updated_at: tl.updated_at || nowIso(),
221
+ });
222
+ }
223
+
224
+ store.save();
225
+ legacy.close();
226
+
227
+ // Rename the old .db out of the way so we never migrate it twice.
228
+ // Keep it (not delete) so the user can roll back if needed.
229
+ const backup = `${LEGACY_SQLITE_PATH}.migrated-${Date.now()}`;
230
+ try {
231
+ fs.renameSync(LEGACY_SQLITE_PATH, backup);
232
+ for (const suffix of ['-wal', '-shm']) {
233
+ if (fs.existsSync(LEGACY_SQLITE_PATH + suffix)) {
234
+ try { fs.renameSync(LEGACY_SQLITE_PATH + suffix, backup + suffix); } catch { /* noop */ }
235
+ }
236
+ }
237
+ } catch (err) {
238
+ console.warn(`[MIGRATION] Migration succeeded but could not rename old DB: ${err.message}`);
239
+ }
240
+
241
+ console.log(`${c.info('[MIGRATION]')} Migration complete. Old DB preserved as ${c.dim(backup)}.`);
242
+ }
243
+
244
+ // Module-load order matters — auth middleware imports `db` and reads the
245
+ // JWT secret before anything else gets to boot. So the store has to be
246
+ // ready synchronously at the first `import { db } from './db.js'`.
247
+ migrateSqliteIfPresent();
248
+
249
+ const store = new JsonStore(JSON_PATH);
250
+
251
+ console.log('');
252
+ console.log(c.dim('═'.repeat(60)));
253
+ console.log(`${c.info('[INFO]')} App Installation: ${c.bright(APP_ROOT)}`);
254
+ console.log(`${c.info('[INFO]')} Auth store: ${c.dim(path.relative(APP_ROOT, JSON_PATH))}`);
255
+ if (process.env.DATABASE_PATH) {
256
+ console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
257
+ }
258
+ console.log(c.dim('═'.repeat(60)));
259
+ console.log('');
260
+
261
+ // initializeDatabase used to run `CREATE TABLE IF NOT EXISTS` + migrations.
262
+ // The JSON store always has its shape pre-baked, so this is a no-op —
263
+ // keeping the export preserves the server boot sequence.
264
+ const initializeDatabase = async () => { /* schema lives in code, not in file */ };
265
+
266
+ // ---------------------------------------------------------------------------
267
+ // Back-compat `db` shim — a few modules outside database/db.js imported `db`
268
+ // and called `db.prepare(sql)` directly. Most of those uses were for trivial
269
+ // transaction markers (BEGIN/COMMIT/ROLLBACK — no-op under our JSON store)
270
+ // or very specific SELECTs we've wrapped in explicit helpers. This shim
271
+ // lets those call sites keep working without a bigger refactor.
272
+ // ---------------------------------------------------------------------------
273
+ const db = {
274
+ prepare(sql) {
275
+ const normalized = sql.trim().toUpperCase();
276
+ // Transaction markers — our store writes atomically per op, so
277
+ // there's no real transaction to start. No-op + success result.
278
+ if (normalized === 'BEGIN' || normalized === 'COMMIT' || normalized === 'ROLLBACK') {
279
+ return {
280
+ run: () => ({ changes: 0, lastInsertRowid: 0 }),
281
+ };
282
+ }
283
+
284
+ // Specific query routed through the new helpers — used by
285
+ // server/routes/projects.js to fetch a single github credential.
286
+ if (/FROM USER_CREDENTIALS\s+WHERE ID = \?\s+AND USER_ID = \?\s+AND CREDENTIAL_TYPE = \?\s+AND IS_ACTIVE = 1/.test(normalized)) {
287
+ return {
288
+ get: (id, userId, credentialType) =>
289
+ store.findWhere('user_credentials',
290
+ (r) => r.id === id && r.user_id === userId && r.credential_type === credentialType && r.is_active)
291
+ || undefined,
292
+ };
293
+ }
294
+
295
+ throw new Error(
296
+ `db.prepare: unsupported SQL passed through the compat shim: ${sql.slice(0, 80)}`
297
+ + '\nExtend server/database/db.js or use a dedicated helper (userDb, credentialsDb, …).',
298
+ );
299
+ },
300
+ };
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // User operations
304
+ // ---------------------------------------------------------------------------
305
+ const userDb = {
306
+ hasUsers: () => store.count('users', (r) => r.is_active) > 0,
307
+
308
+ createUser: (username, passwordHash) => {
309
+ const row = store.insert('users', {
310
+ username,
311
+ password_hash: passwordHash,
312
+ created_at: nowIso(),
313
+ last_login: null,
314
+ is_active: true,
315
+ git_name: null,
316
+ git_email: null,
317
+ has_completed_onboarding: false,
318
+ });
319
+ return { id: row.id, username: row.username };
320
+ },
321
+
322
+ getUserByUsername: (username) =>
323
+ store.findWhere('users', (r) => r.username === username && r.is_active) || undefined,
324
+
325
+ updateLastLogin: (userId) => {
326
+ try {
327
+ store.updateWhere('users', (r) => r.id === userId, { last_login: nowIso() });
328
+ } catch (err) {
329
+ console.warn('Failed to update last login:', err.message);
330
+ }
331
+ },
332
+
333
+ getUserById: (userId) => {
334
+ const row = store.findWhere('users', (r) => r.id === userId && r.is_active);
335
+ if (!row) return undefined;
336
+ return {
337
+ id: row.id,
338
+ username: row.username,
339
+ created_at: row.created_at,
340
+ last_login: row.last_login,
341
+ };
342
+ },
343
+
344
+ getFirstUser: () => {
345
+ const row = store.raw.users.find((r) => r.is_active);
346
+ if (!row) return undefined;
347
+ return {
348
+ id: row.id,
349
+ username: row.username,
350
+ created_at: row.created_at,
351
+ last_login: row.last_login,
352
+ };
353
+ },
354
+
355
+ updateGitConfig: (userId, gitName, gitEmail) => {
356
+ store.updateWhere('users', (r) => r.id === userId, { git_name: gitName, git_email: gitEmail });
357
+ },
358
+
359
+ getGitConfig: (userId) => {
360
+ const row = store.findWhere('users', (r) => r.id === userId);
361
+ if (!row) return undefined;
362
+ return { git_name: row.git_name || null, git_email: row.git_email || null };
363
+ },
364
+
365
+ completeOnboarding: (userId) => {
366
+ store.updateWhere('users', (r) => r.id === userId, { has_completed_onboarding: true });
367
+ },
368
+
369
+ hasCompletedOnboarding: (userId) => {
370
+ const row = store.findWhere('users', (r) => r.id === userId);
371
+ return Boolean(row?.has_completed_onboarding);
372
+ },
373
+ };
374
+
375
+ // ---------------------------------------------------------------------------
376
+ // API key operations
377
+ // ---------------------------------------------------------------------------
378
+ const apiKeysDb = {
379
+ generateApiKey: () => 'ck_' + crypto.randomBytes(32).toString('hex'),
380
+
381
+ createApiKey: (userId, keyName) => {
382
+ const apiKey = apiKeysDb.generateApiKey();
383
+ const row = store.insert('api_keys', {
384
+ user_id: userId,
385
+ key_name: keyName,
386
+ api_key: apiKey,
387
+ created_at: nowIso(),
388
+ last_used: null,
389
+ is_active: true,
390
+ });
391
+ return { id: row.id, keyName, apiKey };
392
+ },
393
+
394
+ getApiKeys: (userId) => {
395
+ const rows = store.filterWhere('api_keys', (r) => r.user_id === userId);
396
+ // Match the old ORDER BY created_at DESC behaviour.
397
+ return rows
398
+ .slice()
399
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
400
+ .map((r) => ({
401
+ id: r.id,
402
+ key_name: r.key_name,
403
+ api_key: r.api_key,
404
+ created_at: r.created_at,
405
+ last_used: r.last_used,
406
+ is_active: r.is_active ? 1 : 0,
407
+ }));
408
+ },
409
+
410
+ validateApiKey: (apiKey) => {
411
+ const key = store.findWhere('api_keys', (r) => r.api_key === apiKey && r.is_active);
412
+ if (!key) return undefined;
413
+ const user = store.findWhere('users', (r) => r.id === key.user_id && r.is_active);
414
+ if (!user) return undefined;
415
+ // Mirror the SQL-era side effect: stamp last_used. Only relevant
416
+ // for the "which key was used last" display in the UI.
417
+ store.updateWhere('api_keys', (r) => r.id === key.id, { last_used: nowIso() });
418
+ return {
419
+ id: user.id,
420
+ username: user.username,
421
+ api_key_id: key.id,
422
+ };
423
+ },
424
+
425
+ deleteApiKey: (userId, apiKeyId) =>
426
+ store.deleteWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId) > 0,
427
+
428
+ toggleApiKey: (userId, apiKeyId, isActive) =>
429
+ store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
430
+ };
431
+
432
+ // ---------------------------------------------------------------------------
433
+ // Credentials (GitHub tokens, etc.) operations
434
+ // ---------------------------------------------------------------------------
435
+ const credentialsDb = {
436
+ createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
437
+ const row = store.insert('user_credentials', {
438
+ user_id: userId,
439
+ credential_name: credentialName,
440
+ credential_type: credentialType,
441
+ credential_value: credentialValue,
442
+ description,
443
+ created_at: nowIso(),
444
+ is_active: true,
445
+ });
446
+ return { id: row.id, credentialName, credentialType };
447
+ },
448
+
449
+ getCredentials: (userId, credentialType = null) => {
450
+ const rows = store.filterWhere('user_credentials', (r) =>
451
+ r.user_id === userId && (credentialType == null || r.credential_type === credentialType),
452
+ );
453
+ return rows
454
+ .slice()
455
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
456
+ .map((r) => ({
457
+ id: r.id,
458
+ credential_name: r.credential_name,
459
+ credential_type: r.credential_type,
460
+ description: r.description,
461
+ created_at: r.created_at,
462
+ is_active: r.is_active ? 1 : 0,
463
+ }));
464
+ },
465
+
466
+ getActiveCredential: (userId, credentialType) => {
467
+ const rows = store.filterWhere('user_credentials', (r) =>
468
+ r.user_id === userId && r.credential_type === credentialType && r.is_active,
469
+ );
470
+ if (rows.length === 0) return null;
471
+ // "Most recent active" — mirror ORDER BY created_at DESC LIMIT 1
472
+ rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
473
+ return rows[0].credential_value;
474
+ },
475
+
476
+ getCredentialById: (userId, credentialId, credentialType = null) => {
477
+ const row = store.findWhere('user_credentials', (r) =>
478
+ r.id === credentialId && r.user_id === userId && r.is_active
479
+ && (credentialType == null || r.credential_type === credentialType),
480
+ );
481
+ return row || undefined;
482
+ },
483
+
484
+ deleteCredential: (userId, credentialId) =>
485
+ store.deleteWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId) > 0,
486
+
487
+ toggleCredential: (userId, credentialId, isActive) =>
488
+ store.updateWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
489
+ };
490
+
491
+ // ---------------------------------------------------------------------------
492
+ // Notification preferences
493
+ // ---------------------------------------------------------------------------
494
+ const DEFAULT_NOTIFICATION_PREFERENCES = {
495
+ channels: { inApp: false, webPush: false },
496
+ events: { actionRequired: true, stop: true, error: true },
497
+ };
498
+
499
+ const normalizeNotificationPreferences = (value) => {
500
+ const source = value && typeof value === 'object' ? value : {};
501
+ return {
502
+ channels: {
503
+ inApp: source.channels?.inApp === true,
504
+ webPush: source.channels?.webPush === true,
505
+ },
506
+ events: {
507
+ actionRequired: source.events?.actionRequired !== false,
508
+ stop: source.events?.stop !== false,
509
+ error: source.events?.error !== false,
510
+ },
511
+ };
512
+ };
513
+
514
+ const notificationPreferencesDb = {
515
+ getPreferences: (userId) => {
516
+ const row = store.findWhere('user_notification_preferences', (r) => r.user_id === userId);
517
+ if (!row) {
518
+ const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
519
+ store.insert('user_notification_preferences', {
520
+ user_id: userId,
521
+ preferences_json: JSON.stringify(defaults),
522
+ updated_at: nowIso(),
523
+ }, { autoId: false });
524
+ return defaults;
525
+ }
526
+ try {
527
+ return normalizeNotificationPreferences(JSON.parse(row.preferences_json));
528
+ } catch {
529
+ return normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
530
+ }
531
+ },
532
+
533
+ updatePreferences: (userId, preferences) => {
534
+ const normalized = normalizeNotificationPreferences(preferences);
535
+ store.upsertWhere(
536
+ 'user_notification_preferences',
537
+ (r) => r.user_id === userId,
538
+ { user_id: userId, preferences_json: JSON.stringify(normalized), updated_at: nowIso() },
539
+ );
540
+ return normalized;
541
+ },
542
+ };
543
+
544
+ // ---------------------------------------------------------------------------
545
+ // Push subscriptions
546
+ // ---------------------------------------------------------------------------
547
+ const pushSubscriptionsDb = {
548
+ saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
549
+ // The old SQL path upserted on `endpoint`, updating user_id as
550
+ // well. Preserve that exact behaviour.
551
+ const existing = store.findWhere('push_subscriptions', (r) => r.endpoint === endpoint);
552
+ if (existing) {
553
+ store.updateWhere('push_subscriptions', (r) => r.endpoint === endpoint, {
554
+ user_id: userId,
555
+ keys_p256dh: keysP256dh,
556
+ keys_auth: keysAuth,
557
+ });
558
+ return;
559
+ }
560
+ store.insert('push_subscriptions', {
561
+ user_id: userId,
562
+ endpoint,
563
+ keys_p256dh: keysP256dh,
564
+ keys_auth: keysAuth,
565
+ created_at: nowIso(),
566
+ });
567
+ },
568
+
569
+ getSubscriptions: (userId) =>
570
+ store.filterWhere('push_subscriptions', (r) => r.user_id === userId).map((r) => ({
571
+ endpoint: r.endpoint,
572
+ keys_p256dh: r.keys_p256dh,
573
+ keys_auth: r.keys_auth,
574
+ })),
575
+
576
+ removeSubscription: (endpoint) => {
577
+ store.deleteWhere('push_subscriptions', (r) => r.endpoint === endpoint);
578
+ },
579
+
580
+ removeAllForUser: (userId) => {
581
+ store.deleteWhere('push_subscriptions', (r) => r.user_id === userId);
582
+ },
583
+ };
584
+
585
+ // ---------------------------------------------------------------------------
586
+ // VAPID key storage (for web push)
587
+ // ---------------------------------------------------------------------------
588
+ const vapidKeysDb = {
589
+ getLatest: () => {
590
+ if (store.raw.vapid_keys.length === 0) return null;
591
+ // Mirror ORDER BY id DESC LIMIT 1 — take the newest row.
592
+ const rows = store.raw.vapid_keys.slice().sort((a, b) => b.id - a.id);
593
+ return { public_key: rows[0].public_key, private_key: rows[0].private_key };
594
+ },
595
+ insert: (publicKey, privateKey) => {
596
+ store.insert('vapid_keys', {
597
+ public_key: publicKey,
598
+ private_key: privateKey,
599
+ created_at: nowIso(),
600
+ });
601
+ },
602
+ };
603
+
604
+ // ---------------------------------------------------------------------------
605
+ // Session custom names
606
+ // ---------------------------------------------------------------------------
607
+ const sessionNamesDb = {
608
+ setName: (sessionId, provider, customName) => {
609
+ store.upsertWhere(
610
+ 'session_names',
611
+ (r) => r.session_id === sessionId && r.provider === provider,
612
+ { session_id: sessionId, provider, custom_name: customName, updated_at: nowIso(), created_at: nowIso() },
613
+ );
614
+ },
615
+
616
+ getName: (sessionId, provider) => {
617
+ const row = store.findWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider);
618
+ return row?.custom_name || null;
619
+ },
620
+
621
+ getNames: (sessionIds, provider) => {
622
+ if (!sessionIds.length) return new Map();
623
+ const lookup = new Set(sessionIds);
624
+ const matches = store.filterWhere('session_names',
625
+ (r) => r.provider === provider && lookup.has(r.session_id));
626
+ return new Map(matches.map((r) => [r.session_id, r.custom_name]));
627
+ },
628
+
629
+ deleteName: (sessionId, provider) =>
630
+ store.deleteWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider) > 0,
631
+ };
632
+
633
+ function applyCustomSessionNames(sessions, provider) {
634
+ if (!sessions?.length) return;
635
+ try {
636
+ const ids = sessions.map((s) => s.id);
637
+ const customNames = sessionNamesDb.getNames(ids, provider);
638
+ for (const session of sessions) {
639
+ const custom = customNames.get(session.id);
640
+ if (custom) session.summary = custom;
641
+ }
642
+ } catch (error) {
643
+ console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
644
+ }
645
+ }
646
+
647
+ // ---------------------------------------------------------------------------
648
+ // App config (key/value)
649
+ // ---------------------------------------------------------------------------
650
+ const appConfigDb = {
651
+ get: (key) => {
652
+ const row = store.findWhere('app_config', (r) => r.key === key);
653
+ return row?.value || null;
654
+ },
655
+
656
+ set: (key, value) => {
657
+ store.upsertWhere('app_config', (r) => r.key === key,
658
+ { key, value, created_at: nowIso() });
659
+ },
660
+
661
+ getOrCreateJwtSecret: () => {
662
+ let secret = appConfigDb.get('jwt_secret');
663
+ if (!secret) {
664
+ secret = crypto.randomBytes(64).toString('hex');
665
+ appConfigDb.set('jwt_secret', secret);
666
+ }
667
+ return secret;
668
+ },
669
+ };
670
+
671
+ // ---------------------------------------------------------------------------
672
+ // Telegram — singleton config + per-user links
673
+ // ---------------------------------------------------------------------------
674
+ const telegramConfigDb = {
675
+ get: () => {
676
+ const row = store.raw.telegram_config[0];
677
+ if (!row) return null;
678
+ return { bot_token: row.bot_token, bot_username: row.bot_username, updated_at: row.updated_at };
679
+ },
680
+ set: (botToken, botUsername = null) => {
681
+ store.raw.telegram_config = [{
682
+ id: 1,
683
+ bot_token: botToken,
684
+ bot_username: botUsername,
685
+ updated_at: nowIso(),
686
+ }];
687
+ store.save();
688
+ },
689
+ clear: () => {
690
+ store.raw.telegram_config = [];
691
+ store.save();
692
+ },
693
+ };
694
+
695
+ const telegramLinksDb = {
696
+ setPairingCode: (userId, code, expiresAt, language) => {
697
+ store.upsertWhere('telegram_links', (r) => r.user_id === userId, {
698
+ user_id: userId,
699
+ pairing_code: code,
700
+ pairing_code_expires_at: expiresAt,
701
+ language,
702
+ chat_id: null,
703
+ telegram_username: null,
704
+ verified_at: null,
705
+ notifications_enabled: true,
706
+ bridge_enabled: true,
707
+ updated_at: nowIso(),
708
+ });
709
+ },
710
+ findByPairingCode: (code) => {
711
+ const row = store.findWhere('telegram_links', (r) => r.pairing_code === code);
712
+ if (!row) return null;
713
+ return {
714
+ user_id: row.user_id,
715
+ pairing_code: row.pairing_code,
716
+ pairing_code_expires_at: row.pairing_code_expires_at,
717
+ language: row.language,
718
+ };
719
+ },
720
+ verify: (userId, chatId, telegramUsername) => {
721
+ store.updateWhere('telegram_links', (r) => r.user_id === userId, {
722
+ chat_id: chatId,
723
+ telegram_username: telegramUsername,
724
+ verified_at: nowIso(),
725
+ pairing_code: null,
726
+ pairing_code_expires_at: null,
727
+ updated_at: nowIso(),
728
+ });
729
+ },
730
+ getByUserId: (userId) => {
731
+ const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
732
+ return row ? { ...row } : null;
733
+ },
734
+ getByChatId: (chatId) => {
735
+ const row = store.findWhere('telegram_links', (r) => r.chat_id === chatId);
736
+ if (!row) return null;
737
+ return {
738
+ user_id: row.user_id,
739
+ chat_id: row.chat_id,
740
+ telegram_username: row.telegram_username,
741
+ language: row.language,
742
+ notifications_enabled: row.notifications_enabled,
743
+ bridge_enabled: row.bridge_enabled,
744
+ };
745
+ },
746
+ listVerified: () =>
747
+ store.filterWhere('telegram_links', (r) => r.chat_id && r.verified_at).map((r) => ({
748
+ user_id: r.user_id,
749
+ chat_id: r.chat_id,
750
+ telegram_username: r.telegram_username,
751
+ language: r.language,
752
+ notifications_enabled: r.notifications_enabled,
753
+ bridge_enabled: r.bridge_enabled,
754
+ })),
755
+ updatePreferences: (userId, { language, notificationsEnabled, bridgeEnabled }) => {
756
+ const patch = { updated_at: nowIso() };
757
+ if (language !== undefined) patch.language = language;
758
+ if (notificationsEnabled !== undefined) patch.notifications_enabled = Boolean(notificationsEnabled);
759
+ if (bridgeEnabled !== undefined) patch.bridge_enabled = Boolean(bridgeEnabled);
760
+ if (Object.keys(patch).length === 1) return; // only updated_at → no real change
761
+ store.updateWhere('telegram_links', (r) => r.user_id === userId, patch);
762
+ },
763
+ unlink: (userId) => {
764
+ store.deleteWhere('telegram_links', (r) => r.user_id === userId);
765
+ },
766
+ };
767
+
768
+ // Back-compat surface — older callers used `githubTokensDb.*`; internally
769
+ // they always delegated to credentialsDb with `credential_type='github_token'`.
770
+ const githubTokensDb = {
771
+ createGithubToken: (userId, tokenName, githubToken, description = null) =>
772
+ credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description),
773
+ getGithubTokens: (userId) => credentialsDb.getCredentials(userId, 'github_token'),
774
+ getActiveGithubToken: (userId) => credentialsDb.getActiveCredential(userId, 'github_token'),
775
+ deleteGithubToken: (userId, tokenId) => credentialsDb.deleteCredential(userId, tokenId),
776
+ toggleGithubToken: (userId, tokenId, isActive) => credentialsDb.toggleCredential(userId, tokenId, isActive),
777
+ };
778
+
779
+ export {
780
+ db,
781
+ initializeDatabase,
782
+ userDb,
783
+ apiKeysDb,
784
+ credentialsDb,
785
+ notificationPreferencesDb,
786
+ pushSubscriptionsDb,
787
+ vapidKeysDb,
788
+ sessionNamesDb,
789
+ applyCustomSessionNames,
790
+ appConfigDb,
791
+ telegramConfigDb,
792
+ telegramLinksDb,
793
+ githubTokensDb,
794
+ };