exe加密网络验证系统(宝塔部署版本)

📋 环境要求
面板:宝塔面板 (Linux)

Web 服务:Nginx

PHP 版本:PHP >= 7.3 (建议 PHP 7.4 或 8.x)

数据库:MySQL (5.6 / 5.7 / 8.0 均可)

第一步:创建网站与数据库
登录宝塔面板,进入 “网站” -> “添加站点”。

域名:填写您的反代域名(例如 proxy.yourdomain.com)。

数据库:选择 “MySQL”,设置好数据库名称、用户名和密码(请务必记下这三个信息,稍后要写进代码里)。

PHP 版本:选择 7.3 或以上版本。

点击 “提交”。

第二步:配置 SSL 证书(必做,否则无法开启 HTTPS)
在网站列表中,点击刚才创建的网站的 “未部署” (SSL 这一列)。

选择 “Let’s Encrypt” 申请免费证书,或者粘贴您自己的证书。

申请成功后,确保右上角的 “强制 HTTPS” 处于关闭状态(因为我们的代码里已经内置了更智能的协议跳转控制)。

第三步:设置全局伪静态(核心:接管所有路由)

在网站设置窗口中,点击左侧的 “伪静态”。

复制并粘贴以下规则:

1
2
3
location / {
try_files $uri $uri/ /index.php?$query_string;
}

点击 “保存”。

第四步:修改并上传代码
在创建的网站的根目录,创建一个 index.php ,然后双击把下面修改代码,把数据库信息填写进去,然后把完整代码黏贴仅 index.php 即可。

1
2
3
4
5
6
7
// ================= 数据库配置 =================
const DB_HOST = '127.0.0.1';
const DB_NAME = '填入宝塔创建的数据库名';
const DB_USER = '填入宝塔创建的数据库用户名';
const DB_PASS = '填入宝塔创建的数据库密码';
const DB_PORT = '3306';
// ==============================================

下面的代码,按上面的这一段对应的填写好

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
// ================= 数据库配置 =================
const DB_HOST = '127.0.0.1';
const DB_NAME = '填入宝塔创建的数据库名';
const DB_USER = '填入宝塔创建的数据库用户名';
const DB_PASS = '填入宝塔创建的数据库密码';
const DB_PORT = '3306';
// ==============================================

set_time_limit(0);
ini_set('memory_limit', '-1');

session_start();
date_default_timezone_set('Asia/Shanghai');

function getIpLocation($ip) {
$ip = trim(explode(',', $ip)[0]);
if (!$ip || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return '局域网/保留地址';
}
$url = "http://ip-api.com/json/{$ip}?lang=zh-CN";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$res = curl_exec($ch);
curl_close($ch);
if ($res) {
$data = json_decode($res, true);
if ($data && isset($data['status']) && $data['status'] === 'success') {
$country = $data['country'] ?? '';
$region = $data['regionName'] ?? '';
$city = $data['city'] ?? '';
if ($country === '中国') return $region . ' ' . $city;
return $country . ' ' . $region . ' ' . $city;
}
}
return '未知';
}

try {
$pdo = new PDO("mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
} catch (PDOException $e) {
die("数据库连接失败: " . $e->getMessage());
}

$pdo->exec("
CREATE TABLE IF NOT EXISTS `proxy_config` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`admin_path` varchar(255) DEFAULT '/admin',
`user_path` varchar(255) DEFAULT '/user',
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`initialized` tinyint(1) DEFAULT '0',
`auth_enabled` tinyint(1) DEFAULT '0',
`require_login` tinyint(1) DEFAULT '1',
`trial_enabled` tinyint(1) DEFAULT '0',
`trial_days` int(11) DEFAULT '0',
`heartbeat_enabled` tinyint(1) DEFAULT '1',
`heartbeat_interval` int(11) DEFAULT '300',
`device_change_enabled` tinyint(1) DEFAULT '1',
`device_change_limit` int(11) DEFAULT '3',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `proxy_projects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`app_key` varchar(50) NOT NULL,
`app_secret` varchar(50) NOT NULL,
`version` varchar(20) DEFAULT '1.0',
`download_url` varchar(255) DEFAULT '',
`notice` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `proxy_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`account` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`qq_number` varchar(50) NOT NULL,
`is_banned` tinyint(1) DEFAULT '0',
`auth_days` int(11) DEFAULT '0',
`auth_start_time` datetime DEFAULT NULL,
`auth_end_time` datetime DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`login_expire_time` datetime DEFAULT NULL,
`last_ip` varchar(100) DEFAULT '',
`last_location` varchar(255) DEFAULT '',
`session_id` varchar(255) DEFAULT '',
`login_count` int(11) DEFAULT '0',
`change_device_count` int(11) DEFAULT '0',
`last_login_time` datetime DEFAULT NULL,
`app_key` varchar(50) DEFAULT 'default_app',
`machine_code` varchar(255) DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

$pdo->exec("INSERT IGNORE INTO proxy_projects (id, name, app_key, app_secret, version, download_url, notice) VALUES (1, '默认项目', 'default_app', 'secret_123', '1.0', '', '欢迎使用本软件!')");

// 自动修补缺少的字段
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN trial_enabled tinyint(1) DEFAULT '0'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN trial_days int(11) DEFAULT '0'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN require_login tinyint(1) DEFAULT '1'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN heartbeat_enabled tinyint(1) DEFAULT '1'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN heartbeat_interval int(11) DEFAULT '300'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN device_change_enabled tinyint(1) DEFAULT '1'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_config ADD COLUMN device_change_limit int(11) DEFAULT '3'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_users ADD COLUMN login_count int(11) DEFAULT '0'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_users ADD COLUMN change_device_count int(11) DEFAULT '0'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_users ADD COLUMN last_login_time datetime DEFAULT NULL"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_users ADD COLUMN app_key varchar(50) DEFAULT 'default_app'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE proxy_users ADD COLUMN machine_code varchar(255) DEFAULT ''"); } catch (Exception $e) {}

