48 lines
1.9 KiB
JavaScript
48 lines
1.9 KiB
JavaScript
const assert = require('node:assert/strict');
|
|
const {readFileSync} = require('node:fs');
|
|
const {webcrypto} = require('node:crypto');
|
|
const vm = require('node:vm');
|
|
const script = readFileSync('static/js/uuid.js', 'utf8');
|
|
const run = crypto => { const context = vm.createContext({crypto}); vm.runInContext(script, context); return context; };
|
|
|
|
const native = () => 'native';
|
|
const supported = {randomUUID: native};
|
|
run(supported);
|
|
assert.equal(supported.randomUUID, native, 'do not replace native implementations');
|
|
|
|
let calls = 0;
|
|
const fallback = {getRandomValues(bytes) {
|
|
assert.equal(this, fallback, 'preserve Web Crypto receiver');
|
|
assert.equal(bytes.length, 16);
|
|
calls++;
|
|
bytes.fill(0xff);
|
|
return bytes;
|
|
}};
|
|
const context = run(fallback);
|
|
assert.equal(fallback.randomUUID(), 'ffffffff-ffff-4fff-bfff-ffffffffffff');
|
|
assert.equal(calls, 1);
|
|
const installed = fallback.randomUUID;
|
|
vm.runInContext(script, context);
|
|
assert.equal(fallback.randomUUID, installed, 'loading twice must be harmless');
|
|
|
|
const zeros = {getRandomValues: bytes => { bytes.fill(0); return bytes; }};
|
|
run(zeros);
|
|
assert.equal(zeros.randomUUID(), '00000000-0000-4000-8000-000000000000');
|
|
const real = {getRandomValues: bytes => webcrypto.getRandomValues(bytes)};
|
|
run(real);
|
|
const ids = new Set();
|
|
for (let i = 0; i < 10000; i++) {
|
|
const id = real.randomUUID();
|
|
assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
|
assert.ok(!ids.has(id), 'unexpected UUID collision');
|
|
ids.add(id);
|
|
}
|
|
const unavailable = {};
|
|
run(unavailable);
|
|
assert.equal(unavailable.randomUUID, undefined, 'do not fabricate insecure randomness');
|
|
run(undefined);
|
|
const broken = {getRandomValues() { throw new Error('entropy unavailable'); }};
|
|
run(broken);
|
|
assert.throws(() => broken.randomUUID(), /entropy unavailable/);
|
|
console.log('UUID compatibility: native, fallback, v4 bits, uniqueness and fail-closed checks passed');
|