@pixelbyte-software/pixcode 1.51.1 → 1.51.3
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.
- package/CODE_OF_CONDUCT.md +41 -41
- package/CONTRIBUTING.md +155 -155
- package/LICENSE +718 -718
- package/README.de.md +169 -169
- package/README.ja.md +167 -167
- package/README.ko.md +167 -167
- package/README.md +419 -419
- package/README.ru.md +169 -169
- package/README.tr.md +298 -298
- package/README.zh-CN.md +167 -167
- package/SECURITY.md +46 -46
- package/dist/api-automation.html +110 -110
- package/dist/api-docs.html +548 -548
- package/dist/assets/{index-DARIZgoD.js → index-17CwxHSZ.js} +185 -185
- package/dist/assets/index-B9N-gfOQ.css +32 -0
- package/dist/clear-cache.html +85 -85
- package/dist/convert-icons.md +52 -52
- package/dist/docs.html +308 -308
- package/dist/favicon.svg +8 -8
- package/dist/features.html +133 -133
- package/dist/generate-icons.js +48 -48
- package/dist/humans.txt +15 -15
- package/dist/icons/codex-white.svg +3 -3
- package/dist/icons/codex.svg +3 -3
- package/dist/icons/cursor-white.svg +11 -11
- package/dist/icons/icon-128x128.svg +9 -9
- package/dist/icons/icon-144x144.svg +9 -9
- package/dist/icons/icon-152x152.svg +9 -9
- package/dist/icons/icon-192x192.svg +9 -9
- package/dist/icons/icon-384x384.svg +9 -9
- package/dist/icons/icon-512x512.svg +9 -9
- package/dist/icons/icon-72x72.svg +9 -9
- package/dist/icons/icon-96x96.svg +9 -9
- package/dist/icons/icon-template.svg +9 -9
- package/dist/icons/qwen-logo.svg +14 -14
- package/dist/index.html +59 -59
- package/dist/landing.html +268 -268
- package/dist/llms-full.txt +119 -119
- package/dist/llms.txt +53 -53
- package/dist/logo.svg +12 -12
- package/dist/manifest.json +60 -60
- package/dist/openapi.yaml +1696 -1696
- package/dist/orchestration.html +125 -125
- package/dist/robots.txt +4 -4
- package/dist/site.css +692 -692
- package/dist/sitemap.xml +51 -51
- package/dist/sw.js +132 -132
- package/dist-server/server/cli.js +96 -96
- package/dist-server/server/daemon/manager.js +33 -33
- package/dist-server/server/daemon-manager.js +64 -64
- package/dist-server/server/index.js +125 -4
- package/dist-server/server/index.js.map +1 -1
- package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js +84 -0
- package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js.map +1 -0
- package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js +43 -0
- package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js.map +1 -0
- package/dist-server/server/modules/orchestration/hermes/hermes.routes.js +55 -1
- package/dist-server/server/modules/orchestration/hermes/hermes.routes.js.map +1 -1
- package/dist-server/server/modules/orchestration/index.js +1 -0
- package/dist-server/server/modules/orchestration/index.js.map +1 -1
- package/dist-server/server/routes/commands.js +25 -25
- package/dist-server/server/routes/git.js +17 -17
- package/dist-server/server/routes/live-view.js +46 -46
- package/dist-server/server/services/hermes-gateway.js +310 -0
- package/dist-server/server/services/hermes-gateway.js.map +1 -1
- package/dist-server/server/services/public-api-manifest.js +59 -51
- package/dist-server/server/services/public-api-manifest.js.map +1 -1
- package/package.json +222 -222
- package/scripts/fix-node-pty.js +67 -67
- package/scripts/github/create-v1.38-issues.mjs +351 -351
- package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
- package/scripts/hermes/configure-pixcode-mcp.mjs +165 -163
- package/scripts/hermes/pixcode-mcp-server.mjs +1009 -958
- package/scripts/smoke/changes-panel-layout.mjs +48 -48
- package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
- package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
- package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
- package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
- package/scripts/smoke/chat-session-state.mjs +19 -19
- package/scripts/smoke/code-editor-theme.mjs +55 -55
- package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
- package/scripts/smoke/command-center-agent-writes.mjs +79 -79
- package/scripts/smoke/command-center-non-git.mjs +46 -46
- package/scripts/smoke/context-packet.mjs +43 -43
- package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
- package/scripts/smoke/daemon-entrypoint.mjs +20 -20
- package/scripts/smoke/default-landing-routing.mjs +33 -33
- package/scripts/smoke/desktop-native-notifications.mjs +30 -30
- package/scripts/smoke/desktop-tray-icon.mjs +33 -33
- package/scripts/smoke/discord-release-workflow.mjs +24 -24
- package/scripts/smoke/git-install-update.mjs +255 -255
- package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
- package/scripts/smoke/hermes-api-install.mjs +56 -56
- package/scripts/smoke/hermes-gateway-persistence.mjs +104 -104
- package/scripts/smoke/hermes-mcp-pixcode-roundtrip.mjs +426 -367
- package/scripts/smoke/hermes-rest-chat-api.mjs +162 -162
- package/scripts/smoke/hermes-rest-chat-live.mjs +45 -45
- package/scripts/smoke/hermes-rest-codex-launch.mjs +209 -209
- package/scripts/smoke/hermes-rest-gateway.mjs +79 -70
- package/scripts/smoke/hermes-rest-live.mjs +42 -42
- package/scripts/smoke/hermes-roundtrip.mjs +167 -167
- package/scripts/smoke/hermes-settings-commands.mjs +349 -346
- package/scripts/smoke/hermes-smoke-launcher-guard.mjs +34 -34
- package/scripts/smoke/live-view-diagnostics.mjs +53 -53
- package/scripts/smoke/live-view-environment.mjs +92 -92
- package/scripts/smoke/live-view-integration.mjs +450 -450
- package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
- package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
- package/scripts/smoke/model-registry.mjs +36 -36
- package/scripts/smoke/multi-project-ui.mjs +45 -45
- package/scripts/smoke/multi-worker-slots.mjs +42 -42
- package/scripts/smoke/notification-center.mjs +87 -87
- package/scripts/smoke/notification-inapp-preference.mjs +23 -23
- package/scripts/smoke/notification-taxonomy.mjs +58 -58
- package/scripts/smoke/orchestration-api.mjs +172 -172
- package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
- package/scripts/smoke/orchestration-live-run.mjs +176 -176
- package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
- package/scripts/smoke/orchestration-model-sync.mjs +30 -30
- package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
- package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
- package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
- package/scripts/smoke/permission-policy.mjs +50 -50
- package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -164
- package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
- package/scripts/smoke/provider-rest-api.mjs +124 -124
- package/scripts/smoke/provider-selection-status.mjs +52 -52
- package/scripts/smoke/run-state-refresh.mjs +52 -52
- package/scripts/smoke/runtime-manager.mjs +99 -99
- package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
- package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
- package/scripts/smoke/static-root-routing.mjs +21 -21
- package/scripts/smoke/strict-handoff-compact.mjs +60 -60
- package/scripts/smoke/taskmaster-config.mjs +24 -24
- package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
- package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
- package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
- package/scripts/smoke/telegram-control.mjs +242 -242
- package/scripts/smoke/tunnel-persistence.mjs +56 -56
- package/scripts/smoke/update-issue-progress.mjs +69 -69
- package/scripts/smoke/update-ux.mjs +55 -55
- package/scripts/smoke/v138-completion.mjs +132 -132
- package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
- package/scripts/smoke/v138-diagnostics.mjs +63 -63
- package/scripts/smoke/v138-issue-planner.mjs +33 -33
- package/scripts/smoke/v143-remote-control.mjs +76 -76
- package/scripts/smoke/v144-production-loop.mjs +47 -47
- package/scripts/smoke/v145-platformization.mjs +46 -46
- package/scripts/smoke/v146-control-room-ui.mjs +150 -150
- package/scripts/smoke/version-modal-autoshow.mjs +29 -29
- package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
- package/scripts/smoke/vscode-workbench-polish.mjs +461 -436
- package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
- package/scripts/smoke/workflow-templates.mjs +43 -43
- package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
- package/scripts/update-git-install.mjs +293 -293
- package/server/claude-sdk.js +920 -920
- package/server/cli.js +1039 -1039
- package/server/constants/config.js +4 -4
- package/server/cursor-cli.js +344 -344
- package/server/daemon/manager.js +563 -563
- package/server/daemon-manager.js +964 -964
- package/server/database/db.js +921 -921
- package/server/database/json-store.js +197 -197
- package/server/gemini-cli.js +550 -550
- package/server/gemini-response-handler.js +79 -79
- package/server/index.js +131 -3
- package/server/load-env.js +35 -35
- package/server/middleware/auth.js +175 -175
- package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
- package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
- package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
- package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
- package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
- package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
- package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -0
- package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -0
- package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
- package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
- package/server/modules/orchestration/a2a/agent-card.ts +55 -55
- package/server/modules/orchestration/a2a/routes.ts +590 -590
- package/server/modules/orchestration/a2a/task-store.ts +178 -178
- package/server/modules/orchestration/a2a/types.ts +126 -126
- package/server/modules/orchestration/a2a/validator.ts +113 -113
- package/server/modules/orchestration/hermes/hermes.routes.ts +642 -583
- package/server/modules/orchestration/index.ts +101 -100
- package/server/modules/orchestration/preview/port-watcher.ts +112 -112
- package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
- package/server/modules/orchestration/preview/types.ts +19 -19
- package/server/modules/orchestration/security/permission-policy.ts +401 -401
- package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
- package/server/modules/orchestration/tasks/orchestration-task.routes.ts +64 -64
- package/server/modules/orchestration/tasks/orchestration-task.service.ts +209 -209
- package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
- package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
- package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
- package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
- package/server/modules/orchestration/workflows/context-packet.ts +186 -186
- package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
- package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
- package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
- package/server/modules/orchestration/workflows/workflow-runner.ts +2070 -2070
- package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
- package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
- package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
- package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
- package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
- package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
- package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
- package/server/modules/orchestration/workspace/path-safety.ts +55 -55
- package/server/modules/orchestration/workspace/types.ts +52 -52
- package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
- package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
- package/server/modules/providers/index.ts +2 -2
- package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
- package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
- package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
- package/server/modules/providers/list/claude/claude.provider.ts +15 -15
- package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
- package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
- package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
- package/server/modules/providers/list/codex/codex.provider.ts +15 -15
- package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
- package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
- package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
- package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
- package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
- package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
- package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
- package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
- package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
- package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
- package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
- package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
- package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
- package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
- package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
- package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
- package/server/modules/providers/provider.registry.ts +40 -40
- package/server/modules/providers/provider.routes.ts +944 -944
- package/server/modules/providers/services/mcp.service.ts +86 -86
- package/server/modules/providers/services/provider-auth.service.ts +26 -26
- package/server/modules/providers/services/sessions.service.ts +45 -45
- package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
- package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
- package/server/modules/providers/shared/provider-configs.ts +142 -142
- package/server/modules/providers/tests/mcp.test.ts +293 -293
- package/server/openai-codex.js +462 -462
- package/server/opencode-cli.js +491 -491
- package/server/opencode-response-handler.js +111 -111
- package/server/projects.js +3008 -3008
- package/server/qwen-code-cli.js +410 -410
- package/server/qwen-response-handler.js +73 -73
- package/server/routes/agent.js +1435 -1435
- package/server/routes/auth.js +159 -159
- package/server/routes/codex.js +20 -20
- package/server/routes/commands.js +570 -570
- package/server/routes/cursor.js +61 -61
- package/server/routes/diagnostics.js +41 -41
- package/server/routes/gemini.js +25 -25
- package/server/routes/git.js +1650 -1650
- package/server/routes/live-view.js +411 -411
- package/server/routes/mcp-utils.js +13 -13
- package/server/routes/messages.js +62 -62
- package/server/routes/network.js +125 -125
- package/server/routes/platformization.js +212 -212
- package/server/routes/plugins.js +320 -320
- package/server/routes/production-agent-loop.js +90 -90
- package/server/routes/projects.js +917 -917
- package/server/routes/public-api.js +34 -34
- package/server/routes/qwen.js +27 -27
- package/server/routes/remote.js +55 -55
- package/server/routes/settings.js +321 -321
- package/server/routes/telegram.js +140 -140
- package/server/routes/user.js +125 -125
- package/server/routes/webhooks.js +63 -63
- package/server/services/control-room.js +102 -102
- package/server/services/diagnostics.js +165 -165
- package/server/services/external-access.js +375 -375
- package/server/services/hermes-gateway.js +1562 -1247
- package/server/services/hermes-install-jobs.js +729 -729
- package/server/services/install-jobs.js +715 -715
- package/server/services/live-view.js +956 -956
- package/server/services/managed-runtimes.js +493 -493
- package/server/services/model-registry.js +144 -144
- package/server/services/notification-orchestrator.js +365 -365
- package/server/services/notification-taxonomy.js +204 -204
- package/server/services/platformization.js +815 -815
- package/server/services/production-agent-loop.js +248 -248
- package/server/services/provider-cli-versions.js +149 -149
- package/server/services/provider-credentials.js +189 -189
- package/server/services/provider-models.js +396 -396
- package/server/services/public-api-manifest.js +190 -182
- package/server/services/remote-connection.js +127 -127
- package/server/services/runtime-manager.js +323 -323
- package/server/services/startup-update.js +234 -234
- package/server/services/telegram/bot.js +331 -331
- package/server/services/telegram/control-center.js +979 -979
- package/server/services/telegram/telegram-http-client.js +151 -151
- package/server/services/telegram/translations.js +340 -340
- package/server/services/vapid-keys.js +36 -36
- package/server/services/webhooks.js +216 -216
- package/server/sessionManager.js +225 -225
- package/server/shared/interfaces.ts +54 -54
- package/server/shared/types.ts +172 -172
- package/server/shared/utils.ts +193 -193
- package/server/tsconfig.json +36 -36
- package/server/utils/colors.js +21 -21
- package/server/utils/commandParser.js +305 -305
- package/server/utils/frontmatter.js +18 -18
- package/server/utils/gitConfig.js +34 -34
- package/server/utils/plugin-loader.js +457 -457
- package/server/utils/plugin-process-manager.js +185 -185
- package/server/utils/port-access.js +209 -209
- package/server/utils/runtime-paths.js +37 -37
- package/server/utils/url-detection.js +71 -71
- package/server/vite-daemon.js +79 -79
- package/shared/modelConstants.js +161 -161
- package/shared/networkHosts.js +22 -22
- package/dist/assets/index-DMz0zv6T.css +0 -32
package/server/database/db.js
CHANGED
|
@@ -1,921 +1,921 @@
|
|
|
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
|
-
telegram_control: null,
|
|
221
|
-
updated_at: tl.updated_at || nowIso(),
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
store.save();
|
|
226
|
-
legacy.close();
|
|
227
|
-
|
|
228
|
-
// Rename the old .db out of the way so we never migrate it twice.
|
|
229
|
-
// Keep it (not delete) so the user can roll back if needed.
|
|
230
|
-
const backup = `${LEGACY_SQLITE_PATH}.migrated-${Date.now()}`;
|
|
231
|
-
try {
|
|
232
|
-
fs.renameSync(LEGACY_SQLITE_PATH, backup);
|
|
233
|
-
for (const suffix of ['-wal', '-shm']) {
|
|
234
|
-
if (fs.existsSync(LEGACY_SQLITE_PATH + suffix)) {
|
|
235
|
-
try { fs.renameSync(LEGACY_SQLITE_PATH + suffix, backup + suffix); } catch { /* noop */ }
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
} catch (err) {
|
|
239
|
-
console.warn(`[MIGRATION] Migration succeeded but could not rename old DB: ${err.message}`);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
console.log(`${c.info('[MIGRATION]')} Migration complete. Old DB preserved as ${c.dim(backup)}.`);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// Module-load order matters — auth middleware imports `db` and reads the
|
|
246
|
-
// JWT secret before anything else gets to boot. So the store has to be
|
|
247
|
-
// ready synchronously at the first `import { db } from './db.js'`.
|
|
248
|
-
migrateSqliteIfPresent();
|
|
249
|
-
|
|
250
|
-
const store = new JsonStore(JSON_PATH);
|
|
251
|
-
|
|
252
|
-
console.log('');
|
|
253
|
-
console.log(c.dim('═'.repeat(60)));
|
|
254
|
-
console.log(`${c.info('[INFO]')} App Installation: ${c.bright(APP_ROOT)}`);
|
|
255
|
-
console.log(`${c.info('[INFO]')} Auth store: ${c.dim(path.relative(APP_ROOT, JSON_PATH))}`);
|
|
256
|
-
if (process.env.DATABASE_PATH) {
|
|
257
|
-
console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
|
|
258
|
-
}
|
|
259
|
-
console.log(c.dim('═'.repeat(60)));
|
|
260
|
-
console.log('');
|
|
261
|
-
|
|
262
|
-
// initializeDatabase used to run `CREATE TABLE IF NOT EXISTS` + migrations.
|
|
263
|
-
// The JSON store always has its shape pre-baked, so this is a no-op —
|
|
264
|
-
// keeping the export preserves the server boot sequence.
|
|
265
|
-
const initializeDatabase = async () => { /* schema lives in code, not in file */ };
|
|
266
|
-
|
|
267
|
-
// ---------------------------------------------------------------------------
|
|
268
|
-
// Back-compat `db` shim — a few modules outside database/db.js imported `db`
|
|
269
|
-
// and called `db.prepare(sql)` directly. Most of those uses were for trivial
|
|
270
|
-
// transaction markers (BEGIN/COMMIT/ROLLBACK — no-op under our JSON store)
|
|
271
|
-
// or very specific SELECTs we've wrapped in explicit helpers. This shim
|
|
272
|
-
// lets those call sites keep working without a bigger refactor.
|
|
273
|
-
// ---------------------------------------------------------------------------
|
|
274
|
-
const db = {
|
|
275
|
-
prepare(sql) {
|
|
276
|
-
const normalized = sql.trim().toUpperCase();
|
|
277
|
-
// Transaction markers — our store writes atomically per op, so
|
|
278
|
-
// there's no real transaction to start. No-op + success result.
|
|
279
|
-
if (normalized === 'BEGIN' || normalized === 'COMMIT' || normalized === 'ROLLBACK') {
|
|
280
|
-
return {
|
|
281
|
-
run: () => ({ changes: 0, lastInsertRowid: 0 }),
|
|
282
|
-
};
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
// Specific query routed through the new helpers — used by
|
|
286
|
-
// server/routes/projects.js to fetch a single github credential.
|
|
287
|
-
if (/FROM USER_CREDENTIALS\s+WHERE ID = \?\s+AND USER_ID = \?\s+AND CREDENTIAL_TYPE = \?\s+AND IS_ACTIVE = 1/.test(normalized)) {
|
|
288
|
-
return {
|
|
289
|
-
get: (id, userId, credentialType) =>
|
|
290
|
-
store.findWhere('user_credentials',
|
|
291
|
-
(r) => r.id === id && r.user_id === userId && r.credential_type === credentialType && r.is_active)
|
|
292
|
-
|| undefined,
|
|
293
|
-
};
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
throw new Error(
|
|
297
|
-
`db.prepare: unsupported SQL passed through the compat shim: ${sql.slice(0, 80)}`
|
|
298
|
-
+ '\nExtend server/database/db.js or use a dedicated helper (userDb, credentialsDb, …).',
|
|
299
|
-
);
|
|
300
|
-
},
|
|
301
|
-
};
|
|
302
|
-
|
|
303
|
-
// ---------------------------------------------------------------------------
|
|
304
|
-
// User operations
|
|
305
|
-
// ---------------------------------------------------------------------------
|
|
306
|
-
const userDb = {
|
|
307
|
-
hasUsers: () => store.count('users', (r) => r.is_active) > 0,
|
|
308
|
-
|
|
309
|
-
listUsers: () => store.raw.users.map((row) => ({
|
|
310
|
-
id: row.id,
|
|
311
|
-
username: row.username,
|
|
312
|
-
created_at: row.created_at,
|
|
313
|
-
last_login: row.last_login,
|
|
314
|
-
is_active: Boolean(row.is_active),
|
|
315
|
-
git_name: row.git_name || null,
|
|
316
|
-
git_email: row.git_email || null,
|
|
317
|
-
has_completed_onboarding: Boolean(row.has_completed_onboarding),
|
|
318
|
-
role: row.role || null,
|
|
319
|
-
})),
|
|
320
|
-
|
|
321
|
-
createUser: (username, passwordHash) => {
|
|
322
|
-
const row = store.insert('users', {
|
|
323
|
-
username,
|
|
324
|
-
password_hash: passwordHash,
|
|
325
|
-
created_at: nowIso(),
|
|
326
|
-
last_login: null,
|
|
327
|
-
is_active: true,
|
|
328
|
-
git_name: null,
|
|
329
|
-
git_email: null,
|
|
330
|
-
has_completed_onboarding: false,
|
|
331
|
-
});
|
|
332
|
-
return { id: row.id, username: row.username };
|
|
333
|
-
},
|
|
334
|
-
|
|
335
|
-
createManagedUser: (username, passwordHash, metadata = {}) => {
|
|
336
|
-
const existing = store.raw.users.find((r) => r.username === username);
|
|
337
|
-
if (existing) {
|
|
338
|
-
throw new Error('Username already exists.');
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
const row = store.insert('users', {
|
|
342
|
-
username,
|
|
343
|
-
password_hash: passwordHash,
|
|
344
|
-
created_at: nowIso(),
|
|
345
|
-
last_login: null,
|
|
346
|
-
is_active: metadata.is_active !== false,
|
|
347
|
-
git_name: metadata.git_name || null,
|
|
348
|
-
git_email: metadata.git_email || null,
|
|
349
|
-
has_completed_onboarding: false,
|
|
350
|
-
role: metadata.role || 'member',
|
|
351
|
-
});
|
|
352
|
-
return {
|
|
353
|
-
id: row.id,
|
|
354
|
-
username: row.username,
|
|
355
|
-
created_at: row.created_at,
|
|
356
|
-
last_login: row.last_login,
|
|
357
|
-
is_active: Boolean(row.is_active),
|
|
358
|
-
role: row.role || 'member',
|
|
359
|
-
};
|
|
360
|
-
},
|
|
361
|
-
|
|
362
|
-
getUserByUsername: (username) =>
|
|
363
|
-
store.findWhere('users', (r) => r.username === username && r.is_active) || undefined,
|
|
364
|
-
|
|
365
|
-
updateLastLogin: (userId) => {
|
|
366
|
-
try {
|
|
367
|
-
store.updateWhere('users', (r) => r.id === userId, { last_login: nowIso() });
|
|
368
|
-
} catch (err) {
|
|
369
|
-
console.warn('Failed to update last login:', err.message);
|
|
370
|
-
}
|
|
371
|
-
},
|
|
372
|
-
|
|
373
|
-
getUserById: (userId) => {
|
|
374
|
-
const row = store.findWhere('users', (r) => r.id === userId && r.is_active);
|
|
375
|
-
if (!row) return undefined;
|
|
376
|
-
return {
|
|
377
|
-
id: row.id,
|
|
378
|
-
username: row.username,
|
|
379
|
-
created_at: row.created_at,
|
|
380
|
-
last_login: row.last_login,
|
|
381
|
-
role: row.role || null,
|
|
382
|
-
};
|
|
383
|
-
},
|
|
384
|
-
|
|
385
|
-
getFirstUser: () => {
|
|
386
|
-
const row = store.raw.users.find((r) => r.is_active);
|
|
387
|
-
if (!row) return undefined;
|
|
388
|
-
return {
|
|
389
|
-
id: row.id,
|
|
390
|
-
username: row.username,
|
|
391
|
-
created_at: row.created_at,
|
|
392
|
-
last_login: row.last_login,
|
|
393
|
-
role: row.role || null,
|
|
394
|
-
};
|
|
395
|
-
},
|
|
396
|
-
|
|
397
|
-
updateUser: (userId, patch = {}) => {
|
|
398
|
-
const allowed = {};
|
|
399
|
-
if (typeof patch.username === 'string' && patch.username.trim()) allowed.username = patch.username.trim();
|
|
400
|
-
if (typeof patch.git_name === 'string') allowed.git_name = patch.git_name;
|
|
401
|
-
if (typeof patch.git_email === 'string') allowed.git_email = patch.git_email;
|
|
402
|
-
if (typeof patch.role === 'string') allowed.role = patch.role;
|
|
403
|
-
if (typeof patch.is_active === 'boolean') allowed.is_active = patch.is_active;
|
|
404
|
-
store.updateWhere('users', (r) => r.id === userId, allowed);
|
|
405
|
-
return userDb.listUsers().find((user) => user.id === userId) || null;
|
|
406
|
-
},
|
|
407
|
-
|
|
408
|
-
setUserActive: (userId, isActive) => userDb.updateUser(userId, { is_active: Boolean(isActive) }),
|
|
409
|
-
|
|
410
|
-
updateGitConfig: (userId, gitName, gitEmail) => {
|
|
411
|
-
store.updateWhere('users', (r) => r.id === userId, { git_name: gitName, git_email: gitEmail });
|
|
412
|
-
},
|
|
413
|
-
|
|
414
|
-
getGitConfig: (userId) => {
|
|
415
|
-
const row = store.findWhere('users', (r) => r.id === userId);
|
|
416
|
-
if (!row) return undefined;
|
|
417
|
-
return { git_name: row.git_name || null, git_email: row.git_email || null };
|
|
418
|
-
},
|
|
419
|
-
|
|
420
|
-
completeOnboarding: (userId) => {
|
|
421
|
-
store.updateWhere('users', (r) => r.id === userId, { has_completed_onboarding: true });
|
|
422
|
-
},
|
|
423
|
-
|
|
424
|
-
hasCompletedOnboarding: (userId) => {
|
|
425
|
-
const row = store.findWhere('users', (r) => r.id === userId);
|
|
426
|
-
return Boolean(row?.has_completed_onboarding);
|
|
427
|
-
},
|
|
428
|
-
};
|
|
429
|
-
|
|
430
|
-
// ---------------------------------------------------------------------------
|
|
431
|
-
// API key operations
|
|
432
|
-
// ---------------------------------------------------------------------------
|
|
433
|
-
const apiKeysDb = {
|
|
434
|
-
generateApiKey: () => 'px_' + crypto.randomBytes(32).toString('hex'),
|
|
435
|
-
|
|
436
|
-
normalizeScopes: (scopes) => {
|
|
437
|
-
if (!Array.isArray(scopes)) return [];
|
|
438
|
-
return Array.from(new Set(scopes
|
|
439
|
-
.filter((scope) => typeof scope === 'string')
|
|
440
|
-
.map((scope) => scope.trim())
|
|
441
|
-
.filter(Boolean)
|
|
442
|
-
)).sort();
|
|
443
|
-
},
|
|
444
|
-
|
|
445
|
-
createApiKey: (userId, keyName, scopes = []) => {
|
|
446
|
-
const apiKey = apiKeysDb.generateApiKey();
|
|
447
|
-
const normalizedScopes = apiKeysDb.normalizeScopes(scopes);
|
|
448
|
-
const row = store.insert('api_keys', {
|
|
449
|
-
user_id: userId,
|
|
450
|
-
key_name: keyName,
|
|
451
|
-
api_key: apiKey,
|
|
452
|
-
scopes: normalizedScopes,
|
|
453
|
-
created_at: nowIso(),
|
|
454
|
-
last_used: null,
|
|
455
|
-
is_active: true,
|
|
456
|
-
});
|
|
457
|
-
return { id: row.id, keyName, apiKey, scopes: normalizedScopes };
|
|
458
|
-
},
|
|
459
|
-
|
|
460
|
-
getApiKeys: (userId) => {
|
|
461
|
-
const rows = store.filterWhere('api_keys', (r) => r.user_id === userId);
|
|
462
|
-
// Match the old ORDER BY created_at DESC behaviour.
|
|
463
|
-
return rows
|
|
464
|
-
.slice()
|
|
465
|
-
.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
|
|
466
|
-
.map((r) => ({
|
|
467
|
-
id: r.id,
|
|
468
|
-
key_name: r.key_name,
|
|
469
|
-
api_key: r.api_key,
|
|
470
|
-
scopes: apiKeysDb.normalizeScopes(r.scopes),
|
|
471
|
-
created_at: r.created_at,
|
|
472
|
-
last_used: r.last_used,
|
|
473
|
-
is_active: r.is_active ? 1 : 0,
|
|
474
|
-
}));
|
|
475
|
-
},
|
|
476
|
-
|
|
477
|
-
validateApiKey: (apiKey) => {
|
|
478
|
-
const key = store.findWhere('api_keys', (r) => r.api_key === apiKey && r.is_active);
|
|
479
|
-
if (!key) return undefined;
|
|
480
|
-
const user = store.findWhere('users', (r) => r.id === key.user_id && r.is_active);
|
|
481
|
-
if (!user) return undefined;
|
|
482
|
-
// Mirror the SQL-era side effect: stamp last_used. Only relevant
|
|
483
|
-
// for the "which key was used last" display in the UI.
|
|
484
|
-
store.updateWhere('api_keys', (r) => r.id === key.id, { last_used: nowIso() });
|
|
485
|
-
return {
|
|
486
|
-
id: user.id,
|
|
487
|
-
username: user.username,
|
|
488
|
-
api_key_id: key.id,
|
|
489
|
-
api_key_scopes: apiKeysDb.normalizeScopes(key.scopes),
|
|
490
|
-
};
|
|
491
|
-
},
|
|
492
|
-
|
|
493
|
-
deleteApiKey: (userId, apiKeyId) =>
|
|
494
|
-
store.deleteWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId) > 0,
|
|
495
|
-
|
|
496
|
-
toggleApiKey: (userId, apiKeyId, isActive) =>
|
|
497
|
-
store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
|
|
498
|
-
|
|
499
|
-
updateApiKeyScopes: (userId, apiKeyId, scopes = []) =>
|
|
500
|
-
store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, {
|
|
501
|
-
scopes: apiKeysDb.normalizeScopes(scopes),
|
|
502
|
-
}) > 0,
|
|
503
|
-
};
|
|
504
|
-
|
|
505
|
-
// ---------------------------------------------------------------------------
|
|
506
|
-
// Credentials (GitHub tokens, etc.) operations
|
|
507
|
-
// ---------------------------------------------------------------------------
|
|
508
|
-
const credentialsDb = {
|
|
509
|
-
createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
|
|
510
|
-
const row = store.insert('user_credentials', {
|
|
511
|
-
user_id: userId,
|
|
512
|
-
credential_name: credentialName,
|
|
513
|
-
credential_type: credentialType,
|
|
514
|
-
credential_value: credentialValue,
|
|
515
|
-
description,
|
|
516
|
-
created_at: nowIso(),
|
|
517
|
-
is_active: true,
|
|
518
|
-
});
|
|
519
|
-
return { id: row.id, credentialName, credentialType };
|
|
520
|
-
},
|
|
521
|
-
|
|
522
|
-
getCredentials: (userId, credentialType = null) => {
|
|
523
|
-
const rows = store.filterWhere('user_credentials', (r) =>
|
|
524
|
-
r.user_id === userId && (credentialType == null || r.credential_type === credentialType),
|
|
525
|
-
);
|
|
526
|
-
return rows
|
|
527
|
-
.slice()
|
|
528
|
-
.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
|
|
529
|
-
.map((r) => ({
|
|
530
|
-
id: r.id,
|
|
531
|
-
credential_name: r.credential_name,
|
|
532
|
-
credential_type: r.credential_type,
|
|
533
|
-
description: r.description,
|
|
534
|
-
created_at: r.created_at,
|
|
535
|
-
is_active: r.is_active ? 1 : 0,
|
|
536
|
-
}));
|
|
537
|
-
},
|
|
538
|
-
|
|
539
|
-
getActiveCredential: (userId, credentialType) => {
|
|
540
|
-
const rows = store.filterWhere('user_credentials', (r) =>
|
|
541
|
-
r.user_id === userId && r.credential_type === credentialType && r.is_active,
|
|
542
|
-
);
|
|
543
|
-
if (rows.length === 0) return null;
|
|
544
|
-
// "Most recent active" — mirror ORDER BY created_at DESC LIMIT 1
|
|
545
|
-
rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
|
|
546
|
-
return rows[0].credential_value;
|
|
547
|
-
},
|
|
548
|
-
|
|
549
|
-
getCredentialById: (userId, credentialId, credentialType = null) => {
|
|
550
|
-
const row = store.findWhere('user_credentials', (r) =>
|
|
551
|
-
r.id === credentialId && r.user_id === userId && r.is_active
|
|
552
|
-
&& (credentialType == null || r.credential_type === credentialType),
|
|
553
|
-
);
|
|
554
|
-
return row || undefined;
|
|
555
|
-
},
|
|
556
|
-
|
|
557
|
-
deleteCredential: (userId, credentialId) =>
|
|
558
|
-
store.deleteWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId) > 0,
|
|
559
|
-
|
|
560
|
-
toggleCredential: (userId, credentialId, isActive) =>
|
|
561
|
-
store.updateWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
|
|
562
|
-
};
|
|
563
|
-
|
|
564
|
-
// ---------------------------------------------------------------------------
|
|
565
|
-
// Notification preferences
|
|
566
|
-
// ---------------------------------------------------------------------------
|
|
567
|
-
const DEFAULT_NOTIFICATION_PREFERENCES = {
|
|
568
|
-
channels: { inApp: true, webPush: false, telegram: true, desktop: true },
|
|
569
|
-
events: { actionRequired: true, stop: true, error: true, updates: true },
|
|
570
|
-
};
|
|
571
|
-
|
|
572
|
-
const normalizeNotificationPreferences = (value) => {
|
|
573
|
-
const source = value && typeof value === 'object' ? value : {};
|
|
574
|
-
return {
|
|
575
|
-
channels: {
|
|
576
|
-
inApp: source.channels?.inApp !== false,
|
|
577
|
-
webPush: source.channels?.webPush === true,
|
|
578
|
-
telegram: source.channels?.telegram !== false,
|
|
579
|
-
desktop: source.channels?.desktop !== false,
|
|
580
|
-
},
|
|
581
|
-
events: {
|
|
582
|
-
actionRequired: source.events?.actionRequired !== false,
|
|
583
|
-
stop: source.events?.stop !== false,
|
|
584
|
-
error: source.events?.error !== false,
|
|
585
|
-
updates: source.events?.updates !== false,
|
|
586
|
-
},
|
|
587
|
-
};
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
const notificationPreferencesDb = {
|
|
591
|
-
getPreferences: (userId) => {
|
|
592
|
-
const row = store.findWhere('user_notification_preferences', (r) => r.user_id === userId);
|
|
593
|
-
if (!row) {
|
|
594
|
-
const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
|
|
595
|
-
store.insert('user_notification_preferences', {
|
|
596
|
-
user_id: userId,
|
|
597
|
-
preferences_json: JSON.stringify(defaults),
|
|
598
|
-
updated_at: nowIso(),
|
|
599
|
-
}, { autoId: false });
|
|
600
|
-
return defaults;
|
|
601
|
-
}
|
|
602
|
-
try {
|
|
603
|
-
return normalizeNotificationPreferences(JSON.parse(row.preferences_json));
|
|
604
|
-
} catch {
|
|
605
|
-
return normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
|
|
606
|
-
}
|
|
607
|
-
},
|
|
608
|
-
|
|
609
|
-
updatePreferences: (userId, preferences) => {
|
|
610
|
-
const normalized = normalizeNotificationPreferences(preferences);
|
|
611
|
-
store.upsertWhere(
|
|
612
|
-
'user_notification_preferences',
|
|
613
|
-
(r) => r.user_id === userId,
|
|
614
|
-
{ user_id: userId, preferences_json: JSON.stringify(normalized), updated_at: nowIso() },
|
|
615
|
-
);
|
|
616
|
-
return normalized;
|
|
617
|
-
},
|
|
618
|
-
};
|
|
619
|
-
|
|
620
|
-
// ---------------------------------------------------------------------------
|
|
621
|
-
// Push subscriptions
|
|
622
|
-
// ---------------------------------------------------------------------------
|
|
623
|
-
const pushSubscriptionsDb = {
|
|
624
|
-
saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
|
|
625
|
-
// The old SQL path upserted on `endpoint`, updating user_id as
|
|
626
|
-
// well. Preserve that exact behaviour.
|
|
627
|
-
const existing = store.findWhere('push_subscriptions', (r) => r.endpoint === endpoint);
|
|
628
|
-
if (existing) {
|
|
629
|
-
store.updateWhere('push_subscriptions', (r) => r.endpoint === endpoint, {
|
|
630
|
-
user_id: userId,
|
|
631
|
-
keys_p256dh: keysP256dh,
|
|
632
|
-
keys_auth: keysAuth,
|
|
633
|
-
});
|
|
634
|
-
return;
|
|
635
|
-
}
|
|
636
|
-
store.insert('push_subscriptions', {
|
|
637
|
-
user_id: userId,
|
|
638
|
-
endpoint,
|
|
639
|
-
keys_p256dh: keysP256dh,
|
|
640
|
-
keys_auth: keysAuth,
|
|
641
|
-
created_at: nowIso(),
|
|
642
|
-
});
|
|
643
|
-
},
|
|
644
|
-
|
|
645
|
-
getSubscriptions: (userId) =>
|
|
646
|
-
store.filterWhere('push_subscriptions', (r) => r.user_id === userId).map((r) => ({
|
|
647
|
-
endpoint: r.endpoint,
|
|
648
|
-
keys_p256dh: r.keys_p256dh,
|
|
649
|
-
keys_auth: r.keys_auth,
|
|
650
|
-
})),
|
|
651
|
-
|
|
652
|
-
removeSubscription: (endpoint) => {
|
|
653
|
-
store.deleteWhere('push_subscriptions', (r) => r.endpoint === endpoint);
|
|
654
|
-
},
|
|
655
|
-
|
|
656
|
-
removeAllForUser: (userId) => {
|
|
657
|
-
store.deleteWhere('push_subscriptions', (r) => r.user_id === userId);
|
|
658
|
-
},
|
|
659
|
-
};
|
|
660
|
-
|
|
661
|
-
// ---------------------------------------------------------------------------
|
|
662
|
-
// VAPID key storage (for web push)
|
|
663
|
-
// ---------------------------------------------------------------------------
|
|
664
|
-
const vapidKeysDb = {
|
|
665
|
-
getLatest: () => {
|
|
666
|
-
if (store.raw.vapid_keys.length === 0) return null;
|
|
667
|
-
// Mirror ORDER BY id DESC LIMIT 1 — take the newest row.
|
|
668
|
-
const rows = store.raw.vapid_keys.slice().sort((a, b) => b.id - a.id);
|
|
669
|
-
return { public_key: rows[0].public_key, private_key: rows[0].private_key };
|
|
670
|
-
},
|
|
671
|
-
insert: (publicKey, privateKey) => {
|
|
672
|
-
store.insert('vapid_keys', {
|
|
673
|
-
public_key: publicKey,
|
|
674
|
-
private_key: privateKey,
|
|
675
|
-
created_at: nowIso(),
|
|
676
|
-
});
|
|
677
|
-
},
|
|
678
|
-
};
|
|
679
|
-
|
|
680
|
-
// ---------------------------------------------------------------------------
|
|
681
|
-
// Session custom names
|
|
682
|
-
// ---------------------------------------------------------------------------
|
|
683
|
-
const sessionNamesDb = {
|
|
684
|
-
setName: (sessionId, provider, customName) => {
|
|
685
|
-
store.upsertWhere(
|
|
686
|
-
'session_names',
|
|
687
|
-
(r) => r.session_id === sessionId && r.provider === provider,
|
|
688
|
-
{ session_id: sessionId, provider, custom_name: customName, updated_at: nowIso(), created_at: nowIso() },
|
|
689
|
-
);
|
|
690
|
-
},
|
|
691
|
-
|
|
692
|
-
getName: (sessionId, provider) => {
|
|
693
|
-
const row = store.findWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider);
|
|
694
|
-
return row?.custom_name || null;
|
|
695
|
-
},
|
|
696
|
-
|
|
697
|
-
getNames: (sessionIds, provider) => {
|
|
698
|
-
if (!sessionIds.length) return new Map();
|
|
699
|
-
const lookup = new Set(sessionIds);
|
|
700
|
-
const matches = store.filterWhere('session_names',
|
|
701
|
-
(r) => r.provider === provider && lookup.has(r.session_id));
|
|
702
|
-
return new Map(matches.map((r) => [r.session_id, r.custom_name]));
|
|
703
|
-
},
|
|
704
|
-
|
|
705
|
-
deleteName: (sessionId, provider) =>
|
|
706
|
-
store.deleteWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider) > 0,
|
|
707
|
-
};
|
|
708
|
-
|
|
709
|
-
function applyCustomSessionNames(sessions, provider) {
|
|
710
|
-
if (!sessions?.length) return;
|
|
711
|
-
try {
|
|
712
|
-
const ids = sessions.map((s) => s.id);
|
|
713
|
-
const customNames = sessionNamesDb.getNames(ids, provider);
|
|
714
|
-
for (const session of sessions) {
|
|
715
|
-
const custom = customNames.get(session.id);
|
|
716
|
-
if (custom) session.summary = custom;
|
|
717
|
-
}
|
|
718
|
-
} catch (error) {
|
|
719
|
-
console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
// ---------------------------------------------------------------------------
|
|
724
|
-
// App config (key/value)
|
|
725
|
-
// ---------------------------------------------------------------------------
|
|
726
|
-
const appConfigDb = {
|
|
727
|
-
get: (key) => {
|
|
728
|
-
const row = store.findWhere('app_config', (r) => r.key === key);
|
|
729
|
-
return row?.value || null;
|
|
730
|
-
},
|
|
731
|
-
|
|
732
|
-
set: (key, value) => {
|
|
733
|
-
store.upsertWhere('app_config', (r) => r.key === key,
|
|
734
|
-
{ key, value, created_at: nowIso() });
|
|
735
|
-
},
|
|
736
|
-
|
|
737
|
-
getOrCreateJwtSecret: () => {
|
|
738
|
-
let secret = appConfigDb.get('jwt_secret');
|
|
739
|
-
if (!secret) {
|
|
740
|
-
secret = crypto.randomBytes(64).toString('hex');
|
|
741
|
-
appConfigDb.set('jwt_secret', secret);
|
|
742
|
-
}
|
|
743
|
-
return secret;
|
|
744
|
-
},
|
|
745
|
-
};
|
|
746
|
-
|
|
747
|
-
// ---------------------------------------------------------------------------
|
|
748
|
-
// Telegram — singleton config + per-user links
|
|
749
|
-
// ---------------------------------------------------------------------------
|
|
750
|
-
const DEFAULT_TELEGRAM_CONTROL_STATE = {
|
|
751
|
-
remoteControlEnabled: true,
|
|
752
|
-
progressMode: 'final',
|
|
753
|
-
selectedProjectName: null,
|
|
754
|
-
selectedProjectPath: null,
|
|
755
|
-
selectedProvider: 'opencode',
|
|
756
|
-
selectedModel: null,
|
|
757
|
-
selectedWorkflowId: null,
|
|
758
|
-
awaiting: null,
|
|
759
|
-
};
|
|
760
|
-
|
|
761
|
-
function normalizeTelegramControlState(value = {}) {
|
|
762
|
-
const raw = value && typeof value === 'object' ? value : {};
|
|
763
|
-
const selectedProvider = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.selectedProvider)
|
|
764
|
-
? raw.selectedProvider
|
|
765
|
-
: DEFAULT_TELEGRAM_CONTROL_STATE.selectedProvider;
|
|
766
|
-
const progressMode = ['final', 'steps', 'all', 'errors'].includes(raw.progressMode)
|
|
767
|
-
? raw.progressMode
|
|
768
|
-
: DEFAULT_TELEGRAM_CONTROL_STATE.progressMode;
|
|
769
|
-
|
|
770
|
-
return {
|
|
771
|
-
...DEFAULT_TELEGRAM_CONTROL_STATE,
|
|
772
|
-
...raw,
|
|
773
|
-
remoteControlEnabled: raw.remoteControlEnabled !== false,
|
|
774
|
-
progressMode,
|
|
775
|
-
selectedProvider,
|
|
776
|
-
selectedProjectName: typeof raw.selectedProjectName === 'string' ? raw.selectedProjectName : null,
|
|
777
|
-
selectedProjectPath: typeof raw.selectedProjectPath === 'string' ? raw.selectedProjectPath : null,
|
|
778
|
-
selectedModel: typeof raw.selectedModel === 'string' ? raw.selectedModel : null,
|
|
779
|
-
selectedWorkflowId: typeof raw.selectedWorkflowId === 'string' ? raw.selectedWorkflowId : null,
|
|
780
|
-
awaiting: raw.awaiting && typeof raw.awaiting === 'object' ? raw.awaiting : null,
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
const telegramConfigDb = {
|
|
785
|
-
get: () => {
|
|
786
|
-
const row = store.raw.telegram_config[0];
|
|
787
|
-
if (!row) return null;
|
|
788
|
-
return { bot_token: row.bot_token, bot_username: row.bot_username, updated_at: row.updated_at };
|
|
789
|
-
},
|
|
790
|
-
set: (botToken, botUsername = null) => {
|
|
791
|
-
store.raw.telegram_config = [{
|
|
792
|
-
id: 1,
|
|
793
|
-
bot_token: botToken,
|
|
794
|
-
bot_username: botUsername,
|
|
795
|
-
updated_at: nowIso(),
|
|
796
|
-
}];
|
|
797
|
-
store.save();
|
|
798
|
-
},
|
|
799
|
-
clear: () => {
|
|
800
|
-
store.raw.telegram_config = [];
|
|
801
|
-
store.save();
|
|
802
|
-
},
|
|
803
|
-
};
|
|
804
|
-
|
|
805
|
-
const telegramLinksDb = {
|
|
806
|
-
setPairingCode: (userId, code, expiresAt, language) => {
|
|
807
|
-
store.upsertWhere('telegram_links', (r) => r.user_id === userId, {
|
|
808
|
-
user_id: userId,
|
|
809
|
-
pairing_code: code,
|
|
810
|
-
pairing_code_expires_at: expiresAt,
|
|
811
|
-
language,
|
|
812
|
-
chat_id: null,
|
|
813
|
-
telegram_username: null,
|
|
814
|
-
verified_at: null,
|
|
815
|
-
notifications_enabled: true,
|
|
816
|
-
bridge_enabled: true,
|
|
817
|
-
telegram_control: normalizeTelegramControlState(),
|
|
818
|
-
updated_at: nowIso(),
|
|
819
|
-
});
|
|
820
|
-
},
|
|
821
|
-
findByPairingCode: (code) => {
|
|
822
|
-
const row = store.findWhere('telegram_links', (r) => r.pairing_code === code);
|
|
823
|
-
if (!row) return null;
|
|
824
|
-
return {
|
|
825
|
-
user_id: row.user_id,
|
|
826
|
-
pairing_code: row.pairing_code,
|
|
827
|
-
pairing_code_expires_at: row.pairing_code_expires_at,
|
|
828
|
-
language: row.language,
|
|
829
|
-
};
|
|
830
|
-
},
|
|
831
|
-
verify: (userId, chatId, telegramUsername) => {
|
|
832
|
-
store.updateWhere('telegram_links', (r) => r.user_id === userId, {
|
|
833
|
-
chat_id: chatId,
|
|
834
|
-
telegram_username: telegramUsername,
|
|
835
|
-
verified_at: nowIso(),
|
|
836
|
-
pairing_code: null,
|
|
837
|
-
pairing_code_expires_at: null,
|
|
838
|
-
updated_at: nowIso(),
|
|
839
|
-
});
|
|
840
|
-
},
|
|
841
|
-
getByUserId: (userId) => {
|
|
842
|
-
const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
|
|
843
|
-
return row ? { ...row } : null;
|
|
844
|
-
},
|
|
845
|
-
getByChatId: (chatId) => {
|
|
846
|
-
const row = store.findWhere('telegram_links', (r) => r.chat_id === chatId);
|
|
847
|
-
if (!row) return null;
|
|
848
|
-
return {
|
|
849
|
-
user_id: row.user_id,
|
|
850
|
-
chat_id: row.chat_id,
|
|
851
|
-
telegram_username: row.telegram_username,
|
|
852
|
-
language: row.language,
|
|
853
|
-
notifications_enabled: row.notifications_enabled,
|
|
854
|
-
bridge_enabled: row.bridge_enabled,
|
|
855
|
-
telegram_control: normalizeTelegramControlState(row.telegram_control),
|
|
856
|
-
};
|
|
857
|
-
},
|
|
858
|
-
listVerified: () =>
|
|
859
|
-
store.filterWhere('telegram_links', (r) => r.chat_id && r.verified_at).map((r) => ({
|
|
860
|
-
user_id: r.user_id,
|
|
861
|
-
chat_id: r.chat_id,
|
|
862
|
-
telegram_username: r.telegram_username,
|
|
863
|
-
language: r.language,
|
|
864
|
-
notifications_enabled: r.notifications_enabled,
|
|
865
|
-
bridge_enabled: r.bridge_enabled,
|
|
866
|
-
telegram_control: normalizeTelegramControlState(r.telegram_control),
|
|
867
|
-
})),
|
|
868
|
-
updatePreferences: (userId, { language, notificationsEnabled, bridgeEnabled }) => {
|
|
869
|
-
const patch = { updated_at: nowIso() };
|
|
870
|
-
if (language !== undefined) patch.language = language;
|
|
871
|
-
if (notificationsEnabled !== undefined) patch.notifications_enabled = Boolean(notificationsEnabled);
|
|
872
|
-
if (bridgeEnabled !== undefined) patch.bridge_enabled = Boolean(bridgeEnabled);
|
|
873
|
-
if (Object.keys(patch).length === 1) return; // only updated_at → no real change
|
|
874
|
-
store.updateWhere('telegram_links', (r) => r.user_id === userId, patch);
|
|
875
|
-
},
|
|
876
|
-
getControlState: (userId) => {
|
|
877
|
-
const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
|
|
878
|
-
return normalizeTelegramControlState(row?.telegram_control);
|
|
879
|
-
},
|
|
880
|
-
updateControlState: (userId, patch) => {
|
|
881
|
-
const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
|
|
882
|
-
const current = normalizeTelegramControlState(row?.telegram_control);
|
|
883
|
-
const next = normalizeTelegramControlState({ ...current, ...(patch || {}) });
|
|
884
|
-
store.updateWhere('telegram_links', (r) => r.user_id === userId, {
|
|
885
|
-
telegram_control: next,
|
|
886
|
-
updated_at: nowIso(),
|
|
887
|
-
});
|
|
888
|
-
return next;
|
|
889
|
-
},
|
|
890
|
-
unlink: (userId) => {
|
|
891
|
-
store.deleteWhere('telegram_links', (r) => r.user_id === userId);
|
|
892
|
-
},
|
|
893
|
-
};
|
|
894
|
-
|
|
895
|
-
// Back-compat surface — older callers used `githubTokensDb.*`; internally
|
|
896
|
-
// they always delegated to credentialsDb with `credential_type='github_token'`.
|
|
897
|
-
const githubTokensDb = {
|
|
898
|
-
createGithubToken: (userId, tokenName, githubToken, description = null) =>
|
|
899
|
-
credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description),
|
|
900
|
-
getGithubTokens: (userId) => credentialsDb.getCredentials(userId, 'github_token'),
|
|
901
|
-
getActiveGithubToken: (userId) => credentialsDb.getActiveCredential(userId, 'github_token'),
|
|
902
|
-
deleteGithubToken: (userId, tokenId) => credentialsDb.deleteCredential(userId, tokenId),
|
|
903
|
-
toggleGithubToken: (userId, tokenId, isActive) => credentialsDb.toggleCredential(userId, tokenId, isActive),
|
|
904
|
-
};
|
|
905
|
-
|
|
906
|
-
export {
|
|
907
|
-
db,
|
|
908
|
-
initializeDatabase,
|
|
909
|
-
userDb,
|
|
910
|
-
apiKeysDb,
|
|
911
|
-
credentialsDb,
|
|
912
|
-
notificationPreferencesDb,
|
|
913
|
-
pushSubscriptionsDb,
|
|
914
|
-
vapidKeysDb,
|
|
915
|
-
sessionNamesDb,
|
|
916
|
-
applyCustomSessionNames,
|
|
917
|
-
appConfigDb,
|
|
918
|
-
telegramConfigDb,
|
|
919
|
-
telegramLinksDb,
|
|
920
|
-
githubTokensDb,
|
|
921
|
-
};
|
|
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
|
+
telegram_control: null,
|
|
221
|
+
updated_at: tl.updated_at || nowIso(),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
store.save();
|
|
226
|
+
legacy.close();
|
|
227
|
+
|
|
228
|
+
// Rename the old .db out of the way so we never migrate it twice.
|
|
229
|
+
// Keep it (not delete) so the user can roll back if needed.
|
|
230
|
+
const backup = `${LEGACY_SQLITE_PATH}.migrated-${Date.now()}`;
|
|
231
|
+
try {
|
|
232
|
+
fs.renameSync(LEGACY_SQLITE_PATH, backup);
|
|
233
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
234
|
+
if (fs.existsSync(LEGACY_SQLITE_PATH + suffix)) {
|
|
235
|
+
try { fs.renameSync(LEGACY_SQLITE_PATH + suffix, backup + suffix); } catch { /* noop */ }
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
} catch (err) {
|
|
239
|
+
console.warn(`[MIGRATION] Migration succeeded but could not rename old DB: ${err.message}`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
console.log(`${c.info('[MIGRATION]')} Migration complete. Old DB preserved as ${c.dim(backup)}.`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Module-load order matters — auth middleware imports `db` and reads the
|
|
246
|
+
// JWT secret before anything else gets to boot. So the store has to be
|
|
247
|
+
// ready synchronously at the first `import { db } from './db.js'`.
|
|
248
|
+
migrateSqliteIfPresent();
|
|
249
|
+
|
|
250
|
+
const store = new JsonStore(JSON_PATH);
|
|
251
|
+
|
|
252
|
+
console.log('');
|
|
253
|
+
console.log(c.dim('═'.repeat(60)));
|
|
254
|
+
console.log(`${c.info('[INFO]')} App Installation: ${c.bright(APP_ROOT)}`);
|
|
255
|
+
console.log(`${c.info('[INFO]')} Auth store: ${c.dim(path.relative(APP_ROOT, JSON_PATH))}`);
|
|
256
|
+
if (process.env.DATABASE_PATH) {
|
|
257
|
+
console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
|
|
258
|
+
}
|
|
259
|
+
console.log(c.dim('═'.repeat(60)));
|
|
260
|
+
console.log('');
|
|
261
|
+
|
|
262
|
+
// initializeDatabase used to run `CREATE TABLE IF NOT EXISTS` + migrations.
|
|
263
|
+
// The JSON store always has its shape pre-baked, so this is a no-op —
|
|
264
|
+
// keeping the export preserves the server boot sequence.
|
|
265
|
+
const initializeDatabase = async () => { /* schema lives in code, not in file */ };
|
|
266
|
+
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// Back-compat `db` shim — a few modules outside database/db.js imported `db`
|
|
269
|
+
// and called `db.prepare(sql)` directly. Most of those uses were for trivial
|
|
270
|
+
// transaction markers (BEGIN/COMMIT/ROLLBACK — no-op under our JSON store)
|
|
271
|
+
// or very specific SELECTs we've wrapped in explicit helpers. This shim
|
|
272
|
+
// lets those call sites keep working without a bigger refactor.
|
|
273
|
+
// ---------------------------------------------------------------------------
|
|
274
|
+
const db = {
|
|
275
|
+
prepare(sql) {
|
|
276
|
+
const normalized = sql.trim().toUpperCase();
|
|
277
|
+
// Transaction markers — our store writes atomically per op, so
|
|
278
|
+
// there's no real transaction to start. No-op + success result.
|
|
279
|
+
if (normalized === 'BEGIN' || normalized === 'COMMIT' || normalized === 'ROLLBACK') {
|
|
280
|
+
return {
|
|
281
|
+
run: () => ({ changes: 0, lastInsertRowid: 0 }),
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Specific query routed through the new helpers — used by
|
|
286
|
+
// server/routes/projects.js to fetch a single github credential.
|
|
287
|
+
if (/FROM USER_CREDENTIALS\s+WHERE ID = \?\s+AND USER_ID = \?\s+AND CREDENTIAL_TYPE = \?\s+AND IS_ACTIVE = 1/.test(normalized)) {
|
|
288
|
+
return {
|
|
289
|
+
get: (id, userId, credentialType) =>
|
|
290
|
+
store.findWhere('user_credentials',
|
|
291
|
+
(r) => r.id === id && r.user_id === userId && r.credential_type === credentialType && r.is_active)
|
|
292
|
+
|| undefined,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
throw new Error(
|
|
297
|
+
`db.prepare: unsupported SQL passed through the compat shim: ${sql.slice(0, 80)}`
|
|
298
|
+
+ '\nExtend server/database/db.js or use a dedicated helper (userDb, credentialsDb, …).',
|
|
299
|
+
);
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
// User operations
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
const userDb = {
|
|
307
|
+
hasUsers: () => store.count('users', (r) => r.is_active) > 0,
|
|
308
|
+
|
|
309
|
+
listUsers: () => store.raw.users.map((row) => ({
|
|
310
|
+
id: row.id,
|
|
311
|
+
username: row.username,
|
|
312
|
+
created_at: row.created_at,
|
|
313
|
+
last_login: row.last_login,
|
|
314
|
+
is_active: Boolean(row.is_active),
|
|
315
|
+
git_name: row.git_name || null,
|
|
316
|
+
git_email: row.git_email || null,
|
|
317
|
+
has_completed_onboarding: Boolean(row.has_completed_onboarding),
|
|
318
|
+
role: row.role || null,
|
|
319
|
+
})),
|
|
320
|
+
|
|
321
|
+
createUser: (username, passwordHash) => {
|
|
322
|
+
const row = store.insert('users', {
|
|
323
|
+
username,
|
|
324
|
+
password_hash: passwordHash,
|
|
325
|
+
created_at: nowIso(),
|
|
326
|
+
last_login: null,
|
|
327
|
+
is_active: true,
|
|
328
|
+
git_name: null,
|
|
329
|
+
git_email: null,
|
|
330
|
+
has_completed_onboarding: false,
|
|
331
|
+
});
|
|
332
|
+
return { id: row.id, username: row.username };
|
|
333
|
+
},
|
|
334
|
+
|
|
335
|
+
createManagedUser: (username, passwordHash, metadata = {}) => {
|
|
336
|
+
const existing = store.raw.users.find((r) => r.username === username);
|
|
337
|
+
if (existing) {
|
|
338
|
+
throw new Error('Username already exists.');
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const row = store.insert('users', {
|
|
342
|
+
username,
|
|
343
|
+
password_hash: passwordHash,
|
|
344
|
+
created_at: nowIso(),
|
|
345
|
+
last_login: null,
|
|
346
|
+
is_active: metadata.is_active !== false,
|
|
347
|
+
git_name: metadata.git_name || null,
|
|
348
|
+
git_email: metadata.git_email || null,
|
|
349
|
+
has_completed_onboarding: false,
|
|
350
|
+
role: metadata.role || 'member',
|
|
351
|
+
});
|
|
352
|
+
return {
|
|
353
|
+
id: row.id,
|
|
354
|
+
username: row.username,
|
|
355
|
+
created_at: row.created_at,
|
|
356
|
+
last_login: row.last_login,
|
|
357
|
+
is_active: Boolean(row.is_active),
|
|
358
|
+
role: row.role || 'member',
|
|
359
|
+
};
|
|
360
|
+
},
|
|
361
|
+
|
|
362
|
+
getUserByUsername: (username) =>
|
|
363
|
+
store.findWhere('users', (r) => r.username === username && r.is_active) || undefined,
|
|
364
|
+
|
|
365
|
+
updateLastLogin: (userId) => {
|
|
366
|
+
try {
|
|
367
|
+
store.updateWhere('users', (r) => r.id === userId, { last_login: nowIso() });
|
|
368
|
+
} catch (err) {
|
|
369
|
+
console.warn('Failed to update last login:', err.message);
|
|
370
|
+
}
|
|
371
|
+
},
|
|
372
|
+
|
|
373
|
+
getUserById: (userId) => {
|
|
374
|
+
const row = store.findWhere('users', (r) => r.id === userId && r.is_active);
|
|
375
|
+
if (!row) return undefined;
|
|
376
|
+
return {
|
|
377
|
+
id: row.id,
|
|
378
|
+
username: row.username,
|
|
379
|
+
created_at: row.created_at,
|
|
380
|
+
last_login: row.last_login,
|
|
381
|
+
role: row.role || null,
|
|
382
|
+
};
|
|
383
|
+
},
|
|
384
|
+
|
|
385
|
+
getFirstUser: () => {
|
|
386
|
+
const row = store.raw.users.find((r) => r.is_active);
|
|
387
|
+
if (!row) return undefined;
|
|
388
|
+
return {
|
|
389
|
+
id: row.id,
|
|
390
|
+
username: row.username,
|
|
391
|
+
created_at: row.created_at,
|
|
392
|
+
last_login: row.last_login,
|
|
393
|
+
role: row.role || null,
|
|
394
|
+
};
|
|
395
|
+
},
|
|
396
|
+
|
|
397
|
+
updateUser: (userId, patch = {}) => {
|
|
398
|
+
const allowed = {};
|
|
399
|
+
if (typeof patch.username === 'string' && patch.username.trim()) allowed.username = patch.username.trim();
|
|
400
|
+
if (typeof patch.git_name === 'string') allowed.git_name = patch.git_name;
|
|
401
|
+
if (typeof patch.git_email === 'string') allowed.git_email = patch.git_email;
|
|
402
|
+
if (typeof patch.role === 'string') allowed.role = patch.role;
|
|
403
|
+
if (typeof patch.is_active === 'boolean') allowed.is_active = patch.is_active;
|
|
404
|
+
store.updateWhere('users', (r) => r.id === userId, allowed);
|
|
405
|
+
return userDb.listUsers().find((user) => user.id === userId) || null;
|
|
406
|
+
},
|
|
407
|
+
|
|
408
|
+
setUserActive: (userId, isActive) => userDb.updateUser(userId, { is_active: Boolean(isActive) }),
|
|
409
|
+
|
|
410
|
+
updateGitConfig: (userId, gitName, gitEmail) => {
|
|
411
|
+
store.updateWhere('users', (r) => r.id === userId, { git_name: gitName, git_email: gitEmail });
|
|
412
|
+
},
|
|
413
|
+
|
|
414
|
+
getGitConfig: (userId) => {
|
|
415
|
+
const row = store.findWhere('users', (r) => r.id === userId);
|
|
416
|
+
if (!row) return undefined;
|
|
417
|
+
return { git_name: row.git_name || null, git_email: row.git_email || null };
|
|
418
|
+
},
|
|
419
|
+
|
|
420
|
+
completeOnboarding: (userId) => {
|
|
421
|
+
store.updateWhere('users', (r) => r.id === userId, { has_completed_onboarding: true });
|
|
422
|
+
},
|
|
423
|
+
|
|
424
|
+
hasCompletedOnboarding: (userId) => {
|
|
425
|
+
const row = store.findWhere('users', (r) => r.id === userId);
|
|
426
|
+
return Boolean(row?.has_completed_onboarding);
|
|
427
|
+
},
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
// ---------------------------------------------------------------------------
|
|
431
|
+
// API key operations
|
|
432
|
+
// ---------------------------------------------------------------------------
|
|
433
|
+
const apiKeysDb = {
|
|
434
|
+
generateApiKey: () => 'px_' + crypto.randomBytes(32).toString('hex'),
|
|
435
|
+
|
|
436
|
+
normalizeScopes: (scopes) => {
|
|
437
|
+
if (!Array.isArray(scopes)) return [];
|
|
438
|
+
return Array.from(new Set(scopes
|
|
439
|
+
.filter((scope) => typeof scope === 'string')
|
|
440
|
+
.map((scope) => scope.trim())
|
|
441
|
+
.filter(Boolean)
|
|
442
|
+
)).sort();
|
|
443
|
+
},
|
|
444
|
+
|
|
445
|
+
createApiKey: (userId, keyName, scopes = []) => {
|
|
446
|
+
const apiKey = apiKeysDb.generateApiKey();
|
|
447
|
+
const normalizedScopes = apiKeysDb.normalizeScopes(scopes);
|
|
448
|
+
const row = store.insert('api_keys', {
|
|
449
|
+
user_id: userId,
|
|
450
|
+
key_name: keyName,
|
|
451
|
+
api_key: apiKey,
|
|
452
|
+
scopes: normalizedScopes,
|
|
453
|
+
created_at: nowIso(),
|
|
454
|
+
last_used: null,
|
|
455
|
+
is_active: true,
|
|
456
|
+
});
|
|
457
|
+
return { id: row.id, keyName, apiKey, scopes: normalizedScopes };
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
getApiKeys: (userId) => {
|
|
461
|
+
const rows = store.filterWhere('api_keys', (r) => r.user_id === userId);
|
|
462
|
+
// Match the old ORDER BY created_at DESC behaviour.
|
|
463
|
+
return rows
|
|
464
|
+
.slice()
|
|
465
|
+
.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
|
|
466
|
+
.map((r) => ({
|
|
467
|
+
id: r.id,
|
|
468
|
+
key_name: r.key_name,
|
|
469
|
+
api_key: r.api_key,
|
|
470
|
+
scopes: apiKeysDb.normalizeScopes(r.scopes),
|
|
471
|
+
created_at: r.created_at,
|
|
472
|
+
last_used: r.last_used,
|
|
473
|
+
is_active: r.is_active ? 1 : 0,
|
|
474
|
+
}));
|
|
475
|
+
},
|
|
476
|
+
|
|
477
|
+
validateApiKey: (apiKey) => {
|
|
478
|
+
const key = store.findWhere('api_keys', (r) => r.api_key === apiKey && r.is_active);
|
|
479
|
+
if (!key) return undefined;
|
|
480
|
+
const user = store.findWhere('users', (r) => r.id === key.user_id && r.is_active);
|
|
481
|
+
if (!user) return undefined;
|
|
482
|
+
// Mirror the SQL-era side effect: stamp last_used. Only relevant
|
|
483
|
+
// for the "which key was used last" display in the UI.
|
|
484
|
+
store.updateWhere('api_keys', (r) => r.id === key.id, { last_used: nowIso() });
|
|
485
|
+
return {
|
|
486
|
+
id: user.id,
|
|
487
|
+
username: user.username,
|
|
488
|
+
api_key_id: key.id,
|
|
489
|
+
api_key_scopes: apiKeysDb.normalizeScopes(key.scopes),
|
|
490
|
+
};
|
|
491
|
+
},
|
|
492
|
+
|
|
493
|
+
deleteApiKey: (userId, apiKeyId) =>
|
|
494
|
+
store.deleteWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId) > 0,
|
|
495
|
+
|
|
496
|
+
toggleApiKey: (userId, apiKeyId, isActive) =>
|
|
497
|
+
store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
|
|
498
|
+
|
|
499
|
+
updateApiKeyScopes: (userId, apiKeyId, scopes = []) =>
|
|
500
|
+
store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, {
|
|
501
|
+
scopes: apiKeysDb.normalizeScopes(scopes),
|
|
502
|
+
}) > 0,
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
// ---------------------------------------------------------------------------
|
|
506
|
+
// Credentials (GitHub tokens, etc.) operations
|
|
507
|
+
// ---------------------------------------------------------------------------
|
|
508
|
+
const credentialsDb = {
|
|
509
|
+
createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
|
|
510
|
+
const row = store.insert('user_credentials', {
|
|
511
|
+
user_id: userId,
|
|
512
|
+
credential_name: credentialName,
|
|
513
|
+
credential_type: credentialType,
|
|
514
|
+
credential_value: credentialValue,
|
|
515
|
+
description,
|
|
516
|
+
created_at: nowIso(),
|
|
517
|
+
is_active: true,
|
|
518
|
+
});
|
|
519
|
+
return { id: row.id, credentialName, credentialType };
|
|
520
|
+
},
|
|
521
|
+
|
|
522
|
+
getCredentials: (userId, credentialType = null) => {
|
|
523
|
+
const rows = store.filterWhere('user_credentials', (r) =>
|
|
524
|
+
r.user_id === userId && (credentialType == null || r.credential_type === credentialType),
|
|
525
|
+
);
|
|
526
|
+
return rows
|
|
527
|
+
.slice()
|
|
528
|
+
.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
|
|
529
|
+
.map((r) => ({
|
|
530
|
+
id: r.id,
|
|
531
|
+
credential_name: r.credential_name,
|
|
532
|
+
credential_type: r.credential_type,
|
|
533
|
+
description: r.description,
|
|
534
|
+
created_at: r.created_at,
|
|
535
|
+
is_active: r.is_active ? 1 : 0,
|
|
536
|
+
}));
|
|
537
|
+
},
|
|
538
|
+
|
|
539
|
+
getActiveCredential: (userId, credentialType) => {
|
|
540
|
+
const rows = store.filterWhere('user_credentials', (r) =>
|
|
541
|
+
r.user_id === userId && r.credential_type === credentialType && r.is_active,
|
|
542
|
+
);
|
|
543
|
+
if (rows.length === 0) return null;
|
|
544
|
+
// "Most recent active" — mirror ORDER BY created_at DESC LIMIT 1
|
|
545
|
+
rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
|
|
546
|
+
return rows[0].credential_value;
|
|
547
|
+
},
|
|
548
|
+
|
|
549
|
+
getCredentialById: (userId, credentialId, credentialType = null) => {
|
|
550
|
+
const row = store.findWhere('user_credentials', (r) =>
|
|
551
|
+
r.id === credentialId && r.user_id === userId && r.is_active
|
|
552
|
+
&& (credentialType == null || r.credential_type === credentialType),
|
|
553
|
+
);
|
|
554
|
+
return row || undefined;
|
|
555
|
+
},
|
|
556
|
+
|
|
557
|
+
deleteCredential: (userId, credentialId) =>
|
|
558
|
+
store.deleteWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId) > 0,
|
|
559
|
+
|
|
560
|
+
toggleCredential: (userId, credentialId, isActive) =>
|
|
561
|
+
store.updateWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
// ---------------------------------------------------------------------------
|
|
565
|
+
// Notification preferences
|
|
566
|
+
// ---------------------------------------------------------------------------
|
|
567
|
+
const DEFAULT_NOTIFICATION_PREFERENCES = {
|
|
568
|
+
channels: { inApp: true, webPush: false, telegram: true, desktop: true },
|
|
569
|
+
events: { actionRequired: true, stop: true, error: true, updates: true },
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
const normalizeNotificationPreferences = (value) => {
|
|
573
|
+
const source = value && typeof value === 'object' ? value : {};
|
|
574
|
+
return {
|
|
575
|
+
channels: {
|
|
576
|
+
inApp: source.channels?.inApp !== false,
|
|
577
|
+
webPush: source.channels?.webPush === true,
|
|
578
|
+
telegram: source.channels?.telegram !== false,
|
|
579
|
+
desktop: source.channels?.desktop !== false,
|
|
580
|
+
},
|
|
581
|
+
events: {
|
|
582
|
+
actionRequired: source.events?.actionRequired !== false,
|
|
583
|
+
stop: source.events?.stop !== false,
|
|
584
|
+
error: source.events?.error !== false,
|
|
585
|
+
updates: source.events?.updates !== false,
|
|
586
|
+
},
|
|
587
|
+
};
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
const notificationPreferencesDb = {
|
|
591
|
+
getPreferences: (userId) => {
|
|
592
|
+
const row = store.findWhere('user_notification_preferences', (r) => r.user_id === userId);
|
|
593
|
+
if (!row) {
|
|
594
|
+
const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
|
|
595
|
+
store.insert('user_notification_preferences', {
|
|
596
|
+
user_id: userId,
|
|
597
|
+
preferences_json: JSON.stringify(defaults),
|
|
598
|
+
updated_at: nowIso(),
|
|
599
|
+
}, { autoId: false });
|
|
600
|
+
return defaults;
|
|
601
|
+
}
|
|
602
|
+
try {
|
|
603
|
+
return normalizeNotificationPreferences(JSON.parse(row.preferences_json));
|
|
604
|
+
} catch {
|
|
605
|
+
return normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
|
|
606
|
+
}
|
|
607
|
+
},
|
|
608
|
+
|
|
609
|
+
updatePreferences: (userId, preferences) => {
|
|
610
|
+
const normalized = normalizeNotificationPreferences(preferences);
|
|
611
|
+
store.upsertWhere(
|
|
612
|
+
'user_notification_preferences',
|
|
613
|
+
(r) => r.user_id === userId,
|
|
614
|
+
{ user_id: userId, preferences_json: JSON.stringify(normalized), updated_at: nowIso() },
|
|
615
|
+
);
|
|
616
|
+
return normalized;
|
|
617
|
+
},
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
// ---------------------------------------------------------------------------
|
|
621
|
+
// Push subscriptions
|
|
622
|
+
// ---------------------------------------------------------------------------
|
|
623
|
+
const pushSubscriptionsDb = {
|
|
624
|
+
saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
|
|
625
|
+
// The old SQL path upserted on `endpoint`, updating user_id as
|
|
626
|
+
// well. Preserve that exact behaviour.
|
|
627
|
+
const existing = store.findWhere('push_subscriptions', (r) => r.endpoint === endpoint);
|
|
628
|
+
if (existing) {
|
|
629
|
+
store.updateWhere('push_subscriptions', (r) => r.endpoint === endpoint, {
|
|
630
|
+
user_id: userId,
|
|
631
|
+
keys_p256dh: keysP256dh,
|
|
632
|
+
keys_auth: keysAuth,
|
|
633
|
+
});
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
store.insert('push_subscriptions', {
|
|
637
|
+
user_id: userId,
|
|
638
|
+
endpoint,
|
|
639
|
+
keys_p256dh: keysP256dh,
|
|
640
|
+
keys_auth: keysAuth,
|
|
641
|
+
created_at: nowIso(),
|
|
642
|
+
});
|
|
643
|
+
},
|
|
644
|
+
|
|
645
|
+
getSubscriptions: (userId) =>
|
|
646
|
+
store.filterWhere('push_subscriptions', (r) => r.user_id === userId).map((r) => ({
|
|
647
|
+
endpoint: r.endpoint,
|
|
648
|
+
keys_p256dh: r.keys_p256dh,
|
|
649
|
+
keys_auth: r.keys_auth,
|
|
650
|
+
})),
|
|
651
|
+
|
|
652
|
+
removeSubscription: (endpoint) => {
|
|
653
|
+
store.deleteWhere('push_subscriptions', (r) => r.endpoint === endpoint);
|
|
654
|
+
},
|
|
655
|
+
|
|
656
|
+
removeAllForUser: (userId) => {
|
|
657
|
+
store.deleteWhere('push_subscriptions', (r) => r.user_id === userId);
|
|
658
|
+
},
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
// ---------------------------------------------------------------------------
|
|
662
|
+
// VAPID key storage (for web push)
|
|
663
|
+
// ---------------------------------------------------------------------------
|
|
664
|
+
const vapidKeysDb = {
|
|
665
|
+
getLatest: () => {
|
|
666
|
+
if (store.raw.vapid_keys.length === 0) return null;
|
|
667
|
+
// Mirror ORDER BY id DESC LIMIT 1 — take the newest row.
|
|
668
|
+
const rows = store.raw.vapid_keys.slice().sort((a, b) => b.id - a.id);
|
|
669
|
+
return { public_key: rows[0].public_key, private_key: rows[0].private_key };
|
|
670
|
+
},
|
|
671
|
+
insert: (publicKey, privateKey) => {
|
|
672
|
+
store.insert('vapid_keys', {
|
|
673
|
+
public_key: publicKey,
|
|
674
|
+
private_key: privateKey,
|
|
675
|
+
created_at: nowIso(),
|
|
676
|
+
});
|
|
677
|
+
},
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// ---------------------------------------------------------------------------
|
|
681
|
+
// Session custom names
|
|
682
|
+
// ---------------------------------------------------------------------------
|
|
683
|
+
const sessionNamesDb = {
|
|
684
|
+
setName: (sessionId, provider, customName) => {
|
|
685
|
+
store.upsertWhere(
|
|
686
|
+
'session_names',
|
|
687
|
+
(r) => r.session_id === sessionId && r.provider === provider,
|
|
688
|
+
{ session_id: sessionId, provider, custom_name: customName, updated_at: nowIso(), created_at: nowIso() },
|
|
689
|
+
);
|
|
690
|
+
},
|
|
691
|
+
|
|
692
|
+
getName: (sessionId, provider) => {
|
|
693
|
+
const row = store.findWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider);
|
|
694
|
+
return row?.custom_name || null;
|
|
695
|
+
},
|
|
696
|
+
|
|
697
|
+
getNames: (sessionIds, provider) => {
|
|
698
|
+
if (!sessionIds.length) return new Map();
|
|
699
|
+
const lookup = new Set(sessionIds);
|
|
700
|
+
const matches = store.filterWhere('session_names',
|
|
701
|
+
(r) => r.provider === provider && lookup.has(r.session_id));
|
|
702
|
+
return new Map(matches.map((r) => [r.session_id, r.custom_name]));
|
|
703
|
+
},
|
|
704
|
+
|
|
705
|
+
deleteName: (sessionId, provider) =>
|
|
706
|
+
store.deleteWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider) > 0,
|
|
707
|
+
};
|
|
708
|
+
|
|
709
|
+
function applyCustomSessionNames(sessions, provider) {
|
|
710
|
+
if (!sessions?.length) return;
|
|
711
|
+
try {
|
|
712
|
+
const ids = sessions.map((s) => s.id);
|
|
713
|
+
const customNames = sessionNamesDb.getNames(ids, provider);
|
|
714
|
+
for (const session of sessions) {
|
|
715
|
+
const custom = customNames.get(session.id);
|
|
716
|
+
if (custom) session.summary = custom;
|
|
717
|
+
}
|
|
718
|
+
} catch (error) {
|
|
719
|
+
console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// ---------------------------------------------------------------------------
|
|
724
|
+
// App config (key/value)
|
|
725
|
+
// ---------------------------------------------------------------------------
|
|
726
|
+
const appConfigDb = {
|
|
727
|
+
get: (key) => {
|
|
728
|
+
const row = store.findWhere('app_config', (r) => r.key === key);
|
|
729
|
+
return row?.value || null;
|
|
730
|
+
},
|
|
731
|
+
|
|
732
|
+
set: (key, value) => {
|
|
733
|
+
store.upsertWhere('app_config', (r) => r.key === key,
|
|
734
|
+
{ key, value, created_at: nowIso() });
|
|
735
|
+
},
|
|
736
|
+
|
|
737
|
+
getOrCreateJwtSecret: () => {
|
|
738
|
+
let secret = appConfigDb.get('jwt_secret');
|
|
739
|
+
if (!secret) {
|
|
740
|
+
secret = crypto.randomBytes(64).toString('hex');
|
|
741
|
+
appConfigDb.set('jwt_secret', secret);
|
|
742
|
+
}
|
|
743
|
+
return secret;
|
|
744
|
+
},
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
// ---------------------------------------------------------------------------
|
|
748
|
+
// Telegram — singleton config + per-user links
|
|
749
|
+
// ---------------------------------------------------------------------------
|
|
750
|
+
const DEFAULT_TELEGRAM_CONTROL_STATE = {
|
|
751
|
+
remoteControlEnabled: true,
|
|
752
|
+
progressMode: 'final',
|
|
753
|
+
selectedProjectName: null,
|
|
754
|
+
selectedProjectPath: null,
|
|
755
|
+
selectedProvider: 'opencode',
|
|
756
|
+
selectedModel: null,
|
|
757
|
+
selectedWorkflowId: null,
|
|
758
|
+
awaiting: null,
|
|
759
|
+
};
|
|
760
|
+
|
|
761
|
+
function normalizeTelegramControlState(value = {}) {
|
|
762
|
+
const raw = value && typeof value === 'object' ? value : {};
|
|
763
|
+
const selectedProvider = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.selectedProvider)
|
|
764
|
+
? raw.selectedProvider
|
|
765
|
+
: DEFAULT_TELEGRAM_CONTROL_STATE.selectedProvider;
|
|
766
|
+
const progressMode = ['final', 'steps', 'all', 'errors'].includes(raw.progressMode)
|
|
767
|
+
? raw.progressMode
|
|
768
|
+
: DEFAULT_TELEGRAM_CONTROL_STATE.progressMode;
|
|
769
|
+
|
|
770
|
+
return {
|
|
771
|
+
...DEFAULT_TELEGRAM_CONTROL_STATE,
|
|
772
|
+
...raw,
|
|
773
|
+
remoteControlEnabled: raw.remoteControlEnabled !== false,
|
|
774
|
+
progressMode,
|
|
775
|
+
selectedProvider,
|
|
776
|
+
selectedProjectName: typeof raw.selectedProjectName === 'string' ? raw.selectedProjectName : null,
|
|
777
|
+
selectedProjectPath: typeof raw.selectedProjectPath === 'string' ? raw.selectedProjectPath : null,
|
|
778
|
+
selectedModel: typeof raw.selectedModel === 'string' ? raw.selectedModel : null,
|
|
779
|
+
selectedWorkflowId: typeof raw.selectedWorkflowId === 'string' ? raw.selectedWorkflowId : null,
|
|
780
|
+
awaiting: raw.awaiting && typeof raw.awaiting === 'object' ? raw.awaiting : null,
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const telegramConfigDb = {
|
|
785
|
+
get: () => {
|
|
786
|
+
const row = store.raw.telegram_config[0];
|
|
787
|
+
if (!row) return null;
|
|
788
|
+
return { bot_token: row.bot_token, bot_username: row.bot_username, updated_at: row.updated_at };
|
|
789
|
+
},
|
|
790
|
+
set: (botToken, botUsername = null) => {
|
|
791
|
+
store.raw.telegram_config = [{
|
|
792
|
+
id: 1,
|
|
793
|
+
bot_token: botToken,
|
|
794
|
+
bot_username: botUsername,
|
|
795
|
+
updated_at: nowIso(),
|
|
796
|
+
}];
|
|
797
|
+
store.save();
|
|
798
|
+
},
|
|
799
|
+
clear: () => {
|
|
800
|
+
store.raw.telegram_config = [];
|
|
801
|
+
store.save();
|
|
802
|
+
},
|
|
803
|
+
};
|
|
804
|
+
|
|
805
|
+
const telegramLinksDb = {
|
|
806
|
+
setPairingCode: (userId, code, expiresAt, language) => {
|
|
807
|
+
store.upsertWhere('telegram_links', (r) => r.user_id === userId, {
|
|
808
|
+
user_id: userId,
|
|
809
|
+
pairing_code: code,
|
|
810
|
+
pairing_code_expires_at: expiresAt,
|
|
811
|
+
language,
|
|
812
|
+
chat_id: null,
|
|
813
|
+
telegram_username: null,
|
|
814
|
+
verified_at: null,
|
|
815
|
+
notifications_enabled: true,
|
|
816
|
+
bridge_enabled: true,
|
|
817
|
+
telegram_control: normalizeTelegramControlState(),
|
|
818
|
+
updated_at: nowIso(),
|
|
819
|
+
});
|
|
820
|
+
},
|
|
821
|
+
findByPairingCode: (code) => {
|
|
822
|
+
const row = store.findWhere('telegram_links', (r) => r.pairing_code === code);
|
|
823
|
+
if (!row) return null;
|
|
824
|
+
return {
|
|
825
|
+
user_id: row.user_id,
|
|
826
|
+
pairing_code: row.pairing_code,
|
|
827
|
+
pairing_code_expires_at: row.pairing_code_expires_at,
|
|
828
|
+
language: row.language,
|
|
829
|
+
};
|
|
830
|
+
},
|
|
831
|
+
verify: (userId, chatId, telegramUsername) => {
|
|
832
|
+
store.updateWhere('telegram_links', (r) => r.user_id === userId, {
|
|
833
|
+
chat_id: chatId,
|
|
834
|
+
telegram_username: telegramUsername,
|
|
835
|
+
verified_at: nowIso(),
|
|
836
|
+
pairing_code: null,
|
|
837
|
+
pairing_code_expires_at: null,
|
|
838
|
+
updated_at: nowIso(),
|
|
839
|
+
});
|
|
840
|
+
},
|
|
841
|
+
getByUserId: (userId) => {
|
|
842
|
+
const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
|
|
843
|
+
return row ? { ...row } : null;
|
|
844
|
+
},
|
|
845
|
+
getByChatId: (chatId) => {
|
|
846
|
+
const row = store.findWhere('telegram_links', (r) => r.chat_id === chatId);
|
|
847
|
+
if (!row) return null;
|
|
848
|
+
return {
|
|
849
|
+
user_id: row.user_id,
|
|
850
|
+
chat_id: row.chat_id,
|
|
851
|
+
telegram_username: row.telegram_username,
|
|
852
|
+
language: row.language,
|
|
853
|
+
notifications_enabled: row.notifications_enabled,
|
|
854
|
+
bridge_enabled: row.bridge_enabled,
|
|
855
|
+
telegram_control: normalizeTelegramControlState(row.telegram_control),
|
|
856
|
+
};
|
|
857
|
+
},
|
|
858
|
+
listVerified: () =>
|
|
859
|
+
store.filterWhere('telegram_links', (r) => r.chat_id && r.verified_at).map((r) => ({
|
|
860
|
+
user_id: r.user_id,
|
|
861
|
+
chat_id: r.chat_id,
|
|
862
|
+
telegram_username: r.telegram_username,
|
|
863
|
+
language: r.language,
|
|
864
|
+
notifications_enabled: r.notifications_enabled,
|
|
865
|
+
bridge_enabled: r.bridge_enabled,
|
|
866
|
+
telegram_control: normalizeTelegramControlState(r.telegram_control),
|
|
867
|
+
})),
|
|
868
|
+
updatePreferences: (userId, { language, notificationsEnabled, bridgeEnabled }) => {
|
|
869
|
+
const patch = { updated_at: nowIso() };
|
|
870
|
+
if (language !== undefined) patch.language = language;
|
|
871
|
+
if (notificationsEnabled !== undefined) patch.notifications_enabled = Boolean(notificationsEnabled);
|
|
872
|
+
if (bridgeEnabled !== undefined) patch.bridge_enabled = Boolean(bridgeEnabled);
|
|
873
|
+
if (Object.keys(patch).length === 1) return; // only updated_at → no real change
|
|
874
|
+
store.updateWhere('telegram_links', (r) => r.user_id === userId, patch);
|
|
875
|
+
},
|
|
876
|
+
getControlState: (userId) => {
|
|
877
|
+
const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
|
|
878
|
+
return normalizeTelegramControlState(row?.telegram_control);
|
|
879
|
+
},
|
|
880
|
+
updateControlState: (userId, patch) => {
|
|
881
|
+
const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
|
|
882
|
+
const current = normalizeTelegramControlState(row?.telegram_control);
|
|
883
|
+
const next = normalizeTelegramControlState({ ...current, ...(patch || {}) });
|
|
884
|
+
store.updateWhere('telegram_links', (r) => r.user_id === userId, {
|
|
885
|
+
telegram_control: next,
|
|
886
|
+
updated_at: nowIso(),
|
|
887
|
+
});
|
|
888
|
+
return next;
|
|
889
|
+
},
|
|
890
|
+
unlink: (userId) => {
|
|
891
|
+
store.deleteWhere('telegram_links', (r) => r.user_id === userId);
|
|
892
|
+
},
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
// Back-compat surface — older callers used `githubTokensDb.*`; internally
|
|
896
|
+
// they always delegated to credentialsDb with `credential_type='github_token'`.
|
|
897
|
+
const githubTokensDb = {
|
|
898
|
+
createGithubToken: (userId, tokenName, githubToken, description = null) =>
|
|
899
|
+
credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description),
|
|
900
|
+
getGithubTokens: (userId) => credentialsDb.getCredentials(userId, 'github_token'),
|
|
901
|
+
getActiveGithubToken: (userId) => credentialsDb.getActiveCredential(userId, 'github_token'),
|
|
902
|
+
deleteGithubToken: (userId, tokenId) => credentialsDb.deleteCredential(userId, tokenId),
|
|
903
|
+
toggleGithubToken: (userId, tokenId, isActive) => credentialsDb.toggleCredential(userId, tokenId, isActive),
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
export {
|
|
907
|
+
db,
|
|
908
|
+
initializeDatabase,
|
|
909
|
+
userDb,
|
|
910
|
+
apiKeysDb,
|
|
911
|
+
credentialsDb,
|
|
912
|
+
notificationPreferencesDb,
|
|
913
|
+
pushSubscriptionsDb,
|
|
914
|
+
vapidKeysDb,
|
|
915
|
+
sessionNamesDb,
|
|
916
|
+
applyCustomSessionNames,
|
|
917
|
+
appConfigDb,
|
|
918
|
+
telegramConfigDb,
|
|
919
|
+
telegramLinksDb,
|
|
920
|
+
githubTokensDb,
|
|
921
|
+
};
|