$requestUri = $_SERVER['REQUEST_URI'];
$urlPath = parse_url($requestUri, PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];
$clientIpRaw = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
$clientIp = trim(explode(',', $clientIpRaw)[0]);

$stmt = $pdo->query("SELECT * FROM proxy_config LIMIT 1");
$config = $stmt->fetch();

if (!$config || $config['initialized'] == 0) {
if ($method === 'POST') {
$adminPath = $_POST['admin_path'] ?? '/admin';
$userPath = $_POST['user_path'] ?? '/user';
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
if ($username && $password) {
$encPwd = base64_encode($password);
$stmt = $pdo->prepare("INSERT INTO proxy_config (admin_path, user_path, username, password, initialized) VALUES (?, ?, ?, ?, 1)");
$stmt->execute([$adminPath, $userPath, $username, $encPwd]);
header("Location: " . $adminPath);
exit;
}
die('请填写完整信息');
}
echo getInitHtml();
exit;
}

$adminPath = $config['admin_path'] ?: '/admin';
$userPath = $config['user_path'] ?: '/user';

// ======================= 全新原生 API 接口 =======================
if (strpos($urlPath, '/api/') === 0) {
header('Content-Type: application/json');
$action = str_replace('/api/', '', $urlPath);

if ($action === 'info' && $method === 'POST') {
$appKey = $_POST['app_key'] ?? '';
$stmt = $pdo->prepare("SELECT version, download_url, notice FROM proxy_projects WHERE app_key=?");
$stmt->execute([$appKey]);
$proj = $stmt->fetch();
if ($proj) {
die(json_encode(['status' => 'success', 'version' => $proj['version'], 'download_url' => $proj['download_url'], 'notice' => $proj['notice']]));
} else {
die(json_encode(['status' => 'error', 'notice' => '该项目在服务器上不存在,请检查打包配置。']));
}
}

if ($action === 'login' && $method === 'POST') {
$account = $_POST['account'] ?? '';
$password = $_POST['password'] ?? '';
$machineCode = trim($_POST['machine_code'] ?? '');
$appKey = $_POST['app_key'] ?? 'default_app';

$stmt = $pdo->prepare("SELECT * FROM proxy_users WHERE account=?");
$stmt->execute([$account]);
$user = $stmt->fetch();

if (!$user) die(json_encode(['status' => 'error', 'msg' => '账号不存在,请先注册!']));
if ($user['is_banned'] == 1) die(json_encode(['status' => 'error', 'msg' => '账号已被封禁!如需解封请联系管理员']));
if (base64_decode($user['password']) !== $password) die(json_encode(['status' => 'error', 'msg' => '密码错误,请检查后重试!']));
if ($config['auth_enabled'] == 1 && strtotime($user['auth_end_time']) <= time()) die(json_encode(['status' => 'error', 'msg' => '账号授权已到期,无法登录!']));

$nowMs = time();
$nowStr = date('Y-m-d H:i:s', $nowMs);
$todayStr = date('Y-m-d', $nowMs);

$lastLoginDay = $user['last_login_time'] ? date('Y-m-d', strtotime($user['last_login_time'])) : '';
if ($lastLoginDay !== $todayStr) {
$changeDeviceCount = 0;
$loginCount = 1;
} else {
$changeDeviceCount = intval($user['change_device_count']);
$loginCount = intval($user['login_count']) + 1;
}

// --- 核心换机判断逻辑 ---
$isChangingDevice = false;
if ($user['machine_code'] !== '' && $machineCode !== '' && $user['machine_code'] !== $machineCode) {
$isChangingDevice = true;
}

if ($isChangingDevice) {
$dcEnabled = !isset($config['device_change_enabled']) ? 1 : intval($config['device_change_enabled']);
if ($dcEnabled == 1) {
$dcLimit = empty($config['device_change_limit']) ? 3 : intval($config['device_change_limit']);
if ($changeDeviceCount >= $dcLimit) {
die(json_encode(['status' => 'error', 'msg' => '今日换机次数已达上限(最大'.$dcLimit.'次)!最后一台登录的电脑仍可继续使用。']));
}
}
$changeDeviceCount++;
}

// 验证通过,自动绑定或刷新最新机器码
$newMachineCode = $machineCode !== '' ? $machineCode : $user['machine_code'];
$sessionId = bin2hex(random_bytes(16));
$expireTime = date('Y-m-d H:i:s', $nowMs + 12 * 3600);
$location = getIpLocation($clientIp);

$pdo->prepare("UPDATE proxy_users SET session_id=?, last_ip=?, last_location=?, login_expire_time=?, last_login_time=?, login_count=?, change_device_count=?, machine_code=? WHERE id=?")->execute([$sessionId, $clientIp, $location, $expireTime, $nowStr, $loginCount, $changeDeviceCount, $newMachineCode, $user['id']]);

$token = base64_encode("{$account}|{$sessionId}|{$clientIp}|{$nowMs}");
$hbEnabled = !isset($config['heartbeat_enabled']) ? 1 : intval($config['heartbeat_enabled']);
$hbInterval = empty($config['heartbeat_interval']) ? 300 : intval($config['heartbeat_interval']);

die(json_encode(['status' => 'success', 'msg' => '登录成功', 'token' => $token, 'heartbeat_enabled' => $hbEnabled, 'heartbeat_interval' => $hbInterval]));
}

if ($action === 'register' && $method === 'POST') {
$username = $_POST['username'] ?? '';
$account = $_POST['account'] ?? '';
$password = $_POST['password'] ?? '';
$qqNumber = $_POST['qq_number'] ?? '';
$appKey = $_POST['app_key'] ?? 'default_app';

if (!$username || !$account || !$password || !$qqNumber) die(json_encode(['status' => 'error', 'msg' => '请填写完整的注册信息!']));
$chk = $pdo->prepare("SELECT id FROM proxy_users WHERE account=? OR qq_number=?");
$chk->execute([$account, $qqNumber]);
if ($chk->fetch()) die(json_encode(['status' => 'error', 'msg' => '注册失败:该登录账号或QQ号已被注册!']));

$now = date('Y-m-d H:i:s');
$authEndTime = $now;
if ($config['trial_enabled'] == 1 && $config['trial_days'] > 0) {
$authEndTime = date('Y-m-d H:i:s', time() + ($config['trial_days'] * 86400));
}

$encPwd = base64_encode($password);
$stmt = $pdo->prepare("INSERT INTO proxy_users (username, account, password, qq_number, is_banned, auth_days, auth_start_time, auth_end_time, create_time, login_expire_time, login_count, change_device_count, app_key) VALUES (?, ?, ?, ?, 0, 0, ?, ?, ?, ?, 0, 0, ?)");
$stmt->execute([$username, $account, $encPwd, $qqNumber, $now, $authEndTime, $now, $now, $appKey]);
die(json_encode(['status' => 'success', 'msg' => '注册成功!请返回界面进行登录。']));
}

if ($action === 'find_pwd' && $method === 'POST') {
$qq = $_POST['qq_number'] ?? '';
$newPwd = $_POST['new_password'] ?? '';

if (!$qq) die(json_encode(['status' => 'error', 'msg' => '请输入您注册时填写的QQ号!']));

$stmt = $pdo->prepare("SELECT * FROM proxy_users WHERE qq_number=?");
$stmt->execute([$qq]);
$user = $stmt->fetch();

if (!$user) die(json_encode(['status' => 'error', 'msg' => '查询不到该QQ号绑定的账号!']));

if ($newPwd) {
$pdo->prepare("UPDATE proxy_users SET password=? WHERE qq_number=?")->execute([base64_encode($newPwd), $qq]);
die(json_encode(['status' => 'success', 'msg' => "账号:{$user['account']} 新密码已重置成功!"]));
} else {
die(json_encode(['status' => 'success', 'msg' => "查询成功!您绑定的登录账号是:{$user['account']}"]));
}
}

if ($action === 'check') {
if (!isset($_SERVER['HTTP_COOKIE']) || strpos($_SERVER['HTTP_COOKIE'], 'proxy_login=') === false) {
die(json_encode(['status' => 'error', 'msg' => '未登录或登录已失效']));
}

preg_match('/proxy_login=([^;]+)/', $_SERVER['HTTP_COOKIE'], $matches);
if (!$matches[1]) die(json_encode(['status' => 'error', 'msg' => '凭证异常']));

$tokenParts = explode('|', base64_decode($matches[1]));
if (count($tokenParts) !== 4) die(json_encode(['status' => 'error', 'msg' => '登录状态异常']));
list($account, $sessionId, $cookieIp, $lastValMs) = $tokenParts;

$stmt = $pdo->prepare("SELECT u.*, p.app_secret FROM proxy_users u LEFT JOIN proxy_projects p ON u.app_key = p.app_key WHERE u.account=?");
$stmt->execute([$account]);
$user = $stmt->fetch();

if (!$user) die(json_encode(['status' => 'error', 'msg' => '用户不存在']));

$secret = $user['app_secret'] ?: 'default_secret';
$time = time();

if ($user['session_id'] !== $sessionId) {
$msg = '账号已在其他设备登录,您已被挤下线!';
die(json_encode(['status' => 'error', 'msg' => $msg, 'time' => $time, 'sign' => md5("error".$msg.$time.$secret)]));
}
if ($user['is_banned'] == 1) {
$msg = '账号已被管理员封禁!';
die(json_encode(['status' => 'error', 'msg' => $msg, 'time' => $time, 'sign' => md5("error".$msg.$time.$secret)]));
}
if ($config['auth_enabled'] == 1 && strtotime($user['auth_end_time']) <= $time) {
$msg = '授权时间已到期,请续费!';
die(json_encode(['status' => 'error', 'msg' => $msg, 'time' => $time, 'sign' => md5("error".$msg.$time.$secret)]));
}

$machineCode = $_POST['machine_code'] ?? '';
if ($user['machine_code'] !== '' && $machineCode !== '' && $user['machine_code'] !== $machineCode) {
$msg = '电脑运行环境发生变更,请重新登录认证!';
die(json_encode(['status' => 'error', 'msg' => $msg, 'time' => $time, 'sign' => md5("error".$msg.$time.$secret)]));
}

$hbEnabled = !isset($config['heartbeat_enabled']) ? 1 : intval($config['heartbeat_enabled']);
$hbInterval = empty($config['heartbeat_interval']) ? 300 : intval($config['heartbeat_interval']);

$msg = '验证通过';
$sign = md5("success" . $msg . $time . $secret);
echo json_encode(['status' => 'success', 'msg' => $msg, 'time' => $time, 'sign' => $sign, 'heartbeat_enabled' => $hbEnabled, 'heartbeat_interval' => $hbInterval]);
exit;
}
}
// =======================================================


