@depup/mongodb 7.1.0-depup.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 (396) hide show
  1. package/LICENSE.md +201 -0
  2. package/README.md +33 -0
  3. package/etc/prepare.js +12 -0
  4. package/lib/admin.js +136 -0
  5. package/lib/admin.js.map +1 -0
  6. package/lib/bson.js +85 -0
  7. package/lib/bson.js.map +1 -0
  8. package/lib/bulk/common.js +835 -0
  9. package/lib/bulk/common.js.map +1 -0
  10. package/lib/bulk/ordered.js +67 -0
  11. package/lib/bulk/ordered.js.map +1 -0
  12. package/lib/bulk/unordered.js +92 -0
  13. package/lib/bulk/unordered.js.map +1 -0
  14. package/lib/change_stream.js +513 -0
  15. package/lib/change_stream.js.map +1 -0
  16. package/lib/client-side-encryption/auto_encrypter.js +272 -0
  17. package/lib/client-side-encryption/auto_encrypter.js.map +1 -0
  18. package/lib/client-side-encryption/client_encryption.js +609 -0
  19. package/lib/client-side-encryption/client_encryption.js.map +1 -0
  20. package/lib/client-side-encryption/errors.js +138 -0
  21. package/lib/client-side-encryption/errors.js.map +1 -0
  22. package/lib/client-side-encryption/mongocryptd_manager.js +85 -0
  23. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -0
  24. package/lib/client-side-encryption/providers/aws.js +23 -0
  25. package/lib/client-side-encryption/providers/aws.js.map +1 -0
  26. package/lib/client-side-encryption/providers/azure.js +132 -0
  27. package/lib/client-side-encryption/providers/azure.js.map +1 -0
  28. package/lib/client-side-encryption/providers/gcp.js +16 -0
  29. package/lib/client-side-encryption/providers/gcp.js.map +1 -0
  30. package/lib/client-side-encryption/providers/index.js +43 -0
  31. package/lib/client-side-encryption/providers/index.js.map +1 -0
  32. package/lib/client-side-encryption/state_machine.js +427 -0
  33. package/lib/client-side-encryption/state_machine.js.map +1 -0
  34. package/lib/cmap/auth/auth_provider.js +51 -0
  35. package/lib/cmap/auth/auth_provider.js.map +1 -0
  36. package/lib/cmap/auth/aws4.js +161 -0
  37. package/lib/cmap/auth/aws4.js.map +1 -0
  38. package/lib/cmap/auth/aws_temporary_credentials.js +103 -0
  39. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -0
  40. package/lib/cmap/auth/gssapi.js +155 -0
  41. package/lib/cmap/auth/gssapi.js.map +1 -0
  42. package/lib/cmap/auth/mongo_credentials.js +169 -0
  43. package/lib/cmap/auth/mongo_credentials.js.map +1 -0
  44. package/lib/cmap/auth/mongodb_aws.js +128 -0
  45. package/lib/cmap/auth/mongodb_aws.js.map +1 -0
  46. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js +84 -0
  47. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -0
  48. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js +62 -0
  49. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -0
  50. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js +141 -0
  51. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map +1 -0
  52. package/lib/cmap/auth/mongodb_oidc/command_builders.js +44 -0
  53. package/lib/cmap/auth/mongodb_oidc/command_builders.js.map +1 -0
  54. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js +39 -0
  55. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -0
  56. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js +122 -0
  57. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js.map +1 -0
  58. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js +32 -0
  59. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js.map +1 -0
  60. package/lib/cmap/auth/mongodb_oidc/token_cache.js +52 -0
  61. package/lib/cmap/auth/mongodb_oidc/token_cache.js.map +1 -0
  62. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js +23 -0
  63. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -0
  64. package/lib/cmap/auth/mongodb_oidc.js +73 -0
  65. package/lib/cmap/auth/mongodb_oidc.js.map +1 -0
  66. package/lib/cmap/auth/plain.js +26 -0
  67. package/lib/cmap/auth/plain.js.map +1 -0
  68. package/lib/cmap/auth/providers.js +22 -0
  69. package/lib/cmap/auth/providers.js.map +1 -0
  70. package/lib/cmap/auth/scram.js +254 -0
  71. package/lib/cmap/auth/scram.js.map +1 -0
  72. package/lib/cmap/auth/x509.js +36 -0
  73. package/lib/cmap/auth/x509.js.map +1 -0
  74. package/lib/cmap/command_monitoring_events.js +223 -0
  75. package/lib/cmap/command_monitoring_events.js.map +1 -0
  76. package/lib/cmap/commands.js +535 -0
  77. package/lib/cmap/commands.js.map +1 -0
  78. package/lib/cmap/connect.js +381 -0
  79. package/lib/cmap/connect.js.map +1 -0
  80. package/lib/cmap/connection.js +571 -0
  81. package/lib/cmap/connection.js.map +1 -0
  82. package/lib/cmap/connection_pool.js +558 -0
  83. package/lib/cmap/connection_pool.js.map +1 -0
  84. package/lib/cmap/connection_pool_events.js +190 -0
  85. package/lib/cmap/connection_pool_events.js.map +1 -0
  86. package/lib/cmap/errors.js +108 -0
  87. package/lib/cmap/errors.js.map +1 -0
  88. package/lib/cmap/handshake/client_metadata.js +242 -0
  89. package/lib/cmap/handshake/client_metadata.js.map +1 -0
  90. package/lib/cmap/metrics.js +62 -0
  91. package/lib/cmap/metrics.js.map +1 -0
  92. package/lib/cmap/stream_description.js +70 -0
  93. package/lib/cmap/stream_description.js.map +1 -0
  94. package/lib/cmap/wire_protocol/compression.js +178 -0
  95. package/lib/cmap/wire_protocol/compression.js.map +1 -0
  96. package/lib/cmap/wire_protocol/constants.js +21 -0
  97. package/lib/cmap/wire_protocol/constants.js.map +1 -0
  98. package/lib/cmap/wire_protocol/on_data.js +111 -0
  99. package/lib/cmap/wire_protocol/on_data.js.map +1 -0
  100. package/lib/cmap/wire_protocol/on_demand/document.js +222 -0
  101. package/lib/cmap/wire_protocol/on_demand/document.js.map +1 -0
  102. package/lib/cmap/wire_protocol/responses.js +315 -0
  103. package/lib/cmap/wire_protocol/responses.js.map +1 -0
  104. package/lib/cmap/wire_protocol/shared.js +35 -0
  105. package/lib/cmap/wire_protocol/shared.js.map +1 -0
  106. package/lib/collection.js +751 -0
  107. package/lib/collection.js.map +1 -0
  108. package/lib/connection_string.js +1090 -0
  109. package/lib/connection_string.js.map +1 -0
  110. package/lib/constants.js +170 -0
  111. package/lib/constants.js.map +1 -0
  112. package/lib/cursor/abstract_cursor.js +924 -0
  113. package/lib/cursor/abstract_cursor.js.map +1 -0
  114. package/lib/cursor/aggregation_cursor.js +164 -0
  115. package/lib/cursor/aggregation_cursor.js.map +1 -0
  116. package/lib/cursor/change_stream_cursor.js +104 -0
  117. package/lib/cursor/change_stream_cursor.js.map +1 -0
  118. package/lib/cursor/client_bulk_write_cursor.js +52 -0
  119. package/lib/cursor/client_bulk_write_cursor.js.map +1 -0
  120. package/lib/cursor/explainable_cursor.js +36 -0
  121. package/lib/cursor/explainable_cursor.js.map +1 -0
  122. package/lib/cursor/find_cursor.js +399 -0
  123. package/lib/cursor/find_cursor.js.map +1 -0
  124. package/lib/cursor/list_collections_cursor.js +34 -0
  125. package/lib/cursor/list_collections_cursor.js.map +1 -0
  126. package/lib/cursor/list_indexes_cursor.js +32 -0
  127. package/lib/cursor/list_indexes_cursor.js.map +1 -0
  128. package/lib/cursor/list_search_indexes_cursor.js +14 -0
  129. package/lib/cursor/list_search_indexes_cursor.js.map +1 -0
  130. package/lib/cursor/run_command_cursor.js +94 -0
  131. package/lib/cursor/run_command_cursor.js.map +1 -0
  132. package/lib/db.js +419 -0
  133. package/lib/db.js.map +1 -0
  134. package/lib/deps.js +112 -0
  135. package/lib/deps.js.map +1 -0
  136. package/lib/encrypter.js +106 -0
  137. package/lib/encrypter.js.map +1 -0
  138. package/lib/error.js +1380 -0
  139. package/lib/error.js.map +1 -0
  140. package/lib/explain.js +59 -0
  141. package/lib/explain.js.map +1 -0
  142. package/lib/gridfs/download.js +305 -0
  143. package/lib/gridfs/download.js.map +1 -0
  144. package/lib/gridfs/index.js +164 -0
  145. package/lib/gridfs/index.js.map +1 -0
  146. package/lib/gridfs/upload.js +358 -0
  147. package/lib/gridfs/upload.js.map +1 -0
  148. package/lib/index.js +193 -0
  149. package/lib/index.js.map +1 -0
  150. package/lib/mongo_client.js +557 -0
  151. package/lib/mongo_client.js.map +1 -0
  152. package/lib/mongo_client_auth_providers.js +80 -0
  153. package/lib/mongo_client_auth_providers.js.map +1 -0
  154. package/lib/mongo_logger.js +655 -0
  155. package/lib/mongo_logger.js.map +1 -0
  156. package/lib/mongo_types.js +56 -0
  157. package/lib/mongo_types.js.map +1 -0
  158. package/lib/operations/aggregate.js +90 -0
  159. package/lib/operations/aggregate.js.map +1 -0
  160. package/lib/operations/client_bulk_write/client_bulk_write.js +51 -0
  161. package/lib/operations/client_bulk_write/client_bulk_write.js.map +1 -0
  162. package/lib/operations/client_bulk_write/command_builder.js +340 -0
  163. package/lib/operations/client_bulk_write/command_builder.js.map +1 -0
  164. package/lib/operations/client_bulk_write/common.js +3 -0
  165. package/lib/operations/client_bulk_write/common.js.map +1 -0
  166. package/lib/operations/client_bulk_write/executor.js +120 -0
  167. package/lib/operations/client_bulk_write/executor.js.map +1 -0
  168. package/lib/operations/client_bulk_write/results_merger.js +204 -0
  169. package/lib/operations/client_bulk_write/results_merger.js.map +1 -0
  170. package/lib/operations/command.js +83 -0
  171. package/lib/operations/command.js.map +1 -0
  172. package/lib/operations/count.js +45 -0
  173. package/lib/operations/count.js.map +1 -0
  174. package/lib/operations/create_collection.js +109 -0
  175. package/lib/operations/create_collection.js.map +1 -0
  176. package/lib/operations/delete.js +125 -0
  177. package/lib/operations/delete.js.map +1 -0
  178. package/lib/operations/distinct.js +61 -0
  179. package/lib/operations/distinct.js.map +1 -0
  180. package/lib/operations/drop.js +93 -0
  181. package/lib/operations/drop.js.map +1 -0
  182. package/lib/operations/end_sessions.js +34 -0
  183. package/lib/operations/end_sessions.js.map +1 -0
  184. package/lib/operations/estimated_document_count.js +41 -0
  185. package/lib/operations/estimated_document_count.js.map +1 -0
  186. package/lib/operations/execute_operation.js +239 -0
  187. package/lib/operations/execute_operation.js.map +1 -0
  188. package/lib/operations/find.js +148 -0
  189. package/lib/operations/find.js.map +1 -0
  190. package/lib/operations/find_and_modify.js +158 -0
  191. package/lib/operations/find_and_modify.js.map +1 -0
  192. package/lib/operations/get_more.js +62 -0
  193. package/lib/operations/get_more.js.map +1 -0
  194. package/lib/operations/indexes.js +186 -0
  195. package/lib/operations/indexes.js.map +1 -0
  196. package/lib/operations/insert.js +70 -0
  197. package/lib/operations/insert.js.map +1 -0
  198. package/lib/operations/kill_cursors.js +43 -0
  199. package/lib/operations/kill_cursors.js.map +1 -0
  200. package/lib/operations/list_collections.js +53 -0
  201. package/lib/operations/list_collections.js.map +1 -0
  202. package/lib/operations/list_databases.js +40 -0
  203. package/lib/operations/list_databases.js.map +1 -0
  204. package/lib/operations/operation.js +102 -0
  205. package/lib/operations/operation.js.map +1 -0
  206. package/lib/operations/profiling_level.js +43 -0
  207. package/lib/operations/profiling_level.js.map +1 -0
  208. package/lib/operations/remove_user.js +27 -0
  209. package/lib/operations/remove_user.js.map +1 -0
  210. package/lib/operations/rename.js +38 -0
  211. package/lib/operations/rename.js.map +1 -0
  212. package/lib/operations/run_command.js +47 -0
  213. package/lib/operations/run_command.js.map +1 -0
  214. package/lib/operations/search_indexes/create.js +33 -0
  215. package/lib/operations/search_indexes/create.js.map +1 -0
  216. package/lib/operations/search_indexes/drop.js +43 -0
  217. package/lib/operations/search_indexes/drop.js.map +1 -0
  218. package/lib/operations/search_indexes/update.js +35 -0
  219. package/lib/operations/search_indexes/update.js.map +1 -0
  220. package/lib/operations/set_profiling_level.js +53 -0
  221. package/lib/operations/set_profiling_level.js.map +1 -0
  222. package/lib/operations/stats.js +27 -0
  223. package/lib/operations/stats.js.map +1 -0
  224. package/lib/operations/update.js +188 -0
  225. package/lib/operations/update.js.map +1 -0
  226. package/lib/operations/validate_collection.js +37 -0
  227. package/lib/operations/validate_collection.js.map +1 -0
  228. package/lib/read_concern.js +73 -0
  229. package/lib/read_concern.js.map +1 -0
  230. package/lib/read_preference.js +191 -0
  231. package/lib/read_preference.js.map +1 -0
  232. package/lib/sdam/common.js +49 -0
  233. package/lib/sdam/common.js.map +1 -0
  234. package/lib/sdam/events.js +146 -0
  235. package/lib/sdam/events.js.map +1 -0
  236. package/lib/sdam/monitor.js +544 -0
  237. package/lib/sdam/monitor.js.map +1 -0
  238. package/lib/sdam/server.js +404 -0
  239. package/lib/sdam/server.js.map +1 -0
  240. package/lib/sdam/server_description.js +204 -0
  241. package/lib/sdam/server_description.js.map +1 -0
  242. package/lib/sdam/server_selection.js +294 -0
  243. package/lib/sdam/server_selection.js.map +1 -0
  244. package/lib/sdam/server_selection_events.js +85 -0
  245. package/lib/sdam/server_selection_events.js.map +1 -0
  246. package/lib/sdam/srv_polling.js +108 -0
  247. package/lib/sdam/srv_polling.js.map +1 -0
  248. package/lib/sdam/topology.js +652 -0
  249. package/lib/sdam/topology.js.map +1 -0
  250. package/lib/sdam/topology_description.js +383 -0
  251. package/lib/sdam/topology_description.js.map +1 -0
  252. package/lib/sessions.js +892 -0
  253. package/lib/sessions.js.map +1 -0
  254. package/lib/sort.js +103 -0
  255. package/lib/sort.js.map +1 -0
  256. package/lib/timeout.js +296 -0
  257. package/lib/timeout.js.map +1 -0
  258. package/lib/transactions.js +135 -0
  259. package/lib/transactions.js.map +1 -0
  260. package/lib/utils.js +1163 -0
  261. package/lib/utils.js.map +1 -0
  262. package/lib/write_concern.js +100 -0
  263. package/lib/write_concern.js.map +1 -0
  264. package/mongodb.d.ts +9018 -0
  265. package/package.json +197 -0
  266. package/src/admin.ts +173 -0
  267. package/src/bson.ts +149 -0
  268. package/src/bulk/common.ts +1251 -0
  269. package/src/bulk/ordered.ts +83 -0
  270. package/src/bulk/unordered.ts +115 -0
  271. package/src/change_stream.ts +1160 -0
  272. package/src/client-side-encryption/auto_encrypter.ts +469 -0
  273. package/src/client-side-encryption/client_encryption.ts +1150 -0
  274. package/src/client-side-encryption/errors.ts +144 -0
  275. package/src/client-side-encryption/mongocryptd_manager.ts +100 -0
  276. package/src/client-side-encryption/providers/aws.ts +33 -0
  277. package/src/client-side-encryption/providers/azure.ts +181 -0
  278. package/src/client-side-encryption/providers/gcp.ts +16 -0
  279. package/src/client-side-encryption/providers/index.ts +207 -0
  280. package/src/client-side-encryption/state_machine.ts +651 -0
  281. package/src/cmap/auth/auth_provider.ts +77 -0
  282. package/src/cmap/auth/aws4.ts +207 -0
  283. package/src/cmap/auth/aws_temporary_credentials.ts +129 -0
  284. package/src/cmap/auth/gssapi.ts +203 -0
  285. package/src/cmap/auth/mongo_credentials.ts +292 -0
  286. package/src/cmap/auth/mongodb_aws.ts +179 -0
  287. package/src/cmap/auth/mongodb_oidc/automated_callback_workflow.ts +88 -0
  288. package/src/cmap/auth/mongodb_oidc/azure_machine_workflow.ts +73 -0
  289. package/src/cmap/auth/mongodb_oidc/callback_workflow.ts +188 -0
  290. package/src/cmap/auth/mongodb_oidc/command_builders.ts +53 -0
  291. package/src/cmap/auth/mongodb_oidc/gcp_machine_workflow.ts +46 -0
  292. package/src/cmap/auth/mongodb_oidc/human_callback_workflow.ts +141 -0
  293. package/src/cmap/auth/mongodb_oidc/k8s_machine_workflow.ts +31 -0
  294. package/src/cmap/auth/mongodb_oidc/token_cache.ts +62 -0
  295. package/src/cmap/auth/mongodb_oidc/token_machine_workflow.ts +22 -0
  296. package/src/cmap/auth/mongodb_oidc.ts +185 -0
  297. package/src/cmap/auth/plain.ts +25 -0
  298. package/src/cmap/auth/providers.ts +22 -0
  299. package/src/cmap/auth/scram.ts +344 -0
  300. package/src/cmap/auth/x509.ts +43 -0
  301. package/src/cmap/command_monitoring_events.ts +316 -0
  302. package/src/cmap/commands.ts +788 -0
  303. package/src/cmap/connect.ts +518 -0
  304. package/src/cmap/connection.ts +931 -0
  305. package/src/cmap/connection_pool.ts +831 -0
  306. package/src/cmap/connection_pool_events.ts +300 -0
  307. package/src/cmap/errors.ts +119 -0
  308. package/src/cmap/handshake/client_metadata.ts +353 -0
  309. package/src/cmap/metrics.ts +58 -0
  310. package/src/cmap/stream_description.ts +96 -0
  311. package/src/cmap/wire_protocol/compression.ts +211 -0
  312. package/src/cmap/wire_protocol/constants.ts +17 -0
  313. package/src/cmap/wire_protocol/on_data.ts +139 -0
  314. package/src/cmap/wire_protocol/on_demand/document.ts +358 -0
  315. package/src/cmap/wire_protocol/responses.ts +393 -0
  316. package/src/cmap/wire_protocol/shared.ts +48 -0
  317. package/src/collection.ts +1314 -0
  318. package/src/connection_string.ts +1297 -0
  319. package/src/constants.ts +176 -0
  320. package/src/cursor/abstract_cursor.ts +1247 -0
  321. package/src/cursor/aggregation_cursor.ts +245 -0
  322. package/src/cursor/change_stream_cursor.ts +171 -0
  323. package/src/cursor/client_bulk_write_cursor.ts +83 -0
  324. package/src/cursor/explainable_cursor.ts +51 -0
  325. package/src/cursor/find_cursor.ts +497 -0
  326. package/src/cursor/list_collections_cursor.ts +50 -0
  327. package/src/cursor/list_indexes_cursor.ts +37 -0
  328. package/src/cursor/list_search_indexes_cursor.ts +20 -0
  329. package/src/cursor/run_command_cursor.ts +178 -0
  330. package/src/db.ts +621 -0
  331. package/src/deps.ts +227 -0
  332. package/src/encrypter.ts +127 -0
  333. package/src/error.ts +1567 -0
  334. package/src/explain.ts +124 -0
  335. package/src/gridfs/download.ts +483 -0
  336. package/src/gridfs/index.ts +264 -0
  337. package/src/gridfs/upload.ts +537 -0
  338. package/src/index.ts +633 -0
  339. package/src/mongo_client.ts +1155 -0
  340. package/src/mongo_client_auth_providers.ts +87 -0
  341. package/src/mongo_logger.ts +1081 -0
  342. package/src/mongo_types.ts +678 -0
  343. package/src/operations/aggregate.ts +153 -0
  344. package/src/operations/client_bulk_write/client_bulk_write.ts +72 -0
  345. package/src/operations/client_bulk_write/command_builder.ts +487 -0
  346. package/src/operations/client_bulk_write/common.ts +276 -0
  347. package/src/operations/client_bulk_write/executor.ts +149 -0
  348. package/src/operations/client_bulk_write/results_merger.ts +260 -0
  349. package/src/operations/command.ts +171 -0
  350. package/src/operations/count.ts +74 -0
  351. package/src/operations/create_collection.ts +218 -0
  352. package/src/operations/delete.ts +183 -0
  353. package/src/operations/distinct.ts +92 -0
  354. package/src/operations/drop.ts +130 -0
  355. package/src/operations/end_sessions.ts +44 -0
  356. package/src/operations/estimated_document_count.ts +61 -0
  357. package/src/operations/execute_operation.ts +319 -0
  358. package/src/operations/find.ts +254 -0
  359. package/src/operations/find_and_modify.ts +319 -0
  360. package/src/operations/get_more.ts +108 -0
  361. package/src/operations/indexes.ts +418 -0
  362. package/src/operations/insert.ts +108 -0
  363. package/src/operations/kill_cursors.ts +64 -0
  364. package/src/operations/list_collections.ts +108 -0
  365. package/src/operations/list_databases.ts +68 -0
  366. package/src/operations/operation.ts +181 -0
  367. package/src/operations/profiling_level.ts +46 -0
  368. package/src/operations/remove_user.ts +36 -0
  369. package/src/operations/rename.ts +60 -0
  370. package/src/operations/run_command.ts +79 -0
  371. package/src/operations/search_indexes/create.ts +56 -0
  372. package/src/operations/search_indexes/drop.ts +58 -0
  373. package/src/operations/search_indexes/update.ts +45 -0
  374. package/src/operations/set_profiling_level.ts +74 -0
  375. package/src/operations/stats.ts +37 -0
  376. package/src/operations/update.ts +318 -0
  377. package/src/operations/validate_collection.ts +50 -0
  378. package/src/read_concern.ts +88 -0
  379. package/src/read_preference.ts +256 -0
  380. package/src/sdam/common.ts +74 -0
  381. package/src/sdam/events.ts +219 -0
  382. package/src/sdam/monitor.ts +771 -0
  383. package/src/sdam/server.ts +595 -0
  384. package/src/sdam/server_description.ts +297 -0
  385. package/src/sdam/server_selection.ts +415 -0
  386. package/src/sdam/server_selection_events.ts +142 -0
  387. package/src/sdam/srv_polling.ts +146 -0
  388. package/src/sdam/topology.ts +1100 -0
  389. package/src/sdam/topology_description.ts +548 -0
  390. package/src/sessions.ts +1244 -0
  391. package/src/sort.ts +141 -0
  392. package/src/timeout.ts +405 -0
  393. package/src/transactions.ts +181 -0
  394. package/src/utils.ts +1434 -0
  395. package/src/write_concern.ts +183 -0
  396. package/tsconfig.json +46 -0
