@fgv/ts-extras 5.1.0-4 → 5.1.0-40

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 (368) hide show
  1. package/dist/index.browser.js +4 -2
  2. package/dist/index.browser.js.map +1 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/packlets/ai-assist/apiClient.js +886 -158
  5. package/dist/packlets/ai-assist/apiClient.js.map +1 -0
  6. package/dist/packlets/ai-assist/chatRequestBuilders.js +282 -0
  7. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
  8. package/dist/packlets/ai-assist/converters.js +47 -3
  9. package/dist/packlets/ai-assist/converters.js.map +1 -0
  10. package/dist/packlets/ai-assist/embeddingClient.js +345 -0
  11. package/dist/packlets/ai-assist/embeddingClient.js.map +1 -0
  12. package/dist/packlets/ai-assist/endpoint.js +78 -0
  13. package/dist/packlets/ai-assist/endpoint.js.map +1 -0
  14. package/dist/packlets/ai-assist/http.js +75 -0
  15. package/dist/packlets/ai-assist/http.js.map +1 -0
  16. package/dist/packlets/ai-assist/imageOptionsResolver.js +193 -0
  17. package/dist/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
  18. package/dist/packlets/ai-assist/index.js +10 -4
  19. package/dist/packlets/ai-assist/index.js.map +1 -0
  20. package/dist/packlets/ai-assist/jsonCompletion.js +93 -0
  21. package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -0
  22. package/dist/packlets/ai-assist/jsonResponse.js +149 -0
  23. package/dist/packlets/ai-assist/jsonResponse.js.map +1 -0
  24. package/dist/packlets/ai-assist/model.js +193 -9
  25. package/dist/packlets/ai-assist/model.js.map +1 -0
  26. package/dist/packlets/ai-assist/registry.js +314 -12
  27. package/dist/packlets/ai-assist/registry.js.map +1 -0
  28. package/dist/packlets/ai-assist/sseParser.js +123 -0
  29. package/dist/packlets/ai-assist/sseParser.js.map +1 -0
  30. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +368 -0
  31. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
  32. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +687 -0
  33. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -0
  34. package/dist/packlets/ai-assist/streamingAdapters/common.js +187 -0
  35. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
  36. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +204 -0
  37. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
  38. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +170 -0
  39. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
  40. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +386 -0
  41. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
  42. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +173 -0
  43. package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
  44. package/dist/packlets/ai-assist/streamingClient.js +140 -0
  45. package/dist/packlets/ai-assist/streamingClient.js.map +1 -0
  46. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +288 -0
  47. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
  48. package/dist/packlets/ai-assist/toolFormats.js +106 -10
  49. package/dist/packlets/ai-assist/toolFormats.js.map +1 -0
  50. package/dist/packlets/conversion/converters.js +35 -1
  51. package/dist/packlets/conversion/converters.js.map +1 -0
  52. package/dist/packlets/conversion/index.js.map +1 -0
  53. package/dist/packlets/crypto-utils/constants.js.map +1 -0
  54. package/dist/packlets/crypto-utils/converters.js +42 -4
  55. package/dist/packlets/crypto-utils/converters.js.map +1 -0
  56. package/dist/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
  57. package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -0
  58. package/dist/packlets/crypto-utils/hpkeProvider.js +333 -0
  59. package/dist/packlets/crypto-utils/hpkeProvider.js.map +1 -0
  60. package/dist/packlets/crypto-utils/index.browser.js +10 -2
  61. package/dist/packlets/crypto-utils/index.browser.js.map +1 -0
  62. package/dist/packlets/crypto-utils/index.js +6 -0
  63. package/dist/packlets/crypto-utils/index.js.map +1 -0
  64. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +71 -0
  65. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
  66. package/dist/packlets/crypto-utils/keystore/converters.js +103 -11
  67. package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -0
  68. package/dist/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js +287 -0
  69. package/dist/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js.map +1 -0
  70. package/dist/packlets/crypto-utils/keystore/index.browser.js +36 -0
  71. package/dist/packlets/crypto-utils/keystore/index.browser.js.map +1 -0
  72. package/dist/packlets/crypto-utils/keystore/index.js +3 -0
  73. package/dist/packlets/crypto-utils/keystore/index.js.map +1 -0
  74. package/dist/packlets/crypto-utils/keystore/keyStore.js +633 -118
  75. package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
  76. package/dist/packlets/crypto-utils/keystore/model.js +22 -1
  77. package/dist/packlets/crypto-utils/keystore/model.js.map +1 -0
  78. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js +21 -0
  79. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
  80. package/dist/packlets/crypto-utils/model.js +32 -0
  81. package/dist/packlets/crypto-utils/model.js.map +1 -0
  82. package/dist/packlets/crypto-utils/nodeCryptoProvider.js +270 -1
  83. package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
  84. package/dist/packlets/crypto-utils/spkiHelpers.js +209 -0
  85. package/dist/packlets/crypto-utils/spkiHelpers.js.map +1 -0
  86. package/dist/packlets/csv/csvFileHelpers.js +0 -14
  87. package/dist/packlets/csv/csvFileHelpers.js.map +1 -0
  88. package/dist/packlets/csv/csvHelpers.js +14 -0
  89. package/dist/packlets/csv/csvHelpers.js.map +1 -0
  90. package/dist/packlets/csv/index.browser.js +1 -3
  91. package/dist/packlets/csv/index.browser.js.map +1 -0
  92. package/dist/packlets/csv/index.js.map +1 -0
  93. package/dist/packlets/experimental/extendedArray.js.map +1 -0
  94. package/dist/packlets/experimental/formatter.js.map +1 -0
  95. package/dist/packlets/experimental/index.js.map +1 -0
  96. package/dist/packlets/experimental/rangeOf.js.map +1 -0
  97. package/dist/packlets/hash/index.browser.js.map +1 -0
  98. package/dist/packlets/hash/index.js.map +1 -0
  99. package/dist/packlets/hash/index.node.js.map +1 -0
  100. package/dist/packlets/hash/md5Normalizer.browser.js.map +1 -0
  101. package/dist/packlets/hash/md5Normalizer.js.map +1 -0
  102. package/dist/packlets/mustache/index.js.map +1 -0
  103. package/dist/packlets/mustache/interfaces.js.map +1 -0
  104. package/dist/packlets/mustache/mustacheTemplate.js +42 -4
  105. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -0
  106. package/dist/packlets/record-jar/index.browser.js +1 -3
  107. package/dist/packlets/record-jar/index.browser.js.map +1 -0
  108. package/dist/packlets/record-jar/index.js.map +1 -0
  109. package/dist/packlets/record-jar/recordJarFileHelpers.js +0 -18
  110. package/dist/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
  111. package/dist/packlets/record-jar/recordJarHelpers.js +18 -0
  112. package/dist/packlets/record-jar/recordJarHelpers.js.map +1 -0
  113. package/dist/packlets/yaml/converters.js.map +1 -0
  114. package/dist/packlets/yaml/index.js +1 -0
  115. package/dist/packlets/yaml/index.js.map +1 -0
  116. package/dist/packlets/yaml/serializers.js +48 -0
  117. package/dist/packlets/yaml/serializers.js.map +1 -0
  118. package/dist/packlets/zip-file-tree/index.js.map +1 -0
  119. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  120. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
  121. package/dist/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
  122. package/dist/ts-extras.d.ts +3880 -105
  123. package/dist/tsdoc-metadata.json +1 -1
  124. package/lib/index.browser.d.ts +4 -2
  125. package/lib/index.browser.d.ts.map +1 -0
  126. package/lib/index.browser.js +8 -3
  127. package/lib/index.browser.js.map +1 -0
  128. package/lib/index.d.ts.map +1 -0
  129. package/lib/index.js.map +1 -0
  130. package/lib/packlets/ai-assist/apiClient.d.ts +115 -32
  131. package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -0
  132. package/lib/packlets/ai-assist/apiClient.js +888 -156
  133. package/lib/packlets/ai-assist/apiClient.js.map +1 -0
  134. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +149 -0
  135. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -0
  136. package/lib/packlets/ai-assist/chatRequestBuilders.js +293 -0
  137. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
  138. package/lib/packlets/ai-assist/converters.d.ts +15 -1
  139. package/lib/packlets/ai-assist/converters.d.ts.map +1 -0
  140. package/lib/packlets/ai-assist/converters.js +47 -3
  141. package/lib/packlets/ai-assist/converters.js.map +1 -0
  142. package/lib/packlets/ai-assist/embeddingClient.d.ts +69 -0
  143. package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -0
  144. package/lib/packlets/ai-assist/embeddingClient.js +349 -0
  145. package/lib/packlets/ai-assist/embeddingClient.js.map +1 -0
  146. package/lib/packlets/ai-assist/endpoint.d.ts +28 -0
  147. package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -0
  148. package/lib/packlets/ai-assist/endpoint.js +82 -0
  149. package/lib/packlets/ai-assist/endpoint.js.map +1 -0
  150. package/lib/packlets/ai-assist/http.d.ts +24 -0
  151. package/lib/packlets/ai-assist/http.d.ts.map +1 -0
  152. package/lib/packlets/ai-assist/http.js +78 -0
  153. package/lib/packlets/ai-assist/http.js.map +1 -0
  154. package/lib/packlets/ai-assist/imageOptionsResolver.d.ts +66 -0
  155. package/lib/packlets/ai-assist/imageOptionsResolver.d.ts.map +1 -0
  156. package/lib/packlets/ai-assist/imageOptionsResolver.js +197 -0
  157. package/lib/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
  158. package/lib/packlets/ai-assist/index.d.ts +10 -4
  159. package/lib/packlets/ai-assist/index.d.ts.map +1 -0
  160. package/lib/packlets/ai-assist/index.js +36 -1
  161. package/lib/packlets/ai-assist/index.js.map +1 -0
  162. package/lib/packlets/ai-assist/jsonCompletion.d.ts +93 -0
  163. package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -0
  164. package/lib/packlets/ai-assist/jsonCompletion.js +97 -0
  165. package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -0
  166. package/lib/packlets/ai-assist/jsonResponse.d.ts +91 -0
  167. package/lib/packlets/ai-assist/jsonResponse.d.ts.map +1 -0
  168. package/lib/packlets/ai-assist/jsonResponse.js +154 -0
  169. package/lib/packlets/ai-assist/jsonResponse.js.map +1 -0
  170. package/lib/packlets/ai-assist/model.d.ts +1202 -12
  171. package/lib/packlets/ai-assist/model.d.ts.map +1 -0
  172. package/lib/packlets/ai-assist/model.js +198 -10
  173. package/lib/packlets/ai-assist/model.js.map +1 -0
  174. package/lib/packlets/ai-assist/registry.d.ts +56 -1
  175. package/lib/packlets/ai-assist/registry.d.ts.map +1 -0
  176. package/lib/packlets/ai-assist/registry.js +319 -13
  177. package/lib/packlets/ai-assist/registry.js.map +1 -0
  178. package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
  179. package/lib/packlets/ai-assist/sseParser.d.ts.map +1 -0
  180. package/lib/packlets/ai-assist/sseParser.js +128 -0
  181. package/lib/packlets/ai-assist/sseParser.js.map +1 -0
  182. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +72 -0
  183. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -0
  184. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +371 -0
  185. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
  186. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +260 -0
  187. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -0
  188. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +694 -0
  189. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -0
  190. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +154 -0
  191. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -0
  192. package/lib/packlets/ai-assist/streamingAdapters/common.js +193 -0
  193. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
  194. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +43 -0
  195. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -0
  196. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +207 -0
  197. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
  198. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +19 -0
  199. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -0
  200. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +173 -0
  201. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
  202. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +33 -0
  203. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -0
  204. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +389 -0
  205. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
  206. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
  207. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -0
  208. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +176 -0
  209. package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
  210. package/lib/packlets/ai-assist/streamingClient.d.ts +50 -0
  211. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -0
  212. package/lib/packlets/ai-assist/streamingClient.js +146 -0
  213. package/lib/packlets/ai-assist/streamingClient.js.map +1 -0
  214. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +87 -0
  215. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -0
  216. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +294 -0
  217. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
  218. package/lib/packlets/ai-assist/toolFormats.d.ts +40 -9
  219. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -0
  220. package/lib/packlets/ai-assist/toolFormats.js +107 -10
  221. package/lib/packlets/ai-assist/toolFormats.js.map +1 -0
  222. package/lib/packlets/conversion/converters.d.ts +8 -1
  223. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  224. package/lib/packlets/conversion/converters.js +36 -2
  225. package/lib/packlets/conversion/converters.js.map +1 -0
  226. package/lib/packlets/conversion/index.d.ts.map +1 -0
  227. package/lib/packlets/conversion/index.js.map +1 -0
  228. package/lib/packlets/crypto-utils/constants.d.ts.map +1 -0
  229. package/lib/packlets/crypto-utils/constants.js.map +1 -0
  230. package/lib/packlets/crypto-utils/converters.d.ts +20 -1
  231. package/lib/packlets/crypto-utils/converters.d.ts.map +1 -0
  232. package/lib/packlets/crypto-utils/converters.js +43 -5
  233. package/lib/packlets/crypto-utils/converters.js.map +1 -0
  234. package/lib/packlets/crypto-utils/directEncryptionProvider.d.ts.map +1 -0
  235. package/lib/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
  236. package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -0
  237. package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -0
  238. package/lib/packlets/crypto-utils/hpkeProvider.d.ts +142 -0
  239. package/lib/packlets/crypto-utils/hpkeProvider.d.ts.map +1 -0
  240. package/lib/packlets/crypto-utils/hpkeProvider.js +337 -0
  241. package/lib/packlets/crypto-utils/hpkeProvider.js.map +1 -0
  242. package/lib/packlets/crypto-utils/index.browser.d.ts +4 -1
  243. package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -0
  244. package/lib/packlets/crypto-utils/index.browser.js +21 -3
  245. package/lib/packlets/crypto-utils/index.browser.js.map +1 -0
  246. package/lib/packlets/crypto-utils/index.d.ts +3 -0
  247. package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
  248. package/lib/packlets/crypto-utils/index.js +17 -1
  249. package/lib/packlets/crypto-utils/index.js.map +1 -0
  250. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +54 -0
  251. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -0
  252. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +74 -0
  253. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
  254. package/lib/packlets/crypto-utils/keystore/converters.d.ts +68 -6
  255. package/lib/packlets/crypto-utils/keystore/converters.d.ts.map +1 -0
  256. package/lib/packlets/crypto-utils/keystore/converters.js +101 -9
  257. package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -0
  258. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.d.ts +148 -0
  259. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.d.ts.map +1 -0
  260. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js +324 -0
  261. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js.map +1 -0
  262. package/lib/packlets/crypto-utils/keystore/index.browser.d.ts +10 -0
  263. package/lib/packlets/crypto-utils/keystore/index.browser.d.ts.map +1 -0
  264. package/lib/packlets/crypto-utils/keystore/index.browser.js +76 -0
  265. package/lib/packlets/crypto-utils/keystore/index.browser.js.map +1 -0
  266. package/lib/packlets/crypto-utils/keystore/index.d.ts +2 -0
  267. package/lib/packlets/crypto-utils/keystore/index.d.ts.map +1 -0
  268. package/lib/packlets/crypto-utils/keystore/index.js +5 -1
  269. package/lib/packlets/crypto-utils/keystore/index.js.map +1 -0
  270. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +205 -13
  271. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -0
  272. package/lib/packlets/crypto-utils/keystore/keyStore.js +639 -124
  273. package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
  274. package/lib/packlets/crypto-utils/keystore/model.d.ts +275 -19
  275. package/lib/packlets/crypto-utils/keystore/model.d.ts.map +1 -0
  276. package/lib/packlets/crypto-utils/keystore/model.js +24 -2
  277. package/lib/packlets/crypto-utils/keystore/model.js.map +1 -0
  278. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts +53 -0
  279. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts.map +1 -0
  280. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js +22 -0
  281. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
  282. package/lib/packlets/crypto-utils/model.d.ts +348 -10
  283. package/lib/packlets/crypto-utils/model.d.ts.map +1 -0
  284. package/lib/packlets/crypto-utils/model.js +33 -1
  285. package/lib/packlets/crypto-utils/model.js.map +1 -0
  286. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +110 -2
  287. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -0
  288. package/lib/packlets/crypto-utils/nodeCryptoProvider.js +269 -0
  289. package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
  290. package/lib/packlets/crypto-utils/spkiHelpers.d.ts +110 -0
  291. package/lib/packlets/crypto-utils/spkiHelpers.d.ts.map +1 -0
  292. package/lib/packlets/crypto-utils/spkiHelpers.js +219 -0
  293. package/lib/packlets/crypto-utils/spkiHelpers.js.map +1 -0
  294. package/lib/packlets/csv/csvFileHelpers.d.ts +0 -10
  295. package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -0
  296. package/lib/packlets/csv/csvFileHelpers.js +0 -15
  297. package/lib/packlets/csv/csvFileHelpers.js.map +1 -0
  298. package/lib/packlets/csv/csvHelpers.d.ts +10 -0
  299. package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
  300. package/lib/packlets/csv/csvHelpers.js +15 -0
  301. package/lib/packlets/csv/csvHelpers.js.map +1 -0
  302. package/lib/packlets/csv/index.browser.d.ts +0 -1
  303. package/lib/packlets/csv/index.browser.d.ts.map +1 -0
  304. package/lib/packlets/csv/index.browser.js +1 -5
  305. package/lib/packlets/csv/index.browser.js.map +1 -0
  306. package/lib/packlets/csv/index.d.ts.map +1 -0
  307. package/lib/packlets/csv/index.js.map +1 -0
  308. package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
  309. package/lib/packlets/experimental/extendedArray.js.map +1 -0
  310. package/lib/packlets/experimental/formatter.d.ts.map +1 -0
  311. package/lib/packlets/experimental/formatter.js.map +1 -0
  312. package/lib/packlets/experimental/index.d.ts.map +1 -0
  313. package/lib/packlets/experimental/index.js.map +1 -0
  314. package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
  315. package/lib/packlets/experimental/rangeOf.js.map +1 -0
  316. package/lib/packlets/hash/index.browser.d.ts.map +1 -0
  317. package/lib/packlets/hash/index.browser.js.map +1 -0
  318. package/lib/packlets/hash/index.d.ts.map +1 -0
  319. package/lib/packlets/hash/index.js.map +1 -0
  320. package/lib/packlets/hash/index.node.d.ts.map +1 -0
  321. package/lib/packlets/hash/index.node.js.map +1 -0
  322. package/lib/packlets/hash/md5Normalizer.browser.d.ts.map +1 -0
  323. package/lib/packlets/hash/md5Normalizer.browser.js.map +1 -0
  324. package/lib/packlets/hash/md5Normalizer.d.ts.map +1 -0
  325. package/lib/packlets/hash/md5Normalizer.js.map +1 -0
  326. package/lib/packlets/mustache/index.d.ts +1 -1
  327. package/lib/packlets/mustache/index.d.ts.map +1 -0
  328. package/lib/packlets/mustache/index.js.map +1 -0
  329. package/lib/packlets/mustache/interfaces.d.ts +34 -0
  330. package/lib/packlets/mustache/interfaces.d.ts.map +1 -0
  331. package/lib/packlets/mustache/interfaces.js.map +1 -0
  332. package/lib/packlets/mustache/mustacheTemplate.d.ts +2 -0
  333. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -0
  334. package/lib/packlets/mustache/mustacheTemplate.js +42 -4
  335. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -0
  336. package/lib/packlets/record-jar/index.browser.d.ts +0 -1
  337. package/lib/packlets/record-jar/index.browser.d.ts.map +1 -0
  338. package/lib/packlets/record-jar/index.browser.js +1 -5
  339. package/lib/packlets/record-jar/index.browser.js.map +1 -0
  340. package/lib/packlets/record-jar/index.d.ts.map +1 -0
  341. package/lib/packlets/record-jar/index.js.map +1 -0
  342. package/lib/packlets/record-jar/recordJarFileHelpers.d.ts +0 -11
  343. package/lib/packlets/record-jar/recordJarFileHelpers.d.ts.map +1 -0
  344. package/lib/packlets/record-jar/recordJarFileHelpers.js +0 -19
  345. package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
  346. package/lib/packlets/record-jar/recordJarHelpers.d.ts +11 -0
  347. package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
  348. package/lib/packlets/record-jar/recordJarHelpers.js +19 -0
  349. package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
  350. package/lib/packlets/yaml/converters.d.ts.map +1 -0
  351. package/lib/packlets/yaml/converters.js.map +1 -0
  352. package/lib/packlets/yaml/index.d.ts +1 -0
  353. package/lib/packlets/yaml/index.d.ts.map +1 -0
  354. package/lib/packlets/yaml/index.js +1 -0
  355. package/lib/packlets/yaml/index.js.map +1 -0
  356. package/lib/packlets/yaml/serializers.d.ts +45 -0
  357. package/lib/packlets/yaml/serializers.d.ts.map +1 -0
  358. package/lib/packlets/yaml/serializers.js +84 -0
  359. package/lib/packlets/yaml/serializers.js.map +1 -0
  360. package/lib/packlets/zip-file-tree/index.d.ts.map +1 -0
  361. package/lib/packlets/zip-file-tree/index.js.map +1 -0
  362. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
  363. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -0
  364. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  365. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
  366. package/lib/packlets/zip-file-tree/zipFileTreeWriter.d.ts.map +1 -0
  367. package/lib/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
  368. package/package.json +20 -15
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/index.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ;;;GAGG;AAEH,iCAAiC;AACjC,cAAc,SAAS,CAAC;AAExB,YAAY;AACZ,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,CAAC;AAErB,qBAAqB;AACrB,OAAO,KAAK,QAAQ,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,CAAC;AAEpB,uBAAuB;AACvB,OAAO,KAAK,UAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,CAAC;AAEtB,6BAA6B;AAC7B,OAAO,EAAE,wBAAwB,EAAmC,MAAM,4BAA4B,CAAC;AAEvG,8DAA8D;AAC9D,OAAO,EAA2B,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAE3F,qDAAqD;AACrD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE9E,yBAAyB;AACzB,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EAEV,QAAQ,EACR,cAAc,EACf,MAAM,iBAAiB,CAAC;AAEzB,qCAAqC;AACrC,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,EAChC,6BAA6B,EAC7B,4BAA4B,EAC5B,wBAAwB,EACxB,wBAAwB,EACzB,MAAM,eAAe,CAAC;AAEvB,qFAAqF;AACrF,OAAO,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Crypto utilities for encrypted file handling and key management.\n * @packageDocumentation\n */\n\n// Re-export all types from model\nexport * from './model';\n\n// Constants\nimport * as Constants from './constants';\nexport { Constants };\n\n// KeyStore namespace\nimport * as KeyStore from './keystore';\nexport { KeyStore };\n\n// Converters namespace\nimport * as Converters from './converters';\nexport { Converters };\n\n// Direct encryption provider\nexport { DirectEncryptionProvider, IDirectEncryptionProviderParams } from './directEncryptionProvider';\n\n// WebCrypto parameter table for asymmetric keypair algorithms\nexport { IKeyPairAlgorithmParams, keyPairAlgorithmParams } from './keyPairAlgorithmParams';\n\n// Node.js crypto provider (Node.js environment only)\nexport { NodeCryptoProvider, nodeCryptoProvider } from './nodeCryptoProvider';\n\n// Encrypted file helpers\nexport {\n createEncryptedFile,\n decryptFile,\n fromBase64,\n ICreateEncryptedFileParams,\n toBase64,\n tryDecryptFile\n} from './encryptedFile';\n\n// Multibase/SPKI + base64url helpers\nexport {\n base64UrlNoPadDecode,\n base64UrlNoPadEncode,\n exportPublicKeyAsMultibaseSpki,\n importPublicKeyFromMultibaseSpki,\n isValidMultibaseSpkiPublicKey,\n MultibaseSpkiPublicKeyRegExp,\n multibaseBase64UrlDecode,\n multibaseBase64UrlEncode\n} from './spkiHelpers';\n\n// HPKE base mode (RFC 9180) — DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM\nexport { HpkeProvider, IHpkeSealResult } from './hpkeProvider';\n"]}
@@ -0,0 +1,71 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ /**
21
+ * Lookup table from {@link CryptoUtils.KeyPairAlgorithm} to the WebCrypto
22
+ * parameters needed to drive `crypto.subtle`. Shared between every
23
+ * {@link CryptoUtils.ICryptoProvider} implementation since both Node and
24
+ * browser providers speak the same WebCrypto API. Exposed for downstream
25
+ * provider implementations (e.g. browser-side providers in `@fgv/ts-web-extras`).
26
+ * @public
27
+ */
28
+ export const keyPairAlgorithmParams = {
29
+ 'ecdsa-p256': {
30
+ generateKey: { name: 'ECDSA', namedCurve: 'P-256' },
31
+ importPublicKey: { name: 'ECDSA', namedCurve: 'P-256' },
32
+ keyPairUsages: ['sign', 'verify'],
33
+ publicKeyUsages: ['verify']
34
+ },
35
+ 'rsa-oaep-2048': {
36
+ generateKey: {
37
+ name: 'RSA-OAEP',
38
+ modulusLength: 2048,
39
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
40
+ hash: 'SHA-256'
41
+ },
42
+ importPublicKey: { name: 'RSA-OAEP', hash: 'SHA-256' },
43
+ keyPairUsages: ['encrypt', 'decrypt'],
44
+ publicKeyUsages: ['encrypt']
45
+ },
46
+ 'ecdh-p256': {
47
+ generateKey: { name: 'ECDH', namedCurve: 'P-256' },
48
+ importPublicKey: { name: 'ECDH', namedCurve: 'P-256' },
49
+ // WebCrypto filters per-role: the private key takes both derive usages,
50
+ // and the public key gets [] since an ECDH public key alone cannot derive.
51
+ keyPairUsages: ['deriveKey', 'deriveBits'],
52
+ // Importing only the recipient's public key — empty usages because a
53
+ // standalone ECDH public key has no derivation capability.
54
+ publicKeyUsages: []
55
+ },
56
+ ed25519: {
57
+ generateKey: { name: 'Ed25519' },
58
+ importPublicKey: { name: 'Ed25519' },
59
+ keyPairUsages: ['sign', 'verify'],
60
+ publicKeyUsages: ['verify']
61
+ },
62
+ x25519: {
63
+ generateKey: { name: 'X25519' },
64
+ importPublicKey: { name: 'X25519' },
65
+ // WebCrypto filters per-role: the private key takes both derive usages,
66
+ // the public key gets [] since a standalone X25519 public key cannot derive.
67
+ keyPairUsages: ['deriveKey', 'deriveBits'],
68
+ publicKeyUsages: []
69
+ }
70
+ };
71
+ //# sourceMappingURL=keyPairAlgorithmParams.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyPairAlgorithmParams.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/keyPairAlgorithmParams.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAmDZ;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAgE;IACjG,YAAY,EAAE;QACZ,WAAW,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE;QACnD,eAAe,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE;QACvD,aAAa,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC;QACjC,eAAe,EAAE,CAAC,QAAQ,CAAC;KAC5B;IACD,eAAe,EAAE;QACf,WAAW,EAAE;YACX,IAAI,EAAE,UAAU;YAChB,aAAa,EAAE,IAAI;YACnB,cAAc,EAAE,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,EAAE,SAAS;SAChB;QACD,eAAe,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE;QACtD,aAAa,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC;QACrC,eAAe,EAAE,CAAC,SAAS,CAAC;KAC7B;IACD,WAAW,EAAE;QACX,WAAW,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE;QAClD,eAAe,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE;QACtD,wEAAwE;QACxE,2EAA2E;QAC3E,aAAa,EAAE,CAAC,WAAW,EAAE,YAAY,CAAC;QAC1C,qEAAqE;QACrE,2DAA2D;QAC3D,eAAe,EAAE,EAAE;KACpB;IACD,OAAO,EAAE;QACP,WAAW,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;QAChC,eAAe,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;QACpC,aAAa,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC;QACjC,eAAe,EAAE,CAAC,QAAQ,CAAC;KAC5B;IACD,MAAM,EAAE;QACN,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QAC/B,eAAe,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QACnC,wEAAwE;QACxE,6EAA6E;QAC7E,aAAa,EAAE,CAAC,WAAW,EAAE,YAAY,CAAC;QAC1C,eAAe,EAAE,EAAE;KACpB;CACF,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { KeyPairAlgorithm } from './model';\n\n/**\n * WebCrypto parameters for a single {@link CryptoUtils.KeyPairAlgorithm}.\n * Implementations of {@link CryptoUtils.ICryptoProvider} use this table to\n * translate the small public algorithm enum into the WebCrypto algorithm\n * objects and key-usage arrays expected by `crypto.subtle`.\n * @public\n */\nexport interface IKeyPairAlgorithmParams {\n /**\n * Algorithm parameters for `crypto.subtle.generateKey`. Always an asymmetric\n * variant — these algorithms produce a `CryptoKeyPair`, not a single key.\n * The literal `{ name: 'Ed25519' }` member covers WebCrypto's Secure-Curves\n * Ed25519 algorithm; `{ name: 'X25519' }` covers the X25519 key-agreement\n * algorithm. Both take only a `name`; using literals rather than the base\n * `Algorithm` keeps the union closed to the algorithms this table supports.\n */\n readonly generateKey:\n | RsaHashedKeyGenParams\n | EcKeyGenParams\n | { readonly name: 'Ed25519' }\n | { readonly name: 'X25519' };\n\n /**\n * Algorithm parameters for `crypto.subtle.importKey('jwk', ...)` when\n * importing the public half of a keypair. The literal `{ name: 'Ed25519' }`\n * member covers Ed25519 imports; `{ name: 'X25519' }` covers X25519 imports.\n * Both take only a `name`; using literals rather than the base `Algorithm`\n * keeps the union closed to the algorithms this table supports.\n */\n readonly importPublicKey:\n | RsaHashedImportParams\n | EcKeyImportParams\n | { readonly name: 'Ed25519' }\n | { readonly name: 'X25519' };\n\n /**\n * Default key usages for the generated `CryptoKeyPair`. Both halves receive\n * the usages WebCrypto considers valid for their role; the platform filters.\n */\n readonly keyPairUsages: ReadonlyArray<KeyUsage>;\n\n /**\n * Key usages applied when re-importing only the public key.\n */\n readonly publicKeyUsages: ReadonlyArray<KeyUsage>;\n}\n\n/**\n * Lookup table from {@link CryptoUtils.KeyPairAlgorithm} to the WebCrypto\n * parameters needed to drive `crypto.subtle`. Shared between every\n * {@link CryptoUtils.ICryptoProvider} implementation since both Node and\n * browser providers speak the same WebCrypto API. Exposed for downstream\n * provider implementations (e.g. browser-side providers in `@fgv/ts-web-extras`).\n * @public\n */\nexport const keyPairAlgorithmParams: Readonly<Record<KeyPairAlgorithm, IKeyPairAlgorithmParams>> = {\n 'ecdsa-p256': {\n generateKey: { name: 'ECDSA', namedCurve: 'P-256' },\n importPublicKey: { name: 'ECDSA', namedCurve: 'P-256' },\n keyPairUsages: ['sign', 'verify'],\n publicKeyUsages: ['verify']\n },\n 'rsa-oaep-2048': {\n generateKey: {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: 'SHA-256'\n },\n importPublicKey: { name: 'RSA-OAEP', hash: 'SHA-256' },\n keyPairUsages: ['encrypt', 'decrypt'],\n publicKeyUsages: ['encrypt']\n },\n 'ecdh-p256': {\n generateKey: { name: 'ECDH', namedCurve: 'P-256' },\n importPublicKey: { name: 'ECDH', namedCurve: 'P-256' },\n // WebCrypto filters per-role: the private key takes both derive usages,\n // and the public key gets [] since an ECDH public key alone cannot derive.\n keyPairUsages: ['deriveKey', 'deriveBits'],\n // Importing only the recipient's public key — empty usages because a\n // standalone ECDH public key has no derivation capability.\n publicKeyUsages: []\n },\n ed25519: {\n generateKey: { name: 'Ed25519' },\n importPublicKey: { name: 'Ed25519' },\n keyPairUsages: ['sign', 'verify'],\n publicKeyUsages: ['verify']\n },\n x25519: {\n generateKey: { name: 'X25519' },\n importPublicKey: { name: 'X25519' },\n // WebCrypto filters per-role: the private key takes both derive usages,\n // the public key gets [] since a standalone X25519 public key cannot derive.\n keyPairUsages: ['deriveKey', 'deriveBits'],\n publicKeyUsages: []\n }\n};\n"]}
@@ -17,9 +17,9 @@
17
17
  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