if (strpos($urlPath, $adminPath) === 0) {
if (empty($_SESSION['admin_logged_in'])) {
if ($method === 'POST' && isset($_POST['admin_user'])) {
if ($_POST['admin_user'] === $config['username'] && base64_encode($_POST['admin_pwd']) === $config['password']) {
$_SESSION['admin_logged_in'] = true;
header("Location: " . $adminPath);
exit;
} else {
echo getLoginHtml('账号或密码错误!');
exit;
}
}
echo getLoginHtml();
exit;
}

if ($method === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'update_base') {
$newAdminPath = $_POST['new_admin_path'] ?: $config['admin_path'];
$newUserPath = $_POST['new_user_path'] ?: $config['user_path'];
$newUsername = $_POST['new_username'] ?: $config['username'];
$newPassword = !empty($_POST['new_password']) ? base64_encode($_POST['new_password']) : $config['password'];
$authEnabled = isset($_POST['auth_enabled']) ? 1 : 0;
$requireLogin = isset($_POST['require_login']) ? 1 : 0;
$trialEnabled = isset($_POST['trial_enabled']) ? 1 : 0;
$trialDays = intval($_POST['trial_days'] ?? 0);

$heartbeatEnabled = isset($_POST['heartbeat_enabled']) ? 1 : 0;
$heartbeatInterval = intval($_POST['heartbeat_interval'] ?? 300);
if ($heartbeatInterval < 10) $heartbeatInterval = 10;

// 每日换机参数
$deviceChangeEnabled = isset($_POST['device_change_enabled']) ? 1 : 0;
$deviceChangeLimit = intval($_POST['device_change_limit'] ?? 3);
if ($deviceChangeLimit < 1) $deviceChangeLimit = 1;

$stmt = $pdo->prepare("UPDATE proxy_config SET admin_path=?, user_path=?, username=?, password=?, auth_enabled=?, require_login=?, trial_enabled=?, trial_days=?, heartbeat_enabled=?, heartbeat_interval=?, device_change_enabled=?, device_change_limit=? WHERE id=?");
$stmt->execute([$newAdminPath, $newUserPath, $newUsername, $newPassword, $authEnabled, $requireLogin, $trialEnabled, $trialDays, $heartbeatEnabled, $heartbeatInterval, $deviceChangeEnabled, $deviceChangeLimit, $config['id']]);
header("Location: " . $newAdminPath . "#base");
exit;
}
if ($action === 'manage_user') {
$userId = intval($_POST['user_id'] ?? 0);
$operation = $_POST['operation'] ?? '';
$authDays = intval($_POST['auth_days'] ?? 0);

if ($userId && $operation) {
switch ($operation) {
case 'ban': $pdo->prepare("UPDATE proxy_users SET is_banned=1 WHERE id=?")->execute([$userId]); break;
case 'unban': $pdo->prepare("UPDATE proxy_users SET is_banned=0 WHERE id=?")->execute([$userId]); break;
case 'delete': $pdo->prepare("DELETE FROM proxy_users WHERE id=?")->execute([$userId]); break;
case 'unbind_hwid': $pdo->prepare("UPDATE proxy_users SET machine_code='' WHERE id=?")->execute([$userId]); break;
case 'reset_device_change': $pdo->prepare("UPDATE proxy_users SET change_device_count=0 WHERE id=?")->execute([$userId]); break;
case 'update_pwd':
if (!empty($_POST['new_password'])) $pdo->prepare("UPDATE proxy_users SET password=? WHERE id=?")->execute([base64_encode($_POST['new_password']), $userId]);
break;
case 'add_auth':
case 'reduce_auth':
$u = $pdo->prepare("SELECT auth_end_time FROM proxy_users WHERE id=?");
$u->execute([$userId]);
$user = $u->fetch();
if ($user) {
$end = strtotime($user['auth_end_time']);
if ($end < time()) $end = time();
$end = $operation === 'add_auth' ? $end + ($authDays * 86400) : $end - ($authDays * 86400);
$pdo->prepare("UPDATE proxy_users SET auth_end_time=? WHERE id=?")->execute([date('Y-m-d H:i:s', $end), $userId]);
}
break;
}
}
header("Location: " . $adminPath . "#user-manage");
exit;
}
if ($action === 'add_project') {
$pName = $_POST['p_name'] ?? '';
$pKey = $_POST['p_key'] ?? '';
$pSecret = $_POST['p_secret'] ?? '';

$chk = $pdo->prepare("SELECT id FROM proxy_projects WHERE app_key=?");
$chk->execute([$pKey]);
if (!$chk->fetch()) {
$pdo->prepare("INSERT INTO proxy_projects (name, app_key, app_secret, version, download_url, notice) VALUES (?, ?, ?, '1.0', '', '')")->execute([$pName, $pKey, $pSecret]);
}
header("Location: " . $adminPath . "#projects");
exit;
}
if ($action === 'update_project_info') {
$pId = intval($_POST['project_id']);
$pVer = $_POST['p_version'] ?? '1.0';
$pUrl = $_POST['p_url'] ?? '';
$pNotice = $_POST['p_notice'] ?? '';
$pdo->prepare("UPDATE proxy_projects SET version=?, download_url=?, notice=? WHERE id=?")->execute([$pVer, $pUrl, $pNotice, $pId]);
header("Location: " . $adminPath . "#projects");
exit;
}
if ($action === 'delete_project') {
$pId = intval($_POST['project_id']);
if ($pId !== 1) {
$pdo->prepare("DELETE FROM proxy_projects WHERE id=?")->execute([$pId]);
}
header("Location: " . $adminPath . "#projects");
exit;
}
}

