@awacloud/fw 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (609) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/NOTICE +8 -0
  3. package/README.md +163 -31
  4. package/dist/build/fw.core.pure.meta.json +6 -6
  5. package/dist/build/fw.core.pure.min.js +15 -12
  6. package/dist/build/fw.full.pure.meta.json +13 -7
  7. package/dist/build/fw.full.pure.min.js +45 -42
  8. package/dist/build/fw.minimal.pure.meta.json +6 -6
  9. package/dist/build/fw.minimal.pure.min.js +16 -13
  10. package/dist/build/fw.pack.compress-heavy.pure.meta.json +6 -6
  11. package/dist/build/fw.pack.compress-heavy.pure.min.js +3 -3
  12. package/dist/build/fw.pack.crypto-advanced.pure.meta.json +6 -6
  13. package/dist/build/fw.pack.crypto-advanced.pure.min.js +1 -1
  14. package/dist/build/fw.pack.crypto-basic.pure.meta.json +6 -6
  15. package/dist/build/fw.pack.crypto-basic.pure.min.js +1 -1
  16. package/dist/build/fw.pack.crypto-identity.pure.meta.json +7 -6
  17. package/dist/build/fw.pack.crypto-identity.pure.min.js +4 -4
  18. package/dist/build/fw.pwa.pure.meta.json +7 -6
  19. package/dist/build/fw.pwa.pure.min.js +38 -35
  20. package/dist/build/fw.site-interactive.pure.meta.json +6 -6
  21. package/dist/build/fw.site-interactive.pure.min.js +37 -34
  22. package/dist/build/fw.site.pure.meta.json +6 -6
  23. package/dist/build/fw.site.pure.min.js +24 -21
  24. package/dist/build/fw.spa.pure.meta.json +8 -7
  25. package/dist/build/fw.spa.pure.min.js +41 -38
  26. package/dist/build/sanity-base-classic.min.js +1 -1
  27. package/dist/build/sanity.min.js +1 -1
  28. package/dist/types/core/internal.d.ts +29 -0
  29. package/dist/types/core/internal.d.ts.map +1 -0
  30. package/dist/types/core/logger.d.ts +23 -4
  31. package/dist/types/core/logger.d.ts.map +1 -1
  32. package/dist/types/core/modules.d.ts +374 -61
  33. package/dist/types/core/modules.d.ts.map +1 -1
  34. package/dist/types/core/runtime.d.ts +10 -6
  35. package/dist/types/core/runtime.d.ts.map +1 -1
  36. package/dist/types/core/worker-helper.d.ts +35 -0
  37. package/dist/types/core/worker-helper.d.ts.map +1 -1
  38. package/dist/types/crypto/cipher/aes.d.ts +1 -7
  39. package/dist/types/crypto/cipher/aes.d.ts.map +1 -1
  40. package/dist/types/crypto/cipher/chacha20.d.ts +0 -10
  41. package/dist/types/crypto/cipher/chacha20.d.ts.map +1 -1
  42. package/dist/types/crypto/hash/argon2.d.ts +0 -15
  43. package/dist/types/crypto/hash/argon2.d.ts.map +1 -1
  44. package/dist/types/crypto/hash/blake2b.d.ts.map +1 -1
  45. package/dist/types/crypto/hash/hmac.d.ts.map +1 -1
  46. package/dist/types/crypto/hash/pbkdf2.d.ts.map +1 -1
  47. package/dist/types/crypto/hash/poly1305.d.ts.map +1 -1
  48. package/dist/types/crypto/hash/sha224.d.ts +1 -1
  49. package/dist/types/crypto/hash/sha256.d.ts +4 -13
  50. package/dist/types/crypto/hash/sha256.d.ts.map +1 -1
  51. package/dist/types/crypto/hash/sha3.d.ts.map +1 -1
  52. package/dist/types/crypto/hash/sha384.d.ts +1 -1
  53. package/dist/types/crypto/hash/sha512.d.ts +4 -13
  54. package/dist/types/crypto/hash/sha512.d.ts.map +1 -1
  55. package/dist/types/crypto/mode/cmac.d.ts +0 -6
  56. package/dist/types/crypto/mode/cmac.d.ts.map +1 -1
  57. package/dist/types/crypto/mode/ctr.d.ts +0 -6
  58. package/dist/types/crypto/mode/ctr.d.ts.map +1 -1
  59. package/dist/types/crypto/mode/gcm.d.ts +0 -9
  60. package/dist/types/crypto/mode/gcm.d.ts.map +1 -1
  61. package/dist/types/crypto/pkc/ecc.d.ts +0 -1
  62. package/dist/types/crypto/pkc/ecc.d.ts.map +1 -1
  63. package/dist/types/crypto/pkc/ed25519.d.ts +4 -25
  64. package/dist/types/crypto/pkc/ed25519.d.ts.map +1 -1
  65. package/dist/types/crypto/pkc/hybridSign.d.ts +25 -5
  66. package/dist/types/crypto/pkc/hybridSign.d.ts.map +1 -1
  67. package/dist/types/crypto/pkc/ml_dsa.d.ts +6 -26
  68. package/dist/types/crypto/pkc/ml_dsa.d.ts.map +1 -1
  69. package/dist/types/crypto/pkc/ml_kem.d.ts +0 -43
  70. package/dist/types/crypto/pkc/ml_kem.d.ts.map +1 -1
  71. package/dist/types/crypto/pkc/rsa.d.ts +0 -24
  72. package/dist/types/crypto/pkc/rsa.d.ts.map +1 -1
  73. package/dist/types/crypto/pkc/slh_dsa.d.ts +6 -16
  74. package/dist/types/crypto/pkc/slh_dsa.d.ts.map +1 -1
  75. package/dist/types/crypto/pkc/x25519.d.ts +0 -6
  76. package/dist/types/crypto/pkc/x25519.d.ts.map +1 -1
  77. package/dist/types/crypto/utils/bitArray.d.ts +0 -8
  78. package/dist/types/crypto/utils/bitArray.d.ts.map +1 -1
  79. package/dist/types/crypto/utils/jws.d.ts +6 -14
  80. package/dist/types/crypto/utils/jws.d.ts.map +1 -1
  81. package/dist/types/crypto/utils/keyformat.d.ts +52 -0
  82. package/dist/types/crypto/utils/keyformat.d.ts.map +1 -1
  83. package/dist/types/crypto/utils/random.d.ts +1 -10
  84. package/dist/types/crypto/utils/random.d.ts.map +1 -1
  85. package/dist/types/crypto/utils/rsaKeygen.d.ts +0 -10
  86. package/dist/types/crypto/utils/rsaKeygen.d.ts.map +1 -1
  87. package/dist/types/crypto/utils/uuid.d.ts.map +1 -1
  88. package/dist/types/crypto/utils/x509.d.ts +397 -0
  89. package/dist/types/crypto/utils/x509.d.ts.map +1 -0
  90. package/dist/types/crypto/wasm/argon2.d.ts +2 -1
  91. package/dist/types/crypto/wasm/argon2.d.ts.map +1 -1
  92. package/dist/types/crypto/wasm/pbkdf2.d.ts +2 -2
  93. package/dist/types/crypto/wasm/pbkdf2.d.ts.map +1 -1
  94. package/dist/types/crypto/wasm/rsa.d.ts.map +1 -1
  95. package/dist/types/crypto/wasm/runtime.d.ts +13 -0
  96. package/dist/types/crypto/wasm/runtime.d.ts.map +1 -1
  97. package/dist/types/crypto/webcrypto/aes.d.ts.map +1 -1
  98. package/dist/types/crypto/webcrypto/aeskw.d.ts.map +1 -1
  99. package/dist/types/crypto/webcrypto/digest.d.ts +0 -4
  100. package/dist/types/crypto/webcrypto/digest.d.ts.map +1 -1
  101. package/dist/types/crypto/webcrypto/rsa.d.ts.map +1 -1
  102. package/dist/types/dom/fs/fileIntake.d.ts +59 -0
  103. package/dist/types/dom/fs/fileIntake.d.ts.map +1 -0
  104. package/dist/types/dom/fs/fsAccess.d.ts.map +1 -1
  105. package/dist/types/dom/query/dnd.d.ts.map +1 -1
  106. package/dist/types/dom/query/sound.d.ts +89 -0
  107. package/dist/types/dom/query/sound.d.ts.map +1 -0
  108. package/dist/types/dom/rendering/chart.d.ts.map +1 -1
  109. package/dist/types/dom/rendering/component.d.ts +9 -3
  110. package/dist/types/dom/rendering/component.d.ts.map +1 -1
  111. package/dist/types/dom/rendering/parser.d.ts +39 -0
  112. package/dist/types/dom/rendering/parser.d.ts.map +1 -1
  113. package/dist/types/dom/rendering/render.d.ts.map +1 -1
  114. package/dist/types/dom/rendering/sanitize.d.ts +4 -0
  115. package/dist/types/dom/rendering/sanitize.d.ts.map +1 -1
  116. package/dist/types/dom/rendering/secPolicy.d.ts.map +1 -1
  117. package/dist/types/dom/rendering/styleSheet.d.ts +74 -0
  118. package/dist/types/dom/rendering/styleSheet.d.ts.map +1 -0
  119. package/dist/types/dom/rendering/template.d.ts +9 -3
  120. package/dist/types/dom/rendering/template.d.ts.map +1 -1
  121. package/dist/types/dom/rendering/themeTokens.d.ts +9 -3
  122. package/dist/types/dom/rendering/themeTokens.d.ts.map +1 -1
  123. package/dist/types/dom/rendering/uiSession-core.d.ts +9 -3
  124. package/dist/types/dom/rendering/uiSession-core.d.ts.map +1 -1
  125. package/dist/types/dom/rendering/uiSession-list.d.ts +9 -3
  126. package/dist/types/dom/rendering/uiSession-list.d.ts.map +1 -1
  127. package/dist/types/dom/rendering/uiSession.d.ts +18 -6
  128. package/dist/types/dom/rendering/uiSession.d.ts.map +1 -1
  129. package/dist/types/dom/sw/installPrompt.d.ts +89 -0
  130. package/dist/types/dom/sw/installPrompt.d.ts.map +1 -0
  131. package/dist/types/dom/sw/precache.d.ts +149 -0
  132. package/dist/types/dom/sw/precache.d.ts.map +1 -0
  133. package/dist/types/dom/sw/swUpdate.d.ts +129 -0
  134. package/dist/types/dom/sw/swUpdate.d.ts.map +1 -0
  135. package/dist/types/dom/utils/clipboard.d.ts +8 -0
  136. package/dist/types/dom/utils/clipboard.d.ts.map +1 -1
  137. package/dist/types/dom/utils/keybindings.d.ts.map +1 -1
  138. package/dist/types/dom/utils/route.d.ts.map +1 -1
  139. package/dist/types/dom/utils/ua.d.ts +2 -2
  140. package/dist/types/dom/utils/ua.d.ts.map +1 -1
  141. package/dist/types/io/calc/crc32.d.ts.map +1 -1
  142. package/dist/types/io/codec/b64.d.ts +24 -0
  143. package/dist/types/io/codec/b64.d.ts.map +1 -1
  144. package/dist/types/io/codec/cbor.d.ts +1 -0
  145. package/dist/types/io/codec/cbor.d.ts.map +1 -1
  146. package/dist/types/io/codec/hex.d.ts.map +1 -1
  147. package/dist/types/io/codec/msgpack.d.ts +1 -0
  148. package/dist/types/io/codec/msgpack.d.ts.map +1 -1
  149. package/dist/types/io/codec/url.d.ts +3 -1
  150. package/dist/types/io/codec/url.d.ts.map +1 -1
  151. package/dist/types/io/codec/utf8.d.ts.map +1 -1
  152. package/dist/types/io/compress/bitstream.d.ts +1 -1
  153. package/dist/types/io/compress/brotli.d.ts +0 -1
  154. package/dist/types/io/compress/brotli.d.ts.map +1 -1
  155. package/dist/types/io/compress/brotli_shared.d.ts +0 -4
  156. package/dist/types/io/compress/brotli_shared.d.ts.map +1 -1
  157. package/dist/types/io/compress/deflate.d.ts +14 -1
  158. package/dist/types/io/compress/deflate.d.ts.map +1 -1
  159. package/dist/types/io/compress/gzip.d.ts +4 -0
  160. package/dist/types/io/compress/gzip.d.ts.map +1 -1
  161. package/dist/types/io/compress/huffman.d.ts +7 -0
  162. package/dist/types/io/compress/huffman.d.ts.map +1 -1
  163. package/dist/types/io/compress/lz4.d.ts +4 -2
  164. package/dist/types/io/compress/lz4.d.ts.map +1 -1
  165. package/dist/types/io/compress/lz77.d.ts +17 -0
  166. package/dist/types/io/compress/lz77.d.ts.map +1 -1
  167. package/dist/types/io/compress/lzw.d.ts +2 -0
  168. package/dist/types/io/compress/lzw.d.ts.map +1 -1
  169. package/dist/types/io/compress/zip.d.ts.map +1 -1
  170. package/dist/types/io/compress/zlib.d.ts +9 -2
  171. package/dist/types/io/compress/zlib.d.ts.map +1 -1
  172. package/dist/types/io/math/linalg.d.ts.map +1 -1
  173. package/dist/types/process/rpc.d.ts.map +1 -1
  174. package/dist/types/process/workerPool.d.ts.map +1 -1
  175. package/dist/types/sanity/base.d.ts +12 -2
  176. package/dist/types/sanity/base.d.ts.map +1 -1
  177. package/dist/types/sanity/lockdown.d.ts +6 -5
  178. package/dist/types/sanity/lockdown.d.ts.map +1 -1
  179. package/dist/types/sanity/wasm-gate.d.ts +1 -1
  180. package/docs/README.md +17 -10
  181. package/docs/api/README.md +5 -5
  182. package/docs/api/core/logger.md +2 -1
  183. package/docs/api/core/modules.md +3 -3
  184. package/docs/api/core/runtime.md +9 -9
  185. package/docs/api/core/worker-helper.md +12 -2
  186. package/docs/api/crypto/README.md +1 -1
  187. package/docs/api/crypto/cipher/README.md +2 -2
  188. package/docs/api/crypto/cipher/aes.md +5 -10
  189. package/docs/api/crypto/cipher/chacha20.md +3 -8
  190. package/docs/api/crypto/hash/README.md +5 -5
  191. package/docs/api/crypto/hash/adf.md +21 -11
  192. package/docs/api/crypto/hash/argon2.md +3 -12
  193. package/docs/api/crypto/hash/blake2b.md +12 -14
  194. package/docs/api/crypto/hash/pbkdf2.md +1 -1
  195. package/docs/api/crypto/hash/sha224.md +2 -2
  196. package/docs/api/crypto/hash/sha256.md +4 -4
  197. package/docs/api/crypto/hash/sha3.md +2 -2
  198. package/docs/api/crypto/hash/sha384.md +1 -1
  199. package/docs/api/crypto/hash/sha512.md +5 -5
  200. package/docs/api/crypto/hash/sha512_224.md +1 -1
  201. package/docs/api/crypto/hash/sha512_256.md +1 -1
  202. package/docs/api/crypto/mode/README.md +3 -3
  203. package/docs/api/crypto/mode/cbc.md +2 -2
  204. package/docs/api/crypto/mode/chacha20poly1305.md +1 -1
  205. package/docs/api/crypto/mode/cmac.md +4 -4
  206. package/docs/api/crypto/mode/ctr.md +2 -3
  207. package/docs/api/crypto/mode/gcm.md +5 -5
  208. package/docs/api/crypto/mode/kw.md +4 -4
  209. package/docs/api/crypto/pkc/README.md +8 -8
  210. package/docs/api/crypto/pkc/ecc.md +19 -17
  211. package/docs/api/crypto/pkc/ed25519.md +10 -15
  212. package/docs/api/crypto/pkc/hybridKem.md +8 -2
  213. package/docs/api/crypto/pkc/hybridSign.md +34 -7
  214. package/docs/api/crypto/pkc/ml_dsa.md +20 -19
  215. package/docs/api/crypto/pkc/ml_kem.md +3 -3
  216. package/docs/api/crypto/pkc/rsa.md +7 -9
  217. package/docs/api/crypto/pkc/slh_dsa.md +12 -12
  218. package/docs/api/crypto/pkc/x25519.md +5 -4
  219. package/docs/api/crypto/utils/README.md +7 -7
  220. package/docs/api/crypto/utils/aes_modes.md +2 -5
  221. package/docs/api/crypto/utils/asn1.md +25 -16
  222. package/docs/api/crypto/utils/jws.md +6 -4
  223. package/docs/api/crypto/utils/keyformat.md +24 -15
  224. package/docs/api/crypto/utils/pad.md +1 -1
  225. package/docs/api/crypto/utils/pem.md +3 -3
  226. package/docs/api/crypto/utils/random.md +3 -4
  227. package/docs/api/crypto/utils/rsaKeygen.md +2 -2
  228. package/docs/api/crypto/utils/totp.md +2 -2
  229. package/docs/api/crypto/utils/uuid.md +5 -5
  230. package/docs/api/crypto/utils/x509.md +124 -0
  231. package/docs/api/crypto/wasm/aes.md +1 -1
  232. package/docs/api/crypto/wasm/argon2.md +6 -4
  233. package/docs/api/crypto/wasm/ml_kem.md +1 -0
  234. package/docs/api/crypto/wasm/pbkdf2.md +8 -8
  235. package/docs/api/crypto/wasm/rsa.md +1 -1
  236. package/docs/api/crypto/wasm/runtime.md +27 -10
  237. package/docs/api/crypto/webcrypto/aes.md +1 -1
  238. package/docs/api/crypto/webcrypto/aeskw.md +2 -2
  239. package/docs/api/crypto/webcrypto/digest.md +3 -5
  240. package/docs/api/crypto/webcrypto/ecc.md +1 -1
  241. package/docs/api/crypto/webcrypto/ed25519.md +1 -1
  242. package/docs/api/crypto/webcrypto/rsa.md +3 -2
  243. package/docs/api/crypto/webcrypto/x25519.md +1 -1
  244. package/docs/api/dom/README.md +6 -1
  245. package/docs/api/dom/fs/README.md +1 -0
  246. package/docs/api/dom/fs/fileIntake.md +120 -0
  247. package/docs/api/dom/fs/fsAccess.md +1 -0
  248. package/docs/api/dom/fs/indexedDB.md +1 -1
  249. package/docs/api/dom/fs/storage.md +1 -1
  250. package/docs/api/dom/query/README.md +2 -1
  251. package/docs/api/dom/query/dnd.md +4 -1
  252. package/docs/api/dom/query/dom.md +5 -0
  253. package/docs/api/dom/query/sound.md +103 -0
  254. package/docs/api/dom/rendering/README.md +4 -3
  255. package/docs/api/dom/rendering/chart.md +5 -4
  256. package/docs/api/dom/rendering/component.md +25 -3
  257. package/docs/api/dom/rendering/parser.md +5 -2
  258. package/docs/api/dom/rendering/reactiveBind.md +1 -1
  259. package/docs/api/dom/rendering/render.md +2 -2
  260. package/docs/api/dom/rendering/sanitize.md +10 -2
  261. package/docs/api/dom/rendering/secPolicy.md +4 -4
  262. package/docs/api/dom/rendering/styleSheet.md +85 -0
  263. package/docs/api/dom/rendering/template.md +20 -5
  264. package/docs/api/dom/rendering/themeTokens.md +6 -3
  265. package/docs/api/dom/rendering/uiSession.md +18 -5
  266. package/docs/api/dom/rendering/virtualScroll.md +2 -2
  267. package/docs/api/dom/sensors/geolocation.md +1 -1
  268. package/docs/api/dom/sw/README.md +7 -1
  269. package/docs/api/dom/sw/cache.md +2 -1
  270. package/docs/api/dom/sw/installPrompt.md +111 -0
  271. package/docs/api/dom/sw/precache.md +124 -0
  272. package/docs/api/dom/sw/serviceWorker.md +4 -2
  273. package/docs/api/dom/sw/swUpdate.md +112 -0
  274. package/docs/api/dom/utils/clipboard.md +56 -5
  275. package/docs/api/dom/utils/entropyCollector.md +1 -1
  276. package/docs/api/dom/utils/keybindings.md +17 -2
  277. package/docs/api/dom/utils/leaderElection.md +2 -2
  278. package/docs/api/dom/utils/route.md +1 -0
  279. package/docs/api/dom/utils/ua.md +15 -10
  280. package/docs/api/io/calc/crc32.md +4 -1
  281. package/docs/api/io/codec/README.md +2 -2
  282. package/docs/api/io/codec/b64.md +31 -2
  283. package/docs/api/io/codec/buffer.md +1 -1
  284. package/docs/api/io/codec/cbor.md +6 -4
  285. package/docs/api/io/codec/csv.md +178 -178
  286. package/docs/api/io/codec/hex.md +10 -2
  287. package/docs/api/io/codec/msgpack.md +4 -3
  288. package/docs/api/io/codec/url.md +4 -3
  289. package/docs/api/io/codec/utf8.md +3 -3
  290. package/docs/api/io/compress/bitstream.md +6 -3
  291. package/docs/api/io/compress/brotli.md +36 -4
  292. package/docs/api/io/compress/brotli_shared.md +1 -1
  293. package/docs/api/io/compress/deflate.md +42 -34
  294. package/docs/api/io/compress/gzip.md +26 -6
  295. package/docs/api/io/compress/huffman.md +2 -1
  296. package/docs/api/io/compress/lz4.md +5 -3
  297. package/docs/api/io/compress/lz77.md +26 -3
  298. package/docs/api/io/compress/lzw.md +13 -8
  299. package/docs/api/io/compress/zip.md +36 -10
  300. package/docs/api/io/compress/zlib.md +21 -5
  301. package/docs/api/io/math/linalg.md +1 -1
  302. package/docs/api/io/utils/valid.md +1 -1
  303. package/docs/api/process/rpc.md +3 -2
  304. package/docs/api/process/workerPool.md +1 -1
  305. package/docs/api/sanity/base.md +9 -5
  306. package/docs/api/sanity/lockdown.md +7 -6
  307. package/docs/api/surface.json +12311 -0
  308. package/docs/api/typed.md +5 -3
  309. package/docs/dev/README.md +2 -0
  310. package/docs/dev/bench.md +76 -0
  311. package/docs/dev/crypto-references.md +54 -0
  312. package/docs/dev/provenance.md +30 -7
  313. package/docs/dev/publishing.md +7 -7
  314. package/docs/dev/runtime.md +1 -1
  315. package/docs/dev/testing.md +13 -0
  316. package/docs/evidence/l4-evidence.md +86 -0
  317. package/docs/evidence/pqc-hybrid-evidence.md +7 -6
  318. package/docs/guide/README.md +1 -0
  319. package/docs/guide/_QUICK_REF.md +5 -5
  320. package/docs/guide/doc-format.md +4 -3
  321. package/docs/guide/integrations-hmr.md +1 -1
  322. package/docs/guide/module-creation-workflow.md +8 -8
  323. package/docs/guide/rendering-pipeline.md +11 -4
  324. package/docs/guide/security.md +7 -5
  325. package/docs/guide/stability.md +123 -0
  326. package/docs/guide/tutorial-todo.md +20 -8
  327. package/docs/guide/typescript.md +9 -0
  328. package/docs/guide/worker-confinement.md +30 -17
  329. package/docs/notes/lz77-deflate-factorization.md +3 -3
  330. package/docs/tools/README.md +1 -1
  331. package/docs/tools/bundler.md +3 -3
  332. package/docs/tools/codegen.md +1 -1
  333. package/docs/tools/standalone.md +0 -1
  334. package/fw.config.json +2 -2
  335. package/integrations/_shared/catalog.generated.json +7 -1
  336. package/integrations/_shared/core.js +1 -1
  337. package/integrations/astro/index.js +1 -1
  338. package/integrations/eslint/README.md +7 -1
  339. package/integrations/nextjs/index.js +1 -1
  340. package/integrations/nodejs/README.md +3 -3
  341. package/integrations/turbopack/index.js +2 -2
  342. package/integrations/typedoc/categorize.js +1 -1
  343. package/integrations/typedoc/typedoc.json +2 -1
  344. package/integrations/vite/index.js +2 -2
  345. package/integrations/vite/vite-env.d.ts +7 -4
  346. package/integrations/webpack/index.js +3 -3
  347. package/package.json +76 -10
  348. package/src/core/internal.js +31 -0
  349. package/src/core/logger.js +95 -23
  350. package/src/core/modules.js +17 -8
  351. package/src/core/readyState.js +1 -1
  352. package/src/core/runtime.js +74 -27
  353. package/src/core/worker-helper.js +83 -4
  354. package/src/crypto/NIST_CONFORMANCE.md +47 -34
  355. package/src/crypto/cipher/aes.acvp.md +7 -8
  356. package/src/crypto/cipher/aes.js +280 -229
  357. package/src/crypto/cipher/chacha20.acvp.md +6 -7
  358. package/src/crypto/cipher/chacha20.js +91 -61
  359. package/src/crypto/hash/adf.js +1 -1
  360. package/src/crypto/hash/argon2.acvp.md +11 -15
  361. package/src/crypto/hash/argon2.js +9 -24
  362. package/src/crypto/hash/blake2b.js +157 -125
  363. package/src/crypto/hash/hkdf.acvp.md +15 -15
  364. package/src/crypto/hash/hkdf.js +1 -1
  365. package/src/crypto/hash/hmac.acvp.md +10 -12
  366. package/src/crypto/hash/hmac.js +5 -1
  367. package/src/crypto/hash/pbkdf2.acvp.md +13 -13
  368. package/src/crypto/hash/pbkdf2.js +36 -8
  369. package/src/crypto/hash/poly1305.acvp.md +10 -6
  370. package/src/crypto/hash/poly1305.js +171 -50
  371. package/src/crypto/hash/sha224.acvp.md +3 -3
  372. package/src/crypto/hash/sha224.js +4 -4
  373. package/src/crypto/hash/sha256.acvp.md +2 -2
  374. package/src/crypto/hash/sha256.js +514 -50
  375. package/src/crypto/hash/sha3.acvp.md +9 -9
  376. package/src/crypto/hash/sha3.js +127 -71
  377. package/src/crypto/hash/sha384.acvp.md +3 -3
  378. package/src/crypto/hash/sha384.js +4 -4
  379. package/src/crypto/hash/sha512.acvp.md +7 -8
  380. package/src/crypto/hash/sha512.js +107 -108
  381. package/src/crypto/hash/sha512_224.acvp.md +6 -6
  382. package/src/crypto/hash/sha512_224.js +2 -2
  383. package/src/crypto/hash/sha512_256.acvp.md +6 -6
  384. package/src/crypto/hash/sha512_256.js +2 -2
  385. package/src/crypto/mode/cbc.acvp.md +2 -2
  386. package/src/crypto/mode/cbc.js +1 -1
  387. package/src/crypto/mode/chacha20poly1305.acvp.md +6 -6
  388. package/src/crypto/mode/chacha20poly1305.js +3 -3
  389. package/src/crypto/mode/cmac.acvp.md +5 -5
  390. package/src/crypto/mode/cmac.js +8 -8
  391. package/src/crypto/mode/ctr.acvp.md +2 -2
  392. package/src/crypto/mode/ctr.js +1 -3
  393. package/src/crypto/mode/gcm.acvp.md +6 -6
  394. package/src/crypto/mode/gcm.js +7 -7
  395. package/src/crypto/mode/kw.acvp.md +4 -4
  396. package/src/crypto/mode/kw.js +5 -5
  397. package/src/crypto/pkc/ecc.acvp.md +13 -13
  398. package/src/crypto/pkc/ecc.js +9 -11
  399. package/src/crypto/pkc/ed25519.acvp.md +30 -34
  400. package/src/crypto/pkc/ed25519.js +453 -94
  401. package/src/crypto/pkc/hybrid-kat.provenance.md +4 -4
  402. package/src/crypto/pkc/hybridSign.js +103 -24
  403. package/src/crypto/pkc/ml_dsa.acvp.md +18 -18
  404. package/src/crypto/pkc/ml_dsa.js +29 -32
  405. package/src/crypto/pkc/ml_kem.acvp.md +7 -7
  406. package/src/crypto/pkc/ml_kem.js +15 -21
  407. package/src/crypto/pkc/rsa.acvp.md +11 -15
  408. package/src/crypto/pkc/rsa.js +7 -44
  409. package/src/crypto/pkc/slh_dsa.acvp.md +16 -16
  410. package/src/crypto/pkc/slh_dsa.js +16 -18
  411. package/src/crypto/pkc/x25519.acvp.md +13 -10
  412. package/src/crypto/pkc/x25519.js +273 -29
  413. package/src/crypto/utils/aes_modes.acvp.md +1 -2
  414. package/src/crypto/utils/aes_modes.js +2 -2
  415. package/src/crypto/utils/asn1-oid.js +1 -1
  416. package/src/crypto/utils/asn1.js +1 -1
  417. package/src/crypto/utils/bitArray.js +33 -48
  418. package/src/crypto/utils/bn.js +1 -1
  419. package/src/crypto/utils/jws.js +37 -41
  420. package/src/crypto/utils/keyformat.js +181 -2
  421. package/src/crypto/utils/pem.js +1 -1
  422. package/src/crypto/utils/random.acvp.md +5 -5
  423. package/src/crypto/utils/random.js +845 -846
  424. package/src/crypto/utils/rsaKeygen.acvp.md +3 -2
  425. package/src/crypto/utils/rsaKeygen.js +6 -6
  426. package/src/crypto/utils/totp.js +1 -1
  427. package/src/crypto/utils/uuid.acvp.md +5 -5
  428. package/src/crypto/utils/uuid.js +11 -10
  429. package/src/crypto/utils/x509.js +591 -0
  430. package/src/crypto/wasm/aes.js +1 -1
  431. package/src/crypto/wasm/aes.scalar.wasm +0 -0
  432. package/src/crypto/wasm/argon2.js +17 -1
  433. package/src/crypto/wasm/argon2.scalar.wasm +0 -0
  434. package/src/crypto/wasm/blake2b.scalar.wasm +0 -0
  435. package/src/crypto/wasm/blake2b.simd.wasm +0 -0
  436. package/src/crypto/wasm/chacha20poly1305.scalar.wasm +0 -0
  437. package/src/crypto/wasm/chacha20poly1305.simd.wasm +0 -0
  438. package/src/crypto/wasm/cmac.scalar.wasm +0 -0
  439. package/src/crypto/wasm/ecc.js +3 -3
  440. package/src/crypto/wasm/ecc.scalar.wasm +0 -0
  441. package/src/crypto/wasm/ed25519.js +1 -1
  442. package/src/crypto/wasm/ed25519.scalar.wasm +0 -0
  443. package/src/crypto/wasm/hkdf.scalar.wasm +0 -0
  444. package/src/crypto/wasm/hmac.scalar.wasm +0 -0
  445. package/src/crypto/wasm/ml_dsa.js +2 -2
  446. package/src/crypto/wasm/ml_dsa.scalar.wasm +0 -0
  447. package/src/crypto/wasm/ml_dsa.simd.wasm +0 -0
  448. package/src/crypto/wasm/ml_kem.js +2 -2
  449. package/src/crypto/wasm/ml_kem.scalar.wasm +0 -0
  450. package/src/crypto/wasm/ml_kem.simd.wasm +0 -0
  451. package/src/crypto/wasm/pbkdf2.js +8 -6
  452. package/src/crypto/wasm/pbkdf2.scalar.wasm +0 -0
  453. package/src/crypto/wasm/rsa.js +6 -5
  454. package/src/crypto/wasm/rsa.scalar.wasm +0 -0
  455. package/src/crypto/wasm/runtime.js +84 -17
  456. package/src/crypto/wasm/sha2.scalar.wasm +0 -0
  457. package/src/crypto/wasm/sha3.scalar.wasm +0 -0
  458. package/src/crypto/wasm/sha3.simd.wasm +0 -0
  459. package/src/crypto/wasm/slh_dsa.js +1 -1
  460. package/src/crypto/wasm/slh_dsa.scalar.wasm +0 -0
  461. package/src/crypto/wasm/x25519.js +1 -1
  462. package/src/crypto/wasm/x25519.scalar.wasm +0 -0
  463. package/src/crypto/webcrypto/aes.js +8 -2
  464. package/src/crypto/webcrypto/aeskw.js +7 -2
  465. package/src/crypto/webcrypto/digest.js +1 -15
  466. package/src/crypto/webcrypto/ecc.js +2 -2
  467. package/src/crypto/webcrypto/ed25519.js +2 -2
  468. package/src/crypto/webcrypto/hmac.js +2 -2
  469. package/src/crypto/webcrypto/rsa.js +7 -2
  470. package/src/crypto/webcrypto/x25519.js +2 -2
  471. package/src/dom/display/animate.js +1 -1
  472. package/src/dom/display/fullscreen.js +1 -1
  473. package/src/dom/fs/download.js +1 -1
  474. package/src/dom/fs/fileIntake.js +192 -0
  475. package/src/dom/fs/fsAccess.js +2 -3
  476. package/src/dom/fs/indexedDB.js +1 -1
  477. package/src/dom/fs/remoteStore.js +1 -1
  478. package/src/dom/fs/storage.js +1 -1
  479. package/src/dom/lifecycle/idle.js +1 -1
  480. package/src/dom/lifecycle/visibility.js +1 -1
  481. package/src/dom/lifecycle/wakeLock.js +1 -1
  482. package/src/dom/net/ajax.js +1 -1
  483. package/src/dom/net/network.js +1 -1
  484. package/src/dom/net/sse.js +1 -1
  485. package/src/dom/net/webrtc.js +1 -1
  486. package/src/dom/net/ws.js +1 -1
  487. package/src/dom/query/dnd.js +56 -4
  488. package/src/dom/query/dom.js +1 -1
  489. package/src/dom/query/events.js +1 -1
  490. package/src/dom/query/gesture.js +1 -1
  491. package/src/dom/query/media.js +1 -1
  492. package/src/dom/query/sound.js +333 -0
  493. package/src/dom/rendering/chart.js +736 -663
  494. package/src/dom/rendering/component.js +25 -14
  495. package/src/dom/rendering/devtools.js +2 -2
  496. package/src/dom/rendering/parser.js +155 -12
  497. package/src/dom/rendering/render.js +14 -4
  498. package/src/dom/rendering/sanitize.js +11 -4
  499. package/src/dom/rendering/secPolicy.js +6 -4
  500. package/src/dom/rendering/styleSheet.js +217 -0
  501. package/src/dom/rendering/template.js +72 -13
  502. package/src/dom/rendering/themeTokens.js +542 -522
  503. package/src/dom/rendering/uiSession-core.js +51 -6
  504. package/src/dom/rendering/uiSession-direct.js +1 -1
  505. package/src/dom/rendering/uiSession-list.js +4 -4
  506. package/src/dom/rendering/uiSession.js +1 -1
  507. package/src/dom/rendering/virtualScroll.js +341 -341
  508. package/src/dom/sensors/battery.js +1 -1
  509. package/src/dom/sensors/geolocation.js +1 -1
  510. package/src/dom/sensors/networkInfo.js +1 -1
  511. package/src/dom/sensors/sensors.js +1 -1
  512. package/src/dom/sw/backgroundSync.js +1 -1
  513. package/src/dom/sw/cache.js +1 -1
  514. package/src/dom/sw/installPrompt.js +151 -0
  515. package/src/dom/sw/precache.js +257 -0
  516. package/src/dom/sw/push.js +1 -1
  517. package/src/dom/sw/sharedWorker.js +1 -1
  518. package/src/dom/sw/swUpdate.js +239 -0
  519. package/src/dom/utils/a11y.js +1 -1
  520. package/src/dom/utils/clipboard.js +56 -6
  521. package/src/dom/utils/entropyCollector.js +1 -1
  522. package/src/dom/utils/focus.js +1 -1
  523. package/src/dom/utils/form.js +1 -1
  524. package/src/dom/utils/keybindings.js +600 -574
  525. package/src/dom/utils/leaderElection.js +1 -1
  526. package/src/dom/utils/notifications.js +1 -1
  527. package/src/dom/utils/permissions.js +107 -107
  528. package/src/dom/utils/route.js +14 -2
  529. package/src/dom/utils/ua.js +42 -28
  530. package/src/dom/utils/webauthn.js +1 -1
  531. package/src/io/binary/reader.js +1 -1
  532. package/src/io/binary/writer.js +1 -1
  533. package/src/io/calc/bigint.js +1 -1
  534. package/src/io/calc/crc32.js +28 -2
  535. package/src/io/calc/easing.js +514 -514
  536. package/src/io/codec/b64.js +189 -52
  537. package/src/io/codec/base32.js +1 -1
  538. package/src/io/codec/base58.js +1 -1
  539. package/src/io/codec/buffer.js +1 -1
  540. package/src/io/codec/cbor.js +111 -18
  541. package/src/io/codec/csv.js +1 -1
  542. package/src/io/codec/hex.js +51 -6
  543. package/src/io/codec/mime.js +1 -1
  544. package/src/io/codec/msgpack.js +47 -6
  545. package/src/io/codec/url.js +24 -7
  546. package/src/io/codec/utf8.js +5 -3
  547. package/src/io/codec/xml.js +1 -1
  548. package/src/io/compress/bitstream.js +2 -2
  549. package/src/io/compress/brotli.js +663 -163
  550. package/src/io/compress/brotli_dict.js +1 -1
  551. package/src/io/compress/brotli_dict_words.js +1 -1
  552. package/src/io/compress/brotli_frame.js +1 -1
  553. package/src/io/compress/brotli_shared.js +7 -7
  554. package/src/io/compress/deflate.js +87 -53
  555. package/src/io/compress/gzip.js +187 -74
  556. package/src/io/compress/huffman.js +24 -1
  557. package/src/io/compress/lz4.js +45 -7
  558. package/src/io/compress/lz77.js +148 -63
  559. package/src/io/compress/lzw.js +35 -19
  560. package/src/io/compress/zip.js +862 -815
  561. package/src/io/compress/zlib.js +87 -7
  562. package/src/io/i18n/i18n.js +1 -1
  563. package/src/io/math/fixed-point.js +1 -1
  564. package/src/io/math/geom.js +1 -1
  565. package/src/io/math/interp.js +1 -1
  566. package/src/io/math/linalg.js +10 -4
  567. package/src/io/math/stats.js +1 -1
  568. package/src/io/structures/btree.js +1 -1
  569. package/src/io/structures/heap.js +1 -1
  570. package/src/io/structures/lruCache.js +1 -1
  571. package/src/io/structures/ringBuffer.js +1 -1
  572. package/src/io/structures/tree-walker.js +1 -1
  573. package/src/io/structures/trie.js +1 -1
  574. package/src/io/sync/abort.js +1 -1
  575. package/src/io/sync/atomics.js +1 -1
  576. package/src/io/sync/cancellable.js +1 -1
  577. package/src/io/sync/channel.js +1 -1
  578. package/src/io/sync/mutex.js +1 -1
  579. package/src/io/sync/semaphore.js +1 -1
  580. package/src/io/sync/tokenBucket.js +1 -1
  581. package/src/io/text/ansi.js +1 -1
  582. package/src/io/text/html-entities.js +1 -1
  583. package/src/io/time/date.js +1 -1
  584. package/src/io/timing/clock.js +1 -1
  585. package/src/io/timing/rateLimit.js +1 -1
  586. package/src/io/timing/scheduler.js +1 -1
  587. package/src/io/utils/errors.js +1 -1
  588. package/src/io/utils/eventBus.js +1 -1
  589. package/src/io/utils/signal.js +1 -1
  590. package/src/io/utils/valid.js +1 -1
  591. package/src/main.js +1 -1
  592. package/src/process/message.js +1 -1
  593. package/src/process/rpc.js +7 -3
  594. package/src/process/workerPool.js +11 -4
  595. package/src/sanity/base.js +85 -39
  596. package/src/sanity/lockdown-apply.js +3 -3
  597. package/src/sanity/lockdown.js +58 -32
  598. package/src/sanity/wasm-gate.js +2 -2
  599. package/src/typed.js +7 -3
  600. package/third-party/NOTICE-brotli-dictionary.txt +69 -0
  601. package/third-party/NOTICE-fw-wasm-crypto.txt +576 -0
  602. package/third-party/NOTICE-whatwg-entities.txt +44 -0
  603. package/types/registry.generated.d.ts +7 -1
  604. package/types/typed.d.ts +7 -3
  605. package/dist/types/crypto/utils/aes_ctr.d.ts +0 -84
  606. package/dist/types/crypto/utils/aes_ctr.d.ts.map +0 -1
  607. package/docs/api/crypto/utils/aes_ctr.md +0 -71
  608. package/src/crypto/utils/aes_ctr.acvp.md +0 -67
  609. package/src/crypto/utils/aes_ctr.js +0 -134