- import { Converters } from '@fgv/ts-utils';
21
- import { base64String, encryptionAlgorithm, keyDerivationParams } from '../converters';
22
- import { allKeyStoreSecretTypes, KEYSTORE_FORMAT } from './model';
20
+ import { Converters, succeed, Validators } from '@fgv/ts-utils';
21
+ import { base64String, encryptionAlgorithm, pbkdf2KeyDerivationParams } from '../converters';
22
+ import { allKeyPairAlgorithms, allKeyStoreSecretTypes, allKeyStoreSymmetricSecretTypes, KEYSTORE_FORMAT, allKeyStoreAsymmetricSecretTypes } from './model';
23
23
  // ============================================================================
24
24
  // Key Store Format Converter
25
25
  // ============================================================================
@@ -31,31 +31,123 @@ export const keystoreFormat = Converters.enumeratedValue([
31
31
  KEYSTORE_FORMAT
32
32
  ]);
33
33
  // ============================================================================
34
- // Secret Type Converter
34
+ // Secret Type Converters
35
35
  // ============================================================================
36
36
  /**
37
- * Converter for {@link CryptoUtils.KeyStore.KeyStoreSecretType | key store secret type} discriminator.
37
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreSecretType | any key store secret type} discriminator.
38
+ * Accepts both symmetric and asymmetric type values.
38
39
  * @public
39
40
  */
