import { afterEach,describe,expect,it } from 'vitest' import { newOperationID } from './operationKey' const uuidPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ const originalCrypto=globalThis.crypto afterEach(()=>{ Object.defineProperty(globalThis,'crypto',{value:originalCrypto,configurable:true,writable:true}) }) describe('newOperationID',()=>{ it('uses crypto.randomUUID when available (secure context)',()=>{ expect(newOperationID()).toMatch(uuidPattern) }) it('falls back to getRandomValues over plain-HTTP LAN (insecure context)',()=>{ const randomUUID=globalThis.crypto?.randomUUID Object.defineProperty(globalThis,'crypto',{configurable:true,value:{randomUUID:undefined,getRandomValues:(buffer:Uint8Array)=>{const source=new Uint8Array([0x6f,0x1a,0x2b,0x3c,0x4d,0x5e,0x6f,0x70,0x81,0x92,0xa3,0xb4,0xc5,0xd6,0xe7,0xf8]);buffer.set(source);return buffer}}}) try{ const id=newOperationID() // version nibble forced to 4 and variant bits to 10x: 0x6f->0x4f, 0x81->0x81 expect(id).toBe('6f1a2b3c-4d5e-4f70-8192-a3b4c5d6e7f8') expect(id).toMatch(uuidPattern) }finally{ void randomUUID } }) it('refuses to fabricate an identifier when no CSPRNG exists',()=>{ Object.defineProperty(globalThis,'crypto',{configurable:true,value:{randomUUID:undefined,getRandomValues:undefined}}) expect(()=>newOperationID()).toThrow('当前环境无法安全生成操作标识') }) })