'use strict'; // 验证工具专用:用 node --require 预加载,只影响本进程。 // 固定 Date 与 crypto 随机源,使 today()、时间戳、ID、盐与会话令牌在两次相同运行中完全一致。 // 环境变量: // FAKE_CLOCK_START 起始时刻(ISO,默认 2026-11-20T02:00:00.000Z,即上海 10:00) // FAKE_CLOCK_TICK_MS 每次读取时钟后前进的毫秒数(默认 0:时钟只在控制端设置时变化) // FAKE_RANDOM_SEED 随机种子(默认 golden-seed) // FAKE_CLOCK_IPC=1 通过 process.send 通道接受 {type:'fake-clock',op,ms,id} 控制消息 const crypto=require('node:crypto'); const RealDate=Date; let current=RealDate.parse(process.env.FAKE_CLOCK_START||'2026-11-20T02:00:00.000Z'); if(!Number.isFinite(current))throw new Error('FAKE_CLOCK_START 无效'); let tick=Number(process.env.FAKE_CLOCK_TICK_MS||0); function read(){const value=current;current+=tick;return value;} function FakeDate(...args){ if(!new.target)return new RealDate(read()).toString(); return Reflect.construct(RealDate,args.length?args:[read()],new.target); } Object.setPrototypeOf(FakeDate,RealDate); FakeDate.prototype=RealDate.prototype; FakeDate.now=()=>read(); FakeDate.parse=RealDate.parse; FakeDate.UTC=RealDate.UTC; Object.defineProperty(RealDate.prototype,'constructor',{value:FakeDate,writable:true,configurable:true}); globalThis.Date=FakeDate; // 计数器式 SHA-256 流,按调用顺序输出确定字节。 const seed=process.env.FAKE_RANDOM_SEED||'golden-seed'; let counter=0,pool=Buffer.alloc(0); function bytes(n){ while(pool.lengthbytes(6).readUIntBE(0,6)/2**48; const control={ now:()=>current, set(ms){if(!Number.isFinite(ms))throw new Error('无效时刻');current=ms;}, advance(ms){current+=ms;}, setTick(ms){tick=ms;}, RealDate, }; globalThis.__fakeClock=control; if(process.env.FAKE_CLOCK_IPC==='1'&&typeof process.send==='function'){ process.on('message',message=>{ if(!message||message.type!=='fake-clock')return; try{ if(message.op==='set')control.set(message.ms); else if(message.op==='advance')control.advance(message.ms); else if(message.op==='tick')control.setTick(message.ms); process.send({type:'fake-clock-ack',id:message.id,now:current}); }catch(error){process.send({type:'fake-clock-ack',id:message.id,error:error.message});} }); }