40
41
  export const keystoreSecretType = Converters.enumeratedValue(allKeyStoreSecretTypes);
42
+ /**
43
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreSymmetricSecretType | symmetric secret type} discriminator.
44
+ * Accepts only `'encryption-key'` and `'api-key'`.
45
+ * @public
46
+ */
47
+ export const keystoreSymmetricSecretType = Converters.enumeratedValue(allKeyStoreSymmetricSecretTypes);
48
+ /**
49
+ * Converter for {@link CryptoUtils.KeyStore.KeyStoreAsymmetricSecretType | asymmetric secret type} discriminator.
50
+ * Accepts only `'asymmetric-keypair'`.
51
+ * @public
52
+ */
53
+ export const keystoreAsymmetricSecretType = Converters.enumeratedValue(allKeyStoreAsymmetricSecretTypes);
54
+ // ============================================================================
55
+ // Key Pair Algorithm Converter
56
+ // ============================================================================
57
+ /**
58
+ * Converter for {@link CryptoUtils.KeyStore.KeyPairAlgorithm | key pair algorithm}.
59
+ * @public
60
+ */
61
+ export const keyPairAlgorithm = Converters.enumeratedValue(allKeyPairAlgorithms);
41
62
  // ============================================================================
42
- // Secret Entry Converters
63
+ // JWK Shape Validator
43
64
  // ============================================================================
