qwenproxy-cli 1.0.0 → 1.0.2
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/LICENSE +14 -14
- package/README.md +906 -906
- package/bin/qwenproxy.js +5 -1
- package/package.json +77 -78
- package/src/api/error-classifier.ts +159 -159
- package/src/api/error-helpers.ts +118 -118
- package/src/api/models.ts +261 -261
- package/src/api/server.ts +860 -859
- package/src/cache/memory-cache.ts +385 -385
- package/src/clean-cache.ts +204 -204
- package/src/core/account-concurrency.ts +671 -671
- package/src/core/account-manager.ts +301 -297
- package/src/core/account-priority.ts +163 -163
- package/src/core/accounts.ts +186 -186
- package/src/core/config.ts +383 -383
- package/src/core/crypto-utils.ts +79 -79
- package/src/core/database.ts +276 -276
- package/src/core/errors.ts +118 -118
- package/src/core/logger.ts +269 -269
- package/src/core/memory-usage.ts +84 -84
- package/src/core/metrics.ts +291 -291
- package/src/core/model-alias.ts +77 -77
- package/src/core/model-registry.ts +544 -544
- package/src/core/mutex.ts +119 -119
- package/src/core/paths.ts +199 -199
- package/src/core/prompt-limits.ts +214 -214
- package/src/core/reasoning-effort.ts +102 -102
- package/src/core/stream-registry.ts +96 -96
- package/src/core/waf-isolation.ts +117 -117
- package/src/core/watchdog.ts +195 -195
- package/src/delete-chats.ts +23 -23
- package/src/index.ts +65 -64
- package/src/login.ts +147 -147
- package/src/reset-cooldowns.ts +11 -11
- package/src/routes/anthropic/index.ts +355 -355
- package/src/routes/anthropic/translate.ts +522 -522
- package/src/routes/anthropic/types.ts +154 -154
- package/src/routes/anthropic/validation.ts +144 -144
- package/src/routes/chat/account.ts +1817 -1817
- package/src/routes/chat/context.ts +241 -241
- package/src/routes/chat/errors.ts +85 -85
- package/src/routes/chat/helpers.ts +268 -268
- package/src/routes/chat/index.ts +618 -618
- package/src/routes/chat/media.ts +285 -285
- package/src/routes/chat/retry-policy.ts +754 -754
- package/src/routes/chat/stop.ts +98 -98
- package/src/routes/chat/streaming.ts +2710 -2710
- package/src/routes/chat/validation.ts +526 -526
- package/src/routes/chat.ts +2 -2
- package/src/routes/completions.ts +290 -290
- package/src/routes/images.ts +139 -139
- package/src/routes/responses/adapter.ts +503 -503
- package/src/routes/responses/index.ts +405 -405
- package/src/routes/responses/state.ts +230 -230
- package/src/routes/responses/streaming.ts +528 -528
- package/src/routes/responses/types.ts +285 -285
- package/src/routes/responses/validation.ts +202 -202
- package/src/routes/upload.ts +731 -731
- package/src/routes/videos.ts +214 -214
- package/src/services/auth-playwright.ts +173 -173
- package/src/services/captcha-coordinator.ts +161 -161
- package/src/services/captcha-solver.ts +553 -553
- package/src/services/chat-cleanup.ts +80 -80
- package/src/services/context-meter.ts +317 -317
- package/src/services/fingerprint.ts +242 -242
- package/src/services/human-behavior.ts +173 -173
- package/src/services/media-generation.ts +1748 -1748
- package/src/services/playwright.ts +2878 -2800
- package/src/services/qwen-chat-pool.ts +345 -345
- package/src/services/qwen-errors.ts +133 -133
- package/src/services/qwen-headers.ts +79 -79
- package/src/services/qwen-thread-state.ts +393 -393
- package/src/services/qwen-url.ts +19 -19
- package/src/services/qwen.ts +3126 -3126
- package/src/services/session-keeper.ts +88 -88
- package/src/services/token-estimation-metrics.ts +118 -118
- package/src/sync/claude-code.ts +75 -75
- package/src/sync/codex.ts +123 -123
- package/src/sync/index.ts +362 -362
- package/src/sync/omp.ts +105 -105
- package/src/sync/opencode.ts +214 -214
- package/src/sync/types.ts +53 -53
- package/src/sync/utils.ts +27 -27
- package/src/sync-clients.ts +189 -189
- package/src/tools/instructions.ts +137 -137
- package/src/tools/manifest.ts +81 -81
- package/src/tools/parser.ts +2989 -2989
- package/src/tools/toolcall-tags.ts +142 -142
- package/src/tui/app.ts +259 -264
- package/src/tui/index.ts +61 -61
- package/src/tui/markdown.ts +258 -258
- package/src/tui/proxy-client.ts +331 -326
- package/src/tui/screen.ts +294 -278
- package/src/tui/server-manager.ts +270 -270
- package/src/tui/theme.ts +432 -432
- package/src/tui/types.ts +33 -33
- package/src/tui/views/accounts-view.ts +656 -656
- package/src/tui/views/chat-view.ts +1018 -823
- package/src/tui/views/logs-view.ts +479 -413
- package/src/tui/views/status-view.ts +204 -204
- package/src/tui/views/storage-view.ts +304 -291
- package/src/tui/views/sync-view.ts +409 -409
- package/src/types/ali-oss.d.ts +32 -32
- package/src/update-cli.ts +121 -0
- package/src/utils/context-truncation.ts +84 -84
- package/src/utils/json.ts +380 -380
- package/src/utils/session-id.ts +37 -37
- package/src/utils/tool-call-guard.ts +84 -84
- package/src/utils/types.ts +109 -109
package/src/core/database.ts
CHANGED
|
@@ -1,276 +1,276 @@
|
|
|
1
|
-
import Database from "better-sqlite3";
|
|
2
|
-
import path from "path";
|
|
3
|
-
import fs from "fs";
|
|
4
|
-
import { encrypt, isEncrypted } from "./crypto-utils.ts";
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Several suites exercise account rotation by deleting every row and restoring
|
|
8
|
-
* it in a `finally`. Pointed at the real database that is one crashed test away
|
|
9
|
-
* from wiping the operator's configured accounts — which is exactly how a whole
|
|
10
|
-
* account set was lost once. Tests get their own file so the blast radius of a
|
|
11
|
-
* failed restore is a throwaway directory.
|
|
12
|
-
*/
|
|
13
|
-
import {
|
|
14
|
-
getDataDir,
|
|
15
|
-
getDbDir,
|
|
16
|
-
getDbPath,
|
|
17
|
-
isRunningUnderNodeTest,
|
|
18
|
-
} from "./paths.ts";
|
|
19
|
-
|
|
20
|
-
const DATA_DIR = getDataDir();
|
|
21
|
-
const DB_DIR = getDbDir();
|
|
22
|
-
const DB_PATH = getDbPath();
|
|
23
|
-
const LEGACY_DB_PATH = path.join(DATA_DIR, "qwenproxy.db");
|
|
24
|
-
const LEGACY_DB_IN_DIR_PATH = path.join(DB_DIR, "qwenproxy.db");
|
|
25
|
-
const LEGACY_DB_WAL_PATH = `${LEGACY_DB_PATH}-wal`;
|
|
26
|
-
const LEGACY_DB_SHM_PATH = `${LEGACY_DB_PATH}-shm`;
|
|
27
|
-
const LEGACY_DB_IN_DIR_WAL_PATH = `${LEGACY_DB_IN_DIR_PATH}-wal`;
|
|
28
|
-
const LEGACY_DB_IN_DIR_SHM_PATH = `${LEGACY_DB_IN_DIR_PATH}-shm`;
|
|
29
|
-
const DB_WAL_PATH = `${DB_PATH}-wal`;
|
|
30
|
-
const DB_SHM_PATH = `${DB_PATH}-shm`;
|
|
31
|
-
const LEGACY_JSON_PATH = path.resolve("accounts.json");
|
|
32
|
-
const LEGACY_JSON_BAK_PATH = path.resolve("accounts.json.bak");
|
|
33
|
-
const DB_JSON_BAK_PATH = path.join(DB_DIR, "accounts.json.bak");
|
|
34
|
-
|
|
35
|
-
let db: Database.Database | null = null;
|
|
36
|
-
|
|
37
|
-
export function getDatabase(): Database.Database {
|
|
38
|
-
if (db) return db;
|
|
39
|
-
|
|
40
|
-
// Ensure data directory exists with proper permissions
|
|
41
|
-
try {
|
|
42
|
-
if (!fs.existsSync(DB_DIR)) {
|
|
43
|
-
fs.mkdirSync(DB_DIR, { recursive: true, mode: 0o755 });
|
|
44
|
-
}
|
|
45
|
-
const migrateLegacyDatabase = (
|
|
46
|
-
legacyPath: string,
|
|
47
|
-
legacyWalPath: string,
|
|
48
|
-
legacyShmPath: string,
|
|
49
|
-
) => {
|
|
50
|
-
if (fs.existsSync(legacyPath) && !fs.existsSync(DB_PATH)) {
|
|
51
|
-
fs.renameSync(legacyPath, DB_PATH);
|
|
52
|
-
if (fs.existsSync(legacyWalPath) && !fs.existsSync(DB_WAL_PATH)) {
|
|
53
|
-
fs.renameSync(legacyWalPath, DB_WAL_PATH);
|
|
54
|
-
}
|
|
55
|
-
if (fs.existsSync(legacyShmPath) && !fs.existsSync(DB_SHM_PATH)) {
|
|
56
|
-
fs.renameSync(legacyShmPath, DB_SHM_PATH);
|
|
57
|
-
}
|
|
58
|
-
console.log(`📦 [Database] Migrated legacy database to ${DB_PATH}`);
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
migrateLegacyDatabase(
|
|
63
|
-
LEGACY_DB_PATH,
|
|
64
|
-
LEGACY_DB_WAL_PATH,
|
|
65
|
-
LEGACY_DB_SHM_PATH,
|
|
66
|
-
);
|
|
67
|
-
migrateLegacyDatabase(
|
|
68
|
-
LEGACY_DB_IN_DIR_PATH,
|
|
69
|
-
LEGACY_DB_IN_DIR_WAL_PATH,
|
|
70
|
-
LEGACY_DB_IN_DIR_SHM_PATH,
|
|
71
|
-
);
|
|
72
|
-
if (
|
|
73
|
-
fs.existsSync(LEGACY_JSON_BAK_PATH) &&
|
|
74
|
-
!fs.existsSync(DB_JSON_BAK_PATH)
|
|
75
|
-
) {
|
|
76
|
-
fs.renameSync(LEGACY_JSON_BAK_PATH, DB_JSON_BAK_PATH);
|
|
77
|
-
}
|
|
78
|
-
// Test write access
|
|
79
|
-
const testFile = path.join(DB_DIR, ".write-test");
|
|
80
|
-
fs.writeFileSync(testFile, "");
|
|
81
|
-
fs.unlinkSync(testFile);
|
|
82
|
-
} catch (err: any) {
|
|
83
|
-
console.error(
|
|
84
|
-
`❌ [Database] Cannot access database directory '${DB_DIR}':`,
|
|
85
|
-
err.message,
|
|
86
|
-
);
|
|
87
|
-
console.error(
|
|
88
|
-
"❌ [Database] Ensure the directory exists and has proper permissions",
|
|
89
|
-
);
|
|
90
|
-
console.error(
|
|
91
|
-
"❌ [Database] In Docker, mount a volume: -v ./data:/app/data",
|
|
92
|
-
);
|
|
93
|
-
throw new Error(`Database directory not accessible: ${DB_DIR}`);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
try {
|
|
97
|
-
db = new Database(DB_PATH);
|
|
98
|
-
} catch (err: any) {
|
|
99
|
-
console.error(
|
|
100
|
-
`❌ [Database] Failed to open database at '${DB_PATH}':`,
|
|
101
|
-
err.message,
|
|
102
|
-
);
|
|
103
|
-
console.error("❌ [Database] Check file permissions and disk space");
|
|
104
|
-
throw err;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// Enable WAL mode for better concurrent read performance (ideal for VPS)
|
|
108
|
-
db.pragma("journal_mode = WAL");
|
|
109
|
-
db.pragma("busy_timeout = 5000");
|
|
110
|
-
db.pragma("synchronous = NORMAL");
|
|
111
|
-
db.pragma("cache_size = -64000"); // 64MB cache
|
|
112
|
-
db.pragma("foreign_keys = ON");
|
|
113
|
-
|
|
114
|
-
runMigrations(db);
|
|
115
|
-
migrateFromJson(db);
|
|
116
|
-
encryptPlaintextPasswords(db);
|
|
117
|
-
|
|
118
|
-
return db;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function runMigrations(db: Database.Database): void {
|
|
122
|
-
db.exec(`
|
|
123
|
-
CREATE TABLE IF NOT EXISTS accounts (
|
|
124
|
-
id TEXT PRIMARY KEY,
|
|
125
|
-
email TEXT UNIQUE NOT NULL,
|
|
126
|
-
password TEXT NOT NULL DEFAULT '',
|
|
127
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
128
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
129
|
-
);
|
|
130
|
-
|
|
131
|
-
CREATE INDEX IF NOT EXISTS idx_accounts_email ON accounts(email);
|
|
132
|
-
|
|
133
|
-
-- Cooldown persistence columns (ignore if already exist)
|
|
134
|
-
-- Note: SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN,
|
|
135
|
-
-- so these are wrapped in try-catch at the application level.
|
|
136
|
-
|
|
137
|
-
CREATE TABLE IF NOT EXISTS qwen_auth_sessions (
|
|
138
|
-
account_id TEXT PRIMARY KEY,
|
|
139
|
-
cookie TEXT NOT NULL,
|
|
140
|
-
user_agent TEXT NOT NULL,
|
|
141
|
-
bx_v TEXT,
|
|
142
|
-
bx_ua TEXT,
|
|
143
|
-
bx_umidtoken TEXT,
|
|
144
|
-
user_id TEXT,
|
|
145
|
-
token_expires_at INTEGER,
|
|
146
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
147
|
-
);
|
|
148
|
-
|
|
149
|
-
CREATE INDEX IF NOT EXISTS idx_qwen_auth_sessions_expires
|
|
150
|
-
ON qwen_auth_sessions(token_expires_at);
|
|
151
|
-
|
|
152
|
-
CREATE TABLE IF NOT EXISTS logical_thread_states (
|
|
153
|
-
session_id TEXT PRIMARY KEY,
|
|
154
|
-
account_id TEXT NOT NULL,
|
|
155
|
-
chat_session_id TEXT NOT NULL,
|
|
156
|
-
parent_id TEXT,
|
|
157
|
-
instructions_sent INTEGER NOT NULL DEFAULT 0,
|
|
158
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
159
|
-
);
|
|
160
|
-
|
|
161
|
-
CREATE INDEX IF NOT EXISTS idx_thread_updated ON logical_thread_states(updated_at);
|
|
162
|
-
|
|
163
|
-
CREATE TABLE IF NOT EXISTS personalization_cache (
|
|
164
|
-
account_id TEXT PRIMARY KEY,
|
|
165
|
-
instruction_hash TEXT NOT NULL,
|
|
166
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
167
|
-
);
|
|
168
|
-
`);
|
|
169
|
-
|
|
170
|
-
// Cooldown persistence columns — wrapped in try-catch because
|
|
171
|
-
// SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN.
|
|
172
|
-
try {
|
|
173
|
-
db.exec(
|
|
174
|
-
`ALTER TABLE accounts ADD COLUMN cooldown_until INTEGER DEFAULT 0;`,
|
|
175
|
-
);
|
|
176
|
-
} catch (err) {
|
|
177
|
-
if (!isDuplicateColumnError(err)) throw err;
|
|
178
|
-
}
|
|
179
|
-
try {
|
|
180
|
-
db.exec(`ALTER TABLE accounts ADD COLUMN cooldown_reason TEXT;`);
|
|
181
|
-
} catch (err) {
|
|
182
|
-
if (!isDuplicateColumnError(err)) throw err;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
function isDuplicateColumnError(err: unknown): boolean {
|
|
187
|
-
return err instanceof Error && err.message.includes("duplicate column name");
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function encryptPlaintextPasswords(db: Database.Database): void {
|
|
191
|
-
const rows = db.prepare("SELECT id, password FROM accounts").all() as Array<{
|
|
192
|
-
id: string;
|
|
193
|
-
password: string;
|
|
194
|
-
}>;
|
|
195
|
-
const update = db.prepare(
|
|
196
|
-
"UPDATE accounts SET password = ?, updated_at = datetime('now') WHERE id = ?",
|
|
197
|
-
);
|
|
198
|
-
let migrated = 0;
|
|
199
|
-
|
|
200
|
-
const migrate = db.transaction(() => {
|
|
201
|
-
for (const row of rows) {
|
|
202
|
-
if (row.password && !isEncrypted(row.password)) {
|
|
203
|
-
update.run(encrypt(row.password), row.id);
|
|
204
|
-
migrated++;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
migrate();
|
|
210
|
-
|
|
211
|
-
if (migrated > 0) {
|
|
212
|
-
console.log(
|
|
213
|
-
`[Database] Encrypted ${migrated} plaintext password(s) in database`,
|
|
214
|
-
);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/**
|
|
219
|
-
* Auto-migrate existing accounts.json into SQLite on first run.
|
|
220
|
-
* The legacy JSON file is moved to data/db/accounts.json.bak after successful migration.
|
|
221
|
-
*/
|
|
222
|
-
function migrateFromJson(db: Database.Database): void {
|
|
223
|
-
const jsonPath = LEGACY_JSON_PATH;
|
|
224
|
-
if (!fs.existsSync(jsonPath)) return;
|
|
225
|
-
|
|
226
|
-
try {
|
|
227
|
-
const raw = fs.readFileSync(jsonPath, "utf-8");
|
|
228
|
-
const accounts = JSON.parse(raw) as Array<{
|
|
229
|
-
id: string;
|
|
230
|
-
email: string;
|
|
231
|
-
password: string;
|
|
232
|
-
}>;
|
|
233
|
-
|
|
234
|
-
if (!Array.isArray(accounts) || accounts.length === 0) {
|
|
235
|
-
// Empty or invalid file — just rename it
|
|
236
|
-
fs.renameSync(jsonPath, DB_JSON_BAK_PATH);
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
const insert = db.prepare(`
|
|
241
|
-
INSERT OR IGNORE INTO accounts (id, email, password) VALUES (?, ?, ?)
|
|
242
|
-
`);
|
|
243
|
-
|
|
244
|
-
const migrate = db.transaction(() => {
|
|
245
|
-
for (const account of accounts) {
|
|
246
|
-
if (
|
|
247
|
-
account.id &&
|
|
248
|
-
typeof account.email === "string" &&
|
|
249
|
-
account.email.trim().length > 0
|
|
250
|
-
) {
|
|
251
|
-
insert.run(account.id, account.email.trim(), account.password || "");
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
migrate();
|
|
257
|
-
|
|
258
|
-
// Rename old file to .bak to avoid re-migration
|
|
259
|
-
fs.renameSync(jsonPath, DB_JSON_BAK_PATH);
|
|
260
|
-
console.log(
|
|
261
|
-
`[Database] Migrated ${accounts.length} account(s) from accounts.json to SQLite`,
|
|
262
|
-
);
|
|
263
|
-
} catch (err: any) {
|
|
264
|
-
console.error(
|
|
265
|
-
"❌ [Database] Failed to migrate accounts.json:",
|
|
266
|
-
err.message,
|
|
267
|
-
);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
export function closeDatabase(): void {
|
|
272
|
-
if (db) {
|
|
273
|
-
db.close();
|
|
274
|
-
db = null;
|
|
275
|
-
}
|
|
276
|
-
}
|
|
1
|
+
import Database from "better-sqlite3";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import { encrypt, isEncrypted } from "./crypto-utils.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Several suites exercise account rotation by deleting every row and restoring
|
|
8
|
+
* it in a `finally`. Pointed at the real database that is one crashed test away
|
|
9
|
+
* from wiping the operator's configured accounts — which is exactly how a whole
|
|
10
|
+
* account set was lost once. Tests get their own file so the blast radius of a
|
|
11
|
+
* failed restore is a throwaway directory.
|
|
12
|
+
*/
|
|
13
|
+
import {
|
|
14
|
+
getDataDir,
|
|
15
|
+
getDbDir,
|
|
16
|
+
getDbPath,
|
|
17
|
+
isRunningUnderNodeTest,
|
|
18
|
+
} from "./paths.ts";
|
|
19
|
+
|
|
20
|
+
const DATA_DIR = getDataDir();
|
|
21
|
+
const DB_DIR = getDbDir();
|
|
22
|
+
const DB_PATH = getDbPath();
|
|
23
|
+
const LEGACY_DB_PATH = path.join(DATA_DIR, "qwenproxy.db");
|
|
24
|
+
const LEGACY_DB_IN_DIR_PATH = path.join(DB_DIR, "qwenproxy.db");
|
|
25
|
+
const LEGACY_DB_WAL_PATH = `${LEGACY_DB_PATH}-wal`;
|
|
26
|
+
const LEGACY_DB_SHM_PATH = `${LEGACY_DB_PATH}-shm`;
|
|
27
|
+
const LEGACY_DB_IN_DIR_WAL_PATH = `${LEGACY_DB_IN_DIR_PATH}-wal`;
|
|
28
|
+
const LEGACY_DB_IN_DIR_SHM_PATH = `${LEGACY_DB_IN_DIR_PATH}-shm`;
|
|
29
|
+
const DB_WAL_PATH = `${DB_PATH}-wal`;
|
|
30
|
+
const DB_SHM_PATH = `${DB_PATH}-shm`;
|
|
31
|
+
const LEGACY_JSON_PATH = path.resolve("accounts.json");
|
|
32
|
+
const LEGACY_JSON_BAK_PATH = path.resolve("accounts.json.bak");
|
|
33
|
+
const DB_JSON_BAK_PATH = path.join(DB_DIR, "accounts.json.bak");
|
|
34
|
+
|
|
35
|
+
let db: Database.Database | null = null;
|
|
36
|
+
|
|
37
|
+
export function getDatabase(): Database.Database {
|
|
38
|
+
if (db) return db;
|
|
39
|
+
|
|
40
|
+
// Ensure data directory exists with proper permissions
|
|
41
|
+
try {
|
|
42
|
+
if (!fs.existsSync(DB_DIR)) {
|
|
43
|
+
fs.mkdirSync(DB_DIR, { recursive: true, mode: 0o755 });
|
|
44
|
+
}
|
|
45
|
+
const migrateLegacyDatabase = (
|
|
46
|
+
legacyPath: string,
|
|
47
|
+
legacyWalPath: string,
|
|
48
|
+
legacyShmPath: string,
|
|
49
|
+
) => {
|
|
50
|
+
if (fs.existsSync(legacyPath) && !fs.existsSync(DB_PATH)) {
|
|
51
|
+
fs.renameSync(legacyPath, DB_PATH);
|
|
52
|
+
if (fs.existsSync(legacyWalPath) && !fs.existsSync(DB_WAL_PATH)) {
|
|
53
|
+
fs.renameSync(legacyWalPath, DB_WAL_PATH);
|
|
54
|
+
}
|
|
55
|
+
if (fs.existsSync(legacyShmPath) && !fs.existsSync(DB_SHM_PATH)) {
|
|
56
|
+
fs.renameSync(legacyShmPath, DB_SHM_PATH);
|
|
57
|
+
}
|
|
58
|
+
console.log(`📦 [Database] Migrated legacy database to ${DB_PATH}`);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
migrateLegacyDatabase(
|
|
63
|
+
LEGACY_DB_PATH,
|
|
64
|
+
LEGACY_DB_WAL_PATH,
|
|
65
|
+
LEGACY_DB_SHM_PATH,
|
|
66
|
+
);
|
|
67
|
+
migrateLegacyDatabase(
|
|
68
|
+
LEGACY_DB_IN_DIR_PATH,
|
|
69
|
+
LEGACY_DB_IN_DIR_WAL_PATH,
|
|
70
|
+
LEGACY_DB_IN_DIR_SHM_PATH,
|
|
71
|
+
);
|
|
72
|
+
if (
|
|
73
|
+
fs.existsSync(LEGACY_JSON_BAK_PATH) &&
|
|
74
|
+
!fs.existsSync(DB_JSON_BAK_PATH)
|
|
75
|
+
) {
|
|
76
|
+
fs.renameSync(LEGACY_JSON_BAK_PATH, DB_JSON_BAK_PATH);
|
|
77
|
+
}
|
|
78
|
+
// Test write access
|
|
79
|
+
const testFile = path.join(DB_DIR, ".write-test");
|
|
80
|
+
fs.writeFileSync(testFile, "");
|
|
81
|
+
fs.unlinkSync(testFile);
|
|
82
|
+
} catch (err: any) {
|
|
83
|
+
console.error(
|
|
84
|
+
`❌ [Database] Cannot access database directory '${DB_DIR}':`,
|
|
85
|
+
err.message,
|
|
86
|
+
);
|
|
87
|
+
console.error(
|
|
88
|
+
"❌ [Database] Ensure the directory exists and has proper permissions",
|
|
89
|
+
);
|
|
90
|
+
console.error(
|
|
91
|
+
"❌ [Database] In Docker, mount a volume: -v ./data:/app/data",
|
|
92
|
+
);
|
|
93
|
+
throw new Error(`Database directory not accessible: ${DB_DIR}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
db = new Database(DB_PATH);
|
|
98
|
+
} catch (err: any) {
|
|
99
|
+
console.error(
|
|
100
|
+
`❌ [Database] Failed to open database at '${DB_PATH}':`,
|
|
101
|
+
err.message,
|
|
102
|
+
);
|
|
103
|
+
console.error("❌ [Database] Check file permissions and disk space");
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Enable WAL mode for better concurrent read performance (ideal for VPS)
|
|
108
|
+
db.pragma("journal_mode = WAL");
|
|
109
|
+
db.pragma("busy_timeout = 5000");
|
|
110
|
+
db.pragma("synchronous = NORMAL");
|
|
111
|
+
db.pragma("cache_size = -64000"); // 64MB cache
|
|
112
|
+
db.pragma("foreign_keys = ON");
|
|
113
|
+
|
|
114
|
+
runMigrations(db);
|
|
115
|
+
migrateFromJson(db);
|
|
116
|
+
encryptPlaintextPasswords(db);
|
|
117
|
+
|
|
118
|
+
return db;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function runMigrations(db: Database.Database): void {
|
|
122
|
+
db.exec(`
|
|
123
|
+
CREATE TABLE IF NOT EXISTS accounts (
|
|
124
|
+
id TEXT PRIMARY KEY,
|
|
125
|
+
email TEXT UNIQUE NOT NULL,
|
|
126
|
+
password TEXT NOT NULL DEFAULT '',
|
|
127
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
128
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
CREATE INDEX IF NOT EXISTS idx_accounts_email ON accounts(email);
|
|
132
|
+
|
|
133
|
+
-- Cooldown persistence columns (ignore if already exist)
|
|
134
|
+
-- Note: SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN,
|
|
135
|
+
-- so these are wrapped in try-catch at the application level.
|
|
136
|
+
|
|
137
|
+
CREATE TABLE IF NOT EXISTS qwen_auth_sessions (
|
|
138
|
+
account_id TEXT PRIMARY KEY,
|
|
139
|
+
cookie TEXT NOT NULL,
|
|
140
|
+
user_agent TEXT NOT NULL,
|
|
141
|
+
bx_v TEXT,
|
|
142
|
+
bx_ua TEXT,
|
|
143
|
+
bx_umidtoken TEXT,
|
|
144
|
+
user_id TEXT,
|
|
145
|
+
token_expires_at INTEGER,
|
|
146
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
CREATE INDEX IF NOT EXISTS idx_qwen_auth_sessions_expires
|
|
150
|
+
ON qwen_auth_sessions(token_expires_at);
|
|
151
|
+
|
|
152
|
+
CREATE TABLE IF NOT EXISTS logical_thread_states (
|
|
153
|
+
session_id TEXT PRIMARY KEY,
|
|
154
|
+
account_id TEXT NOT NULL,
|
|
155
|
+
chat_session_id TEXT NOT NULL,
|
|
156
|
+
parent_id TEXT,
|
|
157
|
+
instructions_sent INTEGER NOT NULL DEFAULT 0,
|
|
158
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
CREATE INDEX IF NOT EXISTS idx_thread_updated ON logical_thread_states(updated_at);
|
|
162
|
+
|
|
163
|
+
CREATE TABLE IF NOT EXISTS personalization_cache (
|
|
164
|
+
account_id TEXT PRIMARY KEY,
|
|
165
|
+
instruction_hash TEXT NOT NULL,
|
|
166
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
167
|
+
);
|
|
168
|
+
`);
|
|
169
|
+
|
|
170
|
+
// Cooldown persistence columns — wrapped in try-catch because
|
|
171
|
+
// SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN.
|
|
172
|
+
try {
|
|
173
|
+
db.exec(
|
|
174
|
+
`ALTER TABLE accounts ADD COLUMN cooldown_until INTEGER DEFAULT 0;`,
|
|
175
|
+
);
|
|
176
|
+
} catch (err) {
|
|
177
|
+
if (!isDuplicateColumnError(err)) throw err;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
db.exec(`ALTER TABLE accounts ADD COLUMN cooldown_reason TEXT;`);
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if (!isDuplicateColumnError(err)) throw err;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function isDuplicateColumnError(err: unknown): boolean {
|
|
187
|
+
return err instanceof Error && err.message.includes("duplicate column name");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function encryptPlaintextPasswords(db: Database.Database): void {
|
|
191
|
+
const rows = db.prepare("SELECT id, password FROM accounts").all() as Array<{
|
|
192
|
+
id: string;
|
|
193
|
+
password: string;
|
|
194
|
+
}>;
|
|
195
|
+
const update = db.prepare(
|
|
196
|
+
"UPDATE accounts SET password = ?, updated_at = datetime('now') WHERE id = ?",
|
|
197
|
+
);
|
|
198
|
+
let migrated = 0;
|
|
199
|
+
|
|
200
|
+
const migrate = db.transaction(() => {
|
|
201
|
+
for (const row of rows) {
|
|
202
|
+
if (row.password && !isEncrypted(row.password)) {
|
|
203
|
+
update.run(encrypt(row.password), row.id);
|
|
204
|
+
migrated++;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
migrate();
|
|
210
|
+
|
|
211
|
+
if (migrated > 0) {
|
|
212
|
+
console.log(
|
|
213
|
+
`[Database] Encrypted ${migrated} plaintext password(s) in database`,
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Auto-migrate existing accounts.json into SQLite on first run.
|
|
220
|
+
* The legacy JSON file is moved to data/db/accounts.json.bak after successful migration.
|
|
221
|
+
*/
|
|
222
|
+
function migrateFromJson(db: Database.Database): void {
|
|
223
|
+
const jsonPath = LEGACY_JSON_PATH;
|
|
224
|
+
if (!fs.existsSync(jsonPath)) return;
|
|
225
|
+
|
|
226
|
+
try {
|
|
227
|
+
const raw = fs.readFileSync(jsonPath, "utf-8");
|
|
228
|
+
const accounts = JSON.parse(raw) as Array<{
|
|
229
|
+
id: string;
|
|
230
|
+
email: string;
|
|
231
|
+
password: string;
|
|
232
|
+
}>;
|
|
233
|
+
|
|
234
|
+
if (!Array.isArray(accounts) || accounts.length === 0) {
|
|
235
|
+
// Empty or invalid file — just rename it
|
|
236
|
+
fs.renameSync(jsonPath, DB_JSON_BAK_PATH);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const insert = db.prepare(`
|
|
241
|
+
INSERT OR IGNORE INTO accounts (id, email, password) VALUES (?, ?, ?)
|
|
242
|
+
`);
|
|
243
|
+
|
|
244
|
+
const migrate = db.transaction(() => {
|
|
245
|
+
for (const account of accounts) {
|
|
246
|
+
if (
|
|
247
|
+
account.id &&
|
|
248
|
+
typeof account.email === "string" &&
|
|
249
|
+
account.email.trim().length > 0
|
|
250
|
+
) {
|
|
251
|
+
insert.run(account.id, account.email.trim(), account.password || "");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
migrate();
|
|
257
|
+
|
|
258
|
+
// Rename old file to .bak to avoid re-migration
|
|
259
|
+
fs.renameSync(jsonPath, DB_JSON_BAK_PATH);
|
|
260
|
+
console.log(
|
|
261
|
+
`[Database] Migrated ${accounts.length} account(s) from accounts.json to SQLite`,
|
|
262
|
+
);
|
|
263
|
+
} catch (err: any) {
|
|
264
|
+
console.error(
|
|
265
|
+
"❌ [Database] Failed to migrate accounts.json:",
|
|
266
|
+
err.message,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function closeDatabase(): void {
|
|
272
|
+
if (db) {
|
|
273
|
+
db.close();
|
|
274
|
+
db = null;
|
|
275
|
+
}
|
|
276
|
+
}
|