Files
weiguang-jewelry-ledger/新账系统/e2e/lib/normalize.js
T

26 lines
1.6 KiB
JavaScript

'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};