crypto-globals.spec.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * The crypto global patch and the shim UUID it installs: on an insecure
  3. * origin the platform withholds `crypto.randomUUID` while product code calls
  4. * it off the global, so the worker fills the one missing method — and leaves
  5. * a platform that already has it untouched.
  6. */
  7. import { afterEach, describe, expect, it, vi } from 'vitest'
  8. import { installCryptoGlobals } from '../../src/node/globals/crypto.ts'
  9. import { randomUUID } from '../../src/node/builtin_modules/implemented/crypto.ts'
  10. const V4_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
  11. describe('the shim randomUUID', () => {
  12. it('emits RFC 9562 v4 ids without touching the platform method', () => {
  13. for (let round = 0; round < 32; round += 1) expect(randomUUID()).toMatch(V4_SHAPE)
  14. expect(new Set(Array.from({ length: 32 }, () => randomUUID())).size).toBe(32)
  15. })
  16. })
  17. describe('installCryptoGlobals', () => {
  18. afterEach(() => { vi.unstubAllGlobals() })
  19. it('fills randomUUID on a crypto that lacks it, the insecure-origin shape', () => {
  20. const bare = { getRandomValues: globalThis.crypto.getRandomValues.bind(globalThis.crypto) }
  21. vi.stubGlobal('crypto', bare)
  22. installCryptoGlobals()
  23. expect((globalThis.crypto as Crypto).randomUUID()).toMatch(V4_SHAPE)
  24. })
  25. it('leaves a platform that already provides randomUUID untouched', () => {
  26. const platform = (): string => 'platform-owned'
  27. vi.stubGlobal('crypto', { randomUUID: platform })
  28. installCryptoGlobals()
  29. expect(globalThis.crypto.randomUUID).toBe(platform)
  30. })
  31. })