forked from joshhu/fingerprints
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1173 lines (997 loc) · 42.1 KB
/
Copy pathserver.js
File metadata and controls
1173 lines (997 loc) · 42.1 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 sqlite3 = require('sqlite3').verbose();
const path = require('path');
const session = require('express-session');
const bcrypt = require('bcryptjs');
const axios = require('axios');
const app = express();
const PORT = process.env.PORT || 3000;
// 簡單的數學 CAPTCHA 驗證
function generateMathCaptcha() {
const num1 = Math.floor(Math.random() * 10) + 1;
const num2 = Math.floor(Math.random() * 10) + 1;
const operators = ['+', '-', '*'];
const operator = operators[Math.floor(Math.random() * operators.length)];
let answer;
switch (operator) {
case '+':
answer = num1 + num2;
break;
case '-':
answer = Math.abs(num1 - num2); // 確保結果為正數
break;
case '*':
answer = num1 * num2;
break;
}
return {
question: `${num1} ${operator} ${num2} = ?`,
answer: answer
};
}
// 驗證數學 CAPTCHA 的函數
function verifyMathCaptcha(sessionAnswer, userAnswer) {
try {
const sessionNum = parseInt(sessionAnswer);
const userNum = parseInt(userAnswer);
return sessionNum === userNum;
} catch (error) {
console.error('CAPTCHA 驗證錯誤:', error);
return false;
}
}
// 中間件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
secret: process.env.SESSION_SECRET || 'fingerprint-session-secret-key-2025',
resave: true, // 在 Render 環境中啟用 resave
saveUninitialized: true, // 在 Render 環境中啟用 saveUninitialized
cookie: {
secure: false, // Render 環境中暫時禁用 secure
httpOnly: true, // 防止 XSS 攻擊
maxAge: 24 * 60 * 60 * 1000, // 1 天,減少 session 存儲時間
sameSite: 'lax' // CSRF 保護
},
name: 'fingerprint.sid' // 自定義 session 名稱
}));
app.use(express.static('public'));
// 資料庫初始化
const db = new sqlite3.Database('fingerprints.db');
// 建立資料表
db.serialize(() => {
// 多重指紋資料表
db.run(`
CREATE TABLE IF NOT EXISTS fingerprints (
id INTEGER PRIMARY KEY AUTOINCREMENT,
visitor_id TEXT UNIQUE,
confidence_score REAL,
confidence_comment TEXT,
version TEXT,
components TEXT,
client_id TEXT,
custom_fingerprint TEXT,
canvas_fingerprint TEXT,
webgl_fingerprint TEXT,
audio_fingerprint TEXT,
fonts_fingerprint TEXT,
plugins_fingerprint TEXT,
hardware_fingerprint TEXT,
collection_time INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_seen DATETIME DEFAULT CURRENT_TIMESTAMP,
linked_user_id INTEGER,
FOREIGN KEY (linked_user_id) REFERENCES accounts(id)
)
`);
// 用戶帳號資料表
db.run(`
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE,
password_hash TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_login DATETIME
)
`);
// 資料庫初始化完成
});
console.log('伺服器運行在 http://localhost:' + PORT);
console.log('FingerprintJS V4 指紋採集測試網站已啟動');
console.log('資料庫相容性已修正 - 版本 2025.01.01');
// 計算多重指紋相似度函數
function calculateMultiFingerprintSimilarity(oldData, newData) {
const similarities = [];
const weights = [];
// 1. FingerprintJS V4 相似度 (權重 40% - 提高權重)
if (oldData.components && newData.components) {
const fpSimilarity = calculateFingerprintJSSimilarity(oldData.components, newData.components);
similarities.push(fpSimilarity);
weights.push(0.4);
console.log('FingerprintJS 相似度:', fpSimilarity);
}
// 2. Canvas 指紋相似度 (權重 20%)
if (oldData.canvas && newData.canvas && oldData.canvas !== '' && newData.canvas !== '') {
const canvasSimilarity = calculateCanvasSimilarity(oldData.canvas, newData.canvas);
similarities.push(canvasSimilarity);
weights.push(0.2);
console.log('Canvas 相似度:', canvasSimilarity);
}
// 3. WebGL 指紋相似度 (權重 15%)
if (oldData.webgl && newData.webgl && Object.keys(oldData.webgl).length > 0 && Object.keys(newData.webgl).length > 0) {
const webglSimilarity = calculateWebGLSimilarity(oldData.webgl, newData.webgl);
similarities.push(webglSimilarity);
weights.push(0.15);
console.log('WebGL 相似度:', webglSimilarity);
}
// 4. 音訊指紋相似度 (權重 10%)
if (oldData.audio && newData.audio && Object.keys(oldData.audio).length > 0 && Object.keys(newData.audio).length > 0) {
const audioSimilarity = calculateAudioSimilarity(oldData.audio, newData.audio);
similarities.push(audioSimilarity);
weights.push(0.1);
console.log('Audio 相似度:', audioSimilarity);
}
// 5. 字體指紋相似度 (權重 10%)
if (oldData.fonts && newData.fonts && Object.keys(oldData.fonts).length > 0 && Object.keys(newData.fonts).length > 0) {
const fontsSimilarity = calculateFontsSimilarity(oldData.fonts, newData.fonts);
similarities.push(fontsSimilarity);
weights.push(0.1);
console.log('Fonts 相似度:', fontsSimilarity);
}
// 6. 硬體指紋相似度 (權重 5%)
if (oldData.hardware && newData.hardware && Object.keys(oldData.hardware).length > 0 && Object.keys(newData.hardware).length > 0) {
const hardwareSimilarity = calculateHardwareSimilarity(oldData.hardware, newData.hardware);
similarities.push(hardwareSimilarity);
weights.push(0.05);
console.log('Hardware 相似度:', hardwareSimilarity);
}
// 7. 自定義指紋相似度 (權重 5%)
if (oldData.custom && newData.custom && Object.keys(oldData.custom).length > 0 && Object.keys(newData.custom).length > 0) {
const customSimilarity = calculateCustomSimilarity(oldData.custom, newData.custom);
similarities.push(customSimilarity);
weights.push(0.05);
console.log('Custom 相似度:', customSimilarity);
}
if (similarities.length === 0) {
return 0;
}
// 計算加權平均相似度
let weightedSum = 0;
let totalWeight = 0;
for (let i = 0; i < similarities.length; i++) {
weightedSum += similarities[i] * weights[i];
totalWeight += weights[i];
}
const finalSimilarity = Math.round((weightedSum / totalWeight) * 10) / 10;
// 調試信息
console.log('相似度計算調試:', {
similarities,
weights,
weightedSum,
totalWeight,
finalSimilarity,
availableTypes: similarities.length
});
return Math.min(100, Math.max(0, finalSimilarity));
}
// 計算 FingerprintJS V4 相似度
function calculateFingerprintJSSimilarity(oldComponents, newComponents) {
const oldKeys = Object.keys(oldComponents);
const newKeys = Object.keys(newComponents);
if (oldKeys.length === 0 || newKeys.length === 0) {
return 0;
}
let totalComponents = 0;
let matchingComponents = 0;
let importantMatches = 0;
let importantTotal = 0;
// 重要的指紋元件(權重較高)
const importantComponents = [
'canvas', 'webgl', 'audio', 'fonts', 'screenResolution',
'hardwareConcurrency', 'deviceMemory', 'platform'
];
// 容易變化的元件(權重較低或忽略)
const volatileComponents = ['viewport', 'timezone'];
// 會因為瀏覽器重啟而變化的元件(完全忽略)
const sessionBasedComponents = ['domBlockers', 'sessionStorage', 'localStorage', 'indexedDB'];
const allKeys = new Set([...oldKeys, ...newKeys]);
for (const key of allKeys) {
const oldValue = oldComponents[key];
const newValue = newComponents[key];
// 跳過錯誤的元件和會話相關元件
if ((oldValue && oldValue.error) || (newValue && newValue.error) || sessionBasedComponents.includes(key)) {
continue;
}
totalComponents++;
const isImportant = importantComponents.includes(key);
const isVolatile = volatileComponents.includes(key);
if (isImportant) {
importantTotal++;
}
// 比較值(忽略 duration 差異)
if (oldValue && newValue) {
const oldVal = JSON.stringify(oldValue.value);
const newVal = JSON.stringify(newValue.value);
if (oldVal === newVal) {
matchingComponents++;
if (isImportant) {
importantMatches++;
}
} else if (isVolatile) {
// 對於容易變化的元件,給予部分分數
matchingComponents += 0.5;
}
}
}
if (totalComponents === 0) {
return 0;
}
// 計算基本相似度
const basicSimilarity = (matchingComponents / totalComponents) * 100;
// 如果重要元件匹配度很高,提升整體分數
const importantSimilarity = importantTotal > 0 ? (importantMatches / importantTotal) * 100 : 100;
// 綜合計算(重要元件權重 70%,一般元件權重 30%)
const finalSimilarity = (importantSimilarity * 0.7) + (basicSimilarity * 0.3);
return Math.round(finalSimilarity * 10) / 10;
}
// 計算 Canvas 相似度
function calculateCanvasSimilarity(oldCanvas, newCanvas) {
if (oldCanvas === newCanvas) {
return 100;
}
// 簡單的雜湊比較
const oldHash = hashString(oldCanvas);
const newHash = hashString(newCanvas);
if (oldHash === newHash) {
return 100;
}
// 如果完全不同,返回 0
return 0;
}
// 計算 WebGL 相似度
function calculateWebGLSimilarity(oldWebGL, newWebGL) {
if (!oldWebGL || !newWebGL) return 0;
let matches = 0;
let total = 0;
// 比較基本資訊
if (oldWebGL.renderer === newWebGL.renderer) matches++;
if (oldWebGL.vendor === newWebGL.vendor) matches++;
if (oldWebGL.version === newWebGL.version) matches++;
total += 3;
// 比較擴展
const oldExtensions = oldWebGL.extensions || [];
const newExtensions = newWebGL.extensions || [];
const extensionSimilarity = calculateArraySimilarity(oldExtensions, newExtensions);
matches += extensionSimilarity * 0.5;
total += 0.5;
return total > 0 ? (matches / total) * 100 : 0;
}
// 計算音訊相似度
function calculateAudioSimilarity(oldAudio, newAudio) {
if (!oldAudio || !newAudio) return 0;
if (oldAudio.fingerprint === newAudio.fingerprint) {
return 100;
}
if (oldAudio.sampleRate === newAudio.sampleRate) {
return 50; // 部分匹配
}
return 0;
}
// 計算字體相似度
function calculateFontsSimilarity(oldFonts, newFonts) {
if (!oldFonts || !newFonts) return 0;
const oldAvailable = oldFonts.available || [];
const newAvailable = newFonts.available || [];
return calculateArraySimilarity(oldAvailable, newAvailable);
}
// 計算硬體相似度
function calculateHardwareSimilarity(oldHardware, newHardware) {
if (!oldHardware || !newHardware) return 0;
let matches = 0;
let total = 0;
if (oldHardware.cores === newHardware.cores) matches++;
if (oldHardware.memory === newHardware.memory) matches++;
if (oldHardware.touchPoints === newHardware.touchPoints) matches++;
total += 3;
return total > 0 ? (matches / total) * 100 : 0;
}
// 計算自定義指紋相似度
function calculateCustomSimilarity(oldCustom, newCustom) {
if (!oldCustom || !newCustom) return 0;
let matches = 0;
let total = 0;
// 比較螢幕資訊
if (oldCustom.screen && newCustom.screen) {
if (oldCustom.screen.width === newCustom.screen.width) matches++;
if (oldCustom.screen.height === newCustom.screen.height) matches++;
if (oldCustom.screen.colorDepth === newCustom.screen.colorDepth) matches++;
total += 3;
}
// 比較時區
if (oldCustom.timezone === newCustom.timezone) matches++;
total++;
return total > 0 ? (matches / total) * 100 : 0;
}
// 計算陣列相似度
function calculateArraySimilarity(oldArray, newArray) {
if (!Array.isArray(oldArray) || !Array.isArray(newArray)) return 0;
const oldSet = new Set(oldArray);
const newSet = new Set(newArray);
const intersection = new Set([...oldSet].filter(x => newSet.has(x)));
const union = new Set([...oldSet, ...newSet]);
return union.size > 0 ? (intersection.size / union.size) * 100 : 0;
}
// 雜湊字串
function hashString(str) {
let hash = 0;
if (str.length === 0) return hash.toString(16);
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // 轉換為 32 位整數
}
return hash.toString(16);
}
// 中間件:檢查是否已登入
function isAuthenticated(req, res, next) {
if (req.session.userId) {
next();
} else {
res.status(401).json({ error: '未登入' });
}
}
// API 路由:生成數學 CAPTCHA
app.get('/api/captcha', (req, res) => {
try {
const captcha = generateMathCaptcha();
// 將答案存儲在 session 中
req.session.captchaAnswer = captcha.answer;
console.log('生成 CAPTCHA:', {
question: captcha.question,
answer: captcha.answer,
sessionId: req.sessionID,
hasCaptchaAnswer: !!req.session.captchaAnswer
});
// 確保 session 被保存
req.session.save((err) => {
if (err) {
console.error('Session 保存錯誤:', err);
// 即使 session 保存失敗,也返回 CAPTCHA 問題
// 這樣用戶至少可以看到問題,雖然驗證可能失敗
return res.json({
question: captcha.question,
timestamp: Date.now(),
warning: 'Session 保存失敗,驗證可能不穩定'
});
}
console.log('CAPTCHA session 保存成功');
res.json({
question: captcha.question,
timestamp: Date.now()
});
});
} catch (error) {
console.error('CAPTCHA 生成錯誤:', error);
res.status(500).json({ error: '無法生成驗證碼' });
}
});
// 找出變化的元件
function findChangedComponents(oldComponents, newComponents) {
const changes = [];
const allKeys = new Set([...Object.keys(oldComponents), ...Object.keys(newComponents)]);
for (const key of allKeys) {
const oldValue = oldComponents[key];
const newValue = newComponents[key];
if (!oldValue && newValue) {
changes.push({ component: key, type: 'added', newValue: newValue.value });
} else if (oldValue && !newValue) {
changes.push({ component: key, type: 'removed', oldValue: oldValue.value });
} else if (oldValue && newValue) {
const oldVal = JSON.stringify(oldValue.value);
const newVal = JSON.stringify(newValue.value);
if (oldVal !== newVal) {
changes.push({
component: key,
type: 'changed',
oldValue: oldValue.value,
newValue: newValue.value
});
}
}
}
return changes;
}
// API 路由:用戶註冊
app.post('/api/auth/register', async (req, res) => {
const { username, email, password, captcha } = req.body;
// 驗證輸入
if (!username || !password) {
return res.status(400).json({ error: '請填寫所有欄位' });
}
// 驗證 email 格式(如果提供)
if (email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({ error: 'Email 格式不正確' });
}
}
// 驗證數學 CAPTCHA
if (!captcha) {
return res.status(400).json({ error: '請完成驗證碼' });
}
console.log('註冊驗證 CAPTCHA:', {
userInput: captcha,
sessionCaptchaAnswer: req.session.captchaAnswer,
sessionId: req.sessionID,
hasSession: !!req.session
});
if (!req.session.captchaAnswer) {
console.log('註冊 CAPTCHA 驗證失敗:session 中沒有 captchaAnswer');
return res.status(400).json({ error: '驗證碼已過期,請重新載入' });
}
const captchaValid = verifyMathCaptcha(req.session.captchaAnswer, captcha);
if (!captchaValid) {
console.log('註冊 CAPTCHA 驗證失敗:答案不匹配');
return res.status(400).json({ error: '驗證碼錯誤,請重試' });
}
// 清除已使用的 CAPTCHA
delete req.session.captchaAnswer;
if (username.length < 3) {
return res.status(400).json({ error: '使用者名稱至少需要 3 個字元' });
}
if (password.length < 6) {
return res.status(400).json({ error: '密碼至少需要 6 個字元' });
}
try {
// 檢查使用者名稱是否已存在
db.get('SELECT id FROM accounts WHERE username = ?', [username], async (err, existingUser) => {
if (err) {
console.error('檢查用戶錯誤:', err);
return res.status(500).json({ error: '系統錯誤' });
}
if (existingUser) {
return res.status(400).json({ error: '使用者名稱已存在' });
}
// 如果提供了 email,檢查是否已存在
if (email) {
db.get('SELECT id FROM accounts WHERE email = ?', [email], async (emailErr, existingEmail) => {
if (emailErr) {
console.error('檢查 email 錯誤:', emailErr);
return res.status(500).json({ error: '系統錯誤' });
}
if (existingEmail) {
return res.status(400).json({ error: 'Email 已被使用' });
}
// 繼續註冊流程
await createUser();
});
} else {
await createUser();
}
async function createUser() {
// 加密密碼
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
// 建立新用戶
db.run(
'INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?)',
[username, email || null, hashedPassword],
function(insertErr) {
if (insertErr) {
console.error('建立用戶錯誤:', insertErr);
return res.status(500).json({ error: '註冊失敗' });
}
console.log('新用戶註冊成功:', { id: this.lastID, username, email });
res.json({
success: true,
message: '註冊成功!',
userId: this.lastID
});
}
);
}
});
} catch (error) {
console.error('註冊錯誤:', error);
res.status(500).json({ error: '註冊失敗' });
}
});
// API 路由:用戶登入
app.post('/api/auth/login', async (req, res) => {
const { username, password, captcha, rememberMe } = req.body;
if (!username || !password) {
return res.status(400).json({ error: '請輸入使用者名稱/Email 和密碼' });
}
// 驗證數學 CAPTCHA
if (!captcha) {
return res.status(400).json({ error: '請完成驗證碼' });
}
console.log('登入驗證 CAPTCHA:', {
userInput: captcha,
sessionCaptchaAnswer: req.session.captchaAnswer,
sessionId: req.sessionID,
hasSession: !!req.session
});
if (!req.session.captchaAnswer) {
console.log('登入 CAPTCHA 驗證失敗:session 中沒有 captchaAnswer');
return res.status(400).json({ error: '驗證碼已過期,請重新載入' });
}
const captchaValid = verifyMathCaptcha(req.session.captchaAnswer, captcha);
if (!captchaValid) {
console.log('登入 CAPTCHA 驗證失敗:答案不匹配');
return res.status(400).json({ error: '驗證碼錯誤,請重試' });
}
// 清除已使用的 CAPTCHA
delete req.session.captchaAnswer;
// 查找用戶(支援 username 或 email)
const query = 'SELECT * FROM accounts WHERE username = ? OR email = ?';
db.get(query, [username, username], async (err, user) => {
if (err) {
console.error('登入查詢錯誤:', err);
return res.status(500).json({ error: '登入失敗' });
}
if (!user) {
return res.status(401).json({ error: '使用者名稱/Email 或密碼錯誤' });
}
try {
// 驗證密碼
const passwordMatch = await bcrypt.compare(password, user.password_hash);
if (!passwordMatch) {
return res.status(401).json({ error: '使用者名稱/Email 或密碼錯誤' });
}
// 設定 session
req.session.userId = user.id;
req.session.username = user.username;
// 如果勾選「記住我」,延長 cookie 有效期到 30 天
if (rememberMe) {
req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000; // 30 天
console.log('啟用「記住我」功能,session 有效期延長至 30 天');
} else {
req.session.cookie.maxAge = 24 * 60 * 60 * 1000; // 1 天(預設)
}
// 更新最後登入時間
db.run('UPDATE accounts SET last_login = CURRENT_TIMESTAMP WHERE id = ?', [user.id]);
console.log('用戶登入成功:', { id: user.id, username: user.username, rememberMe: !!rememberMe });
res.json({
success: true,
message: '登入成功!',
user: {
id: user.id,
username: user.username,
email: user.email
}
});
} catch (error) {
console.error('密碼驗證錯誤:', error);
res.status(500).json({ error: '登入失敗' });
}
});
});
// API 路由:用戶登出
app.post('/api/auth/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('登出錯誤:', err);
return res.status(500).json({ error: '登出失敗' });
}
res.json({ success: true, message: '登出成功!' });
});
});
// API 路由:獲取當前用戶資訊
app.get('/api/auth/me', (req, res) => {
if (!req.session.userId) {
return res.json({ loggedIn: false });
}
db.get('SELECT id, username, created_at, last_login FROM accounts WHERE id = ?', [req.session.userId], (err, user) => {
if (err || !user) {
return res.json({ loggedIn: false });
}
res.json({
loggedIn: true,
user: {
id: user.id,
username: user.username,
createdAt: user.created_at,
lastLogin: user.last_login
}
});
});
});
// API 路由:處理多重指紋資料
app.post('/api/fingerprint', (req, res) => {
const {
visitorId,
confidence,
version,
components,
clientId,
custom,
canvas,
webgl,
audio,
fonts,
plugins,
hardware,
collectionTime,
timestamp
} = req.body;
if (!visitorId) {
return res.status(400).json({ error: '缺少訪客 ID' });
}
console.log('收到多重指紋資料:', {
visitorId,
confidence: confidence?.score,
version,
componentsCount: Object.keys(components || {}).length,
clientId,
hasCustom: !!custom,
hasCanvas: !!canvas,
hasWebGL: !!webgl,
hasAudio: !!audio,
hasFonts: !!fonts,
hasPlugins: !!plugins,
hasHardware: !!hardware,
collectionTime,
isLoggedIn: !!req.session.userId,
userId: req.session.userId
});
// 調試:顯示所有元件名稱
console.log('採集的元件:', Object.keys(components || {}).sort().join(', '));
// **新邏輯:區分登入和未登入用戶**
if (req.session.userId) {
// **已登入用戶:將指紋關聯到該用戶帳號**
handleLoggedInUserFingerprint(req, res, visitorId, confidence, version, components, clientId, custom, canvas, webgl, audio, fonts, plugins, hardware, collectionTime);
} else {
// **未登入用戶:比對現有指紋並顯示相似度**
handleGuestUserFingerprint(req, res, visitorId, confidence, version, components, clientId, custom, canvas, webgl, audio, fonts, plugins, hardware, collectionTime);
}
});
// 處理登入用戶的指紋
function handleLoggedInUserFingerprint(req, res, visitorId, confidence, version, components, clientId, custom, canvas, webgl, audio, fonts, plugins, hardware, collectionTime) {
const userId = req.session.userId;
// 檢查該用戶是否已有指紋記錄
db.get(
'SELECT id, visitor_id, components FROM fingerprints WHERE linked_user_id = ?',
[userId],
(err, existingRecord) => {
if (err) {
console.error('查詢用戶指紋錯誤:', err);
return res.status(500).json({ error: '資料庫查詢失敗' });
}
if (existingRecord) {
// 更新現有指紋
const oldComponents = JSON.parse(existingRecord.components || '{}');
// 構建舊的指紋資料結構進行多重指紋比對
const oldData = {
components: oldComponents,
canvas: existingRecord.canvas_fingerprint,
webgl: existingRecord.webgl_fingerprint ? JSON.parse(existingRecord.webgl_fingerprint) : {},
audio: existingRecord.audio_fingerprint ? JSON.parse(existingRecord.audio_fingerprint) : {},
fonts: existingRecord.fonts_fingerprint ? JSON.parse(existingRecord.fonts_fingerprint) : {},
plugins: existingRecord.plugins_fingerprint ? JSON.parse(existingRecord.plugins_fingerprint) : {},
hardware: existingRecord.hardware_fingerprint ? JSON.parse(existingRecord.hardware_fingerprint) : {},
custom: existingRecord.custom_fingerprint ? JSON.parse(existingRecord.custom_fingerprint) : {}
};
const newData = {
components: components || {},
canvas: canvas,
webgl: webgl || {},
audio: audio || {},
fonts: fonts || {},
plugins: plugins || {},
hardware: hardware || {},
custom: custom || {}
};
const similarity = calculateMultiFingerprintSimilarity(oldData, newData);
// 使用更安全的更新語句,只更新存在的欄位
db.run(
'UPDATE fingerprints SET visitor_id = ?, confidence_score = ?, confidence_comment = ?, version = ?, components = ?, last_seen = CURRENT_TIMESTAMP WHERE linked_user_id = ?',
[
visitorId,
confidence?.score || 0,
confidence?.comment || '',
version || '',
JSON.stringify(components || {}),
userId
],
function(updateErr) {
if (updateErr) {
console.error('更新用戶指紋錯誤:', updateErr);
return res.status(500).json({ error: '更新失敗' });
}
console.log(`更新登入用戶 ${userId} 的指紋, 相似度: ${similarity.toFixed(1)}%`);
// 查詢用戶名稱
db.get('SELECT username FROM accounts WHERE id = ?', [userId], (userErr, user) => {
res.json({
isNewUser: false,
userId: existingRecord.id,
similarity: similarity,
message: `已登入用戶 ${user?.username || userId} 的指紋已更新`,
fingerprintChanged: similarity < 90,
isLoggedIn: true
});
});
}
);
} else {
// 新增指紋記錄(使用基本欄位)
db.run(
'INSERT INTO fingerprints (visitor_id, confidence_score, confidence_comment, version, components, linked_user_id) VALUES (?, ?, ?, ?, ?, ?)',
[
visitorId,
confidence?.score || 0,
confidence?.comment || '',
version || '',
JSON.stringify(components || {}),
userId
],
function(insertErr) {
if (insertErr) {
console.error('新增用戶指紋錯誤:', insertErr);
return res.status(500).json({ error: '新增失敗' });
}
console.log(`新增登入用戶 ${userId} 的指紋記錄`);
// 查詢用戶名稱
db.get('SELECT username FROM accounts WHERE id = ?', [userId], (userErr, user) => {
res.json({
isNewUser: true,
userId: this.lastID,
message: `已登入用戶 ${user?.username || userId} 的指紋已存儲`,
isLoggedIn: true
});
});
}
);
}
}
);
}
// 處理訪客的指紋(未登入)
function handleGuestUserFingerprint(req, res, visitorId, confidence, version, components, clientId, custom, canvas, webgl, audio, fonts, plugins, hardware, collectionTime) {
// 比對現有所有指紋,找出相似度最高的前5個
// 使用更安全的查詢,適應不同的資料庫結構
db.all(
'SELECT f.id, f.visitor_id, f.components, f.linked_user_id, a.username FROM fingerprints f LEFT JOIN accounts a ON f.linked_user_id = a.id',
(err, allUsers) => {
if (err) {
console.error('查詢所有指紋錯誤:', err);
return res.status(500).json({ error: '資料庫查詢失敗' });
}
// 計算與所有用戶的多重指紋相似度並排序
const similarityResults = [];
for (const user of allUsers) {
// 構建舊的指紋資料結構(適應舊資料庫結構)
const oldData = {
components: JSON.parse(user.components || '{}'),
// 舊資料庫可能沒有這些欄位,但我們可以從 components 中提取相關信息
canvas: '', // 暫時使用空值
webgl: {}, // 暫時使用空值
audio: {}, // 暫時使用空值
fonts: {}, // 暫時使用空值
plugins: {}, // 暫時使用空值
hardware: {}, // 暫時使用空值
custom: {} // 暫時使用空值
};
// 構建新的指紋資料結構
const newData = {
components: components || {},
canvas: canvas,
webgl: webgl || {},
audio: audio || {},
fonts: fonts || {},
plugins: plugins || {},
hardware: hardware || {},
custom: custom || {}
};
const similarity = calculateMultiFingerprintSimilarity(oldData, newData);
console.log(`與指紋 ID ${user.id} (用戶: ${user.username || '未登入'}) 多重指紋相似度: ${similarity.toFixed(1)}%`);
if (similarity > 0) { // 只記錄有相似度的結果
similarityResults.push({
id: user.linked_user_id || user.id,
username: user.username || `ID-${user.linked_user_id || user.id}`,
fingerprintId: user.id,
similarity: similarity
});
}
}
// 按相似度降序排序,取前5個
similarityResults.sort((a, b) => b.similarity - a.similarity);
const top5Matches = similarityResults.slice(0, 5);
// **關鍵:返回前5個最相似的用戶**
if (top5Matches.length > 0 && top5Matches[0].similarity >= 20) { // 20% 以上顯示相似度
console.log(`找到 ${top5Matches.length} 個相似用戶,最高相似度: ${top5Matches[0].similarity.toFixed(1)}%`);
// 生成相似度列表訊息
const similarityList = top5Matches.map((match, index) =>
`${index + 1}. 用戶${match.username}: ${match.similarity.toFixed(1)}%`
).join('\n');
// 不存儲訪客指紋,只返回比對結果
res.json({
isNewUser: true, // 訪客是新的,但找到相似的
similarity: top5Matches[0].similarity,
topMatches: top5Matches,
message: `找到 ${top5Matches.length} 個相似用戶:\n\n${similarityList}`,
isGuest: true
});
} else {
// 沒有找到相似的指紋
console.log('沒有找到相似的指紋');
res.json({
isNewUser: true,
similarity: 0,
topMatches: [],
message: '完全新的訪客,沒有找到相似的指紋',
isGuest: true
});
}
}
);
}
// API 路由:獲取所有指紋記錄
app.get('/api/fingerprints', (req, res) => {
db.all(
'SELECT f.id, f.visitor_id, f.confidence_score, f.version, f.created_at, f.last_seen, f.linked_user_id, a.username FROM fingerprints f LEFT JOIN accounts a ON f.linked_user_id = a.id ORDER BY f.last_seen DESC',
(err, rows) => {
if (err) {
console.error('查詢錯誤:', err);
return res.status(500).json({ error: '查詢失敗' });
}
res.json(rows);
}
);
});
// API 路由:獲取指紋詳細資料(用於調試)
app.get('/api/debug/fingerprint/:id', (req, res) => {