发布 0.2.1 并完善工具边界与安全性
This commit is contained in:
+32
-2
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatBytes } from '../src/lib/bytes'
|
||||
import { secureRandomBytes, type RandomSource } from '../src/lib/random'
|
||||
import {
|
||||
DEFAULT_RANDOM_BYTES,
|
||||
MAX_RANDOM_BYTES,
|
||||
MIN_RANDOM_BYTES,
|
||||
secureRandomBytes,
|
||||
type RandomSource,
|
||||
} from '../src/lib/random'
|
||||
|
||||
describe('secure random bytes', () => {
|
||||
it('uses the supplied cryptographic source and preserves requested length', () => {
|
||||
@@ -12,8 +18,32 @@ describe('secure random bytes', () => {
|
||||
return array
|
||||
},
|
||||
}
|
||||
expect(DEFAULT_RANDOM_BYTES).toBe(16)
|
||||
expect(secureRandomBytes(4, source)).toEqual(Uint8Array.from([0, 1, 2, 3]))
|
||||
expect(() => secureRandomBytes(0, source)).toThrow('1 至 65536')
|
||||
})
|
||||
|
||||
it.each([0, -1, 1.5, Number.NaN, MAX_RANDOM_BYTES + 1])('rejects invalid length %s', (length) => {
|
||||
expect(() => secureRandomBytes(length, crypto)).toThrow(`${MIN_RANDOM_BYTES} 至 ${MAX_RANDOM_BYTES}`)
|
||||
})
|
||||
|
||||
it('accepts both length boundaries without exceeding the browser call limit', () => {
|
||||
const calls: number[] = []
|
||||
const source: RandomSource = {
|
||||
getRandomValues<T extends ArrayBufferView>(array: T): T {
|
||||
calls.push(array.byteLength)
|
||||
return array
|
||||
},
|
||||
}
|
||||
expect(secureRandomBytes(MIN_RANDOM_BYTES, source)).toHaveLength(MIN_RANDOM_BYTES)
|
||||
expect(secureRandomBytes(MAX_RANDOM_BYTES, source)).toHaveLength(MAX_RANDOM_BYTES)
|
||||
expect(calls).toEqual([MIN_RANDOM_BYTES, MAX_RANDOM_BYTES])
|
||||
})
|
||||
|
||||
it('fails closed when the cryptographic source is unavailable or throws', () => {
|
||||
expect(() => secureRandomBytes(DEFAULT_RANDOM_BYTES, null as unknown as RandomSource)).toThrow('不支持安全随机数')
|
||||
const failure = new Error('entropy source failed')
|
||||
const source: RandomSource = { getRandomValues: () => { throw failure } }
|
||||
expect(() => secureRandomBytes(DEFAULT_RANDOM_BYTES, source)).toThrow(failure)
|
||||
})
|
||||
|
||||
it('formats the same bytes for OpenSSL and source-code styles', () => {
|
||||
|
||||
Reference in New Issue
Block a user