验证基线:端到端黄金对照、浏览器流程与旧库兼容检查

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 08:37:28 -08:00
1 parent adc0ca88d4
commit 91479fd13f
77 files changed
+225508

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
'use strict';
// HTTP 驱动与记录器:每次请求前把子进程时钟设为“当天起点 + 步数秒”,保证时间戳只取决于步骤顺序。
const {unzip}=require('./zip');
const SHANGHAI_OFFSET=8*3600*1000;
class Session{
constructor({base,server,startDate,startHour=10}){
this.base=base;this.server=server;this.cookies={};this.users={};this.entries=[];this.seq=0;this.keySeq=0;this.problems=[];this.secrets=[];
this.dayStart=null;this.stepInDay=0;this.startHour=startHour;this.date=null;if(startDate)this.pendingDay=startDate;
}
// 把业务“今天”切换到上海时区某日的 startHour 点,之后每次请求前进 1 秒。
async day(date,hour=this.startHour){
this.date=date;this.dayStart=Date.parse(date+'T00:00:00Z')-SHANGHAI_OFFSET+hour*3600*1000;this.stepInDay=0;
await this.server.setTime(this.dayStart);this.note('clock',{date,hour});
}
note(kind,data){this.entries.push({seq:++this.seq,note:kind,...data});}
key(label='op'){this.keySeq++;return ('golden-'+String(this.keySeq).padStart(5,'0')+'-'+String(label).replace(/[^A-Za-z0-9_-]/g,'').slice(0,40)).padEnd(16,'0');}
async tickClock(){this.stepInDay++;await this.server.setTime(this.dayStart+this.stepInDay*1000);}
// 通用请求。opts: {body, key, headers, noOrigin, noXRW, origin, contentType, label, expect, record:'full'|'status'}
async request(actor,method,path,opts={}){
await this.tickClock();
const isPost=method==='POST';const headers={};
const cookie=actor&&this.cookies[actor];if(cookie)headers.Cookie=cookie;
let key=null;
if(isPost){
if(!opts.noOrigin)headers.Origin=opts.origin||this.base;
if(!opts.noXRW)headers['X-Requested-With']='maimai-ledger';
headers['Content-Type']=opts.contentType||'application/json';
key=opts.key===undefined?this.key(opts.label||path.split('/').filter(Boolean).slice(-1)[0]):opts.key;
if(key!==null)headers['Idempotency-Key']=key;
}
Object.assign(headers,opts.headers||{});
const response=await fetch(this.base+path,{method,headers,...(isPost?{body:typeof opts.body==='string'?opts.body:JSON.stringify(opts.body??{})}:{})});
const type=response.headers.get('content-type')||'';const buffer=Buffer.from(await response.arrayBuffer());
let body;
if(opts.record==='status')body={omitted:true,bytes:buffer.length>0};
else if(type.includes('application/json')){try{body=JSON.parse(buffer.toString('utf8'));}catch{body={invalidJson:buffer.toString('utf8')};}}
else if(type.includes('spreadsheetml')||type.includes('zip')){body={zip:unzip(buffer).map(f=>({name:f.name,text:f.data.toString('utf8')}))};}
else if(type.startsWith('text/'))body={text:buffer.toString('utf8')};
else body={binaryBytes:buffer.length};
const setCookie=response.headers.get('set-cookie');
if(setCookie&&actor){const token=setCookie.split(';')[0];if(/mm_session=[0-9a-f]+/.test(token)){this.cookies[actor]=token;this.secrets.push(token.slice(11));}else if(/mm_session=;/.test(setCookie+';'))delete this.cookies[actor];}
const entry={seq:++this.seq,label:opts.label||null,date:this.date,actor:actor||null,method,path,key,
request:isPost?{headers:{origin:headers.Origin??null,xrw:headers['X-Requested-With']??null,contentType:headers['Content-Type']},body:opts.body??{}}:undefined,
status:response.status,contentType:type,disposition:response.headers.get('content-disposition'),setCookie:setCookie?setCookie.replace(/mm_session=[0-9a-f]+/,'mm_session=<session>'):null,body};
this.entries.push(entry);
if(process.env.GOLDEN_PROBE&&isPost&&this.cookies.owner&&!this.probeFailed){
// 调试用:每次写入后以老板身份读取指定地址,报告第一次失败的步骤(不计入记录)。
const probe=await fetch(this.base+process.env.GOLDEN_PROBE,{headers:{Cookie:this.cookies.owner}});
if(probe.status!==200){this.probeFailed=true;console.error('探测失败于 #'+entry.seq,actor,method,path,opts.label,await probe.text());}
}
const expect=opts.expect??200;
if(expect!=='any'&&!(Array.isArray(expect)?expect:[expect]).includes(response.status))this.problems.push(`#${entry.seq} ${actor} ${method} ${path} 期望 ${expect} 实际 ${response.status} ${JSON.stringify(body).slice(0,300)}`);
return {status:response.status,body,json:type.includes('json')?body:null,headers:response.headers};
}
get(actor,path,opts){return this.request(actor,'GET',path,opts).then(r=>r.json??r.body);}
getRaw(actor,path,opts){return this.request(actor,'GET',path,opts);}
post(actor,path,body,opts={}){return this.request(actor,'POST',path,{...opts,body}).then(r=>r.json??r.body);}
postRaw(actor,path,body,opts={}){return this.request(actor,'POST',path,{...opts,body});}
}
module.exports={Session};
+26
View File
@@ -0,0 +1,26 @@
'use strict';
// 完整数据库转储:每张表的建表语句、列、索引,以及按 rowid 排序的全部行和全部列。
const {DatabaseSync}=require('node:sqlite');
function cell(value){
if(value instanceof Uint8Array)return {blob:Buffer.from(value).toString('hex')};
if(typeof value==='bigint')return {bigint:value.toString()};
return value;
}
function dumpDatabase(filename,{mask={}}={}){
const db=new DatabaseSync(filename,{readOnly:true});
try{
const master=db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_autoindex_%' ORDER BY type,name").all();
const tables={};
for(const {name,sql} of master.filter(row=>row.type==='table')){
const columns=db.prepare(`PRAGMA table_info("${name.replace(/"/g,'""')}")`).all().map(c=>c.name);
const withoutRowid=/WITHOUT\s+ROWID/i.test(sql||'');
const order=withoutRowid?columns.map((_,i)=>i+1).join(','):'rowid';
const rows=db.prepare(`SELECT * FROM "${name.replace(/"/g,'""')}" ORDER BY ${order}`).all().map(row=>columns.map(c=>{
const masker=mask[name]?.[c];return masker?masker(row[c],row):cell(row[c]);
}));
tables[name]={columns,rows};
}
return {schema:master.map(({type,name,tbl_name,sql})=>({type,name,table:tbl_name,sql})),tables};
}finally{db.close();}
}
module.exports={dumpDatabase};
+40
View File
@@ -0,0 +1,40 @@
'use strict';
// 语义比较:对象键顺序不计入差异(另行提示),数组顺序与所有值严格比较。
function short(v){const s=JSON.stringify(v);return s===undefined?'undefined':s.length>300?s.slice(0,300)+'…':s;}
function compare(expected,actual,path='$',out={diffs:[],orderNotes:[]}){
if(Object.is(expected,actual))return out;
const te=Array.isArray(expected)?'array':expected===null?'null':typeof expected,ta=Array.isArray(actual)?'array':actual===null?'null':typeof actual;
if(te!==ta){out.diffs.push({path,expected:short(expected),actual:short(actual)});return out;}
if(te==='array'){
const n=Math.max(expected.length,actual.length);
if(expected.length!==actual.length)out.diffs.push({path:path+'.length',expected:String(expected.length),actual:String(actual.length)});
for(let i=0;i<Math.min(expected.length,actual.length);i++)compare(expected[i],actual[i],path+'['+i+']',out);
for(let i=Math.min(expected.length,actual.length);i<n&&out.diffs.length<100000;i++)out.diffs.push({path:path+'['+i+']',expected:short(expected[i]),actual:short(actual[i])});
return out;
}
if(te==='object'){
const ke=Object.keys(expected),ka=Object.keys(actual);
for(const k of ke)if(!(k in actual))out.diffs.push({path:path+'.'+k,expected:short(expected[k]),actual:'(缺失)'});
for(const k of ka)if(!(k in expected))out.diffs.push({path:path+'.'+k,expected:'(缺失)',actual:short(actual[k])});
for(const k of ke)if(k in actual)compare(expected[k],actual[k],path+'.'+k,out);
const common=ke.filter(k=>k in actual),commonActual=ka.filter(k=>k in expected);
if(common.join('\u0000')!==commonActual.join('\u0000'))out.orderNotes.push(path);
return out;
}
if(te==='string'&&expected.length>120){
// 长字符串只显示首个不同字符附近的片段
let i=0;while(i<expected.length&&expected[i]===actual[i])i++;const from=Math.max(0,i-60);
out.diffs.push({path:path+` @字符${i}`,expected:(from?'…':'')+JSON.stringify(expected.slice(from,i+120)).slice(1,-1)+(i+120<expected.length?'…':''),actual:(from?'…':'')+JSON.stringify(actual.slice(from,i+120)).slice(1,-1)+(i+120<actual.length?'…':'')});return out;
}
out.diffs.push({path,expected:short(expected),actual:short(actual)});return out;
}
function report(name,result,limit=30,describe=p=>p){
const lines=[];
if(result.diffs.length){
lines.push(`${name}:发现 ${result.diffs.length} 处差异,前 ${Math.min(limit,result.diffs.length)} 处:`);
for(const d of result.diffs.slice(0,limit))lines.push(` ${describe(d.path)}\n 基线:${d.expected}\n 实际:${d.actual}`);
}
if(result.orderNotes.length)lines.push(`${name}:${result.orderNotes.length} 处对象键顺序变化(不计为失败),例如 ${result.orderNotes.slice(0,3).join('、')}`);
return lines.join('\n');
}
module.exports={compare,report};
+25
View File
@@ -0,0 +1,25 @@
'use strict';
// 规范化:按首次出现顺序把随机标识映射为占位符,屏蔽会话令牌、密码哈希、盐和备份文件名。
// 时钟与随机源已固定,因此只做最少屏蔽,避免掩盖真实回归。
const UUID=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
const ORDER_NUMBER=/\b([A-Z]{2})(\d{8})-([0-9A-F]{8})\b/g;
const BACKUP=/ledger-(?:before-[a-z0-9-]+?-)?\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z(?:-[0-9a-f]{8})?\.sqlite/g;
class Normalizer{
constructor(){this.maps={id:new Map(),no:new Map(),secret:new Map()};this.literals=[];}
literal(raw,masked){if(raw)this.literals.push([raw,masked]);}
token(kind,value,prefix){const map=this.maps[kind];if(!map.has(value))map.set(value,`<${prefix}${map.size+1}>`);return map.get(value);}
secret(value){return value?this.token('secret',value,'secret'):value;}
string(s){
if(typeof s!=='string')return s;
for(const [raw,masked] of this.literals)if(s.includes(raw))s=s.split(raw).join(masked);
for(const [raw,masked] of this.maps.secret)if(raw&&s.includes(raw))s=s.split(raw).join(masked);
return s.replace(BACKUP,'<backup-file>').replace(UUID,m=>this.token('id',m.toLowerCase(),'id')).replace(ORDER_NUMBER,(m,prefix,date,hex)=>prefix+date+'-'+this.token('no',hex,'no'));
}
value(v){
if(typeof v==='string')return this.string(v);
if(Array.isArray(v))return v.map(x=>this.value(x));
if(v&&typeof v==='object'){const out={};for(const [k,x] of Object.entries(v))out[this.string(k)]=this.value(x);return out;}
return v;
}
}
module.exports={Normalizer,UUID};
+29
View File
@@ -0,0 +1,29 @@
'use strict';
// 由 lib/server.js 以 fork + --require fake-clock.cjs 启动;只通过 IPC 接受启动/停止指令。
// 启动参数来自环境变量 E2E_SERVER_OPTIONS(JSON):{mode,dataDir,startup:'create'|'production'}
const path=require('node:path');
const appDir=path.join(__dirname,'..','..');
const options=JSON.parse(process.env.E2E_SERVER_OPTIONS||'{}');
const send=message=>process.send&&process.send(message);
let app=null;
async function start(){
const server=require(path.join(appDir,'server.js'));
let startup={};
if(options.startup==='production'){
// 与 server.js 正式入口一致:先备份升级前旧库,再 createApp,再显式迁移,最后监听。
startup.team=await server.prepareTeamStartupDatabase(options.dataDir);
app=server.createApp({mode:options.mode,dataDir:options.dataDir,host:'127.0.0.1',port:0});
startup.migration=await server.prepareStartupMigrations(app);
}else{
app=server.createApp({mode:options.mode||'trial',dataDir:options.dataDir,host:'127.0.0.1',port:0,inventorySnapshotLogger:()=>{}});
}
await new Promise((resolve,reject)=>{app.server.once('error',reject);app.server.listen(0,'127.0.0.1',resolve);});
send({type:'ready',port:app.server.address().port,startup});
}
process.on('message',async message=>{
if(message?.type!=='stop')return;
try{if(app){app.stop();app.ledger.close();}}catch(error){send({type:'log',message:'stop: '+error.message});}
send({type:'stopped'});setTimeout(()=>process.exit(0),20);
});
process.on('disconnect',()=>process.exit(0));
start().catch(error=>{send({type:'fatal',message:error.stack||String(error)});setTimeout(()=>process.exit(1),20);});
+35
View File
@@ -0,0 +1,35 @@
'use strict';
// 父进程侧:以确定时钟启动应用子进程,提供时钟控制与停止。
const {fork}=require('node:child_process');
const path=require('node:path');
const CLOCK=path.join(__dirname,'..','fake-clock.cjs');
function startServer({mode='trial',dataDir,startup='create',clockStart,seed='golden-seed',tickMs=0,quiet=true}={}){
const child=fork(path.join(__dirname,'server-child.cjs'),[],{
// E2E_MUTATION_REQUIRE:仅用于自检,额外预加载一个故意改变行为的脚本,确认对照能发现回归。
execArgv:['--require',CLOCK,...(process.env.E2E_MUTATION_REQUIRE?['--require',process.env.E2E_MUTATION_REQUIRE]:[]),'--disable-warning=ExperimentalWarning'],
env:{...process.env,TZ:'Asia/Shanghai',FAKE_CLOCK_IPC:'1',FAKE_CLOCK_START:clockStart||'2026-11-20T02:00:00.000Z',FAKE_RANDOM_SEED:seed,FAKE_CLOCK_TICK_MS:String(tickMs),
FEISHU_CONFIG:path.join(dataDir,'no-feishu.json'),APP_MODE:mode,E2E_SERVER_OPTIONS:JSON.stringify({mode,dataDir,startup})},
stdio:['ignore',quiet?'pipe':'inherit',quiet?'pipe':'inherit','ipc'],
});
let output='';if(quiet){child.stdout.on('data',d=>{output+=d;});child.stderr.on('data',d=>{output+=d;});}
let seq=0;const waiting=new Map();let readyResolve,readyReject;
const ready=new Promise((resolve,reject)=>{readyResolve=resolve;readyReject=reject;});
let stoppedResolve;const stopped=new Promise(resolve=>{stoppedResolve=resolve;});
child.on('message',message=>{
if(message.type==='ready')readyResolve(message);
else if(message.type==='fatal')readyReject(new Error('应用启动失败:'+message.message+'\n'+output));
else if(message.type==='fake-clock-ack'){const w=waiting.get(message.id);waiting.delete(message.id);if(w)message.error?w.reject(new Error(message.error)):w.resolve(message.now);}
else if(message.type==='stopped')stoppedResolve();
});
child.on('exit',code=>{readyReject(new Error('应用子进程退出 '+code+'\n'+output));stoppedResolve();for(const w of waiting.values())w.reject(new Error('应用子进程已退出'));});
const clock=(op,ms)=>new Promise((resolve,reject)=>{const id=++seq;waiting.set(id,{resolve,reject});child.send({type:'fake-clock',op,ms,id});});
return {
child,
async ready(){const info=await ready;return {...info,base:'http://127.0.0.1:'+info.port};},
setTime:ms=>clock('set',ms),
advance:ms=>clock('advance',ms),
output:()=>output,
async stop(){if(child.exitCode!==null)return;child.send({type:'stop'});await Promise.race([stopped,new Promise(r=>setTimeout(r,5000))]);if(child.exitCode===null)child.kill();},
};
}
module.exports={startServer};
+19
View File
@@ -0,0 +1,19 @@
'use strict';
// 最小 ZIP 读取器(xlsx 用),只支持 stored/deflate。返回 [{name,data:Buffer}],按中央目录顺序。
const zlib=require('node:zlib');
function unzip(buffer){
let eocd=-1;for(let i=buffer.length-22;i>=Math.max(0,buffer.length-65557);i--)if(buffer.readUInt32LE(i)===0x06054b50){eocd=i;break;}
if(eocd<0)throw new Error('不是有效的 ZIP 文件');
const count=buffer.readUInt16LE(eocd+10);let offset=buffer.readUInt32LE(eocd+16);const files=[];
for(let n=0;n<count;n++){
if(buffer.readUInt32LE(offset)!==0x02014b50)throw new Error('ZIP 中央目录损坏');
const method=buffer.readUInt16LE(offset+10),compressed=buffer.readUInt32LE(offset+20),nameLength=buffer.readUInt16LE(offset+28),extraLength=buffer.readUInt16LE(offset+30),commentLength=buffer.readUInt16LE(offset+32),local=buffer.readUInt32LE(offset+42);
const name=buffer.subarray(offset+46,offset+46+nameLength).toString('utf8');
const localName=buffer.readUInt16LE(local+26),localExtra=buffer.readUInt16LE(local+28),start=local+30+localName+localExtra;
const raw=buffer.subarray(start,start+compressed);
const data=method===0?Buffer.from(raw):method===8?zlib.inflateRawSync(raw):(()=>{throw new Error('不支持的压缩方式 '+method);})();
files.push({name,data});offset+=46+nameLength+extraLength+commentLength;
}
return files;
}
module.exports={unzip};