44
65
  /**
45
- * Converter for {@link CryptoUtils.KeyStore.IKeyStoreSecretEntryJson | key store secret entry} in JSON format.
46
- * The `type` field is optional for backwards compatibility — missing means `'encryption-key'`.
66
+ * In-place shape check for a JSON Web Key. Asserts only that the input is a
67
+ * non-array object whose `kty` discriminator is a string; every other JWK
68
+ * field passes through untouched. This is intentionally **not** a true JWK
69
+ * validator — per-algorithm correctness (RSA `n`/`e`, EC `crv`/`x`/`y`,
70
+ * key-size constraints, etc.) is delegated to `crypto.subtle.importKey` at
71
+ * first use, which is the authoritative checker. The "shape" suffix in the
72
+ * name is the warning sign for readers expecting full validation.
73
+ * @remarks
74
+ * Built with `Validators.object` (in-place, non-strict) so unknown JWK fields
75
+ * survive the round-trip; the cast to `FieldValidators<JsonWebKey>` is required
76
+ * only because TypeScript's mapped type demands an entry for every key in
77
+ * `JsonWebKey`. At runtime the `ObjectValidator` only inspects keys present in
78
+ * the field-validators map.
47
79
  * @public
48
80
  */
49
- export const keystoreSecretEntryJson = Converters.object({
81
+ export const jsonWebKeyShape = Validators.object({
82
+ kty: Validators.string
83
+ });
84
+ // ============================================================================
85
+ // Symmetric Secret Entry Converter
86
+ // ============================================================================
87
+ /**
88
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson | symmetric secret entry} in JSON form.
89
+ *
90
+ * @remarks
91
+ * Backwards compatibility with vaults written before asymmetric-keypair
92
+ * support: those entries may lack the `type` discriminator on the wire. To
93
+ * keep the model type honest (`type` is required on
94
+ * {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson}, see its docs),
95
+ * we declare `type` in `optionalFields` so the inner `Converters.object` will
96
+ * accept input without it, then `.map()` injects the default
97
+ * `'encryption-key'` when missing. The output therefore always carries the
98
+ * discriminator and downstream code never sees the legacy missing-type form.
99
+ *
100
+ * @public
101
+ */
102
+ export const keystoreSymmetricEntryJson = Converters.object({
50
103
  name: Converters.string,
51
- type: keystoreSecretType,
104
+ type: keystoreSymmetricSecretType,
52
105
  key: base64String,
53
106
  description: Converters.string,
54
107
  createdAt: Converters.string
55
108
  }, {
109
+ // `type` is optional at the input layer for legacy-vault compatibility;
110
+ // the .map() below normalizes by injecting the default.
56
111
  optionalFields: ['type', 'description']
112
+ }).map((entry) => {
113
+ var _a;
114
+ return succeed(Object.assign(Object.assign({}, entry), { type: (_a = entry.type) !== null && _a !== void 0 ? _a : 'encryption-key' }));
57
115
  });
58
116
  // ============================================================================
117
+ // Asymmetric Keypair Entry Converter
118
+ // ============================================================================
119
+ /**
120
+ * Converter for {@link CryptoUtils.KeyStore.IKeyStoreAsymmetricEntryJson | asymmetric keypair entry} in JSON form.
121
+ * The `publicKeyJwk` field passes through {@link CryptoUtils.KeyStore.Converters.jsonWebKeyShape | jsonWebKeyShape}
122
+ * (shape check only — see its docs); cryptographic correctness is enforced by
123
+ * `crypto.subtle.importKey` at use.
124
+ * @public
125
+ */
126
+ export const keystoreAsymmetricEntryJson = Converters.object({
127
+ name: Converters.string,
128
+ type: keystoreAsymmetricSecretType,
129
+ id: Converters.string,
130
+ algorithm: keyPairAlgorithm,
131
+ publicKeyJwk: jsonWebKeyShape,
132
+ description: Converters.string.optional(),
133
+ createdAt: Converters.string
134
+ });
135
+ // ============================================================================
136
+ // Discriminated-Union Entry Converter
137
+ // ============================================================================
138
+ /**
139
+ * Discriminated-union converter for any {@link CryptoUtils.KeyStore.IKeyStoreEntryJson | key store entry} in JSON form.
140
+ * Routes by the `type` field: `'asymmetric-keypair'` is parsed by
141
+ * {@link CryptoUtils.KeyStore.Converters.keystoreAsymmetricEntryJson | keystoreAsymmetricEntryJson},
142
+ * anything else (including a missing `type` field for backwards compatibility) by
143
+ * {@link CryptoUtils.KeyStore.Converters.keystoreSymmetricEntryJson | keystoreSymmetricEntryJson}.
144
+ * @public
145
+ */
146
+ export const keystoreSecretEntryJson = Converters.oneOf([
147
+ keystoreAsymmetricEntryJson,
148
+ keystoreSymmetricEntryJson
149
+ ]);
150
+ // ============================================================================
59
151
  // Vault Contents Converter
60
152
  // ============================================================================
61
153
  /**
@@ -79,6 +171,6 @@ export const keystoreFile = Converters.object({
79
171
  iv: base64String,
80
172
  authTag: base64String,
81
173
  encryptedData: base64String,
82
- keyDerivation: keyDerivationParams
174
+ keyDerivation: pbkdf2KeyDerivationParams
83
175
  });
84
176
  //# sourceMappingURL=converters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"converters.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/converters.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,OAAO,EAAa,UAAU,EAAE,OAAO,EAAyB,UAAU,EAAE,MAAM,eAAe,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,+BAA+B,EAM/B,eAAe,EAMf,gCAAgC,EACjC,MAAM,SAAS,CAAC;AAEjB,+EAA+E;AAC/E,6BAA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026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { Converter, Converters, succeed, Validation, Validator, Validators } from '@fgv/ts-utils';\nimport { base64String, encryptionAlgorithm, pbkdf2KeyDerivationParams } from '../converters';\nimport {\n allKeyPairAlgorithms,\n allKeyStoreSecretTypes,\n allKeyStoreSymmetricSecretTypes,\n IKeyStoreAsymmetricEntryJson,\n IKeyStoreEntryJson,\n IKeyStoreFile,\n IKeyStoreSymmetricEntryJson,\n IKeyStoreVaultContents,\n KEYSTORE_FORMAT,\n KeyPairAlgorithm,\n KeyStoreAsymmetricSecretType,\n KeyStoreFormat,\n KeyStoreSecretType,\n KeyStoreSymmetricSecretType,\n allKeyStoreAsymmetricSecretTypes\n} from './model';\n\n// ============================================================================\n// Key Store Format Converter\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.KeyStoreFormat | key store format} version.\n * @public\n */\nexport const keystoreFormat: Converter<KeyStoreFormat> = Converters.enumeratedValue<KeyStoreFormat>([\n KEYSTORE_FORMAT\n]);\n\n// ============================================================================\n// Secret Type Converters\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.KeyStoreSecretType | any key store secret type} discriminator.\n * Accepts both symmetric and asymmetric type values.\n * @public\n */\nexport const keystoreSecretType: Converter<KeyStoreSecretType> =\n Converters.enumeratedValue<KeyStoreSecretType>(allKeyStoreSecretTypes);\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.KeyStoreSymmetricSecretType | symmetric secret type} discriminator.\n * Accepts only `'encryption-key'` and `'api-key'`.\n * @public\n */\nexport const keystoreSymmetricSecretType: Converter<KeyStoreSymmetricSecretType> =\n Converters.enumeratedValue<KeyStoreSymmetricSecretType>(allKeyStoreSymmetricSecretTypes);\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.KeyStoreAsymmetricSecretType | asymmetric secret type} discriminator.\n * Accepts only `'asymmetric-keypair'`.\n * @public\n */\nexport const keystoreAsymmetricSecretType: Converter<KeyStoreAsymmetricSecretType> =\n Converters.enumeratedValue<KeyStoreAsymmetricSecretType>(allKeyStoreAsymmetricSecretTypes);\n\n// ============================================================================\n// Key Pair Algorithm Converter\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.KeyPairAlgorithm | key pair algorithm}.\n * @public\n */\nexport const keyPairAlgorithm: Converter<KeyPairAlgorithm> =\n Converters.enumeratedValue<KeyPairAlgorithm>(allKeyPairAlgorithms);\n\n// ============================================================================\n// JWK Shape Validator\n// ============================================================================\n\n/**\n * In-place shape check for a JSON Web Key. Asserts only that the input is a\n * non-array object whose `kty` discriminator is a string; every other JWK\n * field passes through untouched. This is intentionally **not** a true JWK\n * validator — per-algorithm correctness (RSA `n`/`e`, EC `crv`/`x`/`y`,\n * key-size constraints, etc.) is delegated to `crypto.subtle.importKey` at\n * first use, which is the authoritative checker. The \"shape\" suffix in the\n * name is the warning sign for readers expecting full validation.\n * @remarks\n * Built with `Validators.object` (in-place, non-strict) so unknown JWK fields\n * survive the round-trip; the cast to `FieldValidators<JsonWebKey>` is required\n * only because TypeScript's mapped type demands an entry for every key in\n * `JsonWebKey`. At runtime the `ObjectValidator` only inspects keys present in\n * the field-validators map.\n * @public\n */\nexport const jsonWebKeyShape: Validator<JsonWebKey> = Validators.object<JsonWebKey>({\n kty: Validators.string\n} as Validation.Classes.FieldValidators<JsonWebKey>);\n\n// ============================================================================\n// Symmetric Secret Entry Converter\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson | symmetric secret entry} in JSON form.\n *\n * @remarks\n * Backwards compatibility with vaults written before asymmetric-keypair\n * support: those entries may lack the `type` discriminator on the wire. To\n * keep the model type honest (`type` is required on\n * {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson}, see its docs),\n * we declare `type` in `optionalFields` so the inner `Converters.object` will\n * accept input without it, then `.map()` injects the default\n * `'encryption-key'` when missing. The output therefore always carries the\n * discriminator and downstream code never sees the legacy missing-type form.\n *\n * @public\n */\nexport const keystoreSymmetricEntryJson: Converter<IKeyStoreSymmetricEntryJson> =\n Converters.object<IKeyStoreSymmetricEntryJson>(\n {\n name: Converters.string,\n type: keystoreSymmetricSecretType,\n key: base64String,\n description: Converters.string,\n createdAt: Converters.string\n },\n {\n // `type` is optional at the input layer for legacy-vault compatibility;\n // the .map() below normalizes by injecting the default.\n optionalFields: ['type', 'description']\n }\n ).map((entry) =>\n succeed<IKeyStoreSymmetricEntryJson>({\n ...entry,\n type: entry.type ?? 'encryption-key'\n })\n );\n\n// ============================================================================\n// Asymmetric Keypair Entry Converter\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.IKeyStoreAsymmetricEntryJson | asymmetric keypair entry} in JSON form.\n * The `publicKeyJwk` field passes through {@link CryptoUtils.KeyStore.Converters.jsonWebKeyShape | jsonWebKeyShape}\n * (shape check only — see its docs); cryptographic correctness is enforced by\n * `crypto.subtle.importKey` at use.\n * @public\n */\nexport const keystoreAsymmetricEntryJson: Converter<IKeyStoreAsymmetricEntryJson> =\n Converters.object<IKeyStoreAsymmetricEntryJson>({\n name: Converters.string,\n type: keystoreAsymmetricSecretType,\n id: Converters.string,\n algorithm: keyPairAlgorithm,\n publicKeyJwk: jsonWebKeyShape,\n description: Converters.string.optional(),\n createdAt: Converters.string\n });\n\n// ============================================================================\n// Discriminated-Union Entry Converter\n// ============================================================================\n\n/**\n * Discriminated-union converter for any {@link CryptoUtils.KeyStore.IKeyStoreEntryJson | key store entry} in JSON form.\n * Routes by the `type` field: `'asymmetric-keypair'` is parsed by\n * {@link CryptoUtils.KeyStore.Converters.keystoreAsymmetricEntryJson | keystoreAsymmetricEntryJson},\n * anything else (including a missing `type` field for backwards compatibility) by\n * {@link CryptoUtils.KeyStore.Converters.keystoreSymmetricEntryJson | keystoreSymmetricEntryJson}.\n * @public\n */\nexport const keystoreSecretEntryJson: Converter<IKeyStoreEntryJson> = Converters.oneOf<IKeyStoreEntryJson>([\n keystoreAsymmetricEntryJson,\n keystoreSymmetricEntryJson\n]);\n\n// ============================================================================\n// Vault Contents Converter\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.IKeyStoreVaultContents | key store vault contents} (decrypted state).\n * @public\n */\nexport const keystoreVaultContents: Converter<IKeyStoreVaultContents> =\n Converters.object<IKeyStoreVaultContents>({\n version: keystoreFormat,\n secrets: Converters.recordOf(keystoreSecretEntryJson)\n });\n\n// ============================================================================\n// Key Store File Converter\n// ============================================================================\n\n/**\n * Converter for {@link CryptoUtils.KeyStore.IKeyStoreFile | encrypted key store file}.\n * @public\n */\nexport const keystoreFile: Converter<IKeyStoreFile> = Converters.object<IKeyStoreFile>({\n format: keystoreFormat,\n algorithm: encryptionAlgorithm,\n iv: base64String,\n authTag: base64String,\n encryptedData: base64String,\n keyDerivation: pbkdf2KeyDerivationParams\n});\n"]}
@@ -0,0 +1,287 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ import * as crypto from 'crypto';
21
+ import { captureAsyncResult, captureResult, Converters, fail, succeed } from '@fgv/ts-utils';
22
+ import { FileTree } from '@fgv/ts-json-base';
23
+ import { createEncryptedFile, tryDecryptFile } from '../encryptedFile';
24
+ import { keyPairAlgorithmParams } from '../keyPairAlgorithmParams';
25
+ import * as Constants from '../constants';
26
+ import { jsonWebKeyShape, keyPairAlgorithm } from './converters';
27
+ const envelopeConverter = Converters.object({
28
+ algorithm: keyPairAlgorithm,
29
+ jwk: Converters.string
30
+ });
31
+ // WebCrypto key usages that only ever apply to a public key. Filtering these
32
+ // out of the keypair usages yields the usages valid for the private half, which
33
+ // `crypto.subtle.importKey` requires when re-importing a private JWK.
34
+ const PUBLIC_ONLY_USAGES = ['verify', 'encrypt', 'wrapKey'];
35
+ // Safe-filename id production. The keystore mints UUIDv4 handles, which match;
36
+ // arbitrary consumer-supplied ids that could escape the storage directory are
37
+ // rejected rather than silently mangled.
38
+ const SAFE_ID = /^[A-Za-z0-9._-]+$/;
39
+ const FILE_SUFFIX = '.json';
40
+ /**
41
+ * {@link CryptoUtils.KeyStore.IPrivateKeyStorage | IPrivateKeyStorage}
42
+ * implementation that persists each private key as its own AES-256-GCM-encrypted
43
+ * file in a directory. The file content is the key's JWK, encrypted with a
44
+ * consumer-supplied 32-byte key via the supplied
45
+ * {@link CryptoUtils.ICryptoProvider | crypto provider}.
46
+ *
47
+ * `supportsNonExtractable` is `false`: persisting to disk requires exporting the
48
+ * private key to JWK, which only works for `extractable: true` keys. The
49
+ * keystore generates extractable keys when a backend reports `false` here.
50
+ *
51
+ * I/O goes through the {@link FileTree.FileTree | FileTree} abstraction (default
52
+ * `FsTree`), so the same implementation works against an in-memory tree (tests)
53
+ * or any other Node-compatible backend.
54
+ *
55
+ * This backend is **Node-only**: it round-trips private keys through
56
+ * `node:crypto` (`crypto.webcrypto.subtle`), so it is intentionally excluded
57
+ * from the browser entry point. Browser consumers should use
58
+ * `IdbPrivateKeyStorage` from `@fgv/ts-web-extras` instead.
59
+ *
60
+ * Single-process assumption: there is no inter-process locking. Concurrent
61
+ * writers to the same directory may race.
62
+ *
63
+ * @public
64
+ */
65
+ export class EncryptedFilePrivateKeyStorage {
66
+ constructor(directory, encryptionKey, cryptoProvider) {
67
+ /**
68
+ * `false` — disk persistence round-trips via JWK, which requires extractable
69
+ * keys.
70
+ */
71
+ this.supportsNonExtractable = false;
72
+ this._directory = directory;
73
+ // Clone so the instance holds an immutable snapshot — callers that later
74
+ // reuse or zero their buffer must not be able to mutate our key.
75
+ this._encryptionKey = Uint8Array.from(encryptionKey);
76
+ this._cryptoProvider = cryptoProvider;
77
+ }
78
+ /**
79
+ * Creates a new {@link CryptoUtils.KeyStore.EncryptedFilePrivateKeyStorage}.
80
+ * @param params - {@link CryptoUtils.KeyStore.IEncryptedFilePrivateKeyStorageCreateParams}.
81
+ * @returns `Success` with the new instance, or `Failure` if the encryption
82
+ * key is the wrong size or the storage directory cannot be opened.
83
+ */
84
+ static create(params) {
85
+ const { directory, encryptionKey, cryptoProvider, tree } = params;
86
+ if (encryptionKey.length !== Constants.AES_256_KEY_SIZE) {
87
+ return fail(`EncryptedFilePrivateKeyStorage: encryptionKey must be ${Constants.AES_256_KEY_SIZE} bytes, got ${encryptionKey.length}`);
88
+ }
89
+ if (tree !== undefined) {
90
+ return succeed(new EncryptedFilePrivateKeyStorage(tree, encryptionKey, cryptoProvider));
91
+ }
92
+ return FileTree.forFilesystem({ mutable: true })
93
+ .onSuccess((ft) => ft.getDirectory(directory))
94
+ .withErrorFormat((msg) => `EncryptedFilePrivateKeyStorage: failed to open '${directory}': ${msg}`)
95
+ .onSuccess((dir) => succeed(new EncryptedFilePrivateKeyStorage(dir, encryptionKey, cryptoProvider)));
96
+ }
97
+ /**
98
+ * Stores `key` under `id` as an encrypted JWK file.
99
+ * @param id - Storage handle. Must be a safe filename token
100
+ * (`[A-Za-z0-9._-]+`, not `.`/`..`).
101
+ * @param key - The extractable private `CryptoKey` to persist.
102
+ */
103
+ async store(id, key) {
104
+ return this._validateKeyToStore(id, key).thenOnSuccess(({ fileName, algorithm }) => this._encryptAndWrite(algorithm, key, id, fileName));
105
+ }
106
+ /**
107
+ * Loads the private key stored under `id`, decrypting and re-importing it from
108
+ * JWK.
109
+ * @param id - Storage handle.
110
+ */
111
+ async load(id) {
112
+ return this._fileNameFor(id)
113
+ .onSuccess((fileName) => this._findFile(fileName))
114
+ .onSuccess((file) => file === undefined ? fail(`key not found: '${id}'`) : succeed(file))
115
+ .thenOnSuccess((file) => this._decryptEnvelope(file, id))
116
+ .thenOnSuccess((envelope) => this._importPrivateKey(envelope, id));
117
+ }
118
+ /**
119
+ * Deletes the entry stored under `id`. Missing ids fail (the read path is
120
+ * keystore-driven and never asks to delete an id it did not store).
121
+ * @param id - Storage handle.
122
+ */
123
+ async delete(id) {
124
+ const fileResult = this._fileNameFor(id).onSuccess((fileName) => this._findFile(fileName).onSuccess((file) => succeed({ fileName, file })));
125
+ if (fileResult.isFailure()) {
126
+ return fail(fileResult.message);
127
+ }
128
+ if (fileResult.value.file === undefined) {
129
+ return fail(`key not found: '${id}'`);
130
+ }
131
+ /* c8 ignore next 3 - defensive: directory items from read-only adapters lack mutation methods */
132
+ if (!FileTree.isMutableDirectoryItem(this._directory)) {
133
+ return fail(`failed to delete private key '${id}': storage directory is not mutable`);
134
+ }
135
+ return Promise.resolve(this._directory
136
+ .deleteChild(fileResult.value.fileName)
137
+ .withErrorFormat((msg) => `failed to delete private key '${id}': ${msg}`)
138
+ .onSuccess(() => succeed(id)));
139
+ }
140
+ /**
141
+ * Lists every stored id.
142
+ */
143
+ async list() {
144
+ return Promise.resolve(this._directory.getChildren().onSuccess((children) => {
145
+ const ids = children
146
+ .filter((child) => child.type === 'file' && child.name.endsWith(FILE_SUFFIX))
147
+ .map((child) => child.name.slice(0, -FILE_SUFFIX.length));
148
+ return succeed(ids);
149
+ }));
150
+ }
151
+ _fileNameFor(id) {
152
+ if (id === '.' || id === '..' || !SAFE_ID.test(id)) {
153
+ return fail(`invalid storage id '${id}': must match ${SAFE_ID.source}`);
154
+ }
155
+ return succeed(`${id}${FILE_SUFFIX}`);
156
+ }
157
+ /**
158
+ * Validates the synchronous preconditions for a store: the id is filename-safe,
159
+ * the key is actually a private key, and its algorithm is one we support.
160
+ * Returns the resolved filename and algorithm so the async pipeline can run
161
+ * without re-deriving them.
162
+ */
163
+ _validateKeyToStore(id, key) {
164
+ return this._fileNameFor(id).onSuccess((fileName) => {
165
+ if (key.type !== 'private') {
166
+ return fail(`failed to store private key '${id}': expected a private key, got '${key.type}'`);
167
+ }
168
+ return this._algorithmOf(key)
169
+ .withErrorFormat((msg) => `failed to store private key '${id}': ${msg}`)
170
+ .onSuccess((algorithm) => succeed({ fileName, algorithm }));
171
+ });
172
+ }
173
+ /**
174
+ * Exports `key` to JWK, wraps it in the stored envelope, encrypts it with
175
+ * AES-256-GCM, and writes the resulting file as serialized JSON to `fileName`.
176
+ * Returns the stored `id` on success.
177
+ */
178
+ async _encryptAndWrite(algorithm, key, id, fileName) {
179
+ return captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('jwk', key))
180
+ .withErrorFormat((msg) => `failed to export private key '${id}' to JWK: ${msg}`)
181
+ .onSuccess((jwk) => succeed({ algorithm, jwk: JSON.stringify(jwk) }))
182
+ .thenOnSuccess(async (envelope) => (await createEncryptedFile({
183
+ content: envelope,
184
+ secretName: id,
185
+ key: this._encryptionKey,
186
+ cryptoProvider: this._cryptoProvider
187
+ })).withErrorFormat((msg) => `failed to encrypt private key '${id}': ${msg}`))
188
+ .onSuccess((encrypted) => this._writeFile(fileName, JSON.stringify(encrypted)))
189
+ .onSuccess(() => succeed(id));
190
+ }
191
+ _algorithmOf(key) {
192
+ const alg = key.algorithm;
193
+ switch (alg.name) {
194
+ case 'ECDSA':
195
+ case 'ECDH': {
196
+ const curve = alg.namedCurve;
197
+ if (curve !== 'P-256') {
198
+ return fail(`unsupported ${alg.name} curve '${curve}' (only P-256 is supported)`);
199
+ }
200
+ return succeed(alg.name === 'ECDSA' ? 'ecdsa-p256' : 'ecdh-p256');
201
+ }
202
+ case 'RSA-OAEP': {
203
+ // Only the hash affects the JWK re-import params, so it is the field
204
+ // that must match; the modulus length is recovered from the key data.
205
+ const hash = alg.hash.name;
206
+ if (hash !== 'SHA-256') {
207
+ return fail(`unsupported RSA-OAEP hash '${hash}' (only SHA-256 is supported)`);
208
+ }
209
+ return succeed('rsa-oaep-2048');
210
+ }
211
+ case 'Ed25519':
212
+ return succeed('ed25519');
213
+ case 'X25519':
214
+ return succeed('x25519');
215
+ default:
216
+ return fail(`unsupported key algorithm '${alg.name}'`);
217
+ }
218
+ }
219
+ _findFile(fileName) {
220
+ return this._directory.getChildren().onSuccess((children) => {
221
+ const found = children.find((child) => child.type === 'file' && child.name === fileName);
222
+ return succeed(found);
223
+ });
224
+ }
225
+ _writeFile(fileName, text) {
226
+ return this._findFile(fileName).onSuccess((existing) => {
227
+ if (existing !== undefined) {
228
+ /* c8 ignore next 3 - defensive: file items from read-only adapters lack mutation methods */
229
+ if (!FileTree.isMutableFileItem(existing)) {
230
+ return fail(`${existing.absolutePath}: not mutable`);
231
+ }
232
+ return existing.setRawContents(text);
233
+ }
234
+ /* c8 ignore next 3 - defensive: directory items from read-only adapters lack mutation methods */
235
+ if (!FileTree.isMutableDirectoryItem(this._directory)) {
236
+ return fail(`${this._directory.absolutePath}: not mutable`);
237
+ }
238
+ return this._directory.createChildFile(fileName, text).onSuccess(() => succeed(text));
239
+ });
240
+ }
241
+ /**
242
+ * Reads `file`, decrypts the AES-256-GCM envelope, and validates it into the
243
+ * typed `IStoredPrivateKeyEnvelope`. Read, decrypt, and shape failures
244
+ * all surface as a decrypt failure for `id`.
245
+ */
246
+ async _decryptEnvelope(file, id) {
247
+ return file
248
+ .getContents()
249
+ .thenOnSuccess((json) => tryDecryptFile(json, this._encryptionKey, this._cryptoProvider))
250
+ .onSuccess((decrypted) => envelopeConverter.convert(decrypted))
251
+ .withErrorFormat((msg) => `failed to decrypt private key '${id}': ${msg}`);
252
+ }
253
+ /**
254
+ * Parses and shape-validates the stored JWK, then re-imports it as a private
255
+ * `CryptoKey` for the envelope's algorithm. The WebCrypto JWK-import algorithm
256
+ * descriptor is shared between public and private keys for every supported
257
+ * algorithm, so `IKeyPairAlgorithmParams.importPublicKey` is reused here;
258
+ * the public/private distinction is carried by the requested `usages`.
259
+ */
260
+ async _importPrivateKey(envelope, id) {
261
+ const params = keyPairAlgorithmParams[envelope.algorithm];
262
+ return captureResult(() => JSON.parse(envelope.jwk))
263
+ .onSuccess((parsed) => jsonWebKeyShape.validate(parsed))
264
+ .withErrorFormat((msg) => `malformed JWK: ${msg}`)
265
+ .thenOnSuccess((jwk) => captureAsyncResult(() => crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, this._importUsagesFor(jwk, params))))
266
+ .withErrorFormat((msg) => `failed to import private key '${id}': ${msg}`);
267
+ }
268
+ /**
269
+ * Computes the key usages to request when re-importing a stored private key.
270
+ * WebCrypto rejects `importKey` if the requested usages include operations
271
+ * absent from the JWK's `key_ops`, so a key originally created with a narrower
272
+ * usage set than the algorithm default (e.g. an ECDH key with only
273
+ * `deriveBits`) would fail to load against the algorithm-wide defaults.
274
+ * Intersect the algorithm's private usages with the JWK's recorded `key_ops`
275
+ * so we request exactly the operations the stored key actually supports;
276
+ * fall back to the algorithm's private usages when `key_ops` is absent.
277
+ */
278
+ _importUsagesFor(jwk, params) {
279
+ const privateUsages = params.keyPairUsages.filter((usage) => !PUBLIC_ONLY_USAGES.includes(usage));
280
+ const keyOps = jwk.key_ops;
281
+ if (keyOps === undefined) {
282
+ return [...privateUsages];
283
+ }
284
+ return privateUsages.filter((usage) => keyOps.includes(usage));
285
+ }
286
+ }
287
+ //# sourceMappingURL=encryptedFilePrivateKeyStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryptedFilePrivateKeyStorage.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,EACL,kBAAkB,EAClB,aAAa,EAEb,UAAU,EACV,IAAI,EAEJ,OAAO,EACR,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,QAAQ,EAAc,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EAA2B,sBA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CAAC;IACjE,CAAC;CACF","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport * as crypto from 'crypto';\nimport {\n captureAsyncResult,\n captureResult,\n Converter,\n Converters,\n fail,\n Result,\n succeed\n} from '@fgv/ts-utils';\nimport { FileTree, JsonObject } from '@fgv/ts-json-base';\nimport { createEncryptedFile, tryDecryptFile } from '../encryptedFile';\nimport { IKeyPairAlgorithmParams, keyPairAlgorithmParams } from '../keyPairAlgorithmParams';\nimport { ICryptoProvider, KeyPairAlgorithm } from '../model';\nimport * as Constants from '../constants';\nimport { jsonWebKeyShape, keyPairAlgorithm } from './converters';\nimport { IPrivateKeyStorage } from './privateKeyStorage';\n\n/**\n * Parameters for {@link CryptoUtils.KeyStore.EncryptedFilePrivateKeyStorage.create}.\n * @public\n */\nexport interface IEncryptedFilePrivateKeyStorageCreateParams {\n /**\n * Filesystem path to the directory that holds the encrypted private-key\n * files. Used only when {@link CryptoUtils.KeyStore.IEncryptedFilePrivateKeyStorageCreateParams.tree}\n * is omitted (the default `FsTree` backing). The directory must already\n * exist.\n */\n readonly directory: string;\n\n /**\n * Raw AES-256-GCM key (32 bytes) used to encrypt each file's JWK content.\n * Consumer-supplied and decoupled from the keystore's password lifecycle —\n * derive it however the application sees fit (typically the same\n * password-derived key material the keystore vault uses).\n */\n readonly encryptionKey: Uint8Array;\n\n /**\n * {@link CryptoUtils.ICryptoProvider | Crypto provider} used for the\n * AES-256-GCM encrypt/decrypt of each file's contents.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Optional {@link FileTree.IFileTreeDirectoryItem | FileTree directory}\n * override. When supplied it is used as the storage directory directly and\n * {@link CryptoUtils.KeyStore.IEncryptedFilePrivateKeyStorageCreateParams.directory} is ignored —\n * pass an in-memory tree for tests, or another Node-compatible backend. When\n * omitted, a mutable `FsTree` rooted at `directory` is used. (This backend is\n * Node-only — it round-trips keys through `node:crypto` — so a browser file\n * tree is not a supported target.)\n */\n readonly tree?: FileTree.IFileTreeDirectoryItem;\n}\n\n/**\n * Decrypted on-disk envelope for a single stored private key. The JWK is held\n * as a serialized JSON string so the whole envelope is a flat record of\n * strings, which round-trips through {@link CryptoUtils.createEncryptedFile}\n * without ambiguity.\n */\ninterface IStoredPrivateKeyEnvelope {\n readonly algorithm: KeyPairAlgorithm;\n readonly jwk: string;\n}\n\nconst envelopeConverter: Converter<IStoredPrivateKeyEnvelope> = Converters.object<IStoredPrivateKeyEnvelope>({\n algorithm: keyPairAlgorithm,\n jwk: Converters.string\n});\n\n// WebCrypto key usages that only ever apply to a public key. Filtering these\n// out of the keypair usages yields the usages valid for the private half, which\n// `crypto.subtle.importKey` requires when re-importing a private JWK.\nconst PUBLIC_ONLY_USAGES: ReadonlyArray<KeyUsage> = ['verify', 'encrypt', 'wrapKey'];\n\n// Safe-filename id production. The keystore mints UUIDv4 handles, which match;\n// arbitrary consumer-supplied ids that could escape the storage directory are\n// rejected rather than silently mangled.\nconst SAFE_ID: RegExp = /^[A-Za-z0-9._-]+$/;\n\nconst FILE_SUFFIX: string = '.json';\n\n/**\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage | IPrivateKeyStorage}\n * implementation that persists each private key as its own AES-256-GCM-encrypted\n * file in a directory. The file content is the key's JWK, encrypted with a\n * consumer-supplied 32-byte key via the supplied\n * {@link CryptoUtils.ICryptoProvider | crypto provider}.\n *\n * `supportsNonExtractable` is `false`: persisting to disk requires exporting the\n * private key to JWK, which only works for `extractable: true` keys. The\n * keystore generates extractable keys when a backend reports `false` here.\n *\n * I/O goes through the {@link FileTree.FileTree | FileTree} abstraction (default\n * `FsTree`), so the same implementation works against an in-memory tree (tests)\n * or any other Node-compatible backend.\n *\n * This backend is **Node-only**: it round-trips private keys through\n * `node:crypto` (`crypto.webcrypto.subtle`), so it is intentionally excluded\n * from the browser entry point. Browser consumers should use\n * `IdbPrivateKeyStorage` from `@fgv/ts-web-extras` instead.\n *\n * Single-process assumption: there is no inter-process locking. Concurrent\n * writers to the same directory may race.\n *\n * @public\n */\nexport class EncryptedFilePrivateKeyStorage implements IPrivateKeyStorage {\n /**\n * `false` — disk persistence round-trips via JWK, which requires extractable\n * keys.\n */\n public readonly supportsNonExtractable: false = false;\n\n private readonly _directory: FileTree.IFileTreeDirectoryItem;\n private readonly _encryptionKey: Uint8Array;\n private readonly _cryptoProvider: ICryptoProvider;\n\n private constructor(\n directory: FileTree.IFileTreeDirectoryItem,\n encryptionKey: Uint8Array,\n cryptoProvider: ICryptoProvider\n ) {\n this._directory = directory;\n // Clone so the instance holds an immutable snapshot — callers that later\n // reuse or zero their buffer must not be able to mutate our key.\n this._encryptionKey = Uint8Array.from(encryptionKey);\n this._cryptoProvider = cryptoProvider;\n }\n\n /**\n * Creates a new {@link CryptoUtils.KeyStore.EncryptedFilePrivateKeyStorage}.\n * @param params - {@link CryptoUtils.KeyStore.IEncryptedFilePrivateKeyStorageCreateParams}.\n * @returns `Success` with the new instance, or `Failure` if the encryption\n * key is the wrong size or the storage directory cannot be opened.\n */\n public static create(\n params: IEncryptedFilePrivateKeyStorageCreateParams\n ): Result<EncryptedFilePrivateKeyStorage> {\n const { directory, encryptionKey, cryptoProvider, tree } = params;\n if (encryptionKey.length !== Constants.AES_256_KEY_SIZE) {\n return fail(\n `EncryptedFilePrivateKeyStorage: encryptionKey must be ${Constants.AES_256_KEY_SIZE} bytes, got ${encryptionKey.length}`\n );\n }\n if (tree !== undefined) {\n return succeed(new EncryptedFilePrivateKeyStorage(tree, encryptionKey, cryptoProvider));\n }\n return FileTree.forFilesystem({ mutable: true })\n .onSuccess((ft) => ft.getDirectory(directory))\n .withErrorFormat((msg) => `EncryptedFilePrivateKeyStorage: failed to open '${directory}': ${msg}`)\n .onSuccess((dir) => succeed(new EncryptedFilePrivateKeyStorage(dir, encryptionKey, cryptoProvider)));\n }\n\n /**\n * Stores `key` under `id` as an encrypted JWK file.\n * @param id - Storage handle. Must be a safe filename token\n * (`[A-Za-z0-9._-]+`, not `.`/`..`).\n * @param key - The extractable private `CryptoKey` to persist.\n */\n public async store(id: string, key: CryptoKey): Promise<Result<string>> {\n return this._validateKeyToStore(id, key).thenOnSuccess(({ fileName, algorithm }) =>\n this._encryptAndWrite(algorithm, key, id, fileName)\n );\n }\n\n /**\n * Loads the private key stored under `id`, decrypting and re-importing it from\n * JWK.\n * @param id - Storage handle.\n */\n public async load(id: string): Promise<Result<CryptoKey>> {\n return this._fileNameFor(id)\n .onSuccess((fileName) => this._findFile(fileName))\n .onSuccess((file) =>\n file === undefined ? fail<FileTree.IFileTreeFileItem>(`key not found: '${id}'`) : succeed(file)\n )\n .thenOnSuccess((file) => this._decryptEnvelope(file, id))\n .thenOnSuccess((envelope) => this._importPrivateKey(envelope, id));\n }\n\n /**\n * Deletes the entry stored under `id`. Missing ids fail (the read path is\n * keystore-driven and never asks to delete an id it did not store).\n * @param id - Storage handle.\n */\n public async delete(id: string): Promise<Result<string>> {\n const fileResult = this._fileNameFor(id).onSuccess((fileName) =>\n this._findFile(fileName).onSuccess((file) => succeed({ fileName, file }))\n );\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n if (fileResult.value.file === undefined) {\n return fail(`key not found: '${id}'`);\n }\n /* c8 ignore next 3 - defensive: directory items from read-only adapters lack mutation methods */\n if (!FileTree.isMutableDirectoryItem(this._directory)) {\n return fail(`failed to delete private key '${id}': storage directory is not mutable`);\n }\n return Promise.resolve(\n this._directory\n .deleteChild(fileResult.value.fileName)\n .withErrorFormat((msg) => `failed to delete private key '${id}': ${msg}`)\n .onSuccess(() => succeed(id))\n );\n }\n\n /**\n * Lists every stored id.\n */\n public async list(): Promise<Result<readonly string[]>> {\n return Promise.resolve(\n this._directory.getChildren().onSuccess((children) => {\n const ids = children\n .filter((child) => child.type === 'file' && child.name.endsWith(FILE_SUFFIX))\n .map((child) => child.name.slice(0, -FILE_SUFFIX.length));\n return succeed(ids);\n })\n );\n }\n\n private _fileNameFor(id: string): Result<string> {\n if (id === '.' || id === '..' || !SAFE_ID.test(id)) {\n return fail(`invalid storage id '${id}': must match ${SAFE_ID.source}`);\n }\n return succeed(`${id}${FILE_SUFFIX}`);\n }\n\n /**\n * Validates the synchronous preconditions for a store: the id is filename-safe,\n * the key is actually a private key, and its algorithm is one we support.\n * Returns the resolved filename and algorithm so the async pipeline can run\n * without re-deriving them.\n */\n private _validateKeyToStore(\n id: string,\n key: CryptoKey\n ): Result<{ fileName: string; algorithm: KeyPairAlgorithm }> {\n return this._fileNameFor(id).onSuccess((fileName) => {\n if (key.type !== 'private') {\n return fail(`failed to store private key '${id}': expected a private key, got '${key.type}'`);\n }\n return this._algorithmOf(key)\n .withErrorFormat((msg) => `failed to store private key '${id}': ${msg}`)\n .onSuccess((algorithm) => succeed({ fileName, algorithm }));\n });\n }\n\n /**\n * Exports `key` to JWK, wraps it in the stored envelope, encrypts it with\n * AES-256-GCM, and writes the resulting file as serialized JSON to `fileName`.\n * Returns the stored `id` on success.\n */\n private async _encryptAndWrite(\n algorithm: KeyPairAlgorithm,\n key: CryptoKey,\n id: string,\n fileName: string\n ): Promise<Result<string>> {\n return captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('jwk', key))\n .withErrorFormat((msg) => `failed to export private key '${id}' to JWK: ${msg}`)\n .onSuccess<JsonObject>((jwk) => succeed({ algorithm, jwk: JSON.stringify(jwk) }))\n .thenOnSuccess(async (envelope) =>\n (\n await createEncryptedFile({\n content: envelope,\n secretName: id,\n key: this._encryptionKey,\n cryptoProvider: this._cryptoProvider\n })\n ).withErrorFormat((msg) => `failed to encrypt private key '${id}': ${msg}`)\n )\n .onSuccess((encrypted) => this._writeFile(fileName, JSON.stringify(encrypted)))\n .onSuccess(() => succeed(id));\n }\n\n private _algorithmOf(key: CryptoKey): Result<KeyPairAlgorithm> {\n const alg = key.algorithm;\n switch (alg.name) {\n case 'ECDSA':\n case 'ECDH': {\n const curve = (alg as EcKeyAlgorithm).namedCurve;\n if (curve !== 'P-256') {\n return fail(`unsupported ${alg.name} curve '${curve}' (only P-256 is supported)`);\n }\n return succeed(alg.name === 'ECDSA' ? 'ecdsa-p256' : 'ecdh-p256');\n }\n case 'RSA-OAEP': {\n // Only the hash affects the JWK re-import params, so it is the field\n // that must match; the modulus length is recovered from the key data.\n const hash = (alg as RsaHashedKeyAlgorithm).hash.name;\n if (hash !== 'SHA-256') {\n return fail(`unsupported RSA-OAEP hash '${hash}' (only SHA-256 is supported)`);\n }\n return succeed('rsa-oaep-2048');\n }\n case 'Ed25519':\n return succeed('ed25519');\n case 'X25519':\n return succeed('x25519');\n default:\n return fail(`unsupported key algorithm '${alg.name}'`);\n }\n }\n\n private _findFile(fileName: string): Result<FileTree.IFileTreeFileItem | undefined> {\n return this._directory.getChildren().onSuccess((children) => {\n const found = children.find((child) => child.type === 'file' && child.name === fileName);\n return succeed(found as FileTree.IFileTreeFileItem | undefined);\n });\n }\n\n private _writeFile(fileName: string, text: string): Result<string> {\n return this._findFile(fileName).onSuccess((existing) => {\n if (existing !== undefined) {\n /* c8 ignore next 3 - defensive: file items from read-only adapters lack mutation methods */\n if (!FileTree.isMutableFileItem(existing)) {\n return fail(`${existing.absolutePath}: not mutable`);\n }\n return existing.setRawContents(text);\n }\n /* c8 ignore next 3 - defensive: directory items from read-only adapters lack mutation methods */\n if (!FileTree.isMutableDirectoryItem(this._directory)) {\n return fail(`${this._directory.absolutePath}: not mutable`);\n }\n return this._directory.createChildFile(fileName, text).onSuccess(() => succeed(text));\n });\n }\n\n /**\n * Reads `file`, decrypts the AES-256-GCM envelope, and validates it into the\n * typed `IStoredPrivateKeyEnvelope`. Read, decrypt, and shape failures\n * all surface as a decrypt failure for `id`.\n */\n private async _decryptEnvelope(\n file: FileTree.IFileTreeFileItem,\n id: string\n ): Promise<Result<IStoredPrivateKeyEnvelope>> {\n return file\n .getContents()\n .thenOnSuccess((json) => tryDecryptFile(json, this._encryptionKey, this._cryptoProvider))\n .onSuccess((decrypted) => envelopeConverter.convert(decrypted))\n .withErrorFormat((msg) => `failed to decrypt private key '${id}': ${msg}`);\n }\n\n /**\n * Parses and shape-validates the stored JWK, then re-imports it as a private\n * `CryptoKey` for the envelope's algorithm. The WebCrypto JWK-import algorithm\n * descriptor is shared between public and private keys for every supported\n * algorithm, so `IKeyPairAlgorithmParams.importPublicKey` is reused here;\n * the public/private distinction is carried by the requested `usages`.\n */\n private async _importPrivateKey(\n envelope: IStoredPrivateKeyEnvelope,\n id: string\n ): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[envelope.algorithm];\n return captureResult(() => JSON.parse(envelope.jwk) as unknown)\n .onSuccess((parsed) => jsonWebKeyShape.validate(parsed))\n .withErrorFormat((msg) => `malformed JWK: ${msg}`)\n .thenOnSuccess((jwk) =>\n captureAsyncResult(() =>\n crypto.webcrypto.subtle.importKey(\n 'jwk',\n jwk,\n params.importPublicKey,\n true,\n this._importUsagesFor(jwk, params)\n )\n )\n )\n .withErrorFormat((msg) => `failed to import private key '${id}': ${msg}`);\n }\n\n /**\n * Computes the key usages to request when re-importing a stored private key.\n * WebCrypto rejects `importKey` if the requested usages include operations\n * absent from the JWK's `key_ops`, so a key originally created with a narrower\n * usage set than the algorithm default (e.g. an ECDH key with only\n * `deriveBits`) would fail to load against the algorithm-wide defaults.\n * Intersect the algorithm's private usages with the JWK's recorded `key_ops`\n * so we request exactly the operations the stored key actually supports;\n * fall back to the algorithm's private usages when `key_ops` is absent.\n */\n private _importUsagesFor(jwk: JsonWebKey, params: IKeyPairAlgorithmParams): KeyUsage[] {\n const privateUsages = params.keyPairUsages.filter((usage) => !PUBLIC_ONLY_USAGES.includes(usage));\n const keyOps = jwk.key_ops;\n if (keyOps === undefined) {\n return [...privateUsages];\n }\n return privateUsages.filter((usage) => keyOps.includes(usage));\n }\n}\n"]}