@@ -1,846 +1,845 @@
1
- // Copyright (c) 2026 AwaCloud SAS
2
- // Author: Matthieu Bouilloux
3
- // SPDX-License-Identifier: Apache-2.0
4
-
5
- /**
6
- * @typedef {Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|BigInt64Array|BigUint64Array} TypedArray
7
- */
8
-
9
- /**
10
- * @fileoverview CSPRNG wrapper around `crypto.getRandomValues` plus a
11
- * SP 800-90A compliant CTR_DRBG-AES-256 (no derivation function).
12
- *
13
- * Two surfaces are exposed:
14
- *
15
- * 1. **Direct API** (`bytes`, `words`, `bits`, `isReady`) - thin wrapper
16
- * over `crypto.getRandomValues`. Vetted by the platform; the recommended
17
- * path for general-purpose use.
18
- *
19
- * 2. **`drbg(options)`** - instantiates a CTR_DRBG per NIST SP 800-90A
20
- * §10.2 (AES-256, no df). Suitable as a FIPS 140-3 "approved" DRBG
21
- * assuming the entropy source (`crypto.getRandomValues`, treated as a
22
- * validated NRBG per SP 800-90C) and the surrounding module satisfy
23
- * the rest of the FIPS module-level requirements.
24
- *
25
- * The DRBG performs:
26
- * - **POST / KAT** at first instantiation (cached process-wide),
27
- * - **Continuous health test (RCT)** on every entropy buffer drawn
28
- * from `crypto.getRandomValues` (SP 800-90B §4.4.1),
29
- * - **Reseed** with fresh OS entropy when the reseed_counter exceeds
30
- * the configured limit (default 2^32, well below the 2^48 spec cap),
31
- * - Acceptance of `additional_input` on every `generate()` call so that
32
- * environmental entropy (e.g. from `entropyCollector`) can be mixed
33
- * in without depending on its module at construction time.
34
- *
35
- * `entropyCollector` is **not** a dependency: the caller wires its
36
- * callback to `drbg.addAdditionalInput()` so that the next `generate()`
37
- * consumes the accumulated bytes via the spec-defined update path.
38
- * This keeps `random` worker-safe (DOM-free).
39
- *
40
- * The KAT vector used by `_runSelfTest()` is the official NIST CAVP
41
- * CTR_DRBG-AES-256 (no-df, PredictionResistance=False, COUNT=0) vector from
42
- * the `drbgvectors_pr_false` archive
43
- * (https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/random-number-generators)
44
- * - also mirrored in BoringSSL's `crypto/fipsmodule/rand/ctrdrbg_vectors.txt`.
45
- * Sufficient for the algorithmic KAT; full FIPS 140-3 validation additionally
46
- * requires the surrounding module-level operational tests outside this file.
47
- *
48
- */
49
-
50
- /**
51
- * Low-level CTR_DRBG instance produced by the internal `_makeDrbg` factory
52
- * (exposed via `_internal.makeDrbg`). Caller drives the full SP 800-90A
53
- * lifecycle manually with explicit seed material.
54
- * @typedef {object} DrbgCore
55
- * @property {(entropyBytes: Uint8Array, personalisationBytes?: Uint8Array, nonceBytes?: Uint8Array) => boolean} instantiate Seed the DRBG.
56
- * @property {(entropyBytes: Uint8Array, additionalInputBytes?: Uint8Array) => boolean} reseed Reseed with caller-supplied entropy.
57
- * @property {(n: number, additionalInputBytes?: Uint8Array) => (Uint8Array | false)} generate Produce `n` random bytes.
58
- * @property {() => void} uninstantiate Wipe internal state.
59
- * @property {boolean} isLive Whether the DRBG has been instantiated (getter).
60
- * @property {number} reseedCounter Current reseed counter (getter).
61
- * @property {number} securityStrength Security strength in bits (getter).
62
- * @property {number} aesKeyBits Configured AES key size in bits (getter).
63
- * @property {boolean} useDf Whether a derivation function is used (getter).
64
- * @property {number} seedBytes Seed length in bytes (getter).
65
- */
66
-
67
- /**
68
- * High-level CTR_DRBG instance returned by `api.drbg(options)`. Auto-seeds
69
- * from OS entropy and supports mixing in pending additional input.
70
- * @typedef {object} Drbg
71
- * @property {(n: number, additionalInput?: Uint8Array) => (Uint8Array | false)} generate Produce `n` random bytes, folding in any pending additional input.
72
- * @property {(additionalInput?: Uint8Array) => boolean} reseed Reseed with fresh OS entropy.
73
- * @property {(bytes: Uint8Array | number[] | Uint32Array | number) => boolean} addAdditionalInput Buffer entropy for the next `generate()`/`reseed()`.
74
- * @property {() => void} uninstantiate Wipe internal state and pending buffer.
75
- * @property {boolean} isLive Whether the DRBG is live (getter).
76
- * @property {number} reseedCounter Current reseed counter (getter).
77
- * @property {number} securityStrength Security strength in bits (getter).
78
- */
79
-
80
- /**
81
- * SP 800-90B continuous health-test surface.
82
- * @typedef {object} RandomHealth
83
- * @property {(buf: Uint8Array | number[]) => boolean} feed Push bytes through RCT + APT; `false` on failure.
84
- * @property {() => void} reset Clear state and the latched-dead flag.
85
- * @property {boolean} isDead True once any continuous test has failed (getter).
86
- */
87
-
88
- /**
89
- * Public shape returned by `random.factory()`.
90
- * @typedef {object} RandomAPI
91
- * @property {<T extends TypedArray>(array: T) => T} fill Fill a typed array in place with secure random values.
92
- * @property {() => (number | false)} float Secure random float in `[0, 1)`.
93
- * @property {(min: number, max: number) => (number | false)} int Secure random integer in `[min, max]` (rejection-sampled).
94
- * @property {(n: number) => (Uint8Array | false)} bytes `n` random bytes (direct OS RBG).
95
- * @property {(n: number) => (number[] | false)} words `n` random 32-bit words (direct OS RBG).
96
- * @property {(n: number) => (number[] | false)} bits Random bit array of `n` bits (direct OS RBG).
97
- * @property {() => boolean} isReady Whether `crypto.getRandomValues` is available.
98
- * @property {() => boolean} selfTest Run / re-run the CTR_DRBG power-on self-test.
99
- * @property {{ makeDrbg: (opts?: { aesKeyBits?: 128|192|256, df?: boolean }) => (DrbgCore | false) }} _internal Test-only internal CTR_DRBG factory.
100
- * @property {RandomHealth} health Continuous health-test surface.
101
- * @property {(options?: { aesKeyBits?: 128|192|256, df?: boolean, personalisation?: Uint8Array }) => (Drbg | false)} drbg Build a fresh CTR_DRBG-AES-256 (no-df) instance.
102
- */
103
-
104
- import { bitArray } from './bitArray.js';
105
- import { aes } from '../cipher/aes.js';
106
- import { sha256 } from '../hash/sha256.js';
107
-
108
- export const random = {
109
- name: 'random',
110
- version: '1.0.0',
111
- type: 'fw.crypto.utils',
112
- dependencies: ['bitArray', 'aes', 'sha256'],
113
- deps: [bitArray, aes, sha256],
114
-
115
- /** @returns {RandomAPI} */
116
- factory(bitArray, aes, sha256) {
117
-
118
- const _MAX_BYTES_PER_CALL = 65536;
119
- const _hasCrypto = typeof crypto !== 'undefined' && !!crypto.getRandomValues;
120
-
121
- // ── byte/word helpers (big-endian, AES convention) ───────────────
122
-
123
- function _bytesToWords(b) {
124
- const n = b.length >>> 2;
125
- const out = new Array(n);
126
- for (let i = 0; i < n; i++) {
127
- const j = i << 2;
128
- out[i] = ((b[j] << 24) | (b[j + 1] << 16) | (b[j + 2] << 8) | b[j + 3]) | 0;
129
- }
130
- return out;
131
- }
132
- function _wordsToBytes(w, count, into, off) {
133
- for (let i = 0; i < count; i++) {
134
- const j = off + (i << 2);
135
- into[j] = (w[i] >>> 24) & 0xff;
136
- into[j + 1] = (w[i] >>> 16) & 0xff;
137
- into[j + 2] = (w[i] >>> 8) & 0xff;
138
- into[j + 3] = w[i] & 0xff;
139
- }
140
- }
141
-
142
- // ── continuous health tests (SP 800-90B §4.4) ────────────────────
143
- //
144
- // Both tests run continuously across the lifetime of the entropy
145
- // source - state persists across calls, not per-buffer. Once either
146
- // test fails, the source is marked dead permanently (SP 800-90B §4.5:
147
- // "Once a continuous test failure is detected, no more outputs from
148
- // the noise source shall be used").
149
- //
150
- // Parameters assume a full-entropy byte source (H = 8 bits/byte) and
151
- // α = 2^-20 false-alarm probability:
152
- //
153
- // RCT (§4.4.1) - Repetition Count Test
154
- // C_rct = 1 + ⌈-log2(α) / H⌉ = 1 + ⌈20/8⌉ = 4
155
- // Fail if 4 identical consecutive samples.
156
- //
157
- // APT (§4.4.2) - Adaptive Proportion Test
158
- // Window W = 512 samples, p = 2^-H = 1/256, mean = 2.
159
- // Cutoff C_apt = 13 (smallest C such that P(Bin(512,1/256) > C) ≤ α).
160
- // Fail if the anchor sample appears more than 13 times in the
161
- // non-overlapping 512-sample window.
162
-
163
- const _RCT_CUTOFF = 4;
164
- const _APT_W = 512;
165
- const _APT_C = 13;
166
-
167
- const _rct = { prev: -1, run: 0 };
168
- const _apt = { anchor: -1, count: 0, idx: 0 };
169
- let _entropyDead = false;
170
-
171
- function _healthCheck(buf) {
172
- if (_entropyDead) return false;
173
- for (let i = 0; i < buf.length; i++) {
174
- const b = buf[i];
175
-
176
- // RCT
177
- if (b === _rct.prev) {
178
- _rct.run++;
179
- if (_rct.run >= _RCT_CUTOFF) {
180
- _entropyDead = true;
181
- console.error('[crypto] CORRUPT: random: RCT health-test failed on entropy source');
182
- return false;
183
- }
184
- } else {
185
- _rct.prev = b;
186
- _rct.run = 1;
187
- }
188
-
189
- // APT
190
- if (_apt.anchor === -1) {
191
- _apt.anchor = b;
192
- _apt.count = 1;
193
- _apt.idx = 1;
194
- } else {
195
- _apt.idx++;
196
- if (b === _apt.anchor) {
197
- _apt.count++;
198
- if (_apt.count > _APT_C) {
199
- _entropyDead = true;
200
- console.error('[crypto] CORRUPT: random: APT health-test failed on entropy source');
201
- return false;
202
- }
203
- }
204
- if (_apt.idx >= _APT_W) _apt.anchor = -1;
205
- }
206
- }
207
- return true;
208
- }
209
-
210
- function _resetHealth() {
211
- _rct.prev = -1; _rct.run = 0;
212
- _apt.anchor = -1; _apt.count = 0; _apt.idx = 0;
213
- _entropyDead = false;
214
- }
215
-
216
- // ── raw OS entropy with chunking + continuous health tests ───────
217
-
218
- function _getRandomBytes(out) {
219
- if (!_hasCrypto) {
220
- console.error('[crypto] NOT READY: crypto.getRandomValues unavailable');
221
- return false;
222
- }
223
- let offset = 0;
224
- while (offset < out.length) {
225
- const chunk = Math.min(_MAX_BYTES_PER_CALL, out.length - offset);
226
- crypto.getRandomValues(out.subarray(offset, offset + chunk));
227
- offset += chunk;
228
- }
229
- return out;
230
- }
231
- function _getEntropy(nBytes) {
232
- if (_entropyDead) {
233
- console.error('[crypto] CORRUPT: random: entropy source previously failed health test');
234
- return false;
235
- }
236
- const buf = _getRandomBytes(new Uint8Array(nBytes));
237
- if (buf === false) return false;
238
- if (!_healthCheck(buf)) return false;
239
- return buf;
240
- }
241
-
242
- // ── CTR_DRBG-AES-{128,192,256}, no-df + with-df - SP 800-90A §10.2 ──
243
- //
244
- // Parameters (parametric since Iteration H4):
245
- // aesKeyBits ∈ {128, 192, 256} → keylen = 16 / 24 / 32 bytes
246
- // blocklen = 16 bytes (AES)
247
- // seedlen = keylen + blocklen
248
- // security_strength = aesKeyBits
249
- // reseed_interval ≤ 2^48 (we use 2^32 for safety)
250
- // max_bytes_per_request ≤ 2^19 bits = 65536 bytes
251
- // df : SP 800-90A §10.4.2 Block Cipher Derivation Function.
252
- // If true, instantiate/reseed accept any-length entropy +
253
- // nonce + perso/additional-input strings ; df distills them
254
- // into seedlen bytes via BCC. If false, all inputs must be
255
- // exactly seedlen bytes.
256
-
257
- const _BLK_WORDS = 4;
258
- const _BLK_BYTES = 16;
259
- const _MAX_GEN_BYTES = 65536;
260
- const _RESEED_INTERVAL = 0x100000000; // 2^32, < spec cap 2^48
261
-
262
- // Build a CTR_DRBG instance.
263
- // @param {object} [opts]
264
- // @param {128|192|256} [opts.aesKeyBits=256]
265
- // @param {boolean} [opts.df=false]
266
- function _makeDrbg(opts) {
267
- opts = opts || {};
268
- const aesKeyBits = opts.aesKeyBits || 256;
269
- const useDf = !!opts.df;
270
- if (aesKeyBits !== 128 && aesKeyBits !== 192 && aesKeyBits !== 256) {
271
- console.error('[crypto] BUG: ctr_drbg: aesKeyBits must be 128, 192 or 256');
272
- return false;
273
- }
274
- const KEY_BYTES = aesKeyBits / 8;
275
- const KEY_WORDS = KEY_BYTES / 4;
276
- const SEED_BYTES = KEY_BYTES + _BLK_BYTES;
277
- const SEED_WORDS = SEED_BYTES / 4;
278
-
279
- let K = new Array(KEY_WORDS).fill(0);
280
- let V = new Array(_BLK_WORDS).fill(0);
281
- let cipher = null;
282
- let reseedCt = 0;
283
- let live = false;
284
-
285
- // ── SP 800-90A §10.4.2 - Block Cipher Derivation Function ────
286
- //
287
- // BCC(K, data): CBC-MAC of `data` (multiple of 16 bytes) under K.
288
- function _bcc(Kbytes, dataBytes) {
289
- const cf = aes.fn(_bytesToWords(Kbytes), false);
290
- if (cf === false) return false;
291
- const chain = new Uint8Array(_BLK_BYTES);
292
- for (let off = 0; off < dataBytes.length; off += _BLK_BYTES) {
293
- for (let i = 0; i < _BLK_BYTES; i++) chain[i] ^= dataBytes[off + i];
294
- const blk = cf.encrypt(_bytesToWords(chain));
295
- _wordsToBytes(blk, _BLK_WORDS, chain, 0);
296
- }
297
- return chain;
298
- }
299
-
300
- // Block_Cipher_df(input, no_of_bits_to_return) → bytes.
301
- // Returns SEED_BYTES of distilled output.
302
- function _df(inputBytes, outBytes) {
303
- // S = L (4 BE) || N (4 BE) || input || 0x80 || 0x00…0
304
- const L = inputBytes.length;
305
- const N = outBytes;
306
- const headerLen = 4 + 4;
307
- const rawLen = headerLen + L + 1;
308
- const padLen = (_BLK_BYTES - (rawLen % _BLK_BYTES)) % _BLK_BYTES;
309
- const Slen = rawLen + padLen;
310
- const S = new Uint8Array(Slen);
311
- S[0] = (L >>> 24) & 0xff; S[1] = (L >>> 16) & 0xff;
312
- S[2] = (L >>> 8) & 0xff; S[3] = L & 0xff;
313
- S[4] = (N >>> 24) & 0xff; S[5] = (N >>> 16) & 0xff;
314
- S[6] = (N >>> 8) & 0xff; S[7] = N & 0xff;
315
- for (let i = 0; i < L; i++) S[headerLen + i] = inputBytes[i];
316
- S[headerLen + L] = 0x80;
317
- // padding 0x00 already set by Uint8Array init.
318
-
319
- // K_df = 0x00 01 02 … (KEY_BYTES bytes)
320
- const Kdf = new Uint8Array(KEY_BYTES);
321
- for (let i = 0; i < KEY_BYTES; i++) Kdf[i] = i;
322
-
323
- // temp = "" ; while len(temp) < KEY_BYTES + BLK_BYTES :
324
- // IV = i (4 BE) || 0…0 (BLK-4 zero bytes)
325
- // temp ||= BCC(K_df, IV || S)
326
- const tempLen = KEY_BYTES + _BLK_BYTES;
327
- const temp = new Uint8Array(Math.ceil(tempLen / _BLK_BYTES) * _BLK_BYTES);
328
- let tempOff = 0;
329
- let i = 0;
330
- while (tempOff < tempLen) {
331
- const ivS = new Uint8Array(_BLK_BYTES + Slen);
332
- ivS[0] = (i >>> 24) & 0xff; ivS[1] = (i >>> 16) & 0xff;
333
- ivS[2] = (i >>> 8) & 0xff; ivS[3] = i & 0xff;
334
- ivS.set(S, _BLK_BYTES);
335
- const blk = _bcc(Kdf, ivS);
336
- if (blk === false) return false;
337
- temp.set(blk, tempOff);
338
- tempOff += _BLK_BYTES;
339
- i++;
340
- }
341
-
342
- // K' = first KEY_BYTES of temp ; X = next BLK_BYTES of temp.
343
- const Kp = temp.subarray(0, KEY_BYTES);
344
- let X = temp.slice(KEY_BYTES, KEY_BYTES + _BLK_BYTES);
345
- const cf = aes.fn(_bytesToWords(Kp), false);
346
- if (cf === false) return false;
347
-
348
- const out = new Uint8Array(outBytes);
349
- let outOff = 0;
350
- while (outOff < outBytes) {
351
- const blk = cf.encrypt(_bytesToWords(X));
352
- _wordsToBytes(blk, _BLK_WORDS, X, 0);
353
- const n = Math.min(_BLK_BYTES, outBytes - outOff);
354
- out.set(X.subarray(0, n), outOff);
355
- outOff += n;
356
- }
357
- return out;
358
- }
359
-
360
- function _rebuild() {
361
- cipher = aes.fn(K, false);
362
- if (cipher === false) {
363
- console.error('[crypto] BUG: ctr_drbg: AES key schedule failed');
364
- return false;
365
- }
366
- return true;
367
- }
368
-
369
- function _incV() {
370
- for (let i = _BLK_WORDS - 1; i >= 0; i--) {
371
- V[i] = (V[i] + 1) | 0;
372
- if (V[i] !== 0) break;
373
- }
374
- }
375
-
376
- // CTR_DRBG_Update(provided_data: SEED_WORDS, K, V) - §10.2.1.2
377
- function _update(providedWords) {
378
- const temp = new Array(SEED_WORDS).fill(0);
379
- let pos = 0;
380
- while (pos < SEED_WORDS) {
381
- _incV();
382
- const blk = cipher.encrypt(V);
383
- for (let j = 0; j < _BLK_WORDS && pos < SEED_WORDS; j++) {
384
- temp[pos++] = blk[j];
385
- }
386
- }
387
- for (let i = 0; i < SEED_WORDS; i++) temp[i] ^= providedWords[i];
388
- K = temp.slice(0, KEY_WORDS);
389
- // Slice exactly _BLK_WORDS for V (avoid AES-192 case where
390
- // SEED_WORDS = KEY_WORDS + BLK_WORDS = 10 but temp could be
391
- // longer if generated incorrectly).
392
- V = temp.slice(KEY_WORDS, KEY_WORDS + _BLK_WORDS);
393
- return _rebuild();
394
- }
395
-
396
- // Distill arbitrary inputs to a SEED_BYTES seed.
397
- // no-df : caller must provide exactly SEED_BYTES of entropy ;
398
- // perso/AI is XOR-truncated/padded to SEED_BYTES.
399
- // df : entropy + nonce + perso (concatenated) → df → SEED_BYTES.
400
- function _distill(entropyBytes, personalisationBytes, nonceBytes) {
401
- if (useDf) {
402
- const eLen = entropyBytes ? entropyBytes.length : 0;
403
- const nLen = nonceBytes ? nonceBytes.length : 0;
404
- const pLen = personalisationBytes ? personalisationBytes.length : 0;
405
- const cat = new Uint8Array(eLen + nLen + pLen);
406
- if (eLen) cat.set(entropyBytes, 0);
407
- if (nLen) cat.set(nonceBytes, eLen);
408
- if (pLen) cat.set(personalisationBytes, eLen + nLen);
409
- return _df(cat, SEED_BYTES);
410
- }
411
- if (!entropyBytes || entropyBytes.length !== SEED_BYTES) {
412
- console.error('[crypto] BUG: ctr_drbg (no-df): entropy must be exactly ' + SEED_BYTES + ' bytes');
413
- return false;
414
- }
415
- const seed = new Uint8Array(SEED_BYTES);
416
- seed.set(entropyBytes);
417
- if (personalisationBytes && personalisationBytes.length > 0) {
418
- const lim = Math.min(personalisationBytes.length, SEED_BYTES);
419
- for (let i = 0; i < lim; i++) seed[i] ^= personalisationBytes[i];
420
- }
421
- return seed;
422
- }
423
-
424
- // §10.2.1.3 Instantiate (df or no-df depending on `useDf`).
425
- // df : (entropy, nonce, persoString) → df → seed
426
- // no-df : (entropy, persoString) - entropy must be SEED_BYTES
427
- function instantiate(entropyBytes, personalisationBytes, nonceBytes) {
428
- const seed = _distill(entropyBytes, personalisationBytes, nonceBytes);
429
- if (seed === false) return false;
430
- K.fill(0); V.fill(0);
431
- if (!_rebuild()) return false;
432
- if (!_update(_bytesToWords(seed))) return false;
433
- reseedCt = 1;
434
- live = true;
435
- return true;
436
- }
437
-
438
- // §10.2.1.4 Reseed (df or no-df).
439
- function reseed(entropyBytes, additionalInputBytes) {
440
- if (!live) {
441
- console.warn('[crypto] NOT READY: ctr_drbg.reseed: not instantiated');
442
- return false;
443
- }
444
- // Reseed: nonce field unused (nonce is for instantiate only).
445
- const seed = _distill(entropyBytes, additionalInputBytes, null);
446
- if (seed === false) return false;
447
- if (!_update(_bytesToWords(seed))) return false;
448
- reseedCt = 1;
449
- return true;
450
- }
451
-
452
- // §10.2.1.5.1 Generate (no df)
453
- function generate(n, additionalInputBytes) {
454
- if (!live) {
455
- console.warn('[crypto] NOT READY: ctr_drbg.generate: not instantiated');
456
- return false;
457
- }
458
- if (!Number.isInteger(n) || n < 0 || n > _MAX_GEN_BYTES) {
459
- console.warn('[crypto] INVALID: ctr_drbg.generate: n must be an integer in [0, ' + _MAX_GEN_BYTES + ']');
460
- return false;
461
- }
462
- if (n === 0) return new Uint8Array(0);
463
-
464
- if (reseedCt > _RESEED_INTERVAL) {
465
- const fresh = _getEntropy(SEED_BYTES);
466
- if (fresh === false) return false;
467
- if (!reseed(fresh, additionalInputBytes)) return false;
468
- additionalInputBytes = null;
469
- }
470
-
471
- let aiWords;
472
- if (additionalInputBytes && additionalInputBytes.length > 0) {
473
- let aiBytes;
474
- if (useDf) {
475
- aiBytes = _df(additionalInputBytes, SEED_BYTES);
476
- if (aiBytes === false) return false;
477
- } else {
478
- aiBytes = new Uint8Array(SEED_BYTES);
479
- aiBytes.set(additionalInputBytes.subarray(0, Math.min(SEED_BYTES, additionalInputBytes.length)));
480
- }
481
- aiWords = _bytesToWords(aiBytes);
482
- if (!_update(aiWords)) return false;
483
- } else {
484
- aiWords = new Array(SEED_WORDS).fill(0);
485
- }
486
-
487
- const out = new Uint8Array(n);
488
- let off = 0;
489
- while (off < n) {
490
- _incV();
491
- const blk = cipher.encrypt(V);
492
- const remaining = n - off;
493
- if (remaining >= 16) {
494
- _wordsToBytes(blk, _BLK_WORDS, out, off);
495
- off += 16;
496
- } else {
497
- const tmp = new Uint8Array(16);
498
- _wordsToBytes(blk, _BLK_WORDS, tmp, 0);
499
- out.set(tmp.subarray(0, remaining), off);
500
- off = n;
501
- }
502
- }
503
-
504
- if (!_update(aiWords)) return false;
505
- reseedCt++;
506
- return out;
507
- }
508
-
509
- // §11.3 uninstantiate - wipe state
510
- function uninstantiate() {
511
- K.fill(0); V.fill(0);
512
- cipher = null; reseedCt = 0; live = false;
513
- }
514
-
515
- return {
516
- instantiate, reseed, generate, uninstantiate,
517
- get isLive() { return live; },
518
- get reseedCounter() { return reseedCt; },
519
- get securityStrength() { return aesKeyBits; },
520
- get aesKeyBits() { return aesKeyBits; },
521
- get useDf() { return useDf; },
522
- get seedBytes() { return SEED_BYTES; }
523
- };
524
- }
525
-
526
- // ── Power-On Self-Test (KAT) - FIPS 140-3 §7.10 ──────────────────
527
- //
528
- // Official NIST CAVP CTR_DRBG vector for AES-256 / no derivation
529
- // function, PredictionResistance=False, EntropyInputLen=256+128
530
- // (entropy ‖ nonce, no-df: passed as one 384-bit seed),
531
- // PersonalizationStringLen=0, AdditionalInputLen=0,
532
- // ReturnedBitsLen=512. Distributed as part of NIST CAVP's
533
- // drbgtestvectors archive
534
- // (https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/random-number-generators)
535
- // and mirrored in BoringSSL's
536
- // `crypto/fipsmodule/rand/ctrdrbg_vectors.txt`.
537
- //
538
- // Test sequence (drbgvectors_pr_false, COUNT=0):
539
- // 1. instantiate(EntropyInput, "")
540
- // 2. reseed(EntropyInputReseed, "")
541
- // 3. generate(512 bits, "") ← discarded
542
- // 4. generate(512 bits, "") == ReturnedBits
543
-
544
- const _KAT_ENTROPY_INPUT = _hexToBytes(
545
- 'e4bc23c5089a19d86f4119cb3fa08c0a' +
546
- '4991e0a1def17e101e4c14d9c323460a' +
547
- '7c2fb58e0b086c6c57b55f56cae25bad'
548
- );
549
- const _KAT_ENTROPY_RESEED = _hexToBytes(
550
- 'fd85a836bba85019881e8c6bad23c906' +
551
- '1adc75477659acaea8e4a01dfe07a183' +
552
- '2dad1c136f59d70f8653a5dc118663d6'
553
- );
554
- const _KAT_EXPECTED_HEX =
555
- 'b2cb8905c05e5950ca31895096be29ea' +
556
- '3d5a3b82b269495554eb80fe07de43e1' +
557
- '93b9e7c3ece73b80e062b1c1f68202fb' +
558
- 'b1c52a040ea2478864295282234aaada';
559
- let _selfTestPassed = null;
560
-
561
- function _hexToBytes(h) {
562
- const out = new Uint8Array(h.length >>> 1);
563
- for (let i = 0; i < out.length; i++) {
564
- out[i] = parseInt(h.substring(i * 2, i * 2 + 2), 16);
565
- }
566
- return out;
567
- }
568
-
569
- function _hex(b) {
570
- let s = '';
571
- for (let i = 0; i < b.length; i++) {
572
- const v = b[i];
573
- s += (v < 16 ? '0' : '') + v.toString(16);
574
- }
575
- return s;
576
- }
577
-
578
- function _runSelfTest() {
579
- const d = _makeDrbg();
580
- // @ts-ignore - comparison with object is safe: _makeDrbg returns false on failure, object otherwise
581
- if (!d || d === false) return false;
582
- if (!d.instantiate(_KAT_ENTROPY_INPUT)) return false;
583
- if (!d.reseed(_KAT_ENTROPY_RESEED)) return false;
584
- if (d.generate(64) === false) return false;
585
- const out = d.generate(64);
586
- if (out === false) return false;
587
- const got = _hex(out);
588
- if (got !== _KAT_EXPECTED_HEX) {
589
- console.error('[crypto] CORRUPT: random.selfTest: CTR_DRBG KAT mismatch (got ' + got + ')');
590
- return false;
591
- }
592
- return true;
593
- }
594
-
595
- function _ensureSelfTest() {
596
- if (_selfTestPassed === null) _selfTestPassed = _runSelfTest();
597
- return _selfTestPassed;
598
- }
599
-
600
- // ── Public API ───────────────────────────────────────────────────
601
-
602
- const api = {
603
-
604
- /**
605
- * Fill an existing typed array in-place with cryptographically
606
- * secure random values and return it.
607
- *
608
- * Valid types: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`,
609
- * `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`,
610
- * `BigInt64Array`, `BigUint64Array`. Passing a `Float32Array` or
611
- * `Float64Array` throws a native `TypeMismatchError`.
612
- *
613
- * @template {TypedArray} T
614
- * @param {T} array
615
- * @returns {T}
616
- */
617
- fill(array) {
618
- // todo should throws a native `TypeMismatchError` with crypto.getRandomValues(array).
619
- // ensure same comportement with _getRandomBytes
620
- return _getRandomBytes(array);
621
- },
622
-
623
- /**
624
- * Return a cryptographically secure random float in `[0, 1)`.
625
- * Derived from one 32-bit random integer divided by 2³².
626
- *
627
- * @returns {number|false}
628
- */
629
- float() {
630
- // Route through _getRandomBytes so the dead-source health
631
- // latch covers float() like the rest of the public API.
632
- const bytes = _getRandomBytes(new Uint8Array(4));
633
- if (bytes === false) return false;
634
- const v = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;
635
- return v / 0x1_0000_0000;
636
- },
637
-
638
- /**
639
- * Return a cryptographically secure random integer in the inclusive
640
- * range `[min, max]`.
641
- *
642
- * Uses rejection sampling to eliminate modulo bias. For ranges much
643
- * smaller than 2³² the expected iteration count is below 2.
644
- *
645
- * @param {number} min - Lower bound (inclusive).
646
- * @param {number} max - Upper bound (inclusive).
647
- * @returns {number|false}
648
- * @throws {RangeError} When `min > max`.
649
- */
650
- int(min, max) {
651
- if (min > max) throw new RangeError('min must be ≤ max');
652
- const range = max - min + 1;
653
- const maxUnbiased = Math.floor(0x1_0000_0000 / range) * range;
654
- const buf = new Uint8Array(4);
655
- let value;
656
- do {
657
- if (_getRandomBytes(buf) === false) return false;
658
- value = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]) >>> 0;
659
- } while (value >= maxUnbiased);
660
- return min + (value % range);
661
- },
662
-
663
- /** Generate `n` cryptographically random bytes (direct OS RBG). */
664
- bytes(n) {
665
- if (!Number.isInteger(n) || n < 0) {
666
- console.warn('[crypto] INVALID: random.bytes expects a non-negative integer');
667
- return false;
668
- }
669
- return _getRandomBytes(new Uint8Array(n));
670
- },
671
-
672
- /** Generate `n` cryptographically random 32-bit words (direct OS RBG). */
673
- words(n) {
674
- if (!Number.isInteger(n) || n < 0) {
675
- console.warn('[crypto] INVALID: random.words expects a non-negative integer');
676
- return false;
677
- }
678
- const bytes = _getRandomBytes(new Uint8Array(n * 4));
679
- if (bytes === false) return false;
680
- const out = new Array(n);
681
- for (let i = 0; i < n; i++) {
682
- const j = i * 4;
683
- out[i] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) | 0;
684
- }
685
- return out;
686
- },
687
-
688
- /** Generate a random bit array of `n` bits (direct OS RBG). */
689
- bits(n) {
690
- if (!Number.isInteger(n) || n < 0) {
691
- console.warn('[crypto] INVALID: random.bits expects a non-negative integer');
692
- return false;
693
- }
694
- const wordCount = Math.ceil(n / 32);
695
- const words = api.words(wordCount);
696
- if (words === false) return false;
697
- return bitArray.clamp(words, n);
698
- },
699
-
700
- /** `true` when `crypto.getRandomValues` is available. */
701
- isReady() { return _hasCrypto; },
702
-
703
- /** Run / re-run the CTR_DRBG power-on self-test. */
704
- selfTest() { _selfTestPassed = _runSelfTest(); return _selfTestPassed; },
705
-
706
- /**
707
- * Test-only escape hatch exposing the internal CTR_DRBG factory
708
- * with caller-controlled seed material. **Not for production
709
- * use** - the public `drbg()` API auto-pulls OS entropy and is
710
- * the only path with full FIPS 140-3 lifecycle (POST, RCT/APT
711
- * health tests, OS NRBG seeding). This surface exists exclusively
712
- * to replay NIST CAVP / ACVP DRBG vectors with deterministic
713
- * entropy inputs, so the algorithm itself can be byte-exact
714
- * validated against the reference vectors.
715
- */
716
- _internal: { makeDrbg: _makeDrbg },
717
-
718
- /**
719
- * SP 800-90B continuous health-test surface - primarily for
720
- * test harnesses and operational diagnostics.
721
- *
722
- * NOTE: the RCT/APT state and `_entropyDead` latch are
723
- * **module-singleton** - they are shared across every
724
- * `bytes()`/`words()`/`bits()`/`float()`/`int()`/`drbg()` call,
725
- * and across multiple DRBG instances built from this factory.
726
- * The underlying entropy source (`crypto.getRandomValues`) is
727
- * itself process-global, so a single shared health latch
728
- * matches reality. Tests that need a fresh state must call
729
- * `reset()` between scenarios.
730
- *
731
- * `feed(buf)` : push bytes through RCT + APT (returns false on fail).
732
- * `reset()` : clear state and clear the latched-dead flag.
733
- * `isDead` : true once any continuous test has failed.
734
- */
735
- health: {
736
- feed(buf) { return _healthCheck(buf instanceof Uint8Array ? buf : new Uint8Array(buf)); },
737
- reset() { _resetHealth(); },
738
- get isDead() { return _entropyDead; }
739
- },
740
-
741
- /**
742
- * Build a fresh CTR_DRBG-AES-256 (no-df) instance.
743
- *
744
- * @param {object} [options]
745
- * @param {Uint8Array} [options.personalisation] Up to 48 bytes of personalisation
746
- * string mixed into the seed (XORed,
747
- * truncated as per SP 800-90A §10.2.1.3.1
748
- * when no df is used).
749
- * @returns {object|false} DRBG instance or `false` on POST/seed failure.
750
- *
751
- * The returned object exposes:
752
- * - `generate(n, additionalInput?)` → `Uint8Array | false`
753
- * - `reseed(additionalInput?)` → `boolean` (pulls fresh entropy from OS RBG)
754
- * - `addAdditionalInput(bytes)` → mix arbitrary bytes into the next `generate()`
755
- * - `uninstantiate()` → wipe internal state
756
- * - `isLive`, `reseedCounter`, `securityStrength`
757
- */
758
- drbg(options = {}) {
759
- if (!_ensureSelfTest()) {
760
- console.error('[crypto] CORRUPT: random.drbg refused - POST failed');
761
- return false;
762
- }
763
- const inst = _makeDrbg(options);
764
- if (inst === false) return false;
765
- const seed = _getEntropy(inst.seedBytes);
766
- if (seed === false) return false;
767
- if (!inst.instantiate(seed, options.personalisation)) return false;
768
-
769
- // Buffer of pending additional_input (e.g. from entropyCollector).
770
- let pending = null;
771
-
772
- return {
773
- generate(n, additionalInput) {
774
- let ai = additionalInput || null;
775
- if (pending !== null) {
776
- ai = ai === null ? pending
777
- : (() => { const m = new Uint8Array(pending.length + ai.length);
778
- m.set(pending); m.set(ai, pending.length); return m; })();
779
- pending = null;
780
- }
781
- return inst.generate(n, ai);
782
- },
783
- reseed(additionalInput) {
784
- const fresh = _getEntropy(inst.seedBytes);
785
- if (fresh === false) return false;
786
- let ai = additionalInput || null;
787
- if (pending !== null) {
788
- ai = ai === null ? pending
789
- : (() => { const m = new Uint8Array(pending.length + ai.length);
790
- m.set(pending); m.set(ai, pending.length); return m; })();
791
- pending = null;
792
- }
793
- return inst.reseed(fresh, ai);
794
- },
795
- /**
796
- * Accumulate caller-supplied entropy (e.g. mouse/keyboard timings
797
- * from `entropyCollector`) into a pending buffer that is consumed
798
- * on the next `generate()` or `reseed()` as `additional_input`.
799
- * Inputs longer than `seedlen` (48 bytes) are folded through
800
- * SHA-256 to bound the buffer.
801
- */
802
- addAdditionalInput(bytes) {
803
- if (!(bytes instanceof Uint8Array)) {
804
- if (Array.isArray(bytes) || bytes instanceof Uint32Array) {
805
- const tmp = new Uint8Array(bytes.length * 4);
806
- for (let i = 0; i < bytes.length; i++) {
807
- const v = bytes[i] | 0;
808
- tmp[i * 4] = (v >>> 24) & 0xff;
809
- tmp[i * 4 + 1] = (v >>> 16) & 0xff;
810
- tmp[i * 4 + 2] = (v >>> 8) & 0xff;
811
- tmp[i * 4 + 3] = v & 0xff;
812
- }
813
- bytes = tmp;
814
- } else if (typeof bytes === 'number') {
815
- const v = bytes | 0;
816
- bytes = new Uint8Array([(v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff]);
817
- } else {
818
- console.warn('[crypto] BUG: drbg.addAdditionalInput: unsupported data type');
819
- return false;
820
- }
821
- }
822
- const merged = pending === null ? bytes
823
- : (() => { const m = new Uint8Array(pending.length + bytes.length);
824
- m.set(pending); m.set(bytes, pending.length); return m; })();
825
- if (merged.length <= inst.seedBytes) {
826
- pending = merged;
827
- } else {
828
- // Fold to 32 bytes via SHA-256 to bound the buffer.
829
- const h = sha256.hash(_bytesToWords(merged.subarray(0, merged.length & ~3)));
830
- const folded = new Uint8Array(32);
831
- _wordsToBytes(h, 8, folded, 0);
832
- pending = folded;
833
- }
834
- return true;
835
- },
836
- uninstantiate() { pending = null; inst.uninstantiate(); },
837
- get isLive() { return inst.isLive; },
838
- get reseedCounter() { return inst.reseedCounter; },
839
- get securityStrength() { return inst.securityStrength; }
840
- };
841
- }
842
- };
843
-
844
- return api;
845
- }
846
- };
1
+ // Copyright (c) 2026 AwaCloud SAS
2
+ // Author: Matthieu Bouilloux
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * @typedef {Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|BigInt64Array|BigUint64Array} TypedArray
7
+ */
8
+
9
+ /**
10
+ * @fileoverview CSPRNG wrapper around `crypto.getRandomValues` plus a
11
+ * SP 800-90A compliant CTR_DRBG-AES-256 (no derivation function).
12
+ *
13
+ * Two surfaces are exposed:
14
+ *
15
+ * 1. **Direct API** (`bytes`, `words`, `bits`, `isReady`) - thin wrapper
16
+ * over `crypto.getRandomValues`. Vetted by the platform; the recommended
17
+ * path for general-purpose use.
18
+ *
19
+ * 2. **`drbg(options)`** - instantiates a CTR_DRBG per NIST SP 800-90A
20
+ * §10.2 (AES-256, no df). Suitable as a FIPS 140-3 "approved" DRBG
21
+ * assuming the entropy source (`crypto.getRandomValues`, treated as a
22
+ * validated NRBG per SP 800-90C) and the surrounding module satisfy
23
+ * the rest of the FIPS module-level requirements.
24
+ *
25
+ * The DRBG performs:
26
+ * - **POST / KAT** at first instantiation (cached process-wide),
27
+ * - **Continuous health test (RCT)** on every entropy buffer drawn
28
+ * from `crypto.getRandomValues` (SP 800-90B §4.4.1),
29
+ * - **Reseed** with fresh OS entropy when the reseed_counter exceeds
30
+ * the configured limit (default 2^32, well below the 2^48 spec cap),
31
+ * - Acceptance of `additional_input` on every `generate()` call so that
32
+ * environmental entropy (e.g. from `entropyCollector`) can be mixed
33
+ * in without depending on its module at construction time.
34
+ *
35
+ * `entropyCollector` is **not** a dependency: the caller wires its
36
+ * callback to `drbg.addAdditionalInput()` so that the next `generate()`
37
+ * consumes the accumulated bytes via the spec-defined update path.
38
+ * This keeps `random` worker-safe (DOM-free).
39
+ *
40
+ * The KAT vector used by `_runSelfTest()` is the official NIST CAVP
41
+ * CTR_DRBG-AES-256 (no-df, PredictionResistance=False, COUNT=0) vector from
42
+ * the `drbgvectors_pr_false` archive
43
+ * (https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/random-number-generators)
44
+ * - also mirrored in BoringSSL's `crypto/fipsmodule/rand/ctrdrbg_vectors.txt`.
45
+ * Sufficient for the algorithmic KAT; full FIPS 140-3 validation additionally
46
+ * requires the surrounding module-level operational tests outside this file.
47
+ *
48
+ */
49
+
50
+ /**
51
+ * Low-level CTR_DRBG instance produced by the internal `_makeDrbg` factory
52
+ * (exposed in the internal slot as `makeDrbg`). Caller drives the full SP 800-90A
53
+ * lifecycle manually with explicit seed material.
54
+ * @typedef {object} DrbgCore
55
+ * @property {(entropyBytes: Uint8Array, personalisationBytes?: Uint8Array, nonceBytes?: Uint8Array) => boolean} instantiate Seed the DRBG.
56
+ * @property {(entropyBytes: Uint8Array, additionalInputBytes?: Uint8Array) => boolean} reseed Reseed with caller-supplied entropy.
57
+ * @property {(n: number, additionalInputBytes?: Uint8Array) => (Uint8Array | false)} generate Produce `n` random bytes.
58
+ * @property {() => void} uninstantiate Wipe internal state.
59
+ * @property {boolean} isLive Whether the DRBG has been instantiated (getter).
60
+ * @property {number} reseedCounter Current reseed counter (getter).
61
+ * @property {number} securityStrength Security strength in bits (getter).
62
+ * @property {number} aesKeyBits Configured AES key size in bits (getter).
63
+ * @property {boolean} useDf Whether a derivation function is used (getter).
64
+ * @property {number} seedBytes Seed length in bytes (getter).
65
+ */
66
+
67
+ /**
68
+ * High-level CTR_DRBG instance returned by `api.drbg(options)`. Auto-seeds
69
+ * from OS entropy and supports mixing in pending additional input.
70
+ * @typedef {object} Drbg
71
+ * @property {(n: number, additionalInput?: Uint8Array) => (Uint8Array | false)} generate Produce `n` random bytes, folding in any pending additional input.
72
+ * @property {(additionalInput?: Uint8Array) => boolean} reseed Reseed with fresh OS entropy.
73
+ * @property {(bytes: Uint8Array | number[] | Uint32Array | number) => boolean} addAdditionalInput Buffer entropy for the next `generate()`/`reseed()`.
74
+ * @property {() => void} uninstantiate Wipe internal state and pending buffer.
75
+ * @property {boolean} isLive Whether the DRBG is live (getter).
76
+ * @property {number} reseedCounter Current reseed counter (getter).
77
+ * @property {number} securityStrength Security strength in bits (getter).
78
+ */
79
+
80
+ /**
81
+ * SP 800-90B continuous health-test surface.
82
+ * @typedef {object} RandomHealth
83
+ * @property {(buf: Uint8Array | number[]) => boolean} feed Push bytes through RCT + APT; `false` on failure.
84
+ * @property {() => void} reset Clear state and the latched-dead flag.
85
+ * @property {boolean} isDead True once any continuous test has failed (getter).
86
+ */
87
+
88
+ /**
89
+ * Public shape returned by `random.factory()`.
90
+ * @typedef {object} RandomAPI
91
+ * @property {<T extends TypedArray>(array: T) => T} fill Fill a typed array in place with secure random values.
92
+ * @property {() => (number | false)} float Secure random float in `[0, 1)`.
93
+ * @property {(min: number, max: number) => (number | false)} int Secure random integer in `[min, max]` (rejection-sampled).
94
+ * @property {(n: number) => (Uint8Array | false)} bytes `n` random bytes (direct OS RBG).
95
+ * @property {(n: number) => (number[] | false)} words `n` random 32-bit words (direct OS RBG).
96
+ * @property {(n: number) => (number[] | false)} bits Random bit array of `n` bits (direct OS RBG).
97
+ * @property {() => boolean} isReady Whether `crypto.getRandomValues` is available.
98
+ * @property {() => boolean} selfTest Run / re-run the CTR_DRBG power-on self-test.
99
+ * @property {RandomHealth} health Continuous health-test surface.
100
+ * @property {(options?: { aesKeyBits?: 128|192|256, df?: boolean, personalisation?: Uint8Array }) => (Drbg | false)} drbg Build a fresh CTR_DRBG-AES-256 (no-df) instance.
101
+ */
102
+
103
+ import { bitArray } from './bitArray.js';
104
+ import { aes } from '../cipher/aes.js';
105
+ import { sha256 } from '../hash/sha256.js';
106
+
107
+ export const random = {
108
+ name: 'random',
109
+ version: '1.0.0',
110
+ type: 'fw.crypto.utils',
111
+ dependencies: ['bitArray', 'aes', 'sha256'],
112
+ deps: [bitArray, aes, sha256],
113
+
114
+ /** @returns {RandomAPI} */
115
+ factory(bitArray, aes, sha256) {
116
+
117
+ const _MAX_BYTES_PER_CALL = 65536;
118
+ const _hasCrypto = typeof crypto !== 'undefined' && !!crypto.getRandomValues;
119
+
120
+ // ── byte/word helpers (big-endian, AES convention) ───────────────
121
+
122
+ function _bytesToWords(b) {
123
+ const n = b.length >>> 2;
124
+ const out = new Array(n);
125
+ for (let i = 0; i < n; i++) {
126
+ const j = i << 2;
127
+ out[i] = ((b[j] << 24) | (b[j + 1] << 16) | (b[j + 2] << 8) | b[j + 3]) | 0;
128
+ }
129
+ return out;
130
+ }
131
+ function _wordsToBytes(w, count, into, off) {
132
+ for (let i = 0; i < count; i++) {
133
+ const j = off + (i << 2);
134
+ into[j] = (w[i] >>> 24) & 0xff;
135
+ into[j + 1] = (w[i] >>> 16) & 0xff;
136
+ into[j + 2] = (w[i] >>> 8) & 0xff;
137
+ into[j + 3] = w[i] & 0xff;
138
+ }
139
+ }
140
+
141
+ // ── continuous health tests (SP 800-90B §4.4) ────────────────────
142
+ //
143
+ // Both tests run continuously across the lifetime of the entropy
144
+ // source - state persists across calls, not per-buffer. Once either
145
+ // test fails, the source is marked dead permanently (SP 800-90B §4.5:
146
+ // "Once a continuous test failure is detected, no more outputs from
147
+ // the noise source shall be used").
148
+ //
149
+ // Parameters assume a full-entropy byte source (H = 8 bits/byte) and
150
+ // α = 2^-20 false-alarm probability:
151
+ //
152
+ // RCT (§4.4.1) - Repetition Count Test
153
+ // C_rct = 1 + ⌈-log2(α) / H⌉ = 1 + ⌈20/8⌉ = 4
154
+ // Fail if 4 identical consecutive samples.
155
+ //
156
+ // APT (§4.4.2) - Adaptive Proportion Test
157
+ // Window W = 512 samples, p = 2^-H = 1/256, mean = 2.
158
+ // Cutoff C_apt = 13 (smallest C such that P(Bin(512,1/256) > C) ≤ α).
159
+ // Fail if the anchor sample appears more than 13 times in the
160
+ // non-overlapping 512-sample window.
161
+
162
+ const _RCT_CUTOFF = 4;
163
+ const _APT_W = 512;
164
+ const _APT_C = 13;
165
+
166
+ const _rct = { prev: -1, run: 0 };
167
+ const _apt = { anchor: -1, count: 0, idx: 0 };
168
+ let _entropyDead = false;
169
+
170
+ function _healthCheck(buf) {
171
+ if (_entropyDead) return false;
172
+ for (let i = 0; i < buf.length; i++) {
173
+ const b = buf[i];
174
+
175
+ // RCT
176
+ if (b === _rct.prev) {
177
+ _rct.run++;
178
+ if (_rct.run >= _RCT_CUTOFF) {
179
+ _entropyDead = true;
180
+ console.error('[crypto] CORRUPT: random: RCT health-test failed on entropy source');
181
+ return false;
182
+ }
183
+ } else {
184
+ _rct.prev = b;
185
+ _rct.run = 1;
186
+ }
187
+
188
+ // APT
189
+ if (_apt.anchor === -1) {
190
+ _apt.anchor = b;
191
+ _apt.count = 1;
192
+ _apt.idx = 1;
193
+ } else {
194
+ _apt.idx++;
195
+ if (b === _apt.anchor) {
196
+ _apt.count++;
197
+ if (_apt.count > _APT_C) {
198
+ _entropyDead = true;
199
+ console.error('[crypto] CORRUPT: random: APT health-test failed on entropy source');
200
+ return false;
201
+ }
202
+ }
203
+ if (_apt.idx >= _APT_W) _apt.anchor = -1;
204
+ }
205
+ }
206
+ return true;
207
+ }
208
+
209
+ function _resetHealth() {
210
+ _rct.prev = -1; _rct.run = 0;
211
+ _apt.anchor = -1; _apt.count = 0; _apt.idx = 0;
212
+ _entropyDead = false;
213
+ }
214
+
215
+ // ── raw OS entropy with chunking + continuous health tests ───────
216
+
217
+ function _getRandomBytes(out) {
218
+ if (!_hasCrypto) {
219
+ console.error('[crypto] NOT READY: crypto.getRandomValues unavailable');
220
+ return false;
221
+ }
222
+ let offset = 0;
223
+ while (offset < out.length) {
224
+ const chunk = Math.min(_MAX_BYTES_PER_CALL, out.length - offset);
225
+ crypto.getRandomValues(out.subarray(offset, offset + chunk));
226
+ offset += chunk;
227
+ }
228
+ return out;
229
+ }
230
+ function _getEntropy(nBytes) {
231
+ if (_entropyDead) {
232
+ console.error('[crypto] CORRUPT: random: entropy source previously failed health test');
233
+ return false;
234
+ }
235
+ const buf = _getRandomBytes(new Uint8Array(nBytes));
236
+ if (buf === false) return false;
237
+ if (!_healthCheck(buf)) return false;
238
+ return buf;
239
+ }
240
+
241
+ // ── CTR_DRBG-AES-{128,192,256}, no-df + with-df - SP 800-90A §10.2 ──
242
+ //
243
+ // Parameters (parametric):
244
+ // aesKeyBits ∈ {128, 192, 256} → keylen = 16 / 24 / 32 bytes
245
+ // blocklen = 16 bytes (AES)
246
+ // seedlen = keylen + blocklen
247
+ // security_strength = aesKeyBits
248
+ // reseed_interval ≤ 2^48 (we use 2^32 for safety)
249
+ // max_bytes_per_request ≤ 2^19 bits = 65536 bytes
250
+ // df : SP 800-90A §10.4.2 Block Cipher Derivation Function.
251
+ // If true, instantiate/reseed accept any-length entropy +
252
+ // nonce + perso/additional-input strings ; df distills them
253
+ // into seedlen bytes via BCC. If false, all inputs must be
254
+ // exactly seedlen bytes.
255
+
256
+ const _BLK_WORDS = 4;
257
+ const _BLK_BYTES = 16;
258
+ const _MAX_GEN_BYTES = 65536;
259
+ const _RESEED_INTERVAL = 0x100000000; // 2^32, < spec cap 2^48
260
+
261
+ // Build a CTR_DRBG instance.
262
+ // @param {object} [opts]
263
+ // @param {128|192|256} [opts.aesKeyBits=256]
264
+ // @param {boolean} [opts.df=false]
265
+ function _makeDrbg(opts) {
266
+ opts = opts || {};
267
+ const aesKeyBits = opts.aesKeyBits || 256;
268
+ const useDf = !!opts.df;
269
+ if (aesKeyBits !== 128 && aesKeyBits !== 192 && aesKeyBits !== 256) {
270
+ console.error('[crypto] BUG: ctr_drbg: aesKeyBits must be 128, 192 or 256');
271
+ return false;
272
+ }
273
+ const KEY_BYTES = aesKeyBits / 8;
274
+ const KEY_WORDS = KEY_BYTES / 4;
275
+ const SEED_BYTES = KEY_BYTES + _BLK_BYTES;
276
+ const SEED_WORDS = SEED_BYTES / 4;
277
+
278
+ let K = new Array(KEY_WORDS).fill(0);
279
+ let V = new Array(_BLK_WORDS).fill(0);
280
+ let cipher = null;
281
+ let reseedCt = 0;
282
+ let live = false;
283
+
284
+ // ── SP 800-90A §10.4.2 - Block Cipher Derivation Function ────
285
+ //
286
+ // BCC(K, data): CBC-MAC of `data` (multiple of 16 bytes) under K.
287
+ function _bcc(Kbytes, dataBytes) {
288
+ const cf = aes.fn(_bytesToWords(Kbytes), false);
289
+ if (cf === false) return false;
290
+ const chain = new Uint8Array(_BLK_BYTES);
291
+ for (let off = 0; off < dataBytes.length; off += _BLK_BYTES) {
292
+ for (let i = 0; i < _BLK_BYTES; i++) chain[i] ^= dataBytes[off + i];
293
+ const blk = cf.encrypt(_bytesToWords(chain));
294
+ _wordsToBytes(blk, _BLK_WORDS, chain, 0);
295
+ }
296
+ return chain;
297
+ }
298
+
299
+ // Block_Cipher_df(input, no_of_bits_to_return) → bytes.
300
+ // Returns SEED_BYTES of distilled output.
301
+ function _df(inputBytes, outBytes) {
302
+ // S = L (4 BE) || N (4 BE) || input || 0x80 || 0x00…0
303
+ const L = inputBytes.length;
304
+ const N = outBytes;
305
+ const headerLen = 4 + 4;
306
+ const rawLen = headerLen + L + 1;
307
+ const padLen = (_BLK_BYTES - (rawLen % _BLK_BYTES)) % _BLK_BYTES;
308
+ const Slen = rawLen + padLen;
309
+ const S = new Uint8Array(Slen);
310
+ S[0] = (L >>> 24) & 0xff; S[1] = (L >>> 16) & 0xff;
311
+ S[2] = (L >>> 8) & 0xff; S[3] = L & 0xff;
312
+ S[4] = (N >>> 24) & 0xff; S[5] = (N >>> 16) & 0xff;
313
+ S[6] = (N >>> 8) & 0xff; S[7] = N & 0xff;
314
+ for (let i = 0; i < L; i++) S[headerLen + i] = inputBytes[i];
315
+ S[headerLen + L] = 0x80;
316
+ // padding 0x00 already set by Uint8Array init.
317
+
318
+ // K_df = 0x00 01 02 … (KEY_BYTES bytes)
319
+ const Kdf = new Uint8Array(KEY_BYTES);
320
+ for (let i = 0; i < KEY_BYTES; i++) Kdf[i] = i;
321
+
322
+ // temp = "" ; while len(temp) < KEY_BYTES + BLK_BYTES :
323
+ // IV = i (4 BE) || 0…0 (BLK-4 zero bytes)
324
+ // temp ||= BCC(K_df, IV || S)
325
+ const tempLen = KEY_BYTES + _BLK_BYTES;
326
+ const temp = new Uint8Array(Math.ceil(tempLen / _BLK_BYTES) * _BLK_BYTES);
327
+ let tempOff = 0;
328
+ let i = 0;
329
+ while (tempOff < tempLen) {
330
+ const ivS = new Uint8Array(_BLK_BYTES + Slen);
331
+ ivS[0] = (i >>> 24) & 0xff; ivS[1] = (i >>> 16) & 0xff;
332
+ ivS[2] = (i >>> 8) & 0xff; ivS[3] = i & 0xff;
333
+ ivS.set(S, _BLK_BYTES);
334
+ const blk = _bcc(Kdf, ivS);
335
+ if (blk === false) return false;
336
+ temp.set(blk, tempOff);
337
+ tempOff += _BLK_BYTES;
338
+ i++;
339
+ }
340
+
341
+ // K' = first KEY_BYTES of temp ; X = next BLK_BYTES of temp.
342
+ const Kp = temp.subarray(0, KEY_BYTES);
343
+ let X = temp.slice(KEY_BYTES, KEY_BYTES + _BLK_BYTES);
344
+ const cf = aes.fn(_bytesToWords(Kp), false);
345
+ if (cf === false) return false;
346
+
347
+ const out = new Uint8Array(outBytes);
348
+ let outOff = 0;
349
+ while (outOff < outBytes) {
350
+ const blk = cf.encrypt(_bytesToWords(X));
351
+ _wordsToBytes(blk, _BLK_WORDS, X, 0);
352
+ const n = Math.min(_BLK_BYTES, outBytes - outOff);
353
+ out.set(X.subarray(0, n), outOff);
354
+ outOff += n;
355
+ }
356
+ return out;
357
+ }
358
+
359
+ function _rebuild() {
360
+ cipher = aes.fn(K, false);
361
+ if (cipher === false) {
362
+ console.error('[crypto] BUG: ctr_drbg: AES key schedule failed');
363
+ return false;
364
+ }
365
+ return true;
366
+ }
367
+
368
+ function _incV() {
369
+ for (let i = _BLK_WORDS - 1; i >= 0; i--) {
370
+ V[i] = (V[i] + 1) | 0;
371
+ if (V[i] !== 0) break;
372
+ }
373
+ }
374
+
375
+ // CTR_DRBG_Update(provided_data: SEED_WORDS, K, V) - §10.2.1.2
376
+ function _update(providedWords) {
377
+ const temp = new Array(SEED_WORDS).fill(0);
378
+ let pos = 0;
379
+ while (pos < SEED_WORDS) {
380
+ _incV();
381
+ const blk = cipher.encrypt(V);
382
+ for (let j = 0; j < _BLK_WORDS && pos < SEED_WORDS; j++) {
383
+ temp[pos++] = blk[j];
384
+ }
385
+ }
386
+ for (let i = 0; i < SEED_WORDS; i++) temp[i] ^= providedWords[i];
387
+ K = temp.slice(0, KEY_WORDS);
388
+ // Slice exactly _BLK_WORDS for V (avoid AES-192 case where
389
+ // SEED_WORDS = KEY_WORDS + BLK_WORDS = 10 but temp could be
390
+ // longer if generated incorrectly).
391
+ V = temp.slice(KEY_WORDS, KEY_WORDS + _BLK_WORDS);
392
+ return _rebuild();
393
+ }
394
+
395
+ // Distill arbitrary inputs to a SEED_BYTES seed.
396
+ // no-df : caller must provide exactly SEED_BYTES of entropy ;
397
+ // perso/AI is XOR-truncated/padded to SEED_BYTES.
398
+ // df : entropy + nonce + perso (concatenated) → df → SEED_BYTES.
399
+ function _distill(entropyBytes, personalisationBytes, nonceBytes) {
400
+ if (useDf) {
401
+ const eLen = entropyBytes ? entropyBytes.length : 0;
402
+ const nLen = nonceBytes ? nonceBytes.length : 0;
403
+ const pLen = personalisationBytes ? personalisationBytes.length : 0;
404
+ const cat = new Uint8Array(eLen + nLen + pLen);
405
+ if (eLen) cat.set(entropyBytes, 0);
406
+ if (nLen) cat.set(nonceBytes, eLen);
407
+ if (pLen) cat.set(personalisationBytes, eLen + nLen);
408
+ return _df(cat, SEED_BYTES);
409
+ }
410
+ if (!entropyBytes || entropyBytes.length !== SEED_BYTES) {
411
+ console.error('[crypto] BUG: ctr_drbg (no-df): entropy must be exactly ' + SEED_BYTES + ' bytes');
412
+ return false;
413
+ }
414
+ const seed = new Uint8Array(SEED_BYTES);
415
+ seed.set(entropyBytes);
416
+ if (personalisationBytes && personalisationBytes.length > 0) {
417
+ const lim = Math.min(personalisationBytes.length, SEED_BYTES);
418
+ for (let i = 0; i < lim; i++) seed[i] ^= personalisationBytes[i];
419
+ }
420
+ return seed;
421
+ }
422
+
423
+ // §10.2.1.3 Instantiate (df or no-df depending on `useDf`).
424
+ // df : (entropy, nonce, persoString) → df → seed
425
+ // no-df : (entropy, persoString) - entropy must be SEED_BYTES
426
+ function instantiate(entropyBytes, personalisationBytes, nonceBytes) {
427
+ const seed = _distill(entropyBytes, personalisationBytes, nonceBytes);
428
+ if (seed === false) return false;
429
+ K.fill(0); V.fill(0);
430
+ if (!_rebuild()) return false;
431
+ if (!_update(_bytesToWords(seed))) return false;
432
+ reseedCt = 1;
433
+ live = true;
434
+ return true;
435
+ }
436
+
437
+ // §10.2.1.4 Reseed (df or no-df).
438
+ function reseed(entropyBytes, additionalInputBytes) {
439
+ if (!live) {
440
+ console.warn('[crypto] NOT READY: ctr_drbg.reseed: not instantiated');
441
+ return false;
442
+ }
443
+ // Reseed: nonce field unused (nonce is for instantiate only).
444
+ const seed = _distill(entropyBytes, additionalInputBytes, null);
445
+ if (seed === false) return false;
446
+ if (!_update(_bytesToWords(seed))) return false;
447
+ reseedCt = 1;
448
+ return true;
449
+ }
450
+
451
+ // §10.2.1.5.1 Generate (no df)
452
+ function generate(n, additionalInputBytes) {
453
+ if (!live) {
454
+ console.warn('[crypto] NOT READY: ctr_drbg.generate: not instantiated');
455
+ return false;
456
+ }
457
+ if (!Number.isInteger(n) || n < 0 || n > _MAX_GEN_BYTES) {
458
+ console.warn('[crypto] INVALID: ctr_drbg.generate: n must be an integer in [0, ' + _MAX_GEN_BYTES + ']');
459
+ return false;
460
+ }
461
+ if (n === 0) return new Uint8Array(0);
462
+
463
+ if (reseedCt > _RESEED_INTERVAL) {
464
+ const fresh = _getEntropy(SEED_BYTES);
465
+ if (fresh === false) return false;
466
+ if (!reseed(fresh, additionalInputBytes)) return false;
467
+ additionalInputBytes = null;
468
+ }
469
+
470
+ let aiWords;
471
+ if (additionalInputBytes && additionalInputBytes.length > 0) {
472
+ let aiBytes;
473
+ if (useDf) {
474
+ aiBytes = _df(additionalInputBytes, SEED_BYTES);
475
+ if (aiBytes === false) return false;
476
+ } else {
477
+ aiBytes = new Uint8Array(SEED_BYTES);
478
+ aiBytes.set(additionalInputBytes.subarray(0, Math.min(SEED_BYTES, additionalInputBytes.length)));
479
+ }
480
+ aiWords = _bytesToWords(aiBytes);
481
+ if (!_update(aiWords)) return false;
482
+ } else {
483
+ aiWords = new Array(SEED_WORDS).fill(0);
484
+ }
485
+
486
+ const out = new Uint8Array(n);
487
+ let off = 0;
488
+ while (off < n) {
489
+ _incV();
490
+ const blk = cipher.encrypt(V);
491
+ const remaining = n - off;
492
+ if (remaining >= 16) {
493
+ _wordsToBytes(blk, _BLK_WORDS, out, off);
494
+ off += 16;
495
+ } else {
496
+ const tmp = new Uint8Array(16);
497
+ _wordsToBytes(blk, _BLK_WORDS, tmp, 0);
498
+ out.set(tmp.subarray(0, remaining), off);
499
+ off = n;
500
+ }
501
+ }
502
+
503
+ if (!_update(aiWords)) return false;
504
+ reseedCt++;
505
+ return out;
506
+ }
507
+
508
+ // §11.3 uninstantiate - wipe state
509
+ function uninstantiate() {
510
+ K.fill(0); V.fill(0);
511
+ cipher = null; reseedCt = 0; live = false;
512
+ }
513
+
514
+ return {
515
+ instantiate, reseed, generate, uninstantiate,
516
+ get isLive() { return live; },
517
+ get reseedCounter() { return reseedCt; },
518
+ get securityStrength() { return aesKeyBits; },
519
+ get aesKeyBits() { return aesKeyBits; },
520
+ get useDf() { return useDf; },
521
+ get seedBytes() { return SEED_BYTES; }
522
+ };
523
+ }
524
+
525
+ // ── Power-On Self-Test (KAT) - FIPS 140-3 §7.10 ──────────────────
526
+ //
527
+ // Official NIST CAVP CTR_DRBG vector for AES-256 / no derivation
528
+ // function, PredictionResistance=False, EntropyInputLen=256+128
529
+ // (entropy ‖ nonce, no-df: passed as one 384-bit seed),
530
+ // PersonalizationStringLen=0, AdditionalInputLen=0,
531
+ // ReturnedBitsLen=512. Distributed as part of NIST CAVP's
532
+ // drbgtestvectors archive
533
+ // (https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/random-number-generators)
534
+ // and mirrored in BoringSSL's
535
+ // `crypto/fipsmodule/rand/ctrdrbg_vectors.txt`.
536
+ //
537
+ // Test sequence (drbgvectors_pr_false, COUNT=0):
538
+ // 1. instantiate(EntropyInput, "")
539
+ // 2. reseed(EntropyInputReseed, "")
540
+ // 3. generate(512 bits, "") ← discarded
541
+ // 4. generate(512 bits, "") == ReturnedBits
542
+
543
+ const _KAT_ENTROPY_INPUT = _hexToBytes(
544
+ 'e4bc23c5089a19d86f4119cb3fa08c0a' +
545
+ '4991e0a1def17e101e4c14d9c323460a' +
546
+ '7c2fb58e0b086c6c57b55f56cae25bad'
547
+ );
548
+ const _KAT_ENTROPY_RESEED = _hexToBytes(
549
+ 'fd85a836bba85019881e8c6bad23c906' +
550
+ '1adc75477659acaea8e4a01dfe07a183' +
551
+ '2dad1c136f59d70f8653a5dc118663d6'
552
+ );
553
+ const _KAT_EXPECTED_HEX =
554
+ 'b2cb8905c05e5950ca31895096be29ea' +
555
+ '3d5a3b82b269495554eb80fe07de43e1' +
556
+ '93b9e7c3ece73b80e062b1c1f68202fb' +
557
+ 'b1c52a040ea2478864295282234aaada';
558
+ let _selfTestPassed = null;
559
+
560
+ function _hexToBytes(h) {
561
+ const out = new Uint8Array(h.length >>> 1);
562
+ for (let i = 0; i < out.length; i++) {
563
+ out[i] = parseInt(h.substring(i * 2, i * 2 + 2), 16);
564
+ }
565
+ return out;
566
+ }
567
+
568
+ function _hex(b) {
569
+ let s = '';
570
+ for (let i = 0; i < b.length; i++) {
571
+ const v = b[i];
572
+ s += (v < 16 ? '0' : '') + v.toString(16);
573
+ }
574
+ return s;
575
+ }
576
+
577
+ function _runSelfTest() {
578
+ const d = _makeDrbg();
579
+ // @ts-ignore - comparison with object is safe: _makeDrbg returns false on failure, object otherwise
580
+ if (!d || d === false) return false;
581
+ if (!d.instantiate(_KAT_ENTROPY_INPUT)) return false;
582
+ if (!d.reseed(_KAT_ENTROPY_RESEED)) return false;
583
+ if (d.generate(64) === false) return false;
584
+ const out = d.generate(64);
585
+ if (out === false) return false;
586
+ const got = _hex(out);
587
+ if (got !== _KAT_EXPECTED_HEX) {
588
+ console.error('[crypto] CORRUPT: random.selfTest: CTR_DRBG KAT mismatch (got ' + got + ')');
589
+ return false;
590
+ }
591
+ return true;
592
+ }
593
+
594
+ function _ensureSelfTest() {
595
+ if (_selfTestPassed === null) _selfTestPassed = _runSelfTest();
596
+ return _selfTestPassed;
597
+ }
598
+
599
+ // ── Public API ───────────────────────────────────────────────────
600
+
601
+ const api = Object.defineProperty({
602
+
603
+ /**
604
+ * Fill an existing typed array in-place with cryptographically
605
+ * secure random values and return it.
606
+ *
607
+ * Valid types: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`,
608
+ * `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`,
609
+ * `BigInt64Array`, `BigUint64Array`. Passing a `Float32Array` or
610
+ * `Float64Array` throws a native `TypeMismatchError`.
611
+ *
612
+ * @template {TypedArray} T
613
+ * @param {T} array
614
+ * @returns {T}
615
+ */
616
+ fill(array) {
617
+ // todo should throws a native `TypeMismatchError` with crypto.getRandomValues(array).
618
+ // ensure same comportement with _getRandomBytes
619
+ return _getRandomBytes(array);
620
+ },
621
+
622
+ /**
623
+ * Return a cryptographically secure random float in `[0, 1)`.
624
+ * Derived from one 32-bit random integer divided by 2³².
625
+ *
626
+ * @returns {number|false}
627
+ */
628
+ float() {
629
+ // Route through _getRandomBytes, like the rest of the direct
630
+ // API. Note: the RCT/APT health tests and their dead-source
631
+ // latch cover the DRBG entropy path (_getEntropy) only.
632
+ const bytes = _getRandomBytes(new Uint8Array(4));
633
+ if (bytes === false) return false;
634
+ const v = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;
635
+ return v / 0x1_0000_0000;
636
+ },
637
+
638
+ /**
639
+ * Return a cryptographically secure random integer in the inclusive
640
+ * range `[min, max]`.
641
+ *
642
+ * Uses rejection sampling to eliminate modulo bias. For ranges much
643
+ * smaller than 2³² the expected iteration count is below 2.
644
+ *
645
+ * @param {number} min - Lower bound (inclusive).
646
+ * @param {number} max - Upper bound (inclusive).
647
+ * @returns {number|false}
648
+ * @throws {RangeError} When `min > max`.
649
+ */
650
+ int(min, max) {
651
+ if (min > max) throw new RangeError('min must be ≤ max');
652
+ const range = max - min + 1;
653
+ const maxUnbiased = Math.floor(0x1_0000_0000 / range) * range;
654
+ const buf = new Uint8Array(4);
655
+ let value;
656
+ do {
657
+ if (_getRandomBytes(buf) === false) return false;
658
+ value = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]) >>> 0;
659
+ } while (value >= maxUnbiased);
660
+ return min + (value % range);
661
+ },
662
+
663
+ /** Generate `n` cryptographically random bytes (direct OS RBG). */
664
+ bytes(n) {
665
+ if (!Number.isInteger(n) || n < 0) {
666
+ console.warn('[crypto] INVALID: random.bytes expects a non-negative integer');
667
+ return false;
668
+ }
669
+ return _getRandomBytes(new Uint8Array(n));
670
+ },
671
+
672
+ /** Generate `n` cryptographically random 32-bit words (direct OS RBG). */
673
+ words(n) {
674
+ if (!Number.isInteger(n) || n < 0) {
675
+ console.warn('[crypto] INVALID: random.words expects a non-negative integer');
676
+ return false;
677
+ }
678
+ const bytes = _getRandomBytes(new Uint8Array(n * 4));
679
+ if (bytes === false) return false;
680
+ const out = new Array(n);
681
+ for (let i = 0; i < n; i++) {
682
+ const j = i * 4;
683
+ out[i] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) | 0;
684
+ }
685
+ return out;
686
+ },
687
+
688
+ /** Generate a random bit array of `n` bits (direct OS RBG). */
689
+ bits(n) {
690
+ if (!Number.isInteger(n) || n < 0) {
691
+ console.warn('[crypto] INVALID: random.bits expects a non-negative integer');
692
+ return false;
693
+ }
694
+ const wordCount = Math.ceil(n / 32);
695
+ const words = api.words(wordCount);
696
+ if (words === false) return false;
697
+ return bitArray.clamp(words, n);
698
+ },
699
+
700
+ /** `true` when `crypto.getRandomValues` is available. */
701
+ isReady() { return _hasCrypto; },
702
+
703
+ /** Run / re-run the CTR_DRBG power-on self-test. */
704
+ selfTest() { _selfTestPassed = _runSelfTest(); return _selfTestPassed; },
705
+
706
+ /**
707
+ * SP 800-90B continuous health-test surface - primarily for
708
+ * test harnesses and operational diagnostics.
709
+ *
710
+ * NOTE: the RCT/APT state and `_entropyDead` latch are
711
+ * **module-singleton** - they are shared across every
712
+ * `bytes()`/`words()`/`bits()`/`float()`/`int()`/`drbg()` call,
713
+ * and across multiple DRBG instances built from this factory.
714
+ * The underlying entropy source (`crypto.getRandomValues`) is
715
+ * itself process-global, so a single shared health latch
716
+ * matches reality. Tests that need a fresh state must call
717
+ * `reset()` between scenarios.
718
+ *
719
+ * `feed(buf)` : push bytes through RCT + APT (returns false on fail).
720
+ * `reset()` : clear state and clear the latched-dead flag.
721
+ * `isDead` : true once any continuous test has failed.
722
+ */
723
+ health: {
724
+ feed(buf) { return _healthCheck(buf instanceof Uint8Array ? buf : new Uint8Array(buf)); },
725
+ reset() { _resetHealth(); },
726
+ get isDead() { return _entropyDead; }
727
+ },
728
+
729
+ /**
730
+ * Build a fresh CTR_DRBG-AES-256 (no-df) instance.
731
+ *
732
+ * @param {object} [options]
733
+ * @param {Uint8Array} [options.personalisation] Up to 48 bytes of personalisation
734
+ * string mixed into the seed (XORed,
735
+ * truncated as per SP 800-90A §10.2.1.3.1
736
+ * when no df is used).
737
+ * @returns {object|false} DRBG instance or `false` on POST/seed failure.
738
+ *
739
+ * The returned object exposes:
740
+ * - `generate(n, additionalInput?)` → `Uint8Array | false`
741
+ * - `reseed(additionalInput?)` → `boolean` (pulls fresh entropy from OS RBG)
742
+ * - `addAdditionalInput(bytes)` → mix arbitrary bytes into the next `generate()`
743
+ * - `uninstantiate()` → wipe internal state
744
+ * - `isLive`, `reseedCounter`, `securityStrength`
745
+ */
746
+ drbg(options = {}) {
747
+ if (!_ensureSelfTest()) {
748
+ console.error('[crypto] CORRUPT: random.drbg refused - POST failed');
749
+ return false;
750
+ }
751
+ const inst = _makeDrbg(options);
752
+ if (inst === false) return false;
753
+ const seed = _getEntropy(inst.seedBytes);
754
+ if (seed === false) return false;
755
+ if (!inst.instantiate(seed, options.personalisation)) return false;
756
+
757
+ // Buffer of pending additional_input (e.g. from entropyCollector).
758
+ let pending = null;
759
+
760
+ return {
761
+ generate(n, additionalInput) {
762
+ let ai = additionalInput || null;
763
+ if (pending !== null) {
764
+ ai = ai === null ? pending
765
+ : (() => { const m = new Uint8Array(pending.length + ai.length);
766
+ m.set(pending); m.set(ai, pending.length); return m; })();
767
+ pending = null;
768
+ }
769
+ return inst.generate(n, ai);
770
+ },
771
+ reseed(additionalInput) {
772
+ const fresh = _getEntropy(inst.seedBytes);
773
+ if (fresh === false) return false;
774
+ let ai = additionalInput || null;
775
+ if (pending !== null) {
776
+ ai = ai === null ? pending
777
+ : (() => { const m = new Uint8Array(pending.length + ai.length);
778
+ m.set(pending); m.set(ai, pending.length); return m; })();
779
+ pending = null;
780
+ }
781
+ return inst.reseed(fresh, ai);
782
+ },
783
+ /**
784
+ * Accumulate caller-supplied entropy (e.g. mouse/keyboard timings
785
+ * from `entropyCollector`) into a pending buffer that is consumed
786
+ * on the next `generate()` or `reseed()` as `additional_input`.
787
+ * Inputs longer than `seedlen` (48 bytes) are folded through
788
+ * SHA-256 to bound the buffer.
789
+ */
790
+ addAdditionalInput(bytes) {
791
+ if (!(bytes instanceof Uint8Array)) {
792
+ if (Array.isArray(bytes) || bytes instanceof Uint32Array) {
793
+ const tmp = new Uint8Array(bytes.length * 4);
794
+ for (let i = 0; i < bytes.length; i++) {
795
+ const v = bytes[i] | 0;
796
+ tmp[i * 4] = (v >>> 24) & 0xff;
797
+ tmp[i * 4 + 1] = (v >>> 16) & 0xff;
798
+ tmp[i * 4 + 2] = (v >>> 8) & 0xff;
799
+ tmp[i * 4 + 3] = v & 0xff;
800
+ }
801
+ bytes = tmp;
802
+ } else if (typeof bytes === 'number') {
803
+ const v = bytes | 0;
804
+ bytes = new Uint8Array([(v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff]);
805
+ } else {
806
+ console.warn('[crypto] BUG: drbg.addAdditionalInput: unsupported data type');
807
+ return false;
808
+ }
809
+ }
810
+ const merged = pending === null ? bytes
811
+ : (() => { const m = new Uint8Array(pending.length + bytes.length);
812
+ m.set(pending); m.set(bytes, pending.length); return m; })();
813
+ if (merged.length <= inst.seedBytes) {
814
+ pending = merged;
815
+ } else {
816
+ // Fold to 32 bytes via SHA-256 to bound the buffer.
817
+ const h = sha256.hash(_bytesToWords(merged.subarray(0, merged.length & ~3)));
818
+ const folded = new Uint8Array(32);
819
+ _wordsToBytes(h, 8, folded, 0);
820
+ pending = folded;
821
+ }
822
+ return true;
823
+ },
824
+ uninstantiate() { pending = null; inst.uninstantiate(); },
825
+ get isLive() { return inst.isLive; },
826
+ get reseedCounter() { return inst.reseedCounter; },
827
+ get securityStrength() { return inst.securityStrength; }
828
+ };
829
+ }
830
+ }, Symbol.for('@awacloud/fw/internal'), {
831
+ /**
832
+ * Internal (test-only, outside the API): the CTR_DRBG factory with
833
+ * caller-controlled seed material. **Not for production use** -
834
+ * the public `drbg()` API auto-pulls OS entropy and is the only
835
+ * path with full FIPS 140-3 lifecycle (POST, RCT/APT health
836
+ * tests, OS NRBG seeding). It exists to replay NIST CAVP / ACVP
837
+ * DRBG vectors with deterministic entropy inputs, so the algorithm
838
+ * itself can be byte-exact validated against the reference vectors.
839
+ */
840
+ value: { makeDrbg: _makeDrbg }
841
+ });
842
+
843
+ return api;
844
+ }
845
+ };