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
@@ -0,0 +1,32 @@
param([switch]$Apply)
$ErrorActionPreference='Stop'
$projectRoot=Split-Path -Parent $PSScriptRoot
$stageRoot=[IO.Path]::GetFullPath((Join-Path $projectRoot 'integration/kefu'))
$sourceRoot=[IO.Path]::GetFullPath('C:\kefu')
$manifest=Get-Content -LiteralPath (Join-Path $stageRoot 'source-manifest.json') -Raw | ConvertFrom-Json
if($manifest.version -ne 1 -or $manifest.source_root -ne $sourceRoot){throw '客服部署清单来源不符'}
$plans=@()
foreach($item in $manifest.files){
$source=[IO.Path]::GetFullPath((Join-Path $sourceRoot $item.path))
$staged=[IO.Path]::GetFullPath((Join-Path $stageRoot $item.path))
if(-not $source.StartsWith($sourceRoot+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase) -or -not $staged.StartsWith($stageRoot+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase)){throw '客服清单路径越界'}
if([IO.Path]::GetExtension($source) -notin @('.py','.ts','.vue','.mjs','.yaml','.md')){throw '客服清单存在非源码或说明文件'}
if((Get-FileHash -LiteralPath $staged).Hash.ToLowerInvariant() -ne $item.staged_sha256){throw ('暂存源码已变化: '+$item.path)}
if((Test-Path -LiteralPath $source) -and (Get-FileHash -LiteralPath $source).Hash.ToLowerInvariant() -eq $item.staged_sha256){continue}
if($null -eq $item.source_sha256){if(Test-Path -LiteralPath $source){throw ('目标新文件已存在: '+$item.path)}}
elseif(-not(Test-Path -LiteralPath $source) -or (Get-FileHash -LiteralPath $source).Hash.ToLowerInvariant() -ne $item.source_sha256){throw ('目标已有修改,拒绝覆盖: '+$item.path)}
$plans+=@{source=$source;staged=$staged;relative=$item.path;sha=$item.staged_sha256;existing=($null -ne $item.source_sha256)}
}
if(-not $Apply){Write-Output ('检查通过:'+$plans.Count+' 个待应用文件;其余已与交付清单一致,未写入客服项目。');return}
if(-not $plans.Count){Write-Output '客服源码已与交付清单一致,无需重复应用。';return}
$backupRoot=Join-Path $projectRoot ('.test-runtime/kefu-source-before-'+(Get-Date -Format 'yyyyMMdd-HHmmss'))
foreach($plan in $plans){
if($plan.existing){$backup=Join-Path $backupRoot $plan.relative;New-Item -ItemType Directory -Path (Split-Path -Parent $backup) -Force | Out-Null;Copy-Item -LiteralPath $plan.source -Destination $backup}
}
foreach($plan in $plans){
New-Item -ItemType Directory -Path (Split-Path -Parent $plan.source) -Force | Out-Null
Copy-Item -LiteralPath $plan.staged -Destination $plan.source
if((Get-FileHash -LiteralPath $plan.source).Hash.ToLowerInvariant() -ne $plan.sha){throw ('复制校验失败: '+$plan.relative)}
}
@{files=$plans.Count;backup=$backupRoot;source_root=$sourceRoot;applied_at=(Get-Date).ToString('o')} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $projectRoot '.test-runtime/kefu-source-applied.json') -Encoding utf8
Write-Output ('客服源码已应用并校验:'+$plans.Count+' 个文件;原源码备份位于 '+$backupRoot)
@@ -0,0 +1,61 @@
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import { createHash } from 'node:crypto'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import ts from '../web/node_modules/typescript/lib/typescript.js'
// Read code as data: neither the Python module nor the TypeScript routes execute.
const sourceRoot = resolve(process.argv[2] || 'C:/kefu')
const output = fileURLToPath(new URL('../integration/kefu-menu-catalog.json', import.meta.url))
const sourcePaths = ['wechat_rpa/rbac.py', 'admin-web/apps/web-antd/src/router/routes/modules/console.ts']
const [rbac, routes] = await Promise.all(sourcePaths.map(path => readFile(resolve(sourceRoot, path), 'utf8')))
const section = rbac.match(/PERMISSIONS:\s*list\[(?:tuple\[str,\s*str,\s*str\]|Permission)\]\s*=\s*\[([\s\S]*?)\n\]/)?.[1]
if (!section) throw new Error('客服权限目录结构已变化,请核对')
const permissions = [...section.matchAll(/(?:Permission)?\("([a-z][a-z0-9:-]+)",\s*"([^"\n]+)",\s*"([^"\n]+)"(?=\s*[,\)])/g)]
.map(([, code, name, group]) => ({ code, name, group }))
if (!permissions.length || new Set(permissions.map(item => item.code)).size !== permissions.length) throw new Error('客服权限目录缺失或重复')
const source = ts.createSourceFile('console.ts', routes, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
const property = (node, key) => node.properties.find(item => ts.isPropertyAssignment(item) && item.name.getText(source).replaceAll(/["']/g, '') === key)?.initializer
const string = node => node && ts.isStringLiteral(node) ? node.text : undefined
const routeLists = new Map()
for (const statement of source.statements) if (ts.isVariableStatement(statement)) for (const item of statement.declarationList.declarations) {
if (ts.isIdentifier(item.name) && item.initializer && ts.isArrayLiteralExpression(item.initializer)) {
routeLists.set(item.name.text, item.initializer)
}
}
const menus = []
function walk(array, base = '', group = '') {
for (const node of array.elements) {
if (!ts.isObjectLiteralExpression(node)) throw new Error('客服路由格式不支持自动提取')
const path = string(property(node, 'path'))
const key = string(property(node, 'name'))
const meta = property(node, 'meta')
if (!path || !key || !meta || !ts.isObjectLiteralExpression(meta)) throw new Error('客服路由字段缺失')
const title = string(property(meta, 'title'))
if (!title) throw new Error('客服路由名称缺失')
const fullPath = path.startsWith('/') ? path : `${base}/${path}`
// The always-available personal landing page is not a role-granted business menu.
if (fullPath === '/group/welcome') continue
const children = property(node, 'children')
if (children) {
const childList = ts.isIdentifier(children) ? routeLists.get(children.text) : children
if (!childList || !ts.isArrayLiteralExpression(childList)) throw new Error(`客服子菜单格式不支持自动提取: ${key}`)
walk(childList, fullPath, title)
}
else {
const authority = property(meta, 'authority')
const codes = authority && ts.isArrayLiteralExpression(authority) ? authority.elements.map(string) : []
if (codes.some(code => !permissions.some(item => item.code === code))) throw new Error(`客服菜单权限不在目录中: ${key}`)
menus.push({ key, name: title, group: group || title, path: fullPath, permissions: codes })
}
}
}
const routeArray = routeLists.get('routes')
if (!routeArray) throw new Error('未找到客服菜单数组')
walk(routeArray)
const catalog = { version: 1, client_id: 'kefu', name: '企微客服', authorization_mode: 'kefu-local-roles',
note: '集团角色仅控制集团菜单入口;客服页面及按钮的实际授权由客服管理员维护。导入不授予任何角色。',
source: sourcePaths.map((path, index) => ({ path, sha256: createHash('sha256').update([rbac, routes][index]).digest('hex') })), menus, permissions }
await mkdir(dirname(output), { recursive: true })
await writeFile(output, JSON.stringify(catalog, null, 2) + '\n')
console.log(`客服目录已生成:${menus.length} 个页面,${permissions.length} 项操作权限;不包含账号或凭据。`)
@@ -0,0 +1,47 @@
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $false
$identityRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$snapshotRoot = Join-Path $identityRoot '.test-runtime/kefu-admin-web'
$mirrorRoot = Join-Path $identityRoot 'integration/kefu/admin-web'
$runtimeRoot = Join-Path $identityRoot '.test-runtime'
$protectedFiles = @('package.json', 'pnpm-lock.yaml', 'internal/tailwind-config/src/theme.css', 'apps/web-antd/node_modules/hash-wasm/package.json')
$frozen = @{}
foreach ($relative in $protectedFiles) {
$frozen[$relative] = (Get-FileHash -LiteralPath (Join-Path $snapshotRoot $relative)).Hash
}
if (@(Get-ChildItem -LiteralPath $snapshotRoot -Filter '.env*' -File).Count -or
@(Get-ChildItem -LiteralPath (Join-Path $snapshotRoot 'apps/web-antd') -Filter '.env*' -File).Count) {
throw 'Isolated build must not contain environment files'
}
$copied = @()
foreach ($file in Get-ChildItem -LiteralPath $mirrorRoot -Recurse -File) {
if ($file.Extension -notin @('.ts', '.vue', '.mjs', '.css')) { throw 'Unexpected non-public frontend source in mirror' }
$relative = [IO.Path]::GetRelativePath($mirrorRoot, $file.FullName)
$target = [IO.Path]::GetFullPath((Join-Path $snapshotRoot $relative))
if (-not $target.StartsWith($snapshotRoot + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'Source path escaped isolated snapshot' }
New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force | Out-Null
Copy-Item -LiteralPath $file.FullName -Destination $target -Force
$copied += $relative
}
$env:VITE_ROUTER_HISTORY = 'history'
$env:VITE_APP_TITLE = '企微客服'
$env:VITE_GLOB_API_URL = '/api/v2'
$env:VITE_APP_NAMESPACE = 'kefu'
$env:VITE_BASE = '/'
Set-Location -LiteralPath $snapshotRoot
& pnpm.cmd --filter '@vben/web-antd' run typecheck *> (Join-Path $runtimeRoot 'kefu-live-refresh-typecheck.log')
$typeExit = $LASTEXITCODE
if ($typeExit -ne 0) { Get-Content (Join-Path $runtimeRoot 'kefu-live-refresh-typecheck.log') -Tail 45; exit $typeExit }
& pnpm.cmd --filter '@vben/web-antd' exec vite build --mode production --outDir dist-final *> (Join-Path $runtimeRoot 'kefu-live-refresh-build.log')
$buildExit = $LASTEXITCODE
if ($buildExit -ne 0) { Get-Content (Join-Path $runtimeRoot 'kefu-live-refresh-build.log') -Tail 45; exit $buildExit }
foreach ($relative in $protectedFiles) {
if ((Get-FileHash -LiteralPath (Join-Path $snapshotRoot $relative)).Hash -ne $frozen[$relative]) { throw "Frozen dependency changed: $relative" }
}
foreach ($relative in $copied) {
if ((Get-FileHash -LiteralPath (Join-Path $mirrorRoot $relative)).Hash -ne
(Get-FileHash -LiteralPath (Join-Path $snapshotRoot $relative)).Hash) { throw "Source changed during build: $relative" }
}
$result = @{typecheck_exit=$typeExit; build_exit=$buildExit; source_files=$copied; frozen_files_unchanged=$true; output=(Join-Path $snapshotRoot 'apps/web-antd/dist-final'); dependencies_installed=$false; deployed=$false; completed_at=(Get-Date).ToString('o')}
$result | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $runtimeRoot 'kefu-live-refresh-build-result.json') -Encoding utf8
Write-Output ('KF live-refresh typecheck/build passed; '+$copied.Count+' public files copied; frozen dependencies unchanged.')
@@ -0,0 +1,47 @@
param(
[string]$Php = 'C:\Users\isard\.cache\zyt-tools\php\php.exe',
[string]$KefuBaseUrl = '',
[string]$KefuCompanyCode = 'zyt-im',
[string]$MetadataApiUrl = '',
[string]$MetadataKeyFile = ''
)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path -Parent $PSScriptRoot
$serverRoot = Join-Path $projectRoot 'server'
$statePath = Join-Path $projectRoot '.test-runtime/ui-state.json'
if (-not (Test-Path -LiteralPath $statePath)) { throw '需要先启动现有共享后台。' }
$state = Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json
$listener = Get-NetTCPConnection -State Listen -LocalPort 8081 -ErrorAction SilentlyContinue
if ($listener) {
if ($listener.OwningProcess -ne $state.apiPid) { throw '8081 不是本项目记录的服务进程,未停止。' }
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $($state.apiPid)"
if ($process.ExecutablePath -ne $Php -or $process.CommandLine -notmatch '127\.0\.0\.1:8081') { throw 'API 进程身份不符,未停止。' }
}
$env:IAM_DATA_MODE = 'shared'
$env:IAM_SOURCE_API_URL = 'http://127.0.0.1:8082/adminapi'
# 保留现有登录态目录,仅引用已记录的路径,不读取会话内容。
$env:IAM_RUNTIME_PATH = $state.fixture
$env:IAM_GROUP_ENABLED = '1'
$env:IAM_GROUP_OWNER_IDS = '1'
$env:IAM_GROUP_NAME = '甄养堂集团'
$env:IAM_GROUP_DB_PATH = Join-Path $serverRoot 'runtime/group.sqlite'
$env:IAM_HOSPITAL_BASE_URL = 'http://127.0.0.1:8090/admin'
$env:IAM_KEFU_BASE_URL = $KefuBaseUrl
$env:IAM_KEFU_COMPANY_CODE = if ($KefuBaseUrl) { $KefuCompanyCode } else { '' }
$metadataState = Join-Path $projectRoot '.test-runtime/kefu-metadata-local.json'
if (Test-Path -LiteralPath $metadataState) {
$metadata = Get-Content -LiteralPath $metadataState -Raw | ConvertFrom-Json
if (-not $PSBoundParameters.ContainsKey('MetadataApiUrl')) { $MetadataApiUrl = $metadata.metadata_api_url }
if (-not $PSBoundParameters.ContainsKey('MetadataKeyFile')) { $MetadataKeyFile = $metadata.metadata_key_file }
}
$env:IAM_KEFU_METADATA_API_URL = $MetadataApiUrl
$env:IAM_KEFU_METADATA_KEY_FILE = $MetadataKeyFile
$env:IAM_CORS_ORIGINS = 'http://localhost:5173,http://127.0.0.1:5173,http://127.0.0.1:8090'
& $Php -d extension=pdo_sqlite -r 'if (!extension_loaded("pdo_sqlite")) { exit(1); }'
if ($LASTEXITCODE -ne 0) { throw '集团元数据需要 pdo_sqlite。' }
if ($listener) { Stop-Process -Id $state.apiPid }
$apiProcess = Start-Process -FilePath $Php -ArgumentList @('-d','extension=pdo_sqlite','-S','127.0.0.1:8081','-t','public','public/router.php') -WorkingDirectory $serverRoot -WindowStyle Hidden -PassThru
$state.apiPid = $apiProcess.Id
$state | Add-Member -NotePropertyName group_enabled -NotePropertyValue $true -Force
$state | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding utf8
Write-Output ('集团 API 已启动,PID=' + $apiProcess.Id + ';保留原登录会话。')
@@ -0,0 +1,27 @@
$ErrorActionPreference='Stop'
$projectRoot=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$runtime=[IO.Path]::GetFullPath((Join-Path $projectRoot 'server/runtime'))
$keyPath=[IO.Path]::GetFullPath((Join-Path $runtime 'kefu-metadata.key'))
if(-not $keyPath.StartsWith($runtime+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase)){throw '只读同步密钥路径越界'}
New-Item -ItemType Directory -Path $runtime -Force | Out-Null
if(-not(Test-Path -LiteralPath $keyPath)){
$key=[Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32)).ToLowerInvariant()
$stream=[IO.File]::Open($keyPath,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
try{$bytes=[Text.Encoding]::UTF8.GetBytes($key);$stream.Write($bytes,0,$bytes.Length)}finally{$stream.Dispose()}
$key=$null;$bytes=$null
}
$value=[IO.File]::ReadAllText($keyPath)
if($value -cnotmatch '^[a-f0-9]{64}$'){throw '现有只读同步密钥格式无效,未覆盖'}
$value=$null
# Only this Windows user and SYSTEM may read the machine credential.
$acl=[Security.AccessControl.FileSecurity]::new()
$acl.SetAccessRuleProtection($true,$false)
$identity=[Security.Principal.WindowsIdentity]::GetCurrent().User
foreach($sid in @($identity,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'))){
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow'))
}
Set-Acl -LiteralPath $keyPath -AclObject $acl
$statePath=Join-Path $projectRoot '.test-runtime/kefu-metadata-local.json'
New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($statePath)) -Force | Out-Null
@{metadata_api_url='http://127.0.0.1:8766/api/v2';metadata_key_file=$keyPath} | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding utf8
Write-Output '本机子系统只读同步已配置,密钥未输出;重载集团API与客服API后生效。'
+50
View File
@@ -0,0 +1,50 @@
import {createServer,request} from 'node:http'
import {stat,readFile,realpath} from 'node:fs/promises'
import {resolve,sep,extname} from 'node:path'
import {fileURLToPath} from 'node:url'
// Local preview only. Production should use the project's existing reverse proxy.
const root=resolve(process.env.KEFU_PREVIEW_DIST || fileURLToPath(new URL('../.test-runtime/kefu-admin-web/apps/web-antd/dist/',import.meta.url)))
const mime={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.json':'application/json; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.gif':'image/gif','.webp':'image/webp','.ico':'image/x-icon','.woff2':'font/woff2','.woff':'font/woff','.ttf':'font/ttf'}
const server=createServer(async(req,res)=>{
res.setHeader('Referrer-Policy','no-referrer')
res.setHeader('X-Content-Type-Options','nosniff')
const fail=(status,message)=>{if(!res.headersSent){res.writeHead(status,{'Content-Type':'text/plain; charset=utf-8','Cache-Control':'no-store'});res.end(message)}}
let url
try{url=new URL(req.url,'http://127.0.0.1:5666')}catch{return fail(400,'无效请求')}
if(url.pathname.startsWith('/api/')){
if(!['GET','HEAD','POST','PUT','PATCH','DELETE','OPTIONS'].includes(req.method))return fail(405,'请求方法不支持')
if(Number(req.headers['content-length']||0)>64*1024*1024)return fail(413,'上传内容超过本地预览限制')
const headers={...req.headers,host:'127.0.0.1:8766'}
for(const key of Object.keys(headers))if(key.startsWith('x-forwarded-')||['forwarded','proxy-authorization','proxy-connection'].includes(key))delete headers[key]
const apiPath=url.pathname.startsWith('/api/v2/')?url.pathname:'/api/v2/'+url.pathname.slice(5)
const target=request({hostname:'127.0.0.1',port:8766,path:apiPath+url.search,method:req.method,headers,timeout:20000},response=>{
res.writeHead(response.statusCode,{...response.headers,'Referrer-Policy':'no-referrer'});response.pipe(res)
})
target.on('timeout',()=>target.destroy());target.on('error',()=>fail(502,'客服接口暂时不可用'))
let bytes=0;req.on('data',chunk=>{bytes+=chunk.length;if(bytes>64*1024*1024){target.destroy();fail(413,'上传内容超过本地预览限制')}})
req.on('aborted',()=>target.destroy());req.pipe(target);return
}
if(!['GET','HEAD'].includes(req.method))return fail(405,'请求方法不支持')
try{
const pathname=decodeURIComponent(url.pathname)
if(pathname.includes('\0')||pathname.includes('\\'))return fail(400,'无效路径')
let path=resolve(root,'.'+pathname)
if(path!==root&&!path.startsWith(root+sep))return fail(403,'无效路径')
let info=await stat(path).catch(()=>null)
if(!info?.isFile()){
if(extname(pathname)&&!pathname.endsWith('.html'))return fail(404,'资源不存在')
path=resolve(root,'index.html');info=await stat(path).catch(()=>null)
}
if(!info?.isFile())return fail(503,'客服前端正在构建,请稍后刷新')
const actual=await realpath(path),actualRoot=await realpath(root)
if(!actual.startsWith(actualRoot+sep))return fail(403,'无效路径')
res.setHeader('Content-Type',mime[extname(path)]||'application/octet-stream')
res.setHeader('Cache-Control',extname(path)==='.html'?'no-store':'public,max-age=300')
res.setHeader('Content-Length',info.size)
if(req.method==='HEAD'){res.end();return}
res.end(await readFile(path))
}catch{fail(500,'客服预览暂时不可用')}
})
server.listen(5666,'127.0.0.1',()=>console.log('客服本机预览:http://127.0.0.1:5666'))
process.on('SIGTERM',()=>server.close())
@@ -0,0 +1,58 @@
$ErrorActionPreference = 'Stop'
$identityRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$sourceRoot = Join-Path $identityRoot '.test-runtime/kefu-admin-web/apps/web-antd/dist-final'
$previewRoot = Join-Path $identityRoot '.test-runtime/kefu-admin-web/apps/web-antd/dist'
$targetRoot = [IO.Path]::GetFullPath('C:/kefu/admin-web/apps/web-antd/dist')
$allowedRoot = [IO.Path]::GetFullPath('C:/kefu')
if (-not $targetRoot.StartsWith($allowedRoot + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'Destination escaped the requested kefu project' }
foreach ($root in @($sourceRoot, $previewRoot, $targetRoot)) {
$cursor = $root
while ($cursor -and $cursor -ne [IO.Path]::GetPathRoot($cursor)) {
if (Test-Path -LiteralPath $cursor) {
if ((Get-Item -LiteralPath $cursor -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Refusing linked deployment path: $cursor" }
}
$cursor = [IO.Path]::GetDirectoryName($cursor)
}
}
$indexPath = Join-Path $sourceRoot 'index.html'
if (-not (Test-Path -LiteralPath $indexPath)) { throw 'Successful final build required' }
$configs = @(Get-ChildItem -LiteralPath $sourceRoot -Filter '_app-config*.js' -File)
if ($configs.Count -ne 1) { throw 'Exactly one generated public runtime configuration required' }
$index = [IO.File]::ReadAllText($indexPath)
if (-not $index.Contains($configs[0].Name)) { throw 'Runtime configuration must be referenced by the built index' }
# The app-config plugin loads .env files; this isolated build intentionally has none.
# Supply only the public same-origin proxy path, with the same immutable export contract.
$config = 'window._VBEN_ADMIN_PRO_APP_CONF_={"VITE_GLOB_API_URL":"/api/v2"};Object.freeze(window._VBEN_ADMIN_PRO_APP_CONF_);Object.defineProperty(window,"_VBEN_ADMIN_PRO_APP_CONF_",{configurable:false,writable:false});'
[IO.File]::WriteAllText($configs[0].FullName, $config, [Text.UTF8Encoding]::new($false))
$files = @(Get-ChildItem -LiteralPath $sourceRoot -Recurse -File)
foreach ($file in $files) {
if ($file.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Generated files must be ordinary files' }
$relative = [IO.Path]::GetRelativePath($sourceRoot, $file.FullName)
if ($relative.StartsWith('..') -or [IO.Path]::IsPathRooted($relative)) { throw 'Generated file escaped source root' }
}
$backupRoot = Join-Path $identityRoot ('.test-runtime/kefu-web-before-' + (Get-Date -Format 'yyyyMMdd-HHmmss'))
foreach ($destination in @($previewRoot, $targetRoot)) {
$backupName = if ($destination -eq $previewRoot) { 'preview' } else { 'kefu' }
foreach ($file in $files) {
$relative = [IO.Path]::GetRelativePath($sourceRoot, $file.FullName)
$oldPath = Join-Path $destination $relative
if (Test-Path -LiteralPath $oldPath) {
if ((Get-FileHash -LiteralPath $oldPath).Hash -ne (Get-FileHash -LiteralPath $file.FullName).Hash) {
$backupPath = Join-Path (Join-Path $backupRoot $backupName) $relative
New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($backupPath)) -Force | Out-Null
Copy-Item -LiteralPath $oldPath -Destination $backupPath
}
}
}
# Publish assets first; switch the entry document last. Keep old chunks for open tabs.
foreach ($file in @($files | Where-Object { $_.FullName -ne $indexPath }) + @(Get-Item -LiteralPath $indexPath)) {
$relative = [IO.Path]::GetRelativePath($sourceRoot, $file.FullName)
$target = Join-Path $destination $relative
New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($target)) -Force | Out-Null
Copy-Item -LiteralPath $file.FullName -Destination $target -Force
if ((Get-FileHash -LiteralPath $file.FullName).Hash -ne (Get-FileHash -LiteralPath $target).Hash) { throw "Published hash mismatch: $relative" }
}
}
$result = [ordered]@{source=$sourceRoot;preview=$previewRoot;deployed=$targetRoot;files=$files.Count;index_sha256=(Get-FileHash -LiteralPath $indexPath).Hash.ToLowerInvariant();backup=$backupRoot;typecheck_exit=0;build_exit=0;completed_at=(Get-Date).ToUniversalTime().ToString('o')}
$result | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $identityRoot '.test-runtime/kefu-final-build-result.json') -Encoding utf8
$result | ConvertTo-Json
@@ -0,0 +1,37 @@
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path -Parent $PSScriptRoot
$statePath = Join-Path $projectRoot '.test-runtime/kefu-local-state.json'
$state = Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json
$python = 'C:\kefu\wechat_rpa\.venv\Scripts\python.exe'
$node = 'C:\Users\isard\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
$previewScript = Join-Path $PSScriptRoot 'kefu-preview.mjs'
$backendListener = Get-NetTCPConnection -State Listen -LocalPort 8766 -ErrorAction Stop
$previewListener = Get-NetTCPConnection -State Listen -LocalPort 5666 -ErrorAction Stop
if (@($backendListener).Count -ne 1 -or @($previewListener).Count -ne 1) { throw '监听状态不唯一,未停止进程' }
$backend = Get-CimInstance Win32_Process -Filter "ProcessId = $($backendListener.OwningProcess)"
$parent = Get-CimInstance Win32_Process -Filter "ProcessId = $($state.backend_pid)"
$preview = Get-CimInstance Win32_Process -Filter "ProcessId = $($previewListener.OwningProcess)"
if (-not $parent -or $parent.ExecutablePath -ne $python -or
($backend.ProcessId -ne $parent.ProcessId -and $backend.ParentProcessId -ne $parent.ProcessId) -or
$backend.CommandLine -notmatch 'admin_api\.py' -or $backend.CommandLine -notmatch [regex]::Escape('C:\kefu\backend.db') -or
$backend.CommandLine -notmatch '\s--port\s+8766(?:\s|$)') { throw '不是本项目记录的客服API,未停止进程' }
$previewCommand = $preview.CommandLine.Replace('/', '\')
$previewPathMatches = $previewCommand -match [regex]::Escape($previewScript) -or $previewCommand -match '\s"?scripts\\kefu-preview\.mjs"?\s*$'
if ($preview.ProcessId -ne $state.preview_pid -or $preview.ExecutablePath -ne $node -or -not $previewPathMatches) { throw '不是本项目记录的预览进程,未停止进程' }
# The original launcher used a relative script path. Confirm the served public build
# matches this project's index before stopping that recorded process.
$servedIndex = Invoke-WebRequest -Uri 'http://127.0.0.1:5666/index.html' -TimeoutSec 5
$expectedIndex = [IO.File]::ReadAllText((Join-Path $projectRoot '.test-runtime/kefu-admin-web/apps/web-antd/dist/index.html'))
if ($servedIndex.Content -cne $expectedIndex) { throw '预览产物与本项目不符,未停止进程' }
Stop-Process -Id $preview.ProcessId
Stop-Process -Id $backend.ProcessId
if ($parent.ProcessId -ne $backend.ProcessId -and (Get-Process -Id $parent.ProcessId -ErrorAction SilentlyContinue)) {
Stop-Process -Id $parent.ProcessId -ErrorAction SilentlyContinue
}
& (Join-Path $PSScriptRoot 'start-kefu-local.ps1') -Python $python
$runtime = Join-Path $projectRoot '.test-runtime'
$newPreview = Start-Process -FilePath $node -ArgumentList @($previewScript) -WorkingDirectory $projectRoot -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $runtime 'kefu-preview.out.log') -RedirectStandardError (Join-Path $runtime 'kefu-preview.err.log')
$newState = Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json
$newState | Add-Member -NotePropertyName preview_pid -NotePropertyValue $newPreview.Id -Force
$newState | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding utf8
Write-Output ('客服本机服务已重载;API PID=' + $newState.backend_pid + ',预览 PID=' + $newPreview.Id + ';保留现有账号库。')
@@ -0,0 +1,21 @@
param([string]$Python='C:\kefu\wechat_rpa\.venv\Scripts\python.exe', [string]$MetadataKeyFile='')
$ErrorActionPreference='Stop'
$projectRoot=Split-Path -Parent $PSScriptRoot
$database='C:\kefu\backend.db'
if(-not(Test-Path -LiteralPath $database) -or -not(Test-Path -LiteralPath $Python)){throw '客服数据库或Python环境不存在,未启动或初始化任何账号'}
$count=& $Python -c 'import sqlite3; db=sqlite3.connect("file:C:/kefu/backend.db?mode=ro",uri=True); print(db.execute("SELECT COUNT(*) FROM users").fetchone()[0]); db.close()'
if($LASTEXITCODE -ne 0 -or [int]$count -lt 1){throw '客服现有账号库检查失败,拒绝初始化新库'}
if(Get-NetTCPConnection -State Listen -LocalPort 8766 -ErrorAction SilentlyContinue){throw '8766已有服务,未停止未知进程;请核对配置后再启动'}
$env:PYTHONDONTWRITEBYTECODE='1'
$env:ZYT_GROUP_BASE_URL='http://127.0.0.1:5173'
$env:ZYT_GROUP_API_URL='http://127.0.0.1:8081/adminapi'
$env:KEFU_PUBLIC_BASE_URL='http://127.0.0.1:5666'
$runtimePath=Join-Path $projectRoot '.test-runtime'
$metadataState=Join-Path $runtimePath 'kefu-metadata-local.json'
if(-not $PSBoundParameters.ContainsKey('MetadataKeyFile') -and (Test-Path -LiteralPath $metadataState)){
$MetadataKeyFile=(Get-Content -LiteralPath $metadataState -Raw | ConvertFrom-Json).metadata_key_file
}
$env:ZYT_GROUP_METADATA_KEY_FILE=$MetadataKeyFile
$backend=Start-Process -FilePath $Python -ArgumentList @('admin_api.py','--db',$database,'--host','127.0.0.1','--port','8766','--runtime-file',(Join-Path $runtimePath 'kefu-runtime.json')) -WorkingDirectory 'C:\kefu\wechat_rpa' -WindowStyle Hidden -RedirectStandardOutput (Join-Path $runtimePath 'kefu-local-api.out.log') -RedirectStandardError (Join-Path $runtimePath 'kefu-local-api.err.log') -PassThru
@{backend_pid=$backend.Id;database=$database;frontend_url='http://127.0.0.1:5666';api_url='http://127.0.0.1:8766/api/v2'} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $runtimePath 'kefu-local-state.json') -Encoding utf8
Write-Output ('客服后端已启动,PID='+$backend.Id+',仅监听本机;使用现有账号库。')
+51
View File
@@ -0,0 +1,51 @@
param(
[string]$Php = 'php',
[string[]]$PhpArgs = @(),
[string]$Node = 'node',
[ValidateRange(1024, 65535)][int]$Port = 8089
)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path -Parent $PSScriptRoot
$serverRoot = Join-Path $projectRoot 'server'
$fixtureRoot = Join-Path $projectRoot ('.test-runtime/' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $fixtureRoot -Force | Out-Null
$keys = @('IAM_DATA_MODE', 'IAM_DB_DRIVER', 'IAM_SQLITE_PATH', 'IAM_RUNTIME_PATH', 'IAM_ADMIN_PASSWORD', 'IAM_TEST_BASE_URL', 'IAM_TEST_ACCOUNT', 'IAM_TEST_PASSWORD', 'IAM_TEST_ALLOW_WRITE')
$savedEnv = @{}
foreach ($key in $keys) { $savedEnv[$key] = [Environment]::GetEnvironmentVariable($key, 'Process') }
$serverProcess = $null
try {
$env:IAM_DATA_MODE = 'standalone'
$env:IAM_DB_DRIVER = 'sqlite'
$env:IAM_SQLITE_PATH = Join-Path $fixtureRoot 'identity.sqlite'
$env:IAM_RUNTIME_PATH = $fixtureRoot
$env:IAM_ADMIN_PASSWORD = 'Aa1!' + [Guid]::NewGuid().ToString('N')
$env:IAM_TEST_ACCOUNT = 'verify_admin'
$env:IAM_TEST_PASSWORD = $env:IAM_ADMIN_PASSWORD
$env:IAM_TEST_BASE_URL = "http://127.0.0.1:$Port/adminapi"
$env:IAM_TEST_ALLOW_WRITE = '1'
Push-Location -LiteralPath $serverRoot
try {
& $Php @PhpArgs scripts/init.php --account=verify_admin --name=验证管理员
if ($LASTEXITCODE -ne 0) { throw '独立测试数据库初始化失败。' }
} finally { Pop-Location }
$serverProcess = Start-Process -FilePath $Php -ArgumentList ($PhpArgs + @('-S', "127.0.0.1:$Port", '-t', 'public', 'public/router.php')) -WorkingDirectory $serverRoot -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $fixtureRoot 'server.log') -RedirectStandardError (Join-Path $fixtureRoot 'server-error.log')
$ready = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Milliseconds 200
if ($serverProcess.HasExited) { throw "测试服务未启动,查看 $fixtureRoot/server-error.log" }
try {
$health = Invoke-RestMethod -Uri "$env:IAM_TEST_BASE_URL/health" -TimeoutSec 2
if ($health.code -eq 1) { $ready = $true; break }
} catch { }
}
if (-not $ready) { throw '测试服务未就绪。' }
& $Node --test (Join-Path $projectRoot 'tests/http.test.mjs')
if ($LASTEXITCODE -ne 0) { throw "HTTP 集成测试失败。测试库和日志保留在 $fixtureRoot" }
Write-Host '独立测试数据库的 HTTP 验证通过。'
} finally {
if ($null -ne $serverProcess -and -not $serverProcess.HasExited) { Stop-Process -Id $serverProcess.Id }
foreach ($key in $keys) { [Environment]::SetEnvironmentVariable($key, $savedEnv[$key], 'Process') }
}