@@ -0,0 +1,1150 @@
1
+ import type {
2
+ ExplicitEncryptionContextOptions,
3
+ MongoCrypt,
4
+ MongoCryptOptions
5
+ } from 'mongodb-client-encryption';
6
+
7
+ import {
8
+ type Binary,
9
+ deserialize,
10
+ type Document,
11
+ type Int32,
12
+ type Long,
13
+ serialize,
14
+ type UUID
15
+ } from '../bson';
16
+ import { type AnyBulkWriteOperation, type BulkWriteResult } from '../bulk/common';
17
+ import { type ProxyOptions } from '../cmap/connection';
18
+ import { type Collection } from '../collection';
19
+ import { type FindCursor } from '../cursor/find_cursor';
20
+ import { type Db } from '../db';
21
+ import { getMongoDBClientEncryption } from '../deps';
22
+ import { type MongoClient, type MongoClientOptions } from '../mongo_client';
23
+ import { type Filter, type WithId } from '../mongo_types';
24
+ import { type CreateCollectionOptions } from '../operations/create_collection';
25
+ import { type DeleteResult } from '../operations/delete';
26
+ import { type CSOTTimeoutContext, TimeoutContext } from '../timeout';
27
+ import { MongoDBCollectionNamespace, resolveTimeoutOptions } from '../utils';
28
+ import {
29
+ defaultErrorWrapper,
30
+ MongoCryptCreateDataKeyError,
31
+ MongoCryptCreateEncryptedCollectionError,
32
+ MongoCryptInvalidArgumentError
33
+ } from './errors';
34
+ import {
35
+ type ClientEncryptionDataKeyProvider,
36
+ type CredentialProviders,
37
+ isEmptyCredentials,
38
+ type KMSProviders,
39
+ refreshKMSCredentials
40
+ } from './providers/index';
41
+ import {
42
+ type ClientEncryptionSocketOptions,
43
+ type CSFLEKMSTlsOptions,
44
+ StateMachine
45
+ } from './state_machine';
46
+
47
+ /**
48
+ * @public
49
+ * The schema for a DataKey in the key vault collection.
50
+ */
51
+ export interface DataKey {
52
+ _id: UUID;
53
+ version?: number;
54
+ keyAltNames?: string[];
55
+ keyMaterial: Binary;
56
+ creationDate: Date;
57
+ updateDate: Date;
58
+ status: number;
59
+ masterKey: Document;
60
+ }
61
+
62
+ /**
63
+ * @public
64
+ * The public interface for explicit in-use encryption
65
+ */
66
+ export class ClientEncryption {
67
+ /** @internal */
68
+ _client: MongoClient;
69
+ /** @internal */
70
+ _keyVaultNamespace: string;
71
+ /** @internal */
72
+ _keyVaultClient: MongoClient;
73
+ /** @internal */
74
+ _proxyOptions: ProxyOptions;
75
+ /** @internal */
76
+ _tlsOptions: CSFLEKMSTlsOptions;
77
+ /** @internal */
78
+ _kmsProviders: KMSProviders;
79
+ /** @internal */
80
+ _timeoutMS?: number;
81
+
82
+ /** @internal */
83
+ _mongoCrypt: MongoCrypt;
84
+
85
+ /** @internal */
86
+ _credentialProviders?: CredentialProviders;
87
+
88
+ /** @internal */
89
+ static getMongoCrypt(): typeof MongoCrypt {
90
+ const encryption = getMongoDBClientEncryption();
91
+ if ('kModuleError' in encryption) {
92
+ throw encryption.kModuleError;
93
+ }
94
+ return encryption.MongoCrypt;
95
+ }
96
+
97
+ /**
98
+ * Create a new encryption instance
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * new ClientEncryption(mongoClient, {
103
+ * keyVaultNamespace: 'client.encryption',
104
+ * kmsProviders: {
105
+ * local: {
106
+ * key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
107
+ * }
108
+ * }
109
+ * });
110
+ * ```
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * new ClientEncryption(mongoClient, {
115
+ * keyVaultNamespace: 'client.encryption',
116
+ * kmsProviders: {
117
+ * aws: {
118
+ * accessKeyId: AWS_ACCESS_KEY,
119
+ * secretAccessKey: AWS_SECRET_KEY
120
+ * }
121
+ * }
122
+ * });
123
+ * ```
124
+ */
125
+ constructor(client: MongoClient, options: ClientEncryptionOptions) {
126
+ this._client = client;
127
+ this._proxyOptions = options.proxyOptions ?? {};
128
+ this._tlsOptions = options.tlsOptions ?? {};
129
+ this._kmsProviders = options.kmsProviders || {};
130
+ const { timeoutMS } = resolveTimeoutOptions(client, options);
131
+ this._timeoutMS = timeoutMS;
132
+ this._credentialProviders = options.credentialProviders;
133
+
134
+ if (options.credentialProviders?.aws && !isEmptyCredentials('aws', this._kmsProviders)) {
135
+ throw new MongoCryptInvalidArgumentError(
136
+ 'Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching'
137
+ );
138
+ }
139
+
140
+ if (options.keyVaultNamespace == null) {
141
+ throw new MongoCryptInvalidArgumentError('Missing required option `keyVaultNamespace`');
142
+ }
143
+
144
+ const mongoCryptOptions: MongoCryptOptions = {
145
+ ...options,
146
+ kmsProviders: !Buffer.isBuffer(this._kmsProviders)
147
+ ? (serialize(this._kmsProviders) as Buffer)
148
+ : this._kmsProviders,
149
+ errorWrapper: defaultErrorWrapper
150
+ };
151
+
152
+ this._keyVaultNamespace = options.keyVaultNamespace;
153
+ this._keyVaultClient = options.keyVaultClient || client;
154
+ const MongoCrypt = ClientEncryption.getMongoCrypt();
155
+ this._mongoCrypt = new MongoCrypt(mongoCryptOptions);
156
+ }
157
+
158
+ /**
159
+ * Creates a data key used for explicit encryption and inserts it into the key vault namespace
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * // Using async/await to create a local key
164
+ * const dataKeyId = await clientEncryption.createDataKey('local');
165
+ * ```
166
+ *
167
+ * @example
168
+ * ```ts
169
+ * // Using async/await to create an aws key
170
+ * const dataKeyId = await clientEncryption.createDataKey('aws', {
171
+ * masterKey: {
172
+ * region: 'us-east-1',
173
+ * key: 'xxxxxxxxxxxxxx' // CMK ARN here
174
+ * }
175
+ * });
176
+ * ```
177
+ *
178
+ * @example
179
+ * ```ts
180
+ * // Using async/await to create an aws key with a keyAltName
181
+ * const dataKeyId = await clientEncryption.createDataKey('aws', {
182
+ * masterKey: {
183
+ * region: 'us-east-1',
184
+ * key: 'xxxxxxxxxxxxxx' // CMK ARN here
185
+ * },
186
+ * keyAltNames: [ 'mySpecialKey' ]
187
+ * });
188
+ * ```
189
+ */
190
+ async createDataKey(
191
+ provider: ClientEncryptionDataKeyProvider,
192
+ options: ClientEncryptionCreateDataKeyProviderOptions = {}
193
+ ): Promise<UUID> {
194
+ if (options.keyAltNames && !Array.isArray(options.keyAltNames)) {
195
+ throw new MongoCryptInvalidArgumentError(
196
+ `Option "keyAltNames" must be an array of strings, but was of type ${typeof options.keyAltNames}.`
197
+ );
198
+ }
199
+
200
+ let keyAltNames = undefined;
201
+ if (options.keyAltNames && options.keyAltNames.length > 0) {
202
+ keyAltNames = options.keyAltNames.map((keyAltName, i) => {
203
+ if (typeof keyAltName !== 'string') {
204
+ throw new MongoCryptInvalidArgumentError(
205
+ `Option "keyAltNames" must be an array of strings, but item at index ${i} was of type ${typeof keyAltName}`
206
+ );
207
+ }
208
+
209
+ return serialize({ keyAltName });
210
+ });
211
+ }
212
+
213
+ let keyMaterial = undefined;
214
+ if (options.keyMaterial) {
215
+ keyMaterial = serialize({ keyMaterial: options.keyMaterial });
216
+ }
217
+
218
+ const dataKeyBson = serialize({
219
+ provider,
220
+ ...options.masterKey
221
+ });
222
+
223
+ const context = this._mongoCrypt.makeDataKeyContext(dataKeyBson, {
224
+ keyAltNames,
225
+ keyMaterial
226
+ });
227
+
228
+ const stateMachine = new StateMachine({
229
+ proxyOptions: this._proxyOptions,
230
+ tlsOptions: this._tlsOptions,
231
+ socketOptions: autoSelectSocketOptions(this._client.s.options)
232
+ });
233
+
234
+ const timeoutContext =
235
+ options?.timeoutContext ??
236
+ TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }));
237
+
238
+ const dataKey = deserialize(
239
+ await stateMachine.execute(this, context, { timeoutContext })
240
+ ) as DataKey;
241
+
242
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
243
+ this._keyVaultNamespace
244
+ );
245
+
246
+ const { insertedId } = await this._keyVaultClient
247
+ .db(dbName)
248
+ .collection<DataKey>(collectionName)
249
+ .insertOne(dataKey, {
250
+ writeConcern: { w: 'majority' },
251
+ timeoutMS: timeoutContext?.csotEnabled()
252
+ ? timeoutContext?.getRemainingTimeMSOrThrow()
253
+ : undefined
254
+ });
255
+
256
+ return insertedId;
257
+ }
258
+
259
+ /**
260
+ * Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options.
261
+ *
262
+ * If no matches are found, then no bulk write is performed.
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * // rewrapping all data data keys (using a filter that matches all documents)
267
+ * const filter = {};
268
+ *
269
+ * const result = await clientEncryption.rewrapManyDataKey(filter);
270
+ * if (result.bulkWriteResult != null) {
271
+ * // keys were re-wrapped, results will be available in the bulkWrite object.
272
+ * }
273
+ * ```
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * // attempting to rewrap all data keys with no matches
278
+ * const filter = { _id: new Binary() } // assume _id matches no documents in the database
279
+ * const result = await clientEncryption.rewrapManyDataKey(filter);
280
+ *
281
+ * if (result.bulkWriteResult == null) {
282
+ * // no keys matched, `bulkWriteResult` does not exist on the result object
283
+ * }
284
+ * ```
285
+ */
286
+ async rewrapManyDataKey(
287
+ filter: Filter<DataKey>,
288
+ options?: ClientEncryptionRewrapManyDataKeyProviderOptions
289
+ ): Promise<{ bulkWriteResult?: BulkWriteResult }> {
290
+ let keyEncryptionKeyBson = undefined;
291
+ if (options) {
292
+ const keyEncryptionKey = Object.assign({ provider: options.provider }, options.masterKey);
293
+ keyEncryptionKeyBson = serialize(keyEncryptionKey);
294
+ }
295
+ const filterBson = serialize(filter);
296
+ const context = this._mongoCrypt.makeRewrapManyDataKeyContext(filterBson, keyEncryptionKeyBson);
297
+ const stateMachine = new StateMachine({
298
+ proxyOptions: this._proxyOptions,
299
+ tlsOptions: this._tlsOptions,
300
+ socketOptions: autoSelectSocketOptions(this._client.s.options)
301
+ });
302
+
303
+ const timeoutContext = TimeoutContext.create(
304
+ resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS })
305
+ );
306
+
307
+ const { v: dataKeys } = deserialize(
308
+ await stateMachine.execute(this, context, { timeoutContext })
309
+ );
310
+ if (dataKeys.length === 0) {
311
+ return {};
312
+ }
313
+
314
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
315
+ this._keyVaultNamespace
316
+ );
317
+
318
+ const replacements = dataKeys.map(
319
+ (key: DataKey): AnyBulkWriteOperation<DataKey> => ({
320
+ updateOne: {
321
+ filter: { _id: key._id },
322
+ update: {
323
+ $set: {
324
+ masterKey: key.masterKey,
325
+ keyMaterial: key.keyMaterial
326
+ },
327
+ $currentDate: {
328
+ updateDate: true
329
+ }
330
+ }
331
+ }
332
+ })
333
+ );
334
+
335
+ const result = await this._keyVaultClient
336
+ .db(dbName)
337
+ .collection<DataKey>(collectionName)
338
+ .bulkWrite(replacements, {
339
+ writeConcern: { w: 'majority' },
340
+ timeoutMS: timeoutContext.csotEnabled() ? timeoutContext?.remainingTimeMS : undefined
341
+ });
342
+
343
+ return { bulkWriteResult: result };
344
+ }
345
+
346
+ /**
347
+ * Deletes the key with the provided id from the keyvault, if it exists.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * // delete a key by _id
352
+ * const id = new Binary(); // id is a bson binary subtype 4 object
353
+ * const { deletedCount } = await clientEncryption.deleteKey(id);
354
+ *
355
+ * if (deletedCount != null && deletedCount > 0) {
356
+ * // successful deletion
357
+ * }
358
+ * ```
359
+ *
360
+ */
361
+ async deleteKey(_id: Binary): Promise<DeleteResult> {
362
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
363
+ this._keyVaultNamespace
364
+ );
365
+
366
+ return await this._keyVaultClient
367
+ .db(dbName)
368
+ .collection<DataKey>(collectionName)
369
+ .deleteOne({ _id }, { writeConcern: { w: 'majority' }, timeoutMS: this._timeoutMS });
370
+ }
371
+
372
+ /**
373
+ * Finds all the keys currently stored in the keyvault.
374
+ *
375
+ * This method will not throw.
376
+ *
377
+ * @returns a FindCursor over all keys in the keyvault.
378
+ * @example
379
+ * ```ts
380
+ * // fetching all keys
381
+ * const keys = await clientEncryption.getKeys().toArray();
382
+ * ```
383
+ */
384
+ getKeys(): FindCursor<DataKey> {
385
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
386
+ this._keyVaultNamespace
387
+ );
388
+
389
+ return this._keyVaultClient
390
+ .db(dbName)
391
+ .collection<DataKey>(collectionName)
392
+ .find({}, { readConcern: { level: 'majority' }, timeoutMS: this._timeoutMS });
393
+ }
394
+
395
+ /**
396
+ * Finds a key in the keyvault with the specified _id.
397
+ *
398
+ * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
399
+ * match the id. The promise rejects with an error if an error is thrown.
400
+ * @example
401
+ * ```ts
402
+ * // getting a key by id
403
+ * const id = new Binary(); // id is a bson binary subtype 4 object
404
+ * const key = await clientEncryption.getKey(id);
405
+ * if (!key) {
406
+ * // key is null if there was no matching key
407
+ * }
408
+ * ```
409
+ */
410
+ async getKey(_id: Binary): Promise<DataKey | null> {
411
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
412
+ this._keyVaultNamespace
413
+ );
414
+
415
+ return await this._keyVaultClient
416
+ .db(dbName)
417
+ .collection<DataKey>(collectionName)
418
+ .findOne({ _id }, { readConcern: { level: 'majority' }, timeoutMS: this._timeoutMS });
419
+ }
420
+
421
+ /**
422
+ * Finds a key in the keyvault which has the specified keyAltName.
423
+ *
424
+ * @param keyAltName - a keyAltName to search for a key
425
+ * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
426
+ * match the keyAltName. The promise rejects with an error if an error is thrown.
427
+ * @example
428
+ * ```ts
429
+ * // get a key by alt name
430
+ * const keyAltName = 'keyAltName';
431
+ * const key = await clientEncryption.getKeyByAltName(keyAltName);
432
+ * if (!key) {
433
+ * // key is null if there is no matching key
434
+ * }
435
+ * ```
436
+ */
437
+ async getKeyByAltName(keyAltName: string): Promise<WithId<DataKey> | null> {
438
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
439
+ this._keyVaultNamespace
440
+ );
441
+
442
+ return await this._keyVaultClient
443
+ .db(dbName)
444
+ .collection<DataKey>(collectionName)
445
+ .findOne(
446
+ { keyAltNames: keyAltName },
447
+ { readConcern: { level: 'majority' }, timeoutMS: this._timeoutMS }
448
+ );
449
+ }
450
+
451
+ /**
452
+ * Adds a keyAltName to a key identified by the provided _id.
453
+ *
454
+ * This method resolves to/returns the *old* key value (prior to adding the new altKeyName).
455
+ *
456
+ * @param _id - The id of the document to update.
457
+ * @param keyAltName - a keyAltName to search for a key
458
+ * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
459
+ * match the id. The promise rejects with an error if an error is thrown.
460
+ * @example
461
+ * ```ts
462
+ * // adding an keyAltName to a data key
463
+ * const id = new Binary(); // id is a bson binary subtype 4 object
464
+ * const keyAltName = 'keyAltName';
465
+ * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName);
466
+ * if (!oldKey) {
467
+ * // null is returned if there is no matching document with an id matching the supplied id
468
+ * }
469
+ * ```
470
+ */
471
+ async addKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null> {
472
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
473
+ this._keyVaultNamespace
474
+ );
475
+
476
+ const value = await this._keyVaultClient
477
+ .db(dbName)
478
+ .collection<DataKey>(collectionName)
479
+ .findOneAndUpdate(
480
+ { _id },
481
+ { $addToSet: { keyAltNames: keyAltName } },
482
+ { writeConcern: { w: 'majority' }, returnDocument: 'before', timeoutMS: this._timeoutMS }
483
+ );
484
+
485
+ return value;
486
+ }
487
+
488
+ /**
489
+ * Adds a keyAltName to a key identified by the provided _id.
490
+ *
491
+ * This method resolves to/returns the *old* key value (prior to removing the new altKeyName).
492
+ *
493
+ * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document.
494
+ *
495
+ * @param _id - The id of the document to update.
496
+ * @param keyAltName - a keyAltName to search for a key
497
+ * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
498
+ * match the id. The promise rejects with an error if an error is thrown.
499
+ * @example
500
+ * ```ts
501
+ * // removing a key alt name from a data key
502
+ * const id = new Binary(); // id is a bson binary subtype 4 object
503
+ * const keyAltName = 'keyAltName';
504
+ * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName);
505
+ *
506
+ * if (!oldKey) {
507
+ * // null is returned if there is no matching document with an id matching the supplied id
508
+ * }
509
+ * ```
510
+ */
511
+ async removeKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null> {
512
+ const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
513
+ this._keyVaultNamespace
514
+ );
515
+
516
+ const pipeline = [
517
+ {
518
+ $set: {
519
+ keyAltNames: {
520
+ $cond: [
521
+ {
522
+ $eq: ['$keyAltNames', [keyAltName]]
523
+ },
524
+ '$$REMOVE',
525
+ {
526
+ $filter: {
527
+ input: '$keyAltNames',
528
+ cond: {
529
+ $ne: ['$$this', keyAltName]
530
+ }
531
+ }
532
+ }
533
+ ]
534
+ }
535
+ }
536
+ }
537
+ ];
538
+
539
+ const value = await this._keyVaultClient
540
+ .db(dbName)
541
+ .collection<DataKey>(collectionName)
542
+ .findOneAndUpdate({ _id }, pipeline, {
543
+ writeConcern: { w: 'majority' },
544
+ returnDocument: 'before',
545
+ timeoutMS: this._timeoutMS
546
+ });
547
+
548
+ return value;
549
+ }
550
+
551
+ /**
552
+ * A convenience method for creating an encrypted collection.
553
+ * This method will create data keys for any encryptedFields that do not have a `keyId` defined
554
+ * and then create a new collection with the full set of encryptedFields.
555
+ *
556
+ * @param db - A Node.js driver Db object with which to create the collection
557
+ * @param name - The name of the collection to be created
558
+ * @param options - Options for createDataKey and for createCollection
559
+ * @returns created collection and generated encryptedFields
560
+ * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created.
561
+ * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created.
562
+ */
563
+ async createEncryptedCollection<TSchema extends Document = Document>(
564
+ db: Db,
565
+ name: string,
566
+ options: {
567
+ provider: ClientEncryptionDataKeyProvider;
568
+ createCollectionOptions: Omit<CreateCollectionOptions, 'encryptedFields'> & {
569
+ encryptedFields: Document;
570
+ };
571
+ masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions;
572
+ }
573
+ ): Promise<{ collection: Collection<TSchema>; encryptedFields: Document }> {
574
+ const {
575
+ provider,
576
+ masterKey,
577
+ createCollectionOptions: {
578
+ encryptedFields: { ...encryptedFields },
579
+ ...createCollectionOptions
580
+ }
581
+ } = options;
582
+
583
+ const timeoutContext =
584
+ this._timeoutMS != null
585
+ ? TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }))
586
+ : undefined;
587
+
588
+ if (Array.isArray(encryptedFields.fields)) {
589
+ const createDataKeyPromises = encryptedFields.fields.map(async field =>
590
+ field == null || typeof field !== 'object' || field.keyId != null
591
+ ? field
592
+ : {
593
+ ...field,
594
+ keyId: await this.createDataKey(provider, {
595
+ masterKey,
596
+ // clone the timeoutContext
597
+ // in order to avoid sharing the same timeout for server selection and connection checkout across different concurrent operations
598
+ timeoutContext: timeoutContext?.csotEnabled() ? timeoutContext?.clone() : undefined
599
+ })
600
+ }
601
+ );
602
+ const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises);
603
+
604
+ encryptedFields.fields = createDataKeyResolutions.map((resolution, index) =>
605
+ resolution.status === 'fulfilled' ? resolution.value : encryptedFields.fields[index]
606
+ );
607
+
608
+ const rejection = createDataKeyResolutions.find(
609
+ (result): result is PromiseRejectedResult => result.status === 'rejected'
610
+ );
611
+ if (rejection != null) {
612
+ throw new MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason });
613
+ }
614
+ }
615
+
616
+ try {
617
+ const collection = await db.createCollection<TSchema>(name, {
618
+ ...createCollectionOptions,
619
+ encryptedFields,
620
+ timeoutMS: timeoutContext?.csotEnabled()
621
+ ? timeoutContext?.getRemainingTimeMSOrThrow()
622
+ : undefined
623
+ });
624
+ return { collection, encryptedFields };
625
+ } catch (cause) {
626
+ throw new MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause });
627
+ }
628
+ }
629
+
630
+ /**
631
+ * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
632
+ * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
633
+ *
634
+ * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON
635
+ * @param options -
636
+ * @returns a Promise that either resolves with the encrypted value, or rejects with an error.
637
+ *
638
+ * @example
639
+ * ```ts
640
+ * // Encryption with async/await api
641
+ * async function encryptMyData(value) {
642
+ * const keyId = await clientEncryption.createDataKey('local');
643
+ * return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
644
+ * }
645
+ * ```
646
+ *
647
+ * @example
648
+ * ```ts
649
+ * // Encryption using a keyAltName
650
+ * async function encryptMyData(value) {
651
+ * await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
652
+ * return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
653
+ * }
654
+ * ```
655
+ */
656
+ async encrypt(value: unknown, options: ClientEncryptionEncryptOptions): Promise<Binary> {
657
+ return await this._encrypt(value, false, options);
658
+ }
659
+
660
+ /**
661
+ * Encrypts a Match Expression or Aggregate Expression to query a range index.
662
+ *
663
+ * Only supported when queryType is "range" and algorithm is "Range".
664
+ *
665
+ * @param expression - a BSON document of one of the following forms:
666
+ * 1. A Match Expression of this form:
667
+ * `{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}`
668
+ * 2. An Aggregate Expression of this form:
669
+ * `{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}`
670
+ *
671
+ * `$gt` may also be `$gte`. `$lt` may also be `$lte`.
672
+ *
673
+ * @param options -
674
+ * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error.
675
+ */
676
+ async encryptExpression(
677
+ expression: Document,
678
+ options: ClientEncryptionEncryptOptions
679
+ ): Promise<Binary> {
680
+ return await this._encrypt(expression, true, options);
681
+ }
682
+
683
+ /**
684
+ * Explicitly decrypt a provided encrypted value
685
+ *
686
+ * @param value - An encrypted value
687
+ * @returns a Promise that either resolves with the decrypted value, or rejects with an error
688
+ *
689
+ * @example
690
+ * ```ts
691
+ * // Decrypting value with async/await API
692
+ * async function decryptMyValue(value) {
693
+ * return clientEncryption.decrypt(value);
694
+ * }
695
+ * ```
696
+ */
697
+ async decrypt<T = any>(value: Binary): Promise<T> {
698
+ const valueBuffer = serialize({ v: value });
699
+ const context = this._mongoCrypt.makeExplicitDecryptionContext(valueBuffer);
700
+
701
+ const stateMachine = new StateMachine({
702
+ proxyOptions: this._proxyOptions,
703
+ tlsOptions: this._tlsOptions,
704
+ socketOptions: autoSelectSocketOptions(this._client.s.options)
705
+ });
706
+
707
+ const timeoutContext =
708
+ this._timeoutMS != null
709
+ ? TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }))
710
+ : undefined;
711
+
712
+ const { v } = deserialize(await stateMachine.execute(this, context, { timeoutContext }));
713
+
714
+ return v;
715
+ }
716
+
717
+ /**
718
+ * @internal
719
+ * Ask the user for KMS credentials.
720
+ *
721
+ * This returns anything that looks like the kmsProviders original input
722
+ * option. It can be empty, and any provider specified here will override
723
+ * the original ones.
724
+ */
725
+ async askForKMSCredentials(): Promise<KMSProviders> {
726
+ return await refreshKMSCredentials(this._kmsProviders, this._credentialProviders);
727
+ }
728
+
729
+ static get libmongocryptVersion() {
730
+ return ClientEncryption.getMongoCrypt().libmongocryptVersion;
731
+ }
732
+
733
+ /**
734
+ * @internal
735
+ * A helper that perform explicit encryption of values and expressions.
736
+ * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
737
+ * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
738
+ *
739
+ * @param value - The value that you wish to encrypt. Must be of a type that can be serialized into BSON
740
+ * @param expressionMode - a boolean that indicates whether or not to encrypt the value as an expression
741
+ * @param options - options to pass to encrypt
742
+ * @returns the raw result of the call to stateMachine.execute(). When expressionMode is set to true, the return
743
+ * value will be a bson document. When false, the value will be a BSON Binary.
744
+ *
745
+ */
746
+ private async _encrypt(
747
+ value: unknown,
748
+ expressionMode: boolean,
749
+ options: ClientEncryptionEncryptOptions
750
+ ): Promise<Binary> {
751
+ const { algorithm, keyId, keyAltName, contentionFactor, queryType, rangeOptions, textOptions } =
752
+ options;
753
+ const contextOptions: ExplicitEncryptionContextOptions = {
754
+ expressionMode,
755
+ algorithm
756
+ };
757
+ if (keyId) {
758
+ contextOptions.keyId = keyId.buffer;
759
+ }
760
+ if (keyAltName) {
761
+ if (keyId) {
762
+ throw new MongoCryptInvalidArgumentError(
763
+ `"options" cannot contain both "keyId" and "keyAltName"`
764
+ );
765
+ }
766
+ if (typeof keyAltName !== 'string') {
767
+ throw new MongoCryptInvalidArgumentError(
768
+ `"options.keyAltName" must be of type string, but was of type ${typeof keyAltName}`
769
+ );
770
+ }
771
+
772
+ contextOptions.keyAltName = serialize({ keyAltName });
773
+ }
774
+ if (typeof contentionFactor === 'number' || typeof contentionFactor === 'bigint') {
775
+ contextOptions.contentionFactor = contentionFactor;
776
+ }
777
+ if (typeof queryType === 'string') {
778
+ contextOptions.queryType = queryType;
779
+ }
780
+
781
+ if (typeof rangeOptions === 'object') {
782
+ contextOptions.rangeOptions = serialize(rangeOptions);
783
+ }
784
+
785
+ if (typeof textOptions === 'object') {
786
+ contextOptions.textOptions = serialize(textOptions);
787
+ }
788
+
789
+ const valueBuffer = serialize({ v: value });
790
+ const stateMachine = new StateMachine({
791
+ proxyOptions: this._proxyOptions,
792
+ tlsOptions: this._tlsOptions,
793
+ socketOptions: autoSelectSocketOptions(this._client.s.options)
794
+ });
795
+ const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions);
796
+
797
+ const timeoutContext =
798
+ this._timeoutMS != null
799
+ ? TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }))
800
+ : undefined;
801
+ const { v } = deserialize(await stateMachine.execute(this, context, { timeoutContext }));
802
+ return v;
803
+ }
804
+ }
805
+
806
+ /**
807
+ * @public
808
+ * Options to provide when encrypting data.
809
+ */
810
+ export interface ClientEncryptionEncryptOptions {
811
+ /**
812
+ * The algorithm to use for encryption.
813
+ */
814
+ algorithm:
815
+ | 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
816
+ | 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
817
+ | 'Indexed'
818
+ | 'Unindexed'
819
+ | 'Range'
820
+ | 'TextPreview';
821
+
822
+ /**
823
+ * The id of the Binary dataKey to use for encryption
824
+ */
825
+ keyId?: Binary;
826
+
827
+ /**
828
+ * A unique string name corresponding to an already existing dataKey.
829
+ */
830
+ keyAltName?: string;
831
+
832
+ /** The contention factor. */
833
+ contentionFactor?: bigint | number;
834
+
835
+ /**
836
+ * The query type.
837
+ */
838
+ queryType?: 'equality' | 'range' | 'prefixPreview' | 'suffixPreview' | 'substringPreview';
839
+
840
+ /** The index options for a Queryable Encryption field supporting "range" queries.*/
841
+ rangeOptions?: RangeOptions;
842
+
843
+ /**
844
+ * Options for a Queryable Encryption field supporting text queries. Only valid when `algorithm` is `TextPreview`.
845
+ *
846
+ * @experimental Public Technical Preview: `textPreview` is an experimental feature and may break at any time.
847
+ */
848
+ textOptions?: TextQueryOptions;
849
+ }
850
+
851
+ /**
852
+ * Options for a Queryable Encryption field supporting text queries.
853
+ *
854
+ * @public
855
+ * @experimental Public Technical Preview: `textPreview` is an experimental feature and may break at any time.
856
+ */
857
+ export interface TextQueryOptions {
858
+ /** Indicates that text indexes for this field are case sensitive */
859
+ caseSensitive: boolean;
860
+ /** Indicates that text indexes for this field are diacritic sensitive. */
861
+ diacriticSensitive: boolean;
862
+
863
+ prefix?: {
864
+ /** The maximum allowed query length. */
865
+ strMaxQueryLength: Int32 | number;
866
+ /** The minimum allowed query length. */
867
+ strMinQueryLength: Int32 | number;
868
+ };
869
+
870
+ suffix?: {
871
+ /** The maximum allowed query length. */
872
+ strMaxQueryLength: Int32 | number;
873
+ /** The minimum allowed query length. */
874
+ strMinQueryLength: Int32 | number;
875
+ };
876
+
877
+ substring?: {
878
+ /** The maximum allowed length to insert. */
879
+ strMaxLength: Int32 | number;
880
+ /** The maximum allowed query length. */
881
+ strMaxQueryLength: Int32 | number;
882
+ /** The minimum allowed query length. */
883
+ strMinQueryLength: Int32 | number;
884
+ };
885
+ }
886
+
887
+ /**
888
+ * @public
889
+ * @experimental
890
+ */
891
+ export interface ClientEncryptionRewrapManyDataKeyProviderOptions {
892
+ provider: ClientEncryptionDataKeyProvider;
893
+ masterKey?:
894
+ | AWSEncryptionKeyOptions
895
+ | AzureEncryptionKeyOptions
896
+ | GCPEncryptionKeyOptions
897
+ | KMIPEncryptionKeyOptions
898
+ | undefined;
899
+ }
900
+
901
+ /**
902
+ * @public
903
+ * Additional settings to provide when creating a new `ClientEncryption` instance.
904
+ */
905
+ export interface ClientEncryptionOptions {
906
+ /**
907
+ * The namespace of the key vault, used to store encryption keys
908
+ */
909
+ keyVaultNamespace: string;
910
+
911
+ /**
912
+ * A MongoClient used to fetch keys from a key vault. Defaults to client.
913
+ */
914
+ keyVaultClient?: MongoClient | undefined;
915
+
916
+ /**
917
+ * Options for specific KMS providers to use
918
+ */
919
+ kmsProviders?: KMSProviders;
920
+
921
+ /**
922
+ * Options for user provided custom credential providers.
923
+ */
924
+ credentialProviders?: CredentialProviders;
925
+
926
+ /**
927
+ * Options for specifying a Socks5 proxy to use for connecting to the KMS.
928
+ */
929
+ proxyOptions?: ProxyOptions;
930
+
931
+ /**
932
+ * TLS options for kms providers to use.
933
+ */
934
+ tlsOptions?: CSFLEKMSTlsOptions;
935
+
936
+ /**
937
+ * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
938
+ */
939
+ keyExpirationMS?: number;
940
+
941
+ /**
942
+ * @experimental
943
+ *
944
+ * The timeout setting to be used for all the operations on ClientEncryption.
945
+ *
946
+ * When provided, `timeoutMS` is used as the timeout for each operation executed on
947
+ * the ClientEncryption object. For example:
948
+ *
949
+ * ```typescript
950
+ * const clientEncryption = new ClientEncryption(client, {
951
+ * timeoutMS: 1_000
952
+ * kmsProviders: { local: { key: '<KEY>' } }
953
+ * });
954
+ *
955
+ * // `1_000` is used as the timeout for createDataKey call
956
+ * await clientEncryption.createDataKey('local');
957
+ * ```
958
+ *
959
+ * If `timeoutMS` is configured on the provided client, the client's `timeoutMS` value
960
+ * will be used unless `timeoutMS` is also provided as a client encryption option.
961
+ *
962
+ * ```typescript
963
+ * const client = new MongoClient('<uri>', { timeoutMS: 2_000 });
964
+ *
965
+ * // timeoutMS is set to 1_000 on clientEncryption
966
+ * const clientEncryption = new ClientEncryption(client, {
967
+ * timeoutMS: 1_000
968
+ * kmsProviders: { local: { key: '<KEY>' } }
969
+ * });
970
+ * ```
971
+ */
972
+ timeoutMS?: number;
973
+ }
974
+
975
+ /**
976
+ * @public
977
+ * Configuration options for making an AWS encryption key
978
+ */
979
+ export interface AWSEncryptionKeyOptions {
980
+ /**
981
+ * The AWS region of the KMS
982
+ */
983
+ region: string;
984
+
985
+ /**
986
+ * The Amazon Resource Name (ARN) to the AWS customer master key (CMK)
987
+ */
988
+ key: string;
989
+
990
+ /**
991
+ * An alternate host to send KMS requests to. May include port number.
992
+ */
993
+ endpoint?: string | undefined;
994
+ }
995
+
996
+ /**
997
+ * @public
998
+ * Configuration options for making an AWS encryption key
999
+ */
1000
+ export interface GCPEncryptionKeyOptions {
1001
+ /**
1002
+ * GCP project ID
1003
+ */
1004
+ projectId: string;
1005
+
1006
+ /**
1007
+ * Location name (e.g. "global")
1008
+ */
1009
+ location: string;
1010
+
1011
+ /**
1012
+ * Key ring name
1013
+ */
1014
+ keyRing: string;
1015
+
1016
+ /**
1017
+ * Key name
1018
+ */
1019
+ keyName: string;
1020
+
1021
+ /**
1022
+ * Key version
1023
+ */
1024
+ keyVersion?: string | undefined;
1025
+
1026
+ /**
1027
+ * KMS URL, defaults to `https://www.googleapis.com/auth/cloudkms`
1028
+ */
1029
+ endpoint?: string | undefined;
1030
+ }
1031
+
1032
+ /**
1033
+ * @public
1034
+ * Configuration options for making an Azure encryption key
1035
+ */
1036
+ export interface AzureEncryptionKeyOptions {
1037
+ /**
1038
+ * Key name
1039
+ */
1040
+ keyName: string;
1041
+
1042
+ /**
1043
+ * Key vault URL, typically `<name>.vault.azure.net`
1044
+ */
1045
+ keyVaultEndpoint: string;
1046
+
1047
+ /**
1048
+ * Key version
1049
+ */
1050
+ keyVersion?: string | undefined;
1051
+ }
1052
+
1053
+ /**
1054
+ * @public
1055
+ * Configuration options for making a KMIP encryption key
1056
+ */
1057
+ export interface KMIPEncryptionKeyOptions {
1058
+ /**
1059
+ * keyId is the KMIP Unique Identifier to a 96 byte KMIP Secret Data managed object.
1060
+ *
1061
+ * If keyId is omitted, a random 96 byte KMIP Secret Data managed object will be created.
1062
+ */
1063
+ keyId?: string;
1064
+
1065
+ /**
1066
+ * Host with optional port.
1067
+ */
1068
+ endpoint?: string;
1069
+
1070
+ /**
1071
+ * If true, this key should be decrypted by the KMIP server.
1072
+ *
1073
+ * Requires `mongodb-client-encryption>=6.0.1`.
1074
+ */
1075
+ delegated?: boolean;
1076
+ }
1077
+
1078
+ /**
1079
+ * @public
1080
+ * Options to provide when creating a new data key.
1081
+ */
1082
+ export interface ClientEncryptionCreateDataKeyProviderOptions {
1083
+ /**
1084
+ * Identifies a new KMS-specific key used to encrypt the new data key
1085
+ */
1086
+ masterKey?:
1087
+ | AWSEncryptionKeyOptions
1088
+ | AzureEncryptionKeyOptions
1089
+ | GCPEncryptionKeyOptions
1090
+ | KMIPEncryptionKeyOptions
1091
+ | undefined;
1092
+
1093
+ /**
1094
+ * An optional list of string alternate names used to reference a key.
1095
+ * If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id.
1096
+ */
1097
+ keyAltNames?: string[] | undefined;
1098
+
1099
+ /** @experimental */
1100
+ keyMaterial?: Buffer | Binary;
1101
+
1102
+ /** @internal */
1103
+ timeoutContext?: CSOTTimeoutContext;
1104
+ }
1105
+
1106
+ /**
1107
+ * @public
1108
+ * @experimental
1109
+ */
1110
+ export interface ClientEncryptionRewrapManyDataKeyResult {
1111
+ /** The result of rewrapping data keys. If unset, no keys matched the filter. */
1112
+ bulkWriteResult?: BulkWriteResult;
1113
+ }
1114
+
1115
+ /**
1116
+ * @public
1117
+ * RangeOptions specifies index options for a Queryable Encryption field supporting "range" queries.
1118
+ * min, max, sparsity, trimFactor and range must match the values set in the encryptedFields of the destination collection.
1119
+ * For double and decimal128, min/max/precision must all be set, or all be unset.
1120
+ */
1121
+ export interface RangeOptions {
1122
+ /** min is the minimum value for the encrypted index. Required if precision is set. */
1123
+ min?: any;
1124
+ /** max is the minimum value for the encrypted index. Required if precision is set. */
1125
+ max?: any;
1126
+ /** sparsity may be used to tune performance. must be non-negative. When omitted, a default value is used. */
1127
+ sparsity?: Long | bigint;
1128
+ /** trimFactor may be used to tune performance. must be non-negative. When omitted, a default value is used. */
1129
+ trimFactor?: Int32 | number;
1130
+ /* precision determines the number of significant digits after the decimal point. May only be set for double or decimal128. */
1131
+ precision?: number;
1132
+ }
1133
+
1134
+ /**
1135
+ * Get the socket options from the client.
1136
+ * @param baseOptions - The mongo client options.
1137
+ * @returns ClientEncryptionSocketOptions
1138
+ */
1139
+ export function autoSelectSocketOptions(
1140
+ baseOptions: MongoClientOptions
1141
+ ): ClientEncryptionSocketOptions {
1142
+ const options: ClientEncryptionSocketOptions = { autoSelectFamily: true };
1143
+ if ('autoSelectFamily' in baseOptions) {
1144
+ options.autoSelectFamily = baseOptions.autoSelectFamily;
1145
+ }
1146
+ if ('autoSelectFamilyAttemptTimeout' in baseOptions) {
1147
+ options.autoSelectFamilyAttemptTimeout = baseOptions.autoSelectFamilyAttemptTimeout;
1148
+ }
1149
+ return options;
1150
+ }