-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3193 lines (2733 loc) · 105 KB
/
Copy pathserver.js
File metadata and controls
3193 lines (2733 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require("express");
const path = require("node:path");
const fs = require("node:fs");
const crypto = require("node:crypto");
const { DatabaseSync } = require("node:sqlite");
const {
validateRegistrationCredentials,
validateLoginCredentials,
validatePhoneRegistration,
validateModelName,
getPasswordStrength,
isValidEmail,
isValidPhone,
cleanPhone
} = require("./auth-validation");
const {
getAllowedCorsOrigins,
getSessionCookieOptions
} = require("./deployment-config");
const app = express();
const PORT = Number(process.env.PORT || 3000);
const PUBLIC_DIR = path.join(__dirname, "public");
const DATA_DIR = path.join(__dirname, "data");
const DB_PATH = path.join(DATA_DIR, "personality-improvement.db");
const COOKIE_NAME = "pi_session";
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const REMEMBER_ME_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const VERIFICATION_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const RESET_TOKEN_TTL_MS = 60 * 60 * 1000;
const LOGIN_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
const LOGIN_RATE_LIMIT_MAX = 5;
const LOGIN_LOCK_THRESHOLD = 10;
const TOTAL_QUESTIONS = 56;
const MBTI_TYPES = ["INTJ", "INTP", "ENTJ", "ENTP", "INFJ", "INFP", "ENFJ", "ENFP", "ISTJ", "ISFJ", "ESTJ", "ESFJ", "ISTP", "ISFP", "ESTP", "ESFP"];
const SCENARIOS = ["团队会议", "冲突处理", "决策时刻", "压力管理", "自我表达"];
const DEFAULT_AI_MODEL = process.env.OPENAI_MODEL || "gpt-4.1-mini";
const DEFAULT_AI_PROVIDER = "openai_compatible";
const DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
const DEFAULT_AI_PROMPT = [
"# 角色定义",
"你是【愈格】软件的专属AI性格成长助手,核心使命是基于用户性格特征(如MBTI)和具体场景,生成分梯度、多方式的性格改进方案,帮助用户循序渐进优化性格。",
"",
"# 核心能力强化",
"1. 场景化分析:精准识别用户的具体场景,结合其性格特征定位核心问题。",
"2. 梯度方案设计:针对每个场景,优先生成缓慢改善、中等改善、快速改善三类方案。",
"3. 多解决方式:每类方案下提供3到4种具体、可落地的解决方式,并说明操作步骤和预期效果。",
"4. 个性化适配:结合用户MBTI和性格特点调整建议强度,避免给高敏感或内向用户过重压力。",
"5. 激励引导:在结尾给出选择建议,帮助用户根据接受度选择下一步。",
"",
"# 行为准则",
"1. 所有建议都要具体、能执行,避免空泛表达。",
"2. 三类方案的难度、执行成本、见效速度要明显区分。",
"3. 不否定用户当前状态,只提供不同路径的改进可能。",
"4. 全程使用简洁、温和、无评判的中文。",
"",
"# 输出规则",
"如果用户明确希望得到系统方案,请优先按以下结构输出:核心问题分析 -> 缓慢改善 -> 中等改善 -> 快速改善 -> 选择建议。",
"如果用户是在继续聊天、追问、倾诉或复盘,就自然承接上下文回答,不要每次都强行套固定模板。",
"如果用户只想要一个可立刻执行的动作,就直接给出最小可执行的一步。",
"回复中不要使用 emoji、彩色符号、花哨装饰或代码块围栏。",
"如果需要列点,请只使用普通中文段落或 1. 2. 3. 这种简洁序号。"
].join("\n");
const STRUCTURED_PLAN_PROMPT = [
"你是一个性格改进方案设计师。",
"用户会告诉你他想改进的性格方面,请你为他生成一套可执行的改进计划。",
"你必须只输出一个 JSON 对象,不要输出任何解释文字、Markdown、代码块或额外注释。",
"JSON 结构必须是:{\"plan_groups\":[{\"group_name\":string,\"group_description\":string,\"plans\":[{\"plan_name\":string,\"plan_description\":string,\"estimated_days\":number,\"completion_threshold\":number,\"tasks\":[{\"task_description\":string}]}]}]}",
"计划分组 2 到 4 组,每组 2 到 3 个计划,每个计划 3 到 6 个任务。",
"所有字段名必须使用英文;所有值必须使用中文。",
"任务必须具体、简洁、可勾选,适合放入用户的计划簿。",
"completion_threshold 必须是 0 到 1 之间的小数。",
"不要输出任何 schema 说明或额外字段。"
].join("\n");
const STRUCTURED_PLAN_REPAIR_PROMPT = [
"你是一个 JSON 修复器。",
"请把用户提供的内容修复为一个合法的 JSON 对象。",
"只输出 JSON 对象本身,不要输出任何解释、Markdown 或额外文字。",
"字段结构必须严格为 plan_groups -> group_name/group_description/plans -> plan_name/plan_description/estimated_days/completion_threshold/tasks -> task_description。",
"所有字段名必须是英文,值必须是中文。"
].join("\n");
const APP_BUILD = process.env.APP_BUILD || `local-${new Date(fs.statSync(__filename).mtimeMs).toISOString()}`;
const BACKEND_CAPABILITIES = Object.freeze({
structuredPlan: true,
planBook: true
});
const ALLOWED_CORS_ORIGINS = getAllowedCorsOrigins(process.env.CORS_ORIGINS);
fs.mkdirSync(DATA_DIR, { recursive: true });
const db = new DatabaseSync(DB_PATH);
initializeDatabase();
// In-memory rate limiting: IP -> { count, windowStart }
const loginRateLimitMap = new Map();
function getClientIP(req) {
const forwarded = req.headers["x-forwarded-for"];
if (forwarded) {
return String(forwarded).split(",")[0].trim();
}
return req.socket.remoteAddress || "127.0.0.1";
}
function checkLoginRateLimit(ip) {
const now = Date.now();
const entry = loginRateLimitMap.get(ip);
if (!entry || now - entry.windowStart > LOGIN_RATE_LIMIT_WINDOW_MS) {
loginRateLimitMap.set(ip, { count: 1, windowStart: now });
return { limited: false, remaining: LOGIN_RATE_LIMIT_MAX - 1 };
}
entry.count += 1;
if (entry.count > LOGIN_RATE_LIMIT_MAX) {
const retryAfter = Math.ceil((LOGIN_RATE_LIMIT_WINDOW_MS - (now - entry.windowStart)) / 1000);
return { limited: true, retryAfter, remaining: 0 };
}
return { limited: false, remaining: LOGIN_RATE_LIMIT_MAX - entry.count };
}
// Clean up rate limit map every 5 minutes
setInterval(() => {
const cutoff = Date.now() - LOGIN_RATE_LIMIT_WINDOW_MS;
for (const [ip, entry] of loginRateLimitMap) {
if (entry.windowStart < cutoff) {
loginRateLimitMap.delete(ip);
}
}
}, 5 * 60 * 1000).unref();
app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: true }));
app.use(applyCors);
app.use(loadSession);
app.use(express.static(PUBLIC_DIR));
app.use("/assets/react-mbti", express.static(path.join(__dirname, "assets", "react-mbti")));
function applyCors(req, res, next) {
const origin = req.headers.origin;
if (origin && ALLOWED_CORS_ORIGINS.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Vary", "Origin");
}
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
if (req.method === "OPTIONS") {
res.status(204).end();
return;
}
next();
}
function initializeDatabase() {
db.exec("PRAGMA foreign_keys = ON;");
db.exec("PRAGMA journal_mode = WAL;");
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL,
email TEXT,
password_hash TEXT NOT NULL,
password_salt TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS user_state (
user_id TEXT PRIMARY KEY,
current_question INTEGER NOT NULL DEFAULT 0,
answers_json TEXT NOT NULL,
mbti_type TEXT,
mbti_source TEXT NOT NULL DEFAULT 'none',
reliability INTEGER NOT NULL DEFAULT 0,
match_score INTEGER NOT NULL DEFAULT 0,
radar_json TEXT NOT NULL,
selected_scenario TEXT NOT NULL DEFAULT '团队会议',
active_ai_conversation_id TEXT,
theme TEXT NOT NULL DEFAULT 'light',
onboarding_completed INTEGER NOT NULL DEFAULT 0,
imported_from_local INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS todos (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
text TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS activities (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
kind TEXT NOT NULL,
text TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_history (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
conversation_id TEXT,
scenario TEXT NOT NULL,
goal TEXT NOT NULL,
details TEXT,
response_json TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(conversation_id) REFERENCES ai_conversations(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_conversations (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
title TEXT NOT NULL,
scenario TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
last_message_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_settings (
user_id TEXT PRIMARY KEY,
api_key TEXT NOT NULL DEFAULT '',
base_url TEXT NOT NULL DEFAULT '',
model TEXT NOT NULL DEFAULT 'gpt-4.1-mini',
provider TEXT NOT NULL DEFAULT 'openai_compatible',
updated_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS plan_book_entries (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
source_history_id TEXT NOT NULL,
conversation_id TEXT,
source_group_index INTEGER NOT NULL,
source_plan_index INTEGER NOT NULL,
group_name TEXT NOT NULL,
group_description TEXT NOT NULL,
plan_name TEXT NOT NULL,
plan_description TEXT NOT NULL,
estimated_days INTEGER NOT NULL,
completion_threshold REAL NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
achieved_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS plan_book_tasks (
id TEXT PRIMARY KEY,
entry_id TEXT NOT NULL,
task_description TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL,
completed_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(entry_id) REFERENCES plan_book_entries(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id);
CREATE INDEX IF NOT EXISTS idx_activities_user_id ON activities(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_history_user_id ON ai_history(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_conversations_user_id ON ai_conversations(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_conversations_last_message_at ON ai_conversations(last_message_at);
CREATE INDEX IF NOT EXISTS idx_plan_book_entries_user_id ON plan_book_entries(user_id);
CREATE INDEX IF NOT EXISTS idx_plan_book_entries_source_plan ON plan_book_entries(user_id, source_history_id, source_group_index, source_plan_index);
CREATE INDEX IF NOT EXISTS idx_plan_book_tasks_entry_id ON plan_book_tasks(entry_id);
CREATE TABLE IF NOT EXISTS email_verifications (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
token TEXT NOT NULL UNIQUE,
email TEXT NOT NULL,
expires_at TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS password_reset_tokens (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
token TEXT NOT NULL UNIQUE,
expires_at TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_email_verifications_token ON email_verifications(token);
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_token ON password_reset_tokens(token);
`);
ensureTableColumn("ai_settings", "provider", `TEXT NOT NULL DEFAULT '${DEFAULT_AI_PROVIDER}'`);
ensureTableColumn("users", "email", "TEXT");
ensureTableColumn("users", "phone", "TEXT");
ensureTableColumn("users", "email_verified", "INTEGER NOT NULL DEFAULT 0");
ensureTableColumn("users", "failed_attempts", "INTEGER NOT NULL DEFAULT 0");
ensureTableColumn("users", "locked_until", "TEXT");
ensureTableColumn("user_state", "mbti_source", "TEXT NOT NULL DEFAULT 'none'");
ensureTableColumn("user_state", "active_ai_conversation_id", "TEXT");
ensureTableColumn("ai_history", "conversation_id", "TEXT");
db.exec(`
DROP INDEX IF EXISTS idx_plan_book_entries_source_plan;
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_lower ON users(lower(email)) WHERE email IS NOT NULL AND trim(email) <> '';
CREATE INDEX IF NOT EXISTS idx_plan_book_entries_source_plan ON plan_book_entries(user_id, source_history_id, source_group_index, source_plan_index);
CREATE UNIQUE INDEX IF NOT EXISTS idx_plan_book_entries_active_source_plan
ON plan_book_entries(user_id, source_history_id, source_group_index, source_plan_index)
WHERE status = 'active';
CREATE INDEX IF NOT EXISTS idx_ai_conversations_user_id ON ai_conversations(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_conversations_last_message_at ON ai_conversations(last_message_at);
`);
db.exec(`
UPDATE user_state
SET mbti_source = 'test'
WHERE (mbti_source IS NULL OR mbti_source = '' OR mbti_source = 'none')
AND mbti_type IS NOT NULL
AND trim(mbti_type) <> ''
`);
migrateLegacyAiHistoryConversations();
}
function ensureTableColumn(tableName, columnName, definition) {
const columns = db.prepare(`PRAGMA table_info(${tableName})`).all();
if (columns.some((column) => column.name === columnName)) {
return;
}
db.exec(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${definition}`);
}
function nowIso() {
return new Date().toISOString();
}
function generateId() {
return crypto.randomUUID();
}
function parseCookies(rawHeader) {
const cookies = {};
if (!rawHeader) return cookies;
rawHeader.split(";").forEach((part) => {
const trimmed = part.trim();
if (!trimmed) return;
const equalsIndex = trimmed.indexOf("=");
if (equalsIndex === -1) return;
const key = decodeURIComponent(trimmed.slice(0, equalsIndex));
const value = decodeURIComponent(trimmed.slice(equalsIndex + 1));
cookies[key] = value;
});
return cookies;
}
function sessionCookieBaseOptions() {
return getSessionCookieOptions(process.env.NODE_ENV);
}
function createSession(res, userId, rememberMe = false) {
const sessionId = crypto.randomBytes(32).toString("hex");
const createdAt = nowIso();
const ttlMs = rememberMe ? REMEMBER_ME_TTL_MS : SESSION_TTL_MS;
const expiresAt = new Date(Date.now() + ttlMs).toISOString();
db.prepare(
`INSERT INTO sessions (id, user_id, expires_at, created_at)
VALUES (?, ?, ?, ?)`
).run(sessionId, userId, expiresAt, createdAt);
res.cookie(COOKIE_NAME, sessionId, {
...sessionCookieBaseOptions(),
expires: new Date(Date.now() + ttlMs),
maxAge: ttlMs
});
}
function clearSession(res, sessionId) {
if (sessionId) {
db.prepare("DELETE FROM sessions WHERE id = ?").run(sessionId);
}
res.clearCookie(COOKIE_NAME, sessionCookieBaseOptions());
}
function loadSession(req, res, next) {
db.prepare("DELETE FROM sessions WHERE expires_at <= ?").run(nowIso());
const cookies = parseCookies(req.headers.cookie || "");
const sessionId = cookies[COOKIE_NAME];
if (!sessionId) {
next();
return;
}
const row = db.prepare(
`SELECT sessions.id AS session_id, users.id AS user_id, users.username, users.email,
users.email_verified, users.phone
FROM sessions
JOIN users ON users.id = sessions.user_id
WHERE sessions.id = ? AND sessions.expires_at > ?`
).get(sessionId, nowIso());
if (!row) {
clearSession(res, sessionId);
next();
return;
}
req.sessionId = row.session_id;
req.user = {
id: row.user_id,
username: row.username,
email: row.email || "",
emailVerified: row.email_verified === 1,
phone: row.phone || ""
};
next();
}
function requireAuth(req, res, next) {
if (!req.user) {
res.status(401).json({ message: "未登录或登录已失效" });
return;
}
next();
}
function defaultCoreState() {
return {
currentQuestion: 0,
answers: new Array(TOTAL_QUESTIONS).fill(null),
mbti: null,
mbtiSource: "none",
reliability: 0,
match: 0,
radar: [],
selectedScenario: SCENARIOS[0],
activeAiConversationId: null,
theme: "light",
onboardingCompleted: false,
importedFromLocal: false
};
}
function sanitizeAnswers(candidate) {
if (!Array.isArray(candidate) || candidate.length !== TOTAL_QUESTIONS) {
return new Array(TOTAL_QUESTIONS).fill(null);
}
return candidate.map((value) => {
if (value === null) return null;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : null;
});
}
function sanitizeTheme(theme) {
return theme === "dark" ? "dark" : "light";
}
function sanitizeMbtiType(value) {
const raw = String(value || "").trim().toUpperCase();
return MBTI_TYPES.includes(raw) ? raw : null;
}
function sanitizeMbtiSource(value) {
return value === "manual" || value === "test" ? value : "none";
}
function sanitizeScenario(scenario) {
return SCENARIOS.includes(scenario) ? scenario : SCENARIOS[0];
}
function sanitizeConversationId(value) {
const raw = String(value || "").trim();
return raw ? raw : null;
}
function sanitizeRadar(radar) {
if (!Array.isArray(radar)) return [];
return radar
.map((value) => Number(value))
.filter((value) => Number.isFinite(value))
.slice(0, 8);
}
function sanitizeCoreState(candidate) {
const base = defaultCoreState();
const source = candidate || {};
const mbti = sanitizeMbtiType(source.mbti);
const mbtiSource = mbti ? sanitizeMbtiSource(source.mbtiSource) : "none";
return {
currentQuestion: Math.min(TOTAL_QUESTIONS - 1, Math.max(0, Number(source.currentQuestion) || 0)),
answers: sanitizeAnswers(source.answers),
mbti,
mbtiSource,
reliability: mbtiSource === "test" ? Math.max(0, Math.min(100, Number(source.reliability) || 0)) : 0,
match: mbtiSource === "test" ? Math.max(0, Math.min(100, Number(source.match) || 0)) : 0,
radar: mbti ? sanitizeRadar(source.radar) : [],
selectedScenario: sanitizeScenario(source.selectedScenario || base.selectedScenario),
activeAiConversationId: sanitizeConversationId(source.activeAiConversationId),
theme: sanitizeTheme(source.theme || base.theme),
onboardingCompleted: Boolean(source.onboardingCompleted),
importedFromLocal: Boolean(source.importedFromLocal)
};
}
function parseJsonOrFallback(raw, fallback) {
if (!raw) return fallback;
try {
return JSON.parse(raw);
} catch (error) {
return fallback;
}
}
function sanitizeBaseUrl(value) {
const raw = String(value || "").trim();
if (!raw) return "";
if (!/^https?:\/\//i.test(raw)) return "";
return raw.replace(/\/+$/, "");
}
function sanitizeAiModel(value) {
return validateModelName(value, DEFAULT_AI_MODEL);
}
function sanitizeAiProvider(value) {
const raw = String(value || "").trim();
return raw === "gemini_native" ? "gemini_native" : DEFAULT_AI_PROVIDER;
}
function normalizeProviderBaseUrl(provider, value) {
const raw = sanitizeBaseUrl(value);
if (!raw) return "";
try {
const url = new URL(raw);
if (
sanitizeAiProvider(provider) === DEFAULT_AI_PROVIDER &&
url.hostname === "api.openai.com" &&
(!url.pathname || url.pathname === "/")
) {
url.pathname = "/v1";
}
return url.toString().replace(/\/+$/, "");
} catch (error) {
return raw;
}
}
function maskApiKey(apiKey) {
const raw = String(apiKey || "").trim();
if (!raw) return "";
return raw.length <= 8 ? "已保存" : `${raw.slice(0, 4)}...${raw.slice(-4)}`;
}
function ensureUserState(userId) {
const existing = db.prepare("SELECT user_id FROM user_state WHERE user_id = ?").get(userId);
if (existing) return;
const defaults = defaultCoreState();
db.prepare(
`INSERT INTO user_state (
user_id,
current_question,
answers_json,
mbti_type,
mbti_source,
reliability,
match_score,
radar_json,
selected_scenario,
theme,
onboarding_completed,
imported_from_local,
updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).run(
userId,
defaults.currentQuestion,
JSON.stringify(defaults.answers),
defaults.mbti,
defaults.mbtiSource,
defaults.reliability,
defaults.match,
JSON.stringify(defaults.radar),
defaults.selectedScenario,
defaults.theme,
defaults.onboardingCompleted ? 1 : 0,
defaults.importedFromLocal ? 1 : 0,
nowIso()
);
}
function ensureAiSettings(userId) {
const existing = db.prepare("SELECT user_id FROM ai_settings WHERE user_id = ?").get(userId);
if (existing) return;
db.prepare(
`INSERT INTO ai_settings (user_id, api_key, base_url, model, provider, updated_at)
VALUES (?, ?, ?, ?, ?, ?)`
).run(userId, "", "", DEFAULT_AI_MODEL, DEFAULT_AI_PROVIDER, nowIso());
}
function getStoredAiSettings(userId) {
ensureAiSettings(userId);
const row = db.prepare("SELECT * FROM ai_settings WHERE user_id = ?").get(userId);
const provider = sanitizeAiProvider(row.provider);
return {
apiKey: String(row.api_key || "").trim(),
baseUrl: normalizeProviderBaseUrl(provider, row.base_url),
model: sanitizeAiModel(row.model),
provider
};
}
function getPublicAiSettings(userId) {
const settings = getStoredAiSettings(userId);
return {
baseUrl: settings.baseUrl,
model: settings.model,
provider: settings.provider,
hasApiKey: Boolean(settings.apiKey),
apiKeyMasked: maskApiKey(settings.apiKey)
};
}
function writeAiSettings(userId, candidate) {
const current = getStoredAiSettings(userId);
const nextProvider = candidate.provider !== undefined ? sanitizeAiProvider(candidate.provider) : current.provider;
const nextApiKey = String(candidate.apiKey || "").trim() || current.apiKey;
const nextBaseUrl = candidate.baseUrl !== undefined
? normalizeProviderBaseUrl(nextProvider, candidate.baseUrl)
: normalizeProviderBaseUrl(nextProvider, current.baseUrl);
const nextModel = candidate.model !== undefined ? sanitizeAiModel(candidate.model) : current.model;
db.prepare(
`UPDATE ai_settings
SET api_key = ?,
base_url = ?,
model = ?,
provider = ?,
updated_at = ?
WHERE user_id = ?`
).run(nextApiKey, nextBaseUrl, nextModel, nextProvider, nowIso(), userId);
return getPublicAiSettings(userId);
}
function getCoreState(userId) {
ensureUserState(userId);
const row = db.prepare("SELECT * FROM user_state WHERE user_id = ?").get(userId);
return sanitizeCoreState({
currentQuestion: row.current_question,
answers: parseJsonOrFallback(row.answers_json, new Array(TOTAL_QUESTIONS).fill(null)),
mbti: row.mbti_type,
mbtiSource: row.mbti_source || (row.mbti_type ? "test" : "none"),
reliability: row.reliability,
match: row.match_score,
radar: parseJsonOrFallback(row.radar_json, []),
selectedScenario: row.selected_scenario,
activeAiConversationId: row.active_ai_conversation_id,
theme: row.theme,
onboardingCompleted: row.onboarding_completed === 1,
importedFromLocal: row.imported_from_local === 1
});
}
function writeCoreState(userId, candidate) {
const state = sanitizeCoreState(candidate);
db.prepare(
`UPDATE user_state
SET current_question = ?,
answers_json = ?,
mbti_type = ?,
mbti_source = ?,
reliability = ?,
match_score = ?,
radar_json = ?,
selected_scenario = ?,
active_ai_conversation_id = ?,
theme = ?,
onboarding_completed = ?,
imported_from_local = ?,
updated_at = ?
WHERE user_id = ?`
).run(
state.currentQuestion,
JSON.stringify(state.answers),
state.mbti,
state.mbtiSource,
state.reliability,
state.match,
JSON.stringify(state.radar),
state.selectedScenario,
state.activeAiConversationId,
state.theme,
state.onboardingCompleted ? 1 : 0,
state.importedFromLocal ? 1 : 0,
nowIso(),
userId
);
return state;
}
function formatActivityRow(row) {
return `${new Date(row.created_at).toLocaleString("zh-CN", { hour12: false })} - ${row.text}`;
}
function getUserSummary(userId) {
const user = db.prepare("SELECT id, username, email, phone, email_verified, created_at FROM users WHERE id = ?").get(userId);
if (!user) return null;
return {
id: user.id,
username: user.username,
email: user.email || "",
phone: user.phone || "",
emailVerified: user.email_verified === 1,
createdAt: user.created_at
};
}
function buildConversationTitle(text) {
const normalized = String(text || "").replace(/\s+/g, " ").trim();
if (!normalized) return "新的对话";
return normalized.length > 26 ? `${normalized.slice(0, 26)}...` : normalized;
}
function getConversationRow(userId, conversationId) {
const safeConversationId = sanitizeConversationId(conversationId);
if (!safeConversationId) return null;
return db.prepare(
`SELECT id, user_id, title, scenario, created_at, updated_at, last_message_at
FROM ai_conversations
WHERE id = ? AND user_id = ?`
).get(safeConversationId, userId) || null;
}
function getLatestConversationId(userId) {
const row = db.prepare(
`SELECT id
FROM ai_conversations
WHERE user_id = ?
ORDER BY last_message_at DESC, created_at DESC
LIMIT 1`
).get(userId);
return row ? row.id : null;
}
function setActiveConversation(userId, conversationId) {
const current = getCoreState(userId);
writeCoreState(userId, {
...current,
activeAiConversationId: sanitizeConversationId(conversationId)
});
}
function createConversationRecord(userId, scenario, firstMessage, timestamp = nowIso()) {
const conversationId = generateId();
const safeScenario = sanitizeScenario(scenario);
const title = buildConversationTitle(firstMessage);
db.prepare(
`INSERT INTO ai_conversations (id, user_id, title, scenario, created_at, updated_at, last_message_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
).run(conversationId, userId, title, safeScenario, timestamp, timestamp, timestamp);
return getConversationRow(userId, conversationId);
}
function updateConversationAfterReply(userId, conversationId, scenario, timestamp = nowIso()) {
db.prepare(
`UPDATE ai_conversations
SET scenario = ?, updated_at = ?, last_message_at = ?
WHERE id = ? AND user_id = ?`
).run(sanitizeScenario(scenario), timestamp, timestamp, conversationId, userId);
}
function syncConversationAfterTurnDeletion(userId, conversationId) {
const safeConversationId = sanitizeConversationId(conversationId);
if (!safeConversationId) return;
const latestTurn = db.prepare(
`SELECT scenario, created_at
FROM ai_history
WHERE user_id = ? AND conversation_id = ?
ORDER BY created_at DESC, id DESC
LIMIT 1`
).get(userId, safeConversationId);
if (!latestTurn) {
db.prepare("DELETE FROM ai_conversations WHERE id = ? AND user_id = ?").run(safeConversationId, userId);
const core = getCoreState(userId);
if (core.activeAiConversationId === safeConversationId) {
setActiveConversation(userId, getLatestConversationId(userId));
}
return;
}
db.prepare(
`UPDATE ai_conversations
SET scenario = ?, updated_at = ?, last_message_at = ?
WHERE id = ? AND user_id = ?`
).run(sanitizeScenario(latestTurn.scenario), nowIso(), latestTurn.created_at, safeConversationId, userId);
}
function getConversationSummaries(userId) {
const rows = db.prepare(
`SELECT c.id, c.title, c.scenario, c.created_at, c.updated_at, c.last_message_at,
(SELECT COUNT(*) FROM ai_history h WHERE h.conversation_id = c.id) AS turn_count,
(SELECT response_json FROM ai_history h WHERE h.conversation_id = c.id ORDER BY h.created_at DESC, h.id DESC LIMIT 1) AS latest_response_json
FROM ai_conversations c
WHERE c.user_id = ?
ORDER BY c.last_message_at DESC, c.created_at DESC`
).all(userId);
return rows.map((row) => {
const latestResponse = sanitizeStoredCoachResponse(parseJsonOrFallback(row.latest_response_json, null));
const previewText = extractReplyText(latestResponse) || row.title;
return {
id: row.id,
title: row.title,
scenario: row.scenario,
createdAt: row.created_at,
updatedAt: row.updated_at,
lastMessageAt: row.last_message_at,
preview: previewText.length > 90 ? `${previewText.slice(0, 90)}...` : previewText,
turnCount: Number(row.turn_count) || 0
};
});
}
function getConversationMessages(userId, conversationId) {
const conversation = getConversationRow(userId, conversationId);
if (!conversation) return [];
const turns = db.prepare(
`SELECT id, goal, details, response_json, created_at
FROM ai_history
WHERE user_id = ? AND conversation_id = ?
ORDER BY created_at ASC, id ASC`
).all(userId, conversation.id);
const messages = [];
turns.forEach((row) => {
const response = sanitizeStoredCoachResponse(parseJsonOrFallback(row.response_json, null));
messages.push({
id: `${row.id}:user`,
turnId: row.id,
historyId: row.id,
role: "user",
text: row.goal,
details: String(row.details || ""),
createdAt: row.created_at
});
messages.push({
id: `${row.id}:assistant`,
turnId: row.id,
historyId: row.id,
role: "assistant",
text: extractReplyText(response) || "我已经收到你的消息。",
structuredPlan: response && response.structuredPlan ? response.structuredPlan : null,
createdAt: row.created_at
});
});
return messages;
}
function getPlanBookEntries(userId) {
const entryRows = db.prepare(
`SELECT id, user_id, source_history_id, conversation_id, source_group_index, source_plan_index,
group_name, group_description, plan_name, plan_description, estimated_days, completion_threshold,
status, achieved_at, created_at, updated_at
FROM plan_book_entries
WHERE user_id = ?
ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, updated_at DESC, created_at DESC`
).all(userId);
const taskRows = db.prepare(
`SELECT t.id, t.entry_id, t.task_description, t.done, t.sort_order, t.completed_at, t.created_at, t.updated_at
FROM plan_book_tasks t
JOIN plan_book_entries e ON e.id = t.entry_id
WHERE e.user_id = ?
ORDER BY t.sort_order ASC, t.created_at ASC`
).all(userId);
const tasksByEntry = new Map();
taskRows.forEach((row) => {
const list = tasksByEntry.get(row.entry_id) || [];
list.push({
id: row.id,
taskDescription: row.task_description,
done: row.done === 1,
sortOrder: Number(row.sort_order) || 0,
completedAt: row.completed_at || "",
createdAt: row.created_at || "",
updatedAt: row.updated_at || ""
});
tasksByEntry.set(row.entry_id, list);
});
return entryRows.map((row) => {
const tasks = tasksByEntry.get(row.id) || [];
const totalTasks = tasks.length;
const completedTasks = tasks.filter((task) => task.done).length;
const completionThreshold = Math.max(0, Math.min(1, Number(row.completion_threshold) || 0.75));
const completionRatio = totalTasks ? Number((completedTasks / totalTasks).toFixed(4)) : 0;
const status = totalTasks > 0 && completionRatio >= completionThreshold ? "achieved" : "active";
return {
id: row.id,
sourceHistoryId: row.source_history_id,
conversationId: row.conversation_id || null,
sourceGroupIndex: Number(row.source_group_index) || 0,
sourcePlanIndex: Number(row.source_plan_index) || 0,
groupName: row.group_name,
groupDescription: row.group_description,
planName: row.plan_name,
planDescription: row.plan_description,
estimatedDays: Math.max(1, Number(row.estimated_days) || 14),
completionThreshold,
status,
achievedAt: status === "achieved" ? String(row.achieved_at || "") : "",
createdAt: row.created_at,
updatedAt: row.updated_at,
totalTasks,
completedTasks,
completionRatio,
tasks
};
});
}
function getPlanBookStats(entries) {
const items = Array.isArray(entries) ? entries : [];
const activeEntries = items.filter((entry) => entry.status !== "achieved");
const achievedEntries = items.filter((entry) => entry.status === "achieved");
const totalTaskCount = items.reduce((sum, entry) => sum + (Number(entry.totalTasks) || 0), 0);
const completedTaskCount = items.reduce((sum, entry) => sum + (Number(entry.completedTasks) || 0), 0);
const overallCompletionRatio = totalTaskCount ? Number((completedTaskCount / totalTaskCount).toFixed(4)) : 0;
const currentPlanProgress = activeEntries[0]
? {
entryId: activeEntries[0].id,
planName: activeEntries[0].planName,
completionRatio: activeEntries[0].completionRatio,
completionThreshold: activeEntries[0].completionThreshold,
completedTasks: activeEntries[0].completedTasks,
totalTasks: activeEntries[0].totalTasks,
estimatedDays: activeEntries[0].estimatedDays
}
: null;
const recentAchieved = achievedEntries.length
? achievedEntries
.slice()
.sort((a, b) => new Date(b.achievedAt || b.updatedAt || 0).getTime() - new Date(a.achievedAt || a.updatedAt || 0).getTime())[0]