更新
This commit is contained in:
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
class EsignProviderException extends \RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode) {}
|
||||
}
|
||||
|
||||
final class EsignClient
|
||||
{
|
||||
public const NAME = '测试医师';
|
||||
public const DOCUMENT = '110101199001011237';
|
||||
public static array $identity = ['status' => 'INIT'];
|
||||
public static int $starts = 0;
|
||||
public static int $creates = 0;
|
||||
public static ?string $mobile = null;
|
||||
public static bool $expired = false;
|
||||
public static ?\Closure $duringStart = null;
|
||||
public static ?\Closure $duringRecipientLookup = null;
|
||||
public static ?string $account = null;
|
||||
public static int $quickStarts = 0;
|
||||
public static int $willingnessChecks = 0;
|
||||
public static int $willingnessExpiry = 0;
|
||||
public static bool $willingnessValid = true;
|
||||
public static ?\Closure $duringWillingnessCheck = null;
|
||||
|
||||
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId): array
|
||||
{
|
||||
++self::$starts;
|
||||
self::$account = $accountId;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
return ['flow_id' => 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/example/' . self::$starts];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
{
|
||||
return self::$identity + ['flowId' => $flowId, 'appId' => 'fixture', 'objectType' => 'INDIVIDUAL'];
|
||||
}
|
||||
|
||||
public function startDoctorQuickAuthorization(string $name, string $document, string $contextId, string $accountId): array
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT || $accountId !== 'bound-account'
|
||||
|| !str_starts_with($contextId, 'doctor-quicksign-')) {
|
||||
throw new \RuntimeException('Wrong quick-sign authorization subject or context');
|
||||
}
|
||||
++self::$quickStarts;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
return ['flow_id' => 'quick-proof-' . self::$quickStarts, 'auth_url' => 'https://smlt.esign.cn/quick/' . self::$quickStarts];
|
||||
}
|
||||
|
||||
public function willingnessValidity(string $flowId): array
|
||||
{
|
||||
++self::$willingnessChecks;
|
||||
if (self::$duringWillingnessCheck) {
|
||||
(self::$duringWillingnessCheck)();
|
||||
}
|
||||
if ($flowId !== 'quick-proof-' . self::$quickStarts || !self::$willingnessValid) {
|
||||
return ['state' => 'exhausted', 'expires_at' => 0, 'remaining_times' => 0];
|
||||
}
|
||||
return ['state' => 'valid', 'expires_at' => self::$willingnessExpiry, 'remaining_times' => 2];
|
||||
}
|
||||
|
||||
public function createPerson(string $name, string $document, string $flowId): string
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT || $flowId !== 'flow-' . self::$starts) {
|
||||
throw new \RuntimeException('Identity proof mismatch');
|
||||
}
|
||||
++self::$creates;
|
||||
return 'bound-account';
|
||||
}
|
||||
|
||||
public function signingAccount(string $accountId): array
|
||||
{
|
||||
return ['accountId' => $accountId, 'name' => self::NAME, 'idNo' => self::DOCUMENT,
|
||||
'accountType' => 'PERSON', 'idNoType' => 'MAINLAND'];
|
||||
}
|
||||
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
return ['startDate' => '2024-01-01 08:00:00',
|
||||
'endDate' => self::$expired ? '2024-02-01 08:00:00' : '2099-01-01 08:00:00'];
|
||||
}
|
||||
|
||||
public function authorizedMobile(string $name, string $document): ?string
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT) {
|
||||
throw new \RuntimeException('Wrong provider subject');
|
||||
}
|
||||
if (self::$duringRecipientLookup) {
|
||||
(self::$duringRecipientLookup)();
|
||||
}
|
||||
return self::$mobile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\common\service\esign\DoctorEsignIdentityRequired;
|
||||
use app\common\service\esign\DoctorEsignAuthorizationRequired;
|
||||
use app\common\service\esign\DoctorEsignIdentityService as Enrollment;
|
||||
use app\common\service\esign\EsignClient as Provider;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
$app = new think\App();
|
||||
$app->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'app_secret' => 'fixture-secret'];
|
||||
$config->set($settings, 'esign');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
|
||||
foreach (['identity', 'quicksign'] as $migration) {
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_' . $migration . '.sql');
|
||||
$sql = preg_replace('/\) ENGINE=.*;/u', ');', $sql);
|
||||
Db::execute($sql);
|
||||
Db::execute($sql);
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER,role_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_esign_account (doctor_id INTEGER,environment TEXT,app_id TEXT,account_id TEXT,
|
||||
doctor_name TEXT,create_time INTEGER,UNIQUE(doctor_id,environment,app_id))');
|
||||
Db::name('admin')->insertAll([['id' => 1, 'name' => Provider::NAME], ['id' => 2, 'name' => '另一位医师'], ['id' => 3, 'name' => '客服']]);
|
||||
Db::name('admin_role')->insertAll([['admin_id' => 1, 'role_id' => 1], ['admin_id' => 2, 'role_id' => 1], ['admin_id' => 3, 'role_id' => 2]]);
|
||||
|
||||
$checks = 0;
|
||||
$assert = static function (bool $condition, string $message) use (&$checks): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
++$checks;
|
||||
};
|
||||
$throws = static function (callable $operation, string $expected, string $message) use ($assert): void {
|
||||
try {
|
||||
$operation();
|
||||
} catch (DomainException $error) {
|
||||
$assert(is_a($error, $expected), $message);
|
||||
return;
|
||||
}
|
||||
$assert(false, $message);
|
||||
};
|
||||
|
||||
$phone = '13800000000';
|
||||
$assert(Enrollment::status(1)['enabled'] === false, 'SMS enrollment defaults off');
|
||||
$config->set(['doctor_sms_enabled' => true], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'doctor starts unbound');
|
||||
$throws(static fn () => Enrollment::status(3), DomainException::class, 'non-physician denied');
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, ''), DoctorEsignIdentityRequired::class, 'setup-required reason distinguishes an unbound doctor');
|
||||
|
||||
Provider::$duringStart = static function () use ($assert, $phone): void {
|
||||
$duplicate = Enrollment::start(1, $phone);
|
||||
$assert($duplicate['status'] === 'authenticating' && !isset($duplicate['auth_url']), 'concurrent start is held by the operation lease');
|
||||
};
|
||||
$first = Enrollment::start(1, $phone);
|
||||
Provider::$duringStart = null;
|
||||
$assert($first['status'] === 'authenticating' && Enrollment::start(1, $phone) === $first && Provider::$starts === 1,
|
||||
'explicit repeat resumes the hosted flow');
|
||||
$assert(Enrollment::status(2)['status'] === 'unbound', 'another physician cannot see this URL');
|
||||
$config->set(['app_id' => 'other-app'], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'another eSign application cannot see this URL');
|
||||
$config->set(['app_id' => 'fixture'], 'esign');
|
||||
$assert(!str_contains(json_encode(Db::name('doctor_esign_identity')->find()), $phone), 'mobile stored only as a keyed digest');
|
||||
$assert(Enrollment::complete(1)['status'] === 'authenticating' && Provider::$creates === 0, 'unfinished H5 does not bind');
|
||||
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
|
||||
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => '1101**********123X']];
|
||||
$pending = Enrollment::status(1);
|
||||
$assert($pending['status'] === 'binding_required' && $pending['identity_details_required'] && !isset($pending['auth_url'])
|
||||
&& Provider::$creates === 0, 'successful polling exposes only safe metadata and accepts masked identity as supplemental');
|
||||
$assert(Enrollment::complete(1, 'bad-input')['identity_details_required'] && Provider::$creates === 0, 'invalid supplemental number never reaches SDK');
|
||||
$assert(Enrollment::complete(1, Provider::DOCUMENT)['status'] === 'needs_mobile' && Provider::$creates === 1,
|
||||
'successful provider proof binds without signing, but an absent provider authorization is not ready');
|
||||
$assert(Db::name('doctor_esign_identity')->count() === 0 && !str_contains(json_encode(Db::name('doctor_esign_account')->find()), Provider::DOCUMENT),
|
||||
'completed enrollment clears hosted URL and does not persist identity number');
|
||||
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class, 'willingness requires a current authorized mobile');
|
||||
Provider::$expired = true;
|
||||
$assert(Enrollment::status(1)['status'] === 'renewal_required', 'expired provider certificate requires renewal');
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account', 'renewal reuses canonical account');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
Provider::$mobile = $phone;
|
||||
Provider::$expired = false;
|
||||
$assert(Enrollment::status(1)['identity_details_required'] === false, 'a bound account needs no supplemental input');
|
||||
$ready = Enrollment::complete(1);
|
||||
$assert($ready['status'] === 'ready' && $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
'same account becomes ready with certificate date in configured SDK timezone');
|
||||
$assert(!str_contains(json_encode($ready), $phone) && !str_contains(json_encode($ready), Provider::DOCUMENT), 'status never returns provider identity');
|
||||
$recipient = Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account');
|
||||
$assert($recipient === ['name' => Provider::NAME, 'idNo' => Provider::DOCUMENT, 'mobile' => $phone], 'recipient includes only verified transient provider fields');
|
||||
|
||||
Provider::$duringRecipientLookup = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DomainException::class, 'mid-flight account change cannot authorize willingness');
|
||||
Provider::$duringRecipientLookup = null;
|
||||
Provider::$mobile = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
|
||||
$assert(!Enrollment::quickEnabled(), 'quick-sign is disabled by default');
|
||||
$config->set(['doctor_sms_enabled' => false, 'doctor_quicksign_enabled' => true], 'esign');
|
||||
$quickReady = Enrollment::status(1);
|
||||
$assert($quickReady['status'] === 'ready' && $quickReady['quicksign_enabled'] && $quickReady['quicksign_expires_at'] === 0,
|
||||
'a bound current certificate can enter quick-sign without SMS or previous authorization');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'an established signing account and historical identity are insufficient to sign');
|
||||
$assert(Enrollment::start(2, '')['status'] === 'unbound' && Provider::$quickStarts === 0, 'an unbound physician cannot start a quick-sign grant');
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$duringStart = static function () use ($assert): void {
|
||||
$processing = Enrollment::status(1);
|
||||
$assert($processing['status'] === 'authenticating' && $processing['quicksign_authorizing'] && !isset($processing['auth_url']),
|
||||
'quick-sign grant initiation is serialized');
|
||||
};
|
||||
$quick = Enrollment::start(1, '');
|
||||
Provider::$duringStart = null;
|
||||
$assert($quick['quicksign_authorizing'] && $quick['status'] === 'authenticating' && $quick['quicksign_expires_at'] === 0
|
||||
&& isset($quick['auth_url']) && Enrollment::start(1, '') === $quick && Provider::$quickStarts === 1,
|
||||
'empty mobile starts or resumes a distinct provider grant');
|
||||
$assert(Enrollment::complete(1) === $quick && Provider::$willingnessChecks === 0, 'incomplete face authentication cannot grant signing');
|
||||
|
||||
$now = time();
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null, 'endTime' => $now * 1000];
|
||||
Provider::$willingnessExpiry = ($now + 3 * 86400) * 1000;
|
||||
$quickPending = Enrollment::status(1);
|
||||
$assert($quickPending['status'] === 'binding_required' && $quickPending['quicksign_authorizing']
|
||||
&& !$quickPending['identity_details_required'] && $quickPending['quicksign_expires_at'] === 0 && !isset($quickPending['auth_url']),
|
||||
'provider success waits for explicit physician confirmation without another identity prompt');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider face verification alone does not activate grant');
|
||||
$quickGranted = Enrollment::complete(1);
|
||||
$assert($quickGranted['status'] === 'ready' && !$quickGranted['quicksign_authorizing']
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& !str_contains(json_encode($quickGranted), 'quick-proof') && !str_contains(json_encode($quickGranted), Provider::DOCUMENT),
|
||||
'confirmed provider proof is capped to 24 hours and remains server-only');
|
||||
$quickRow = Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->find();
|
||||
$assert($quickRow['flow_id'] === 'quick-proof-1' && $quickRow['auth_url'] === null
|
||||
&& Db::name('doctor_esign_identity')->count() === 0 && Provider::$creates === 1, 'grant clears its hosted link and keeps enrollment untouched');
|
||||
|
||||
$checksBeforeReuse = Provider::$willingnessChecks;
|
||||
Provider::$willingnessExpiry = ($now + 120) * 1000 + 123;
|
||||
$assert(Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
|
||||
&& Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
|
||||
&& Provider::$willingnessChecks === $checksBeforeReuse + 2,
|
||||
'the same independent proof can be reused with a fresh provider check each time');
|
||||
$assert(Enrollment::status(1)['quicksign_expires_at'] === $now + 120, 'reported validity honors a shorter provider expiry');
|
||||
$assert(Enrollment::start(1, '')['quicksign_expires_at'] === $now + 120 && Provider::$quickStarts === 1, 'a current grant is never replaced by a casual repeat');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(2, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'another physician cannot use this proof');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'other-account'), DomainException::class,
|
||||
'signatures must match the authorized SDK account');
|
||||
$config->set(['app_id' => 'other-app'], 'esign');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'another eSign application cannot use this proof');
|
||||
$config->set(['app_id' => 'fixture'], 'esign');
|
||||
Provider::$duringWillingnessCheck = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DomainException::class,
|
||||
'a mid-flight account change invalidates the checked result');
|
||||
Provider::$duringWillingnessCheck = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
Provider::$willingnessValid = false;
|
||||
$spent = Enrollment::status(1);
|
||||
$assert($spent['quicksign_expires_at'] === 0 && $spent['quicksign_remaining_times'] === 0
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready',
|
||||
'provider exhaustion leaves certificate enrollment valid and reports the spent grant');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider cancellation/exhaustion blocks dispatch');
|
||||
Provider::$willingnessValid = true;
|
||||
Provider::$expired = true;
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'expired identity certificate is distinct from an unavailable signing grant');
|
||||
Provider::$expired = false;
|
||||
$checksBeforeExpiry = Provider::$willingnessChecks;
|
||||
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update(['expires_at' => time() - 1]);
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'locally expired grant remains invalid even if the provider still accepts the flow');
|
||||
$assert(Provider::$willingnessChecks === $checksBeforeExpiry && Enrollment::status(1)['status'] === 'ready'
|
||||
&& Enrollment::status(1)['quicksign_expires_at'] === 0, 'expired grant leaves the current signing account enrolled');
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, '')['quicksign_authorizing'] && Provider::$quickStarts === 2, 'expired grant permits a new standalone grant');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['quicksign_expires_at'] === $now + 120, 'provider validity is preserved when shorter than the local bound');
|
||||
echo "Doctor eSign enrollment: $checks checks passed (SQLite and provider doubles)\n";
|
||||
}
|
||||
Reference in New Issue
Block a user