This commit is contained in:
gr
2026-11-11 13:53:14 +08:00
parent 85ffda8fd0
commit fc347bf9a6
490 changed files with 70862 additions and 386 deletions
+106
View File
@@ -0,0 +1,106 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { webcrypto } from 'node:crypto'
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, fixedOrigin, groupLoginDestination, GROUP_TRANSACTION_KEY, pkceChallenge } from '../src/utils/groupSso.mjs'
const identityOrigin = 'http://127.0.0.1:5173'
const hospitalOrigin = 'http://127.0.0.1:8090'
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
function store() {
const values = new Map()
return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: (key) => values.delete(key) }
}
async function transaction() {
const storage = store()
const target = new URL(await beginGroupLogin({ identityOrigin, hospitalOrigin, storage, cryptoApi: webcrypto, now: 1000 }))
const history = { state: null, calls: [], replaceState(...args) { this.calls.push(args) } }
const url = new URL('/admin/group-login', hospitalOrigin)
url.search = new URLSearchParams({ code: 'c'.repeat(64), state: target.searchParams.get('state') }).toString()
return { storage, target, history, url }
}
function consume(fixture, overrides = {}) {
return consumeGroupCallback({ ...fixture, url: fixture.url.href, identityOrigin, hospitalOrigin, now: 1500, ...overrides })
}
test('S256 对照 RFC 7636 向量', async () => {
assert.equal(await pkceChallenge(verifier, webcrypto), 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM')
})
test('只允许 HTTPS 或回环 HTTP 固定 origin', () => {
assert.equal(fixedOrigin(identityOrigin), identityOrigin)
for (const value of ['http://example.com', identityOrigin + '/bad', identityOrigin + '?redirect=x', 'https://u:p@example.com', 'javascript:alert(1)']) {
assert.throws(() => fixedOrigin(value))
}
})
test('初始化在医院存 verifier,授权 URL 仅有 S256 challenge', async () => {
const fixture = await transaction()
const saved = JSON.parse(fixture.storage.getItem(GROUP_TRANSACTION_KEY))
assert.equal(saved.verifier.length, 43)
assert.equal(saved.state.length, 43)
assert.equal(fixture.target.pathname, '/sso/authorize')
assert.equal(fixture.target.searchParams.get('redirect_uri'), hospitalOrigin + '/admin/group-login')
assert.equal(fixture.target.searchParams.get('code_challenge'), await pkceChallenge(saved.verifier, webcrypto))
assert.equal(fixture.target.href.includes(saved.verifier), false)
})
test('回调同步清 URL 和消费本地事务,不能重放', async () => {
const fixture = await transaction()
const result = consume(fixture)
assert.equal(result.code, 'c'.repeat(64))
assert.equal(fixture.history.calls[0][2], '/admin/group-login')
assert.equal(fixture.storage.getItem(GROUP_TRANSACTION_KEY), null)
assert.throws(() => consume(fixture))
})
test('拒绝错误 state、过期、未来事务、任意 redirect、重复参数和错误医院地址', async () => {
for (const mutate of [
(f) => f.url.searchParams.set('state', 'x'.repeat(43)),
(f) => f.url.searchParams.set('redirect', 'https://example.com'),
(f) => f.url.searchParams.append('code', 'x'.repeat(64)),
(f) => { f.url.pathname = '/admin/login' },
(f) => { f.url.hash = 'unexpected' },
(f) => { const saved = JSON.parse(f.storage.getItem(GROUP_TRANSACTION_KEY)); saved.createdAt = -400000; f.storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify(saved)) },
(f) => { const saved = JSON.parse(f.storage.getItem(GROUP_TRANSACTION_KEY)); saved.createdAt = 2000; f.storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify(saved)) }
]) {
const fixture = await transaction()
mutate(fixture)
assert.throws(() => consume(fixture))
assert.equal(fixture.history.calls.length, 1)
assert.equal(fixture.storage.getItem(GROUP_TRANSACTION_KEY), null)
}
})
test('只执行中央/医院两次 POST,不携带旧 token、拒绝响应指定任意兑换地址', async () => {
const fixture = await transaction()
const current = consume(fixture)
const calls = []
const responses = [{ ticket: 't'.repeat(64), exchange_path: '/adminapi/identity.hospitalSso/exchange' }, { token: 'fixture-hospital-session-only', is_paw: 1 }]
const result = await exchangeGroupCode({ transaction: current, identityOrigin, hospitalOrigin, fetcher: async (url, options) => {
calls.push({ url, options }); return { ok: true, json: async () => ({ code: 1, data: responses.shift() }) }
} })
assert.equal(result.is_paw, 1)
assert.equal(calls.length, 2)
assert.equal(calls[0].url, identityOrigin + '/adminapi/group/sso/exchange')
assert.equal(calls[1].url, hospitalOrigin + '/adminapi/identity.hospitalSso/exchange')
assert.equal(calls[0].options.credentials, 'omit')
assert.equal(calls[1].options.credentials, 'same-origin')
assert.equal(calls.every(({ options }) => options.method === 'POST' && options.redirect === 'error' && !options.headers.Authorization && !options.headers.token), true)
let rejectedCalls = 0
await assert.rejects(exchangeGroupCode({ transaction: current, identityOrigin, hospitalOrigin, fetcher: async () => {
rejectedCalls++; return { ok: true, json: async () => ({ code: 1, data: { ticket: 't'.repeat(64), exchange_path: 'https://example.com' } }) }
} }))
assert.equal(rejectedCalls, 1)
})
test('网络失败不重试,首次改密与企微门禁保留', async () => {
const fixture = await transaction()
let count = 0
await assert.rejects(exchangeGroupCode({ transaction: consume(fixture), identityOrigin, hospitalOrigin, fetcher: async () => { count++; throw new Error('fixture offline') } }))
assert.equal(count, 1)
const secondFixture = await transaction()
count = 0
await assert.rejects(exchangeGroupCode({ transaction: consume(secondFixture), identityOrigin, hospitalOrigin, fetcher: async () => {
count++
if (count === 2) throw new Error('fixture hospital offline')
return { ok: true, json: async () => ({ code: 1, data: { ticket: 't'.repeat(64), exchange_path: '/adminapi/identity.hospitalSso/exchange' } }) }
} }))
assert.equal(count, 2)
assert.equal(groupLoginDestination({ is_paw: 0, need_bind_work_wechat: true }), '/admin/change-password')
assert.equal(groupLoginDestination({ is_paw: 1, need_bind_work_wechat: true }), '/admin/bind-work-wechat')
assert.equal(groupLoginDestination({ is_paw: 1 }), '/admin/')
})
+87
View File
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
// 仅供回环预览:静态文件来自隔离副本,PHP 只从固定原入口加载。
$project = realpath(__DIR__ . '/../..');
$public = $project . '/server/public';
$preview = $project . '/.test-runtime/hospital-preview/admin';
$path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
header('Referrer-Policy: no-referrer');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');
function missing(): never
{
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo '{"code":0,"msg":"接口不存在","data":{}}';
exit;
}
if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true)
|| !in_array($_SERVER['HTTP_HOST'] ?? '', ['127.0.0.1:8090', 'localhost:8090'], true)
|| array_key_exists('s', $_GET) || preg_match('/[\\\\\x00-\x20\x7f]/', $path)) {
missing();
}
if (in_array($method, ['GET', 'HEAD'], true) && ($path === '/admin' || str_starts_with($path, '/admin/'))) {
if ($path === '/admin/group-login') {
$file = $preview . '/group-login.html';
$type = 'text/html; charset=utf-8';
} elseif ($path === '/admin/group-sso.mjs') {
$file = $preview . '/group-sso.mjs';
$type = 'text/javascript; charset=utf-8';
} elseif (preg_match('~^/admin/(assets/[A-Za-z0-9_.@/-]+|ai-chat-icon\.png)$~D', $path)) {
$file = realpath($preview . substr($path, strlen('/admin')));
$base = realpath($preview);
$normalizedFile = is_string($file) ? str_replace('\\', '/', $file) : '';
$normalizedBase = is_string($base) ? str_replace('\\', '/', $base) . '/' : '';
if (!$file || !$base || !str_starts_with($normalizedFile, $normalizedBase) || !is_file($file)) { missing(); }
$types = ['js' => 'text/javascript', 'mjs' => 'text/javascript', 'css' => 'text/css', 'png' => 'image/png',
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'webp' => 'image/webp', 'svg' => 'image/svg+xml',
'woff' => 'font/woff', 'woff2' => 'font/woff2', 'ttf' => 'font/ttf', 'ico' => 'image/x-icon'];
$type = $types[strtolower(pathinfo($file, PATHINFO_EXTENSION))] ?? null;
if ($type === null) { missing(); }
} elseif (preg_match('~^/admin(?:/[A-Za-z0-9_-]+)*/?$~D', $path)) {
$file = $preview . '/index.html';
$type = 'text/html; charset=utf-8';
} else { missing(); }
if (!is_file($file)) { missing(); }
header('Content-Type: ' . $type);
if ($method !== 'HEAD') { readfile($file); }
exit;
}
// 不透传任意磁盘路径、安装器、测试脚本或 PHP 文件。
if (!in_array($method, ['GET', 'POST', 'OPTIONS'], true)
|| !preg_match('~^/adminapi/[A-Za-z][A-Za-z0-9_.]*/[A-Za-z][A-Za-z0-9_]*$~D', $path)) {
missing();
}
$root = $project . '/server';
if (!is_file($root . '/vendor/autoload.php') || !is_file($root . '/config/install.lock')) {
http_response_code(503);
header('Content-Type: application/json; charset=utf-8');
echo '{"code":0,"msg":"原项目服务尚未配置","data":{}}';
exit;
}
require $root . '/vendor/autoload.php';
$_SERVER['SCRIPT_FILENAME'] = $public . '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['PHP_SELF'] = '/index.php';
$_SERVER['PATH_INFO'] = $path;
foreach (['HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP'] as $key) { unset($_SERVER[$key]); }
$application = new class($root . DIRECTORY_SEPARATOR) extends think\App {
public function loadEnv(string $envName = ''): void
{
parent::loadEnv($envName);
$this->env->set('APP_DEBUG', false);
$this->env->set('LOCAL_DEBUG_LOGIN_SKIP_PASSWORD', false);
}
};
$application->initialize();
$application->request->setPathinfo(ltrim($path, '/'));
$http = $application->http;
$response = $http->run();
$response->send();
$http->end($response);
@@ -0,0 +1,29 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const project = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const source = path.join(project, 'server/public/admin')
const runtime = path.join(project, '.test-runtime')
const output = path.join(runtime, 'hospital-preview')
const target = path.join(output, 'admin')
const sourceHtml = fs.readFileSync(path.join(source, 'index.html'), 'utf8')
const entryPath = sourceHtml.match(/<script\b[^>]*\bsrc="\/admin\/assets\/([^"/]+\.js)"/i)?.[1]
if (!entryPath) throw new Error('未找到原医院构建入口')
const entry = fs.readFileSync(path.join(source, 'assets', entryPath), 'utf8')
const original = 'baseUrl:"https://admin.zhenyangtang.com.cn//"'
if (entry.split(original).length !== 2) throw new Error('医院公开 API baseUrl 字面量必须恰好出现一次')
fs.mkdirSync(runtime, { recursive: true })
// 只忽略生成物,不修改根 .gitignore 或原发布目录。
const ignoreFile = path.join(runtime, '.gitignore')
if (!fs.existsSync(ignoreFile)) fs.writeFileSync(ignoreFile, '*\n')
fs.cpSync(source, target, { recursive: true, force: true })
fs.writeFileSync(path.join(target, 'assets', entryPath), entry.replace(original, 'baseUrl:"/"'))
// 预览只加载原本地模块;不启动原 HTML 附带的远程客服/音视频脚本及其内联初始化。
const previewHtml = sourceHtml.replace(/<script\b([^>]*)>[\s\S]*?<\/script>/gi, (tag, attrs) =>
/\bsrc="\/admin\/assets\/[^"/]+\.js"/.test(attrs) ? tag : '')
fs.writeFileSync(path.join(target, 'index.html'), previewHtml.replace('<title>后台管理系统</title>', '<title>互联网医院</title>'))
fs.copyFileSync(path.join(project, 'admin/src/utils/groupSso.mjs'), path.join(target, 'group-sso.mjs'))
fs.copyFileSync(path.join(project, 'admin/public/group-login.html'), path.join(target, 'group-login.html'))
if (fs.readFileSync(path.join(target, 'assets', entryPath), 'utf8').includes(original)) throw new Error('本地 API 适配未完成')
process.stdout.write(JSON.stringify({ path: output, entry: entryPath }) + '\n')
+18
View File
@@ -0,0 +1,18 @@
param(
[string]$PhpPath = 'C:\Users\isard\.cache\zyt-tools\php\php.exe'
)
$ErrorActionPreference = 'Stop'
$projectPath = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
if (-not (Test-Path -LiteralPath $PhpPath -PathType Leaf)) { throw 'PHP 可执行文件不存在' }
if (Get-NetTCPConnection -LocalPort 8090 -State Listen -ErrorAction SilentlyContinue) { throw '8090 端口已占用,未停止任何进程' }
& node (Join-Path $PSScriptRoot 'prepare-hospital-preview.mjs')
if ($LASTEXITCODE -ne 0) { throw '医院预览准备失败' }
$runtimePath = Join-Path $projectPath '.test-runtime\hospital-preview'
$routerPath = Join-Path $PSScriptRoot 'hospital-preview-router.php'
$publicPath = Join-Path $projectPath 'server\public'
$arguments = @('-S', '127.0.0.1:8090', '-t', ('"' + $publicPath + '"'), ('"' + $routerPath + '"'))
# 隐藏控制台,不将 PHP 请求日志重定向到文件,避免保存回调 URL 中的短码。
$process = Start-Process -FilePath $PhpPath -ArgumentList $arguments -WorkingDirectory (Join-Path $projectPath 'server') -WindowStyle Hidden -PassThru
$state = [ordered]@{ pid = $process.Id; port = 8090; path = $runtimePath }
$state | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $runtimePath 'status.json') -Encoding utf8
$state | ConvertTo-Json
+32
View File
@@ -0,0 +1,32 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const project = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const base = 'http://127.0.0.1:8090'
const callback = await fetch(base + '/admin/group-login')
const callbackText = await callback.text()
if (callback.status !== 200 || !callbackText.includes('集团账号登录') || !callbackText.includes('/admin/group-sso.mjs')) throw new Error('医院回调入口验证失败')
const moduleResponse = await fetch(base + '/admin/group-sso.mjs')
if (moduleResponse.status !== 200 || !(moduleResponse.headers.get('content-type') || '').includes('javascript')) throw new Error('医院登录模块验证失败')
const page = await fetch(base + '/admin/')
const html = await page.text()
if (!html.includes('<title>互联网医院</title>') || /<script[^>]+src="https?:/i.test(html)) throw new Error('预览标题或远程脚本边界验证失败')
const asset = html.match(/<script\b[^>]*\bsrc="(\/admin\/assets\/[^"/]+\.js)"/i)?.[1]
if (!asset) throw new Error('未找到预览入口模块')
const bundle = await (await fetch(base + asset)).text()
if (!bundle.includes('baseUrl:"/"') || bundle.includes('baseUrl:"https://admin.zhenyangtang.com.cn//"')) throw new Error('预览 API 地址验证失败')
const paths = ['/test.php', '/admin/assets/anything.php', '/install/install.php', '/admin/group-login?s=auth.admin/mySelf']
for (const route of paths) {
if ((await fetch(base + route)).status !== 404) throw new Error('静态路径或兼容路由未被拒绝')
}
const denied = await (await fetch(base + '/adminapi/auth.admin/mySelf')).json()
if (denied.code === 1) throw new Error('未认证 API 意外放行')
const original = fs.readFileSync(path.join(project, 'server/public' + asset), 'utf8')
if (!original.includes('baseUrl:"https://admin.zhenyangtang.com.cn//"')) throw new Error('原发布产物发生修改')
const runtime = path.join(project, '.test-runtime/hospital-preview')
if (['php.stdout.log', 'php.stderr.log'].some((name) => fs.existsSync(path.join(runtime, name)))) throw new Error('预览不应生成持久化请求日志')
const state = JSON.parse(fs.readFileSync(path.join(runtime, 'status.json'), 'utf8').replace(/^\uFEFF/, ''))
if (Object.keys(state).sort().join(',') !== 'path,pid,port') throw new Error('启动状态包含额外字段')
fs.writeFileSync(path.join(project, 'artifacts/iam-extraction/hospital-preview-status.json'), JSON.stringify(state, null, 2) + '\n')
process.stdout.write('医院预览验证通过:回调/模块/首页 200,本地 API,4 条危险路径 404,未认证拒绝,无请求日志,原产物未改。\n')