$users = $pdo->query("SELECT * FROM proxy_users ORDER BY id DESC")->fetchAll();
$projects = $pdo->query("SELECT * FROM proxy_projects ORDER BY id DESC")->fetchAll();
echo getAdminHtml($config, $users, $projects);
exit;
}

header('Content-Type: text/html; charset=utf-8');
echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>访问限制</title><style>body{background:#f8fafc;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;font-family:sans-serif;color:#64748b;font-size:1.2rem;}</style></head><body><div>该服务仅支持通过原生加密客户端交互,拒绝网页直连。</div></body></html>';
exit;

function getInitHtml() {
return <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>初始化</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body style="background: #f5f7fa; padding: 20px;">
<div style="background: #fff; padding: 2.5rem; max-width: 500px; margin: 0 auto; border-radius: 12px;">
<h1 style="font-size: 1.5rem; margin-bottom: 1rem;">系统初始化</h1>
<form method="POST">
<div style="margin-bottom: 1rem;"><input type="text" name="admin_path" placeholder="后台路径 /admin" value="/admin" required style="width: 100%; padding: 0.8rem; border: 1px solid #ccc; border-radius: 6px;"></div>
<div style="margin-bottom: 1rem;"><input type="text" name="user_path" placeholder="前台路径 /user" value="/user" required style="width: 100%; padding: 0.8rem; border: 1px solid #ccc; border-radius: 6px;"></div>
<div style="margin-bottom: 1rem;"><input type="text" name="username" placeholder="管理员账号" required style="width: 100%; padding: 0.8rem; border: 1px solid #ccc; border-radius: 6px;"></div>
<div style="margin-bottom: 1rem;"><input type="password" name="password" placeholder="管理员密码" required style="width: 100%; padding: 0.8rem; border: 1px solid #ccc; border-radius: 6px;"></div>
<button type="submit" style="width: 100%; padding: 1rem; background: #2563eb; color: #fff; border-radius: 6px;">完成</button>
</form>
</div>
</body>
</html>
HTML;
}

function getLoginHtml($errorMsg = '') {
$alertHtml = $errorMsg ? '<div style="color:red; margin-bottom:1rem;">' . $errorMsg . '</div>' : '';
return <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>后台登录</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body style="background: #f5f7fa; padding: 20px; display:flex; align-items:center; justify-content:center; height:100vh;">
<div style="background: #fff; padding: 2.5rem; width: 450px; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.1);">
<h1 style="font-size: 1.5rem; text-align:center; margin-bottom: 1.5rem;">管理员登录</h1>
{$alertHtml}
<form method="POST">
<div style="margin-bottom: 1rem;"><input type="text" name="admin_user" placeholder="管理员账号" required style="width: 100%; padding: 0.8rem; border: 1px solid #ccc; border-radius: 6px;"></div>
<div style="margin-bottom: 1.5rem;"><input type="password" name="admin_pwd" placeholder="密码" required style="width: 100%; padding: 0.8rem; border: 1px solid #ccc; border-radius: 6px;"></div>
<button type="submit" style="width: 100%; padding: 1rem; background: #2563eb; color: #fff; border-radius: 6px; cursor: pointer;">登录</button>
</form>
</div>
</body>
</html>
HTML;
}

function getAdminHtml($config, $users, $projects) {
$projectTableHtml = '';
foreach ($projects as $proj) {
$projectTableHtml .= '
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; margin-bottom: 1.5rem; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #f1f5f9; padding-bottom: 1rem; margin-bottom: 1rem;">
<div>
<span style="font-weight: 600; font-size: 1.2rem; color: #1e293b;">' . htmlspecialchars($proj['name']) . '</span>
<span style="background: #f1f5f9; color: #475569; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.85rem; margin-left: 0.75rem; font-family: monospace;">AppKey: ' . htmlspecialchars($proj['app_key']) . '</span>
<span style="background: #f1f5f9; color: #475569; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.85rem; margin-left: 0.5rem; font-family: monospace;">Secret: ' . htmlspecialchars($proj['app_secret']) . '</span>
</div>
<form method="POST" onsubmit="return confirm(\'确定删除此项目吗?该项目下的用户将受影响!\');" style="margin: 0;">
<input type="hidden" name="action" value="delete_project">
<input type="hidden" name="project_id" value="' . $proj['id'] . '">
<button type="submit" style="color: #ef4444; background: none; border: none; cursor: pointer; font-size: 0.95rem; font-weight: 500;"><i class="fa fa-trash"></i> 删除</button>
</form>
</div>
<form method="POST">
<input type="hidden" name="action" value="update_project_info">
<input type="hidden" name="project_id" value="' . $proj['id'] . '">
<div style="display: grid; grid-template-columns: 150px 1fr; gap: 1.5rem; margin-bottom: 1rem;">
<div>
<label style="display: block; font-size: 0.9rem; font-weight: 500; color: #475569; margin-bottom: 0.5rem;">最新版本号</label>
<input type="text" name="p_version" value="' . htmlspecialchars($proj['version']) . '" class="form-input" style="padding: 0.6rem; font-size: 0.95rem;">
</div>
<div>
<label style="display: block; font-size: 0.9rem; font-weight: 500; color: #475569; margin-bottom: 0.5rem;">更新下载链接 (选填)</label>
<input type="text" name="p_url" value="' . htmlspecialchars($proj['download_url']) . '" class="form-input" style="padding: 0.6rem; font-size: 0.95rem;" placeholder="填入链接后,将在客户端登录界面的副屏提供跳转按钮">
</div>
</div>
<div style="margin-bottom: 1rem;">
<label style="display: block; font-size: 0.9rem; font-weight: 500; color: #475569; margin-bottom: 0.5rem;">软件公告内容 (支持多行排版)</label>
<textarea name="p_notice" class="form-input" rows="4" style="padding: 0.6rem; font-size: 0.95rem; resize: vertical;" placeholder="在此输入公告内容,例如:修复了已知BUG,增加了新功能...">' . htmlspecialchars($proj['notice']) . '</textarea>
</div>
<button type="submit" style="background: #10b981; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 8px; cursor: pointer; font-size: 1rem; font-weight: 500; transition: background 0.2s;"><i class="fa fa-paper-plane"></i> 发布公告 / 保存配置</button>
</form>
</div>';
}

$userTableHtml = '';
if (count($users) > 0) {
foreach ($users as $user) {
$pwdHtml = '
<div class="mb-1">' . base64_decode($user['password']) . '</div>
<form method="POST" style="display: flex; gap: 0.2rem;">
<input type="hidden" name="action" value="manage_user">
<input type="hidden" name="user_id" value="' . $user['id'] . '">
<input type="hidden" name="operation" value="update_pwd">
<input type="text" name="new_password" placeholder="新密" class="px-1 py-0.5 text-xs border rounded w-16" required>
<button type="submit" class="px-1 py-0.5 text-xs bg-gray-600 text-white rounded">改密</button>
</form>
';
$statusStr = $user['is_banned'] == 1 ? '<span class="text-red-600">已封禁</span>' : '<span class="text-green-600">正常</span>';
$banOp = $user['is_banned'] == 1 ? 'unban' : 'ban';
$banBtnCls = $user['is_banned'] == 1 ? 'bg-green-600' : 'bg-red-600';
$banBtnTxt = $user['is_banned'] == 1 ? '解禁' : '封禁';
$statusActionHtml = '
<div class="mb-1">' . $statusStr . '</div>
<div style="display: flex; gap: 0.2rem;">
<form method="POST">
<input type="hidden" name="action" value="manage_user">
<input type="hidden" name="user_id" value="' . $user['id'] . '">
<input type="hidden" name="operation" value="' . $banOp . '">
<button type="submit" class="px-2 py-1 text-xs rounded ' . $banBtnCls . ' text-white">' . $banBtnTxt . '</button>
</form>
<form method="POST" onsubmit="return confirm(\'确定要删除此用户吗?\');">
<input type="hidden" name="action" value="manage_user">
<input type="hidden" name="user_id" value="' . $user['id'] . '">
<input type="hidden" name="operation" value="delete">
<button type="submit" class="px-2 py-1 text-xs bg-red-800 text-white rounded">删除</button>
</form>
</div>
';
$ipHtml = '
<div class="text-xs text-gray-600 whitespace-nowrap">' . ($user['last_ip'] ?: '-') . '</div>
<div class="text-xs text-blue-600 whitespace-nowrap">' . ($user['last_location'] ?: '未知') . '</div>
';
$authOpHtml = '
<form method="POST" style="display: flex; gap: 0.2rem; align-items: center;">
<input type="hidden" name="action" value="manage_user">
<input type="hidden" name="user_id" value="' . $user['id'] . '">
<input type="number" name="auth_days" placeholder="天" class="px-1 py-0.5 text-xs border rounded w-10" required>
<button type="submit" name="operation" value="add_auth" class="px-1 py-0.5 text-xs bg-blue-600 text-white rounded">增</button>
<button type="submit" name="operation" value="reduce_auth" class="px-1 py-0.5 text-xs bg-orange-500 text-white rounded">减</button>
</form>
';

$hwidHtml = $user['machine_code'] ?: '<span class="text-gray-400">无记录</span>';
if ($user['machine_code']) {
$hwidHtml .= '<form method="POST" style="margin-top:0.25rem;"><input type="hidden" name="action" value="manage_user"><input type="hidden" name="user_id" value="' . $user['id'] . '"><input type="hidden" name="operation" value="unbind_hwid"><button type="submit" class="px-2 py-0.5 text-xs bg-yellow-500 text-white rounded" title="解绑后下次登录重新绑定新设备">解绑</button></form>';
}

$dcResetHtml = '
<form method="POST">
<input type="hidden" name="action" value="manage_user">
<input type="hidden" name="user_id" value="' . $user['id'] . '">
<input type="hidden" name="operation" value="reset_device_change">
<button type="submit" class="px-2 py-1 text-xs bg-indigo-500 text-white rounded" title="将该用户今日已换机次数清零">重置次数</button>
</form>
';

$userTableHtml .= '
<tr class="border-b border-gray-200 hover:bg-gray-50">
<td class="px-4 py-3">' . $user['username'] . '<br><span class="text-xs text-gray-500">[' . $user['app_key'] . ']</span></td>
<td class="px-4 py-3">' . $user['account'] . '</td>
<td class="px-4 py-3">' . $pwdHtml . '</td>
<td class="px-4 py-3">' . $user['qq_number'] . '</td>
<td class="px-4 py-3">' . $statusActionHtml . '</td>
<td class="px-4 py-3">' . $ipHtml . '</td>
<td class="px-4 py-3">' . $user['auth_end_time'] . '</td>
<td class="px-4 py-3">' . $hwidHtml . '</td>
<td class="px-4 py-3">' . $dcResetHtml . '</td>
<td class="px-4 py-3">' . $authOpHtml . '</td>
</tr>
';
}
} else {
$userTableHtml = '<tr><td colspan="10" class="px-4 py-3 text-center text-gray-500">暂无用户</td></tr>';
}

$todayStr = date('Y-m-d');
$onlineUsers = array_filter($users, function($u) use ($todayStr) {
$lastLoginDay = $u['last_login_time'] ? date('Y-m-d', strtotime($u['last_login_time'])) : '';
return ($lastLoginDay === $todayStr) && (strtotime($u['login_expire_time']) > time());
});

$onlineTableHtml = '';
if (count($onlineUsers) > 0) {
foreach ($onlineUsers as $ou) {
$ipLoc = '<div class="text-xs text-gray-600 whitespace-nowrap">' . ($ou['last_ip'] ?: '-') . '</div><div class="text-xs text-blue-600 whitespace-nowrap">' . ($ou['last_location'] ?: '未知') . '</div>';
$onlineTableHtml .= '
<tr class="border-b border-gray-200 hover:bg-gray-50">
<td class="px-4 py-3">' . $ou['username'] . '<br><span class="text-xs text-gray-500">[' . $ou['app_key'] . ']</span></td>
<td class="px-4 py-3">' . $ou['account'] . '</td>
<td class="px-4 py-3">' . $ipLoc . '</td>
<td class="px-4 py-3">' . ($ou['last_login_time'] ?: '-') . '</td>
<td class="px-4 py-3">' . $ou['login_count'] . '</td>
<td class="px-4 py-3">' . $ou['change_device_count'] . '</td>
</tr>
';
}
} else {
$onlineTableHtml = '<tr><td colspan="6" class="px-4 py-3 text-center text-gray-500">暂无今日在线用户</td></tr>';
}

$authCheck = $config['auth_enabled'] == 1 ? 'checked' : '';
$requireLoginCheck = (!isset($config['require_login']) || $config['require_login'] == 1) ? 'checked' : '';
$trialCheck = $config['trial_enabled'] == 1 ? 'checked' : '';

$heartbeatCheck = (!isset($config['heartbeat_enabled']) || $config['heartbeat_enabled'] == 1) ? 'checked' : '';
$dcCheck = (!isset($config['device_change_enabled']) || $config['device_change_enabled'] == 1) ? 'checked' : '';

return <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>验证管理系统 - 后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #f8fafc; color: #1e293b; min-height: 100vh; display: flex; }
.sidebar { width: 250px; background: #1e293b; color: #f8fafc; min-height: 100vh; padding: 1.5rem 0; position: fixed; }
.sidebar-header { padding: 0 1.5rem 1.5rem; border-bottom: 1px solid #334155; margin-bottom: 1rem; }
.sidebar-header h2 { font-size: 1.2rem; font-weight: 600; color: #ffffff; display: flex; align-items: center; }
.menu-item { padding: 0.875rem 1.5rem; display: flex; align-items: center; color: #94a3b8; text-decoration: none; cursor: pointer; border-left: 3px solid transparent; }
.menu-item.active { background: #334155; color: #ffffff; border-left-color: #38bdf8; }
.main-content { margin-left: 250px; flex: 1; padding: 2rem; }
.content-header { margin-bottom: 2rem; padding-bottom: 1rem; border-bottom: 1px solid #e2e8f0; }
.content-header h1 { font-size: 1.75rem; font-weight: 600; }
.content-card { background: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); padding: 2rem; margin-bottom: 2rem; overflow-x: auto; }
.form-group { margin-bottom: 1.5rem; }
.form-label { display: block; margin-bottom: 0.75rem; font-weight: 500; font-size: 0.95rem; }
.form-input { width: 100%; padding: 0.875rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.95rem; background: #f8fafc; }
.switch-group { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 1.5rem; }
.switch-group input { height: 1.25rem; width: 1.25rem; }
.submit-btn { padding: 0.875rem 1.5rem; background: linear-gradient(135deg, #2563eb 0%, #3b82f6 100%); color: #ffffff; border: none; border-radius: 8px; cursor: pointer; }
.tab-content { display: none; }
.tab-content.active { display: block; }
.user-table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
.user-table th { padding: 0.75rem 1rem; text-align: left; background: #f1f5f9; font-weight: 500; }
.user-table td { padding: 0.75rem 1rem; border-bottom: 1px solid #f1f5f9;}
</style>
</head>
<body>
<div class="sidebar">
<div class="sidebar-header"><h2><i class="fa fa-cogs"></i> <span>验证管理系统</span></h2></div>
<div class="sidebar-menu">
<div class="menu-item active" onclick="switchTab('base', event)"><i class="fa fa-user-circle" style="margin-right:8px;"></i><span>基础配置</span></div>
<div class="menu-item" onclick="switchTab('projects', event)"><i class="fa fa-cube" style="margin-right:8px;"></i><span>项目配置</span></div>
<div class="menu-item" onclick="switchTab('online', event)"><i class="fa fa-line-chart" style="margin-right:8px;"></i><span>日在线量</span></div>
<div class="menu-item" onclick="switchTab('user-manage', event)"><i class="fa fa-users" style="margin-right:8px;"></i><span>用户管理</span></div>
</div>
</div>
<div class="main-content">
<div class="content-header"><h1>后台管理中心</h1></div>
<div id="base-tab" class="tab-content active">
<div class="content-card">
<h3 style="font-size:1.25rem;font-weight:bold;margin-bottom:1.5rem;"><i class="fa fa-user-circle"></i> 基础配置</h3>
<form method="POST">
<input type="hidden" name="action" value="update_base">
<div class="form-group"><label class="form-label">后台访问路径</label><input type="text" name="new_admin_path" class="form-input" value="{$config['admin_path']}" required></div>
<div class="form-group"><label class="form-label">管理员账号</label><input type="text" name="new_username" class="form-input" value="{$config['username']}" required></div>
<div class="form-group"><label class="form-label">管理员密码(留空则不修改)</label><input type="password" name="new_password" class="form-input" placeholder="留空不修改密码"></div>

<div class="switch-group"><input type="checkbox" name="auth_enabled" id="auth_enabled" {$authCheck}><label for="auth_enabled" class="form-label mb-0">开启授权验证(开启后仅在授权期内可登录)</label></div>
<div class="switch-group"><input type="checkbox" name="trial_enabled" id="trial_enabled" {$trialCheck}><label for="trial_enabled" class="form-label mb-0">开启新用户试用(新注册用户自动赠送试用天数)</label></div>
<div class="form-group"><label class="form-label">试用天数</label><input type="number" name="trial_days" class="form-input" value="{$config['trial_days']}" min="0"></div>

<div style="border-top: 1px dashed #cbd5e1; margin: 1.5rem 0;"></div>

<div class="switch-group"><input type="checkbox" name="device_change_enabled" id="device_change_enabled" {$dcCheck}><label for="device_change_enabled" class="form-label mb-0" style="color:#d97706; font-weight:bold;">开启每日换机限制(控制多设备恶意共享)</label></div>
<div class="form-group"><label class="form-label">每日最大换机次数 (默认 3 次)</label><input type="number" name="device_change_limit" class="form-input" value="{$config['device_change_limit']}" min="1"><p style="font-size: 0.85rem; color: #94a3b8; margin-top: 0.4rem;">不勾选则无限制。超出次数后新电脑禁止登录,但最后一台电脑可继续使用。每日0点自动重置。</p></div>

<div style="border-top: 1px dashed #cbd5e1; margin: 1.5rem 0;"></div>

<div class="switch-group"><input type="checkbox" name="heartbeat_enabled" id="heartbeat_enabled" {$heartbeatCheck}><label for="heartbeat_enabled" class="form-label mb-0" style="color:#10b981; font-weight:bold;">开启心跳检测 (防挂机/防篡改/被顶号秒踢下线)</label></div>
<div class="form-group"><label class="form-label">心跳间隔时间 (秒) - 默认 300秒</label><input type="number" name="heartbeat_interval" class="form-input" value="{$config['heartbeat_interval']}" min="10"><p style="font-size: 0.85rem; color: #94a3b8; margin-top: 0.4rem;">修改此数值,在线的软件会在下一次通信时自动更新间隔频率,无需重启。</p></div>

<button type="submit" class="submit-btn"><i class="fa fa-save"></i> 保存基础配置</button>
</form>
</div>
</div>

<div id="projects-tab" class="tab-content">
<div class="content-card">
<h3 style="font-size:1.25rem;font-weight:bold;margin-bottom:1.5rem;"><i class="fa fa-cube"></i> 项目配置 (多软件支持)</h3>
<script>
function autoGenKeys() {
let r1 = 'app_' + Math.random().toString(36).substr(2, 8);
let r2 = Math.random().toString(36).substr(2, 12) + Math.random().toString(36).substr(2, 12);
document.querySelector('input[name="p_key"]').value = r1;
document.querySelector('input[name="p_secret"]').value = r2;
}
</script>
<form method="POST" style="margin-bottom: 2.5rem; padding: 1.5rem; background: #f8fafc; border-radius: 8px; border: 1px dashed #cbd5e1;">
<input type="hidden" name="action" value="add_project">
<div style="display: grid; grid-template-columns: 1fr 1.2fr 1.5fr; gap: 1rem; margin-bottom: 1rem;">
<div><label class="form-label">项目名称</label><input type="text" name="p_name" class="form-input" placeholder="例如:脚本A" required></div>
<div>
<label class="form-label">AppKey <a href="javascript:;" onclick="autoGenKeys()" style="color:#2563eb; font-size:0.8rem; font-weight:normal;">[一键随机生成]</a></label>
<input type="text" name="p_key" class="form-input" placeholder="可自定义或随机" required>
</div>
<div>
<label class="form-label">AppSecret <a href="javascript:;" onclick="autoGenKeys()" style="color:#2563eb; font-size:0.8rem; font-weight:normal;">[一键随机生成]</a></label>
<input type="text" name="p_secret" class="form-input" placeholder="可自定义或随机" required>
</div>
</div>
<button type="submit" class="submit-btn"><i class="fa fa-plus-circle"></i> 新建项目</button>
</form>
<div>{$projectTableHtml}</div>
</div>
</div>

<div id="online-tab" class="tab-content">
<div class="content-card">
<h3 style="font-size:1.25rem;font-weight:bold;margin-bottom:1.5rem;"><i class="fa fa-line-chart"></i> 日在线量</h3>
<table class="user-table text-sm">
<thead><tr class="border-b border-gray-300"><th>用户名/项目</th><th>账号</th><th>IP/位置</th><th>登录时间</th><th>登录次数</th><th>换机次数</th></tr></thead>
<tbody>{$onlineTableHtml}</tbody>
</table>
</div>
</div>

<div id="user-manage-tab" class="tab-content">
<div class="content-card">
<h3 style="font-size:1.25rem;font-weight:bold;margin-bottom:1.5rem;"><i class="fa fa-users"></i> 用户管理</h3>
<table class="user-table text-sm">
<thead><tr class="border-b border-gray-300"><th>用户名/项目</th><th>账号</th><th>密码管理</th><th>QQ号</th><th>状态管理</th><th>IP/位置</th><th>到期时间</th><th>机器码</th><th>换机重置</th><th>授权操作</th></tr></thead>
<tbody>{$userTableHtml}</tbody>
</table>
</div>
</div>
</div>

<script>
if (window.location.hash) {
let tabId = window.location.hash.substring(1);
if (tabId.endsWith('-tab')) tabId = tabId.replace('-tab', '');
if(document.getElementById(tabId + '-tab')) switchTab(tabId, null);
}
function switchTab(tabId, event) {
document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.menu-item').forEach(item => item.classList.remove('active'));
document.getElementById(tabId + '-tab').classList.add('active');
if(event && event.currentTarget) event.currentTarget.classList.add('active');
else {
const items = document.querySelectorAll('.menu-item');
for(let item of items) if(item.getAttribute('onclick').includes(tabId)) { item.classList.add('active'); break; }
}
window.history.replaceState(null, null, '#' + tabId);
}
</script>
</body>
</html>
HTML;
}

第五步:系统初始化
在浏览器中访问您的域名(例如 http://proxy.yourdomain.com)。

此时会自动跳转到初始化安装界面。

按照提示设置:

后台访问路径(例如 /admin,为了安全建议改成不规则的,如 /my_admin_666)

用户访问路径(例如 /user)

管理员账号(例如 admin)

管理员密码(例如 123456)

点击完成初始化,系统会自动创建所有的数据库表结构。