igengx
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// 默认仅使用内存 SQLite。可选的本机独立 MySQL 可重复验证生产迁移和旧会话唯一键。
|
||||
namespace {
|
||||
final class WorkstationClock { public static int $now; }
|
||||
}
|
||||
namespace app\adminapi\service { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\adminapi\logic { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\adminapi\http\middleware { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\common\cache {
|
||||
function time(): int { return \WorkstationClock::$now; }
|
||||
// 故意保留过期缓存,验证服务端始终以数据库为准。
|
||||
abstract class BaseCache {
|
||||
private static array $entries = [];
|
||||
public function get($key) { return self::$entries[$key] ?? null; }
|
||||
public function set($key, $value, $ttl = null) { self::$entries[$key] = $value; }
|
||||
public function delete($key): bool { return false; }
|
||||
}
|
||||
}
|
||||
namespace app\common\service {
|
||||
final class FileService {
|
||||
public static function getFileUrl($uri = ''): string { return (string) $uri; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
use app\adminapi\controller\LoginController;
|
||||
use app\adminapi\http\middleware\LoginMiddleware;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum as Terminal;
|
||||
use think\facade\Db;
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
function create_token(string $extra = ''): string { return bin2hex(random_bytes(16)); }
|
||||
function wsExpect(bool $ok, string $label): void {
|
||||
if (!$ok) { throw new RuntimeException($label); }
|
||||
$GLOBALS['wsChecks']++;
|
||||
}
|
||||
final class WorkstationLoginController extends LoginController {
|
||||
public function __construct(think\Request $request) {
|
||||
$this->request = $request;
|
||||
$this->initialize();
|
||||
}
|
||||
}
|
||||
$GLOBALS['wsChecks'] = 0;
|
||||
$port = (int) getenv('ZYT_WORKSTATION_TEST_MYSQL_PORT');
|
||||
$temporaryDb = 'workstation_test_' . bin2hex(random_bytes(8));
|
||||
$app = new think\App(sys_get_temp_dir() . '/' . $temporaryDb);
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'auto_timestamp' => false, 'datetime_format' => false,
|
||||
'connections' => ['test' => $port
|
||||
? ['type' => 'mysql', 'database' => $temporaryDb, 'prefix' => 'zyt_', 'hostname' => '127.0.0.1',
|
||||
'username' => 'root', 'password' => '', 'hostport' => $port, 'charset' => 'utf8mb4']
|
||||
: ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_']]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
$app->instance('log', new Psr\Log\NullLogger());
|
||||
$config = new think\Config();
|
||||
$config->set(['admin_token' => ['expire_duration' => 28800, 'be_expire_duration' => 3600],
|
||||
'default_image' => ['admin_avatar' => '']], 'project');
|
||||
$app->instance('config', $config);
|
||||
$app->env->set('work_wechat.force_bind_login', false);
|
||||
$app->env->set('WORK_WECHAT_FORCE_BIND_LOGIN', false);
|
||||
$request = static function (string $token = '', string $action = 'desktopHeartbeat', string $method = 'POST') use ($app) {
|
||||
$req = (new think\Request())->withServer(['REMOTE_ADDR' => '192.0.2.10', 'REQUEST_METHOD' => $method])
|
||||
->withHeader(['token' => $token]);
|
||||
$req->setController('Login');
|
||||
$req->setAction($action);
|
||||
$req->controllerObject = new WorkstationLoginController($req);
|
||||
$app->instance('request', $req);
|
||||
return $req;
|
||||
};
|
||||
$invoke = static function (string $token, string $action = 'desktopHeartbeat', string $method = 'POST') use ($request) {
|
||||
$req = $request($token, $action, $method);
|
||||
return (new LoginMiddleware())->handle($req, static function ($req) use ($action) {
|
||||
return (new WorkstationLoginController($req))->$action();
|
||||
})->getData();
|
||||
};
|
||||
$login = static function (int $terminal = Terminal::WORKSTATION) use ($request) {
|
||||
$request('', 'account');
|
||||
return (new LoginLogic())->login(['account' => 'doctor.ws', 'terminal' => $terminal]);
|
||||
};
|
||||
$ledger = static fn() => Db::name('desktop_login_session')->order('id', 'desc')->find();
|
||||
$root = null;
|
||||
try {
|
||||
if ($port) {
|
||||
$root = new PDO("mysql:host=127.0.0.1;port=$port;charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$root->exec("CREATE DATABASE `$temporaryDb` CHARACTER SET utf8mb4");
|
||||
$root->exec("USE `$temporaryDb`");
|
||||
$root->exec('CREATE TABLE zyt_admin_session (id INT PRIMARY KEY AUTO_INCREMENT, admin_id INT NOT NULL, terminal INT NOT NULL,
|
||||
token VARCHAR(32) UNIQUE, expire_time INT NOT NULL, update_time INT, UNIQUE KEY old_install_index(admin_id,terminal)) ENGINE=InnoDB');
|
||||
$root->exec('CREATE TABLE zyt_dev_crontab (name VARCHAR(64),type INT,`system` INT,remark TEXT,command VARCHAR(64),
|
||||
params VARCHAR(64),status INT,expression VARCHAR(64),last_time INT,create_time INT,update_time INT,delete_time INT)');
|
||||
$root->exec("INSERT INTO zyt_admin_session (admin_id,terminal,token,expire_time) VALUES (77,1,'legacy',123)");
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_24_desktop_login_session.sql');
|
||||
for ($run = 0; $run < 2; $run++) {
|
||||
$migration = $root->query($sql);
|
||||
while ($migration->nextRowset()) {
|
||||
// 消费可重复迁移中的所有 SELECT 与 DDL 结果。
|
||||
}
|
||||
$migration->closeCursor();
|
||||
}
|
||||
wsExpect((int) Db::name('dev_crontab')->where('command', 'desktop-session:settle')->count() === 1, 'one scheduled sweep');
|
||||
wsExpect((int) Db::name('admin_session')->where('token', 'legacy')->value('workstation_slot') === 0, 'old tokens retain ordinary slot');
|
||||
$duplicateRejected = false;
|
||||
try { $root->exec("INSERT INTO zyt_admin_session (admin_id,terminal,token,expire_time) VALUES (77,1,'other',123)"); }
|
||||
catch (PDOException $e) { $duplicateRejected = $e->getCode() === '23000'; }
|
||||
wsExpect($duplicateRejected, 'legacy terminals keep unique account-terminal constraint');
|
||||
} else {
|
||||
Db::execute('CREATE TABLE zyt_admin_session (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT, terminal INT, token TEXT UNIQUE,
|
||||
expire_time INT, update_time INT, workstation_slot INT NOT NULL DEFAULT 0, UNIQUE(admin_id, terminal, workstation_slot))');
|
||||
Db::execute("CREATE TABLE zyt_desktop_login_session (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT, account TEXT,
|
||||
name TEXT, login_ip TEXT, login_time INT, last_seen_time INT, expires_at INT, due_time INT, logout_time INT,
|
||||
duration_seconds INT DEFAULT 0, end_reason TEXT DEFAULT '')");
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INT PRIMARY KEY, account VARCHAR(60), name VARCHAR(60), root INT, disable INT,
|
||||
multipoint_login INT, delete_time INT, login_ip VARCHAR(45), login_time INT, update_time INT, avatar VARCHAR(100),
|
||||
is_paw INT, work_wechat_userid VARCHAR(100))');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
|
||||
Db::execute('CREATE TABLE zyt_system_role (id INT PRIMARY KEY, name VARCHAR(60), delete_time INT)');
|
||||
Db::name('admin')->insert(['id' => 7, 'account' => 'doctor.ws', 'name' => '甲医生', 'root' => 0,
|
||||
'disable' => 0, 'multipoint_login' => 1, 'is_paw' => 1, 'avatar' => '', 'work_wechat_userid' => '']);
|
||||
$start = (new DateTimeImmutable('2026-11-24 04:56:00+08:00'))->getTimestamp();
|
||||
$cutoff = $start + 240;
|
||||
WorkstationClock::$now = $start;
|
||||
wsExpect(DesktopSessionService::nextCutoff($cutoff - 1) === $cutoff
|
||||
&& DesktopSessionService::nextCutoff($cutoff) === $cutoff + 86400, 'exact Beijing cutoff independent of PHP timezone');
|
||||
$web = $login(Terminal::PC);
|
||||
wsExpect(!isset($web['desktop_expires_at']) && Db::name('desktop_login_session')->count() === 0, 'web login remains separate');
|
||||
wsExpect($invoke($web['token'])['code'] === -1, 'legacy desktop/web token cannot assert a workstation heartbeat');
|
||||
$first = $login();
|
||||
$firstId = $ledger()['id'];
|
||||
$second = $login();
|
||||
wsExpect($first['desktop_expires_at'] === $cutoff && $first['token'] !== $second['token'], 'parallel desktops get separate tokens');
|
||||
wsExpect($ledger()['account'] === 'doctor.ws' && $ledger()['name'] === '甲医生', 'identity snapshot persisted');
|
||||
wsExpect($invoke($second['token'], 'desktopHeartbeat', 'GET')['code'] === 0, 'heartbeat is POST only');
|
||||
WorkstationClock::$now += 62;
|
||||
wsExpect($invoke($first['token'])['data']['desktop_expires_at'] === $cutoff, 'heartbeat refreshes lease only');
|
||||
wsExpect($invoke($second['token'], 'logout')['code'] === 1 && $ledger()['end_reason'] === 'logout'
|
||||
&& (int) $ledger()['duration_seconds'] === 62, 'explicit logout settles only that instance to the second');
|
||||
wsExpect($invoke($second['token'])['code'] === -1 && !(new AdminTokenCache())->getAdminInfo($second['token']), 'stale cache cannot restore closed device');
|
||||
wsExpect((bool) (new AdminTokenCache())->getAdminInfo($web['token']), 'web token survives desktop logout');
|
||||
WorkstationClock::$now = $cutoff;
|
||||
wsExpect(!AdminTokenService::overtimeToken($first['token']) && $invoke($first['token'])['code'] === -1, 'no request or renewal at 05:00');
|
||||
WorkstationClock::$now += 3600;
|
||||
wsExpect(DesktopSessionService::settleDue() === 1 && DesktopSessionService::settleDue() === 0, 'delayed sweep settles once');
|
||||
$old = Db::name('desktop_login_session')->where('id', $firstId)->find();
|
||||
wsExpect((int) $old['logout_time'] === $cutoff && (int) $old['duration_seconds'] === 240 && $old['end_reason'] === 'daily_cutoff', 'durable daily cutoff even without requests');
|
||||
$idle = $login();
|
||||
WorkstationClock::$now += 52;
|
||||
$invoke($idle['token']);
|
||||
$lastSeen = WorkstationClock::$now;
|
||||
WorkstationClock::$now += 180;
|
||||
wsExpect($invoke($idle['token'])['code'] === -1 && DesktopSessionService::settleDue() === 1, 'expired heartbeat cannot revive a slot');
|
||||
wsExpect((int) $ledger()['logout_time'] === $lastSeen && (int) $ledger()['duration_seconds'] === 52
|
||||
&& $ledger()['end_reason'] === 'timeout', 'disconnected time excluded');
|
||||
Db::name('admin')->where('id', 7)->update(['multipoint_login' => 0]);
|
||||
$replaced = $login();
|
||||
$replacedId = $ledger()['id'];
|
||||
WorkstationClock::$now += 11;
|
||||
$replacement = $login();
|
||||
$old = Db::name('desktop_login_session')->where('id', $replacedId)->find();
|
||||
wsExpect($old['end_reason'] === 'replaced' && (int) $old['duration_seconds'] === 11, 'single-point relog closes old record');
|
||||
wsExpect($invoke($replaced['token'], 'logout')['code'] === -1 && $invoke($replacement['token'])['code'] === 1,
|
||||
'late logout cannot affect replacement');
|
||||
AdminTokenService::revokeNativeSessions(7);
|
||||
wsExpect($ledger()['end_reason'] === 'revoked' && $invoke($replacement['token'])['code'] === -1, 'account credential revocation settles the ledger');
|
||||
echo 'WorkstationSessionTest ' . ($port ? 'MySQL' : 'SQLite') . ': ' . $GLOBALS['wsChecks'] . " checks passed\n";
|
||||
} finally {
|
||||
if ($root) { $root->exec("DROP DATABASE IF EXISTS `$temporaryDb`"); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user