@encharm/cws 4.5.1 → 4.5.2

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 (237) hide show
  1. package/binding.gyp +1 -1
  2. package/dist/bindings/cws_darwin_arm64_node137.node +0 -0
  3. package/dist/bindings/cws_linux_x64_node137.node +0 -0
  4. package/package.json +1 -1
  5. package/src/Addon.h +6 -1
  6. package/src/headers/24/acorn_version.h +6 -0
  7. package/src/headers/24/addon_permission.h +31 -0
  8. package/src/headers/24/agent.h +195 -0
  9. package/src/headers/24/aliased_buffer-inl.h +244 -0
  10. package/src/headers/24/aliased_buffer.h +206 -0
  11. package/src/headers/24/aliased_struct-inl.h +54 -0
  12. package/src/headers/24/aliased_struct.h +63 -0
  13. package/src/headers/24/amaro_version.h +6 -0
  14. package/src/headers/24/application.h +165 -0
  15. package/src/headers/24/async_context_frame.h +33 -0
  16. package/src/headers/24/async_wrap-inl.h +96 -0
  17. package/src/headers/24/async_wrap.h +244 -0
  18. package/src/headers/24/base_object-inl.h +330 -0
  19. package/src/headers/24/base_object.h +338 -0
  20. package/src/headers/24/base_object_types.h +74 -0
  21. package/src/headers/24/bindingdata.h +272 -0
  22. package/src/headers/24/blob_serializer_deserializer-inl.h +385 -0
  23. package/src/headers/24/blob_serializer_deserializer.h +132 -0
  24. package/src/headers/24/callback_queue-inl.h +97 -0
  25. package/src/headers/24/callback_queue.h +79 -0
  26. package/src/headers/24/cares_wrap.h +447 -0
  27. package/src/headers/24/child_process_permission.h +31 -0
  28. package/src/headers/24/cid.h +127 -0
  29. package/src/headers/24/cjs_module_lexer_version.h +6 -0
  30. package/src/headers/24/cleanup_queue-inl.h +36 -0
  31. package/src/headers/24/cleanup_queue.h +79 -0
  32. package/src/headers/24/compile_cache.h +113 -0
  33. package/src/headers/24/connect_wrap.h +26 -0
  34. package/src/headers/24/connection_wrap.h +30 -0
  35. package/src/headers/24/cppgc_helpers-inl.h +65 -0
  36. package/src/headers/24/cppgc_helpers.h +162 -0
  37. package/src/headers/24/crypto/crypto_aes.h +97 -0
  38. package/src/headers/24/crypto/crypto_argon2.h +86 -0
  39. package/src/headers/24/crypto/crypto_bio.h +193 -0
  40. package/src/headers/24/crypto/crypto_chacha20_poly1305.h +64 -0
  41. package/src/headers/24/crypto/crypto_cipher.h +281 -0
  42. package/src/headers/24/crypto/crypto_clienthello-inl.h +90 -0
  43. package/src/headers/24/crypto/crypto_clienthello.h +131 -0
  44. package/src/headers/24/crypto/crypto_common.h +48 -0
  45. package/src/headers/24/crypto/crypto_context.h +171 -0
  46. package/src/headers/24/crypto/crypto_dh.h +126 -0
  47. package/src/headers/24/crypto/crypto_dsa.h +50 -0
  48. package/src/headers/24/crypto/crypto_ec.h +163 -0
  49. package/src/headers/24/crypto/crypto_hash.h +89 -0
  50. package/src/headers/24/crypto/crypto_hkdf.h +61 -0
  51. package/src/headers/24/crypto/crypto_hmac.h +92 -0
  52. package/src/headers/24/crypto/crypto_kem.h +113 -0
  53. package/src/headers/24/crypto/crypto_keygen.h +290 -0
  54. package/src/headers/24/crypto/crypto_keys.h +392 -0
  55. package/src/headers/24/crypto/crypto_ml_dsa.h +21 -0
  56. package/src/headers/24/crypto/crypto_pbkdf2.h +74 -0
  57. package/src/headers/24/crypto/crypto_random.h +124 -0
  58. package/src/headers/24/crypto/crypto_rsa.h +136 -0
  59. package/src/headers/24/crypto/crypto_scrypt.h +85 -0
  60. package/src/headers/24/crypto/crypto_sig.h +156 -0
  61. package/src/headers/24/crypto/crypto_spkac.h +21 -0
  62. package/src/headers/24/crypto/crypto_timing.h +20 -0
  63. package/src/headers/24/crypto/crypto_tls.h +309 -0
  64. package/src/headers/24/crypto/crypto_util.h +598 -0
  65. package/src/headers/24/crypto/crypto_x509.h +140 -0
  66. package/src/headers/24/data.h +148 -0
  67. package/src/headers/24/debug_utils-inl.h +232 -0
  68. package/src/headers/24/debug_utils.h +193 -0
  69. package/src/headers/24/defs.h +254 -0
  70. package/src/headers/24/diagnosticfilename-inl.h +33 -0
  71. package/src/headers/24/embedded_data.h +17 -0
  72. package/src/headers/24/encoding_binding.h +60 -0
  73. package/src/headers/24/endpoint.h +421 -0
  74. package/src/headers/24/env-inl.h +935 -0
  75. package/src/headers/24/env.h +1257 -0
  76. package/src/headers/24/env_properties.h +561 -0
  77. package/src/headers/24/fs_permission.h +167 -0
  78. package/src/headers/24/handle_wrap.h +123 -0
  79. package/src/headers/24/histogram-inl.h +107 -0
  80. package/src/headers/24/histogram.h +279 -0
  81. package/src/headers/24/http3.h +44 -0
  82. package/src/headers/24/inspector_agent.h +165 -0
  83. package/src/headers/24/inspector_io.h +78 -0
  84. package/src/headers/24/inspector_permission.h +31 -0
  85. package/src/headers/24/inspector_profiler.h +149 -0
  86. package/src/headers/24/inspector_socket.h +60 -0
  87. package/src/headers/24/inspector_socket_server.h +110 -0
  88. package/src/headers/24/io_agent.h +30 -0
  89. package/src/headers/24/js_native_api.h +615 -0
  90. package/src/headers/24/js_native_api_types.h +211 -0
  91. package/src/headers/24/js_native_api_v8.h +485 -0
  92. package/src/headers/24/js_native_api_v8_internals.h +45 -0
  93. package/src/headers/24/js_stream.h +52 -0
  94. package/src/headers/24/json_parser.h +40 -0
  95. package/src/headers/24/json_utils.h +172 -0
  96. package/src/headers/24/logstream.h +81 -0
  97. package/src/headers/24/main_thread_interface.h +116 -0
  98. package/src/headers/24/memory_tracker-inl.h +454 -0
  99. package/src/headers/24/memory_tracker.h +333 -0
  100. package/src/headers/24/module_wrap.h +229 -0
  101. package/src/headers/24/ncrypto.h +1625 -0
  102. package/src/headers/24/network_agent.h +118 -0
  103. package/src/headers/24/network_inspector.h +45 -0
  104. package/src/headers/24/network_resource_manager.h +29 -0
  105. package/src/headers/24/node.h +1620 -0
  106. package/src/headers/24/node_api.h +269 -0
  107. package/src/headers/24/node_api_internals.h +46 -0
  108. package/src/headers/24/node_api_types.h +52 -0
  109. package/src/headers/24/node_binding.h +163 -0
  110. package/src/headers/24/node_blob.h +159 -0
  111. package/src/headers/24/node_bob-inl.h +36 -0
  112. package/src/headers/24/node_bob.h +107 -0
  113. package/src/headers/24/node_buffer.h +92 -0
  114. package/src/headers/24/node_builtins.h +223 -0
  115. package/src/headers/24/node_config_file.h +65 -0
  116. package/src/headers/24/node_constants.h +82 -0
  117. package/src/headers/24/node_context_data.h +168 -0
  118. package/src/headers/24/node_contextify.h +261 -0
  119. package/src/headers/24/node_crypto.h +62 -0
  120. package/src/headers/24/node_debug.h +25 -0
  121. package/src/headers/24/node_dir.h +52 -0
  122. package/src/headers/24/node_dotenv.h +45 -0
  123. package/src/headers/24/node_errors.h +391 -0
  124. package/src/headers/24/node_exit_code.h +54 -0
  125. package/src/headers/24/node_external_reference.h +167 -0
  126. package/src/headers/24/node_file-inl.h +412 -0
  127. package/src/headers/24/node_file.h +540 -0
  128. package/src/headers/24/node_http2.h +1175 -0
  129. package/src/headers/24/node_http2_state.h +159 -0
  130. package/src/headers/24/node_http_common-inl.h +198 -0
  131. package/src/headers/24/node_http_common.h +535 -0
  132. package/src/headers/24/node_i18n.h +132 -0
  133. package/src/headers/24/node_internals.h +476 -0
  134. package/src/headers/24/node_json.h +24 -0
  135. package/src/headers/24/node_large_page.h +34 -0
  136. package/src/headers/24/node_locks.h +180 -0
  137. package/src/headers/24/node_main_instance.h +67 -0
  138. package/src/headers/24/node_mem-inl.h +112 -0
  139. package/src/headers/24/node_mem.h +45 -0
  140. package/src/headers/24/node_messaging.h +389 -0
  141. package/src/headers/24/node_metadata.h +164 -0
  142. package/src/headers/24/node_modules.h +93 -0
  143. package/src/headers/24/node_mutex.h +323 -0
  144. package/src/headers/24/node_object_wrap.h +132 -0
  145. package/src/headers/24/node_options-inl.h +524 -0
  146. package/src/headers/24/node_options.h +682 -0
  147. package/src/headers/24/node_perf.h +166 -0
  148. package/src/headers/24/node_perf_common.h +102 -0
  149. package/src/headers/24/node_platform.h +286 -0
  150. package/src/headers/24/node_process-inl.h +26 -0
  151. package/src/headers/24/node_process.h +111 -0
  152. package/src/headers/24/node_realm-inl.h +153 -0
  153. package/src/headers/24/node_realm.h +236 -0
  154. package/src/headers/24/node_report.h +43 -0
  155. package/src/headers/24/node_revert.h +82 -0
  156. package/src/headers/24/node_root_certs.h +3546 -0
  157. package/src/headers/24/node_sea.h +74 -0
  158. package/src/headers/24/node_shadow_realm.h +46 -0
  159. package/src/headers/24/node_snapshot_builder.h +57 -0
  160. package/src/headers/24/node_snapshotable.h +174 -0
  161. package/src/headers/24/node_sockaddr-inl.h +257 -0
  162. package/src/headers/24/node_sockaddr.h +394 -0
  163. package/src/headers/24/node_sqlite.h +270 -0
  164. package/src/headers/24/node_stat_watcher.h +73 -0
  165. package/src/headers/24/node_string.h +101 -0
  166. package/src/headers/24/node_task_runner.h +92 -0
  167. package/src/headers/24/node_threadsafe_cow-inl.h +54 -0
  168. package/src/headers/24/node_threadsafe_cow.h +105 -0
  169. package/src/headers/24/node_trace_buffer.h +83 -0
  170. package/src/headers/24/node_trace_writer.h +75 -0
  171. package/src/headers/24/node_union_bytes.h +81 -0
  172. package/src/headers/24/node_url.h +101 -0
  173. package/src/headers/24/node_url_pattern.h +118 -0
  174. package/src/headers/24/node_v8.h +77 -0
  175. package/src/headers/24/node_v8_platform-inl.h +185 -0
  176. package/src/headers/24/node_version.h +110 -0
  177. package/src/headers/24/node_wasi.h +185 -0
  178. package/src/headers/24/node_wasm_web_api.h +55 -0
  179. package/src/headers/24/node_watchdog.h +154 -0
  180. package/src/headers/24/node_webstorage.h +60 -0
  181. package/src/headers/24/node_worker.h +159 -0
  182. package/src/headers/24/packet.h +155 -0
  183. package/src/headers/24/path.h +33 -0
  184. package/src/headers/24/permission/addon_permission.h +31 -0
  185. package/src/headers/24/permission/child_process_permission.h +31 -0
  186. package/src/headers/24/permission/fs_permission.h +167 -0
  187. package/src/headers/24/permission/inspector_permission.h +31 -0
  188. package/src/headers/24/permission/permission.h +100 -0
  189. package/src/headers/24/permission/permission_base.h +65 -0
  190. package/src/headers/24/permission/wasi_permission.h +31 -0
  191. package/src/headers/24/permission/worker_permission.h +31 -0
  192. package/src/headers/24/permission.h +100 -0
  193. package/src/headers/24/permission_base.h +65 -0
  194. package/src/headers/24/pipe_wrap.h +80 -0
  195. package/src/headers/24/preferredaddress.h +72 -0
  196. package/src/headers/24/protocol_helper.h +27 -0
  197. package/src/headers/24/queue.h +306 -0
  198. package/src/headers/24/req_wrap-inl.h +176 -0
  199. package/src/headers/24/req_wrap.h +79 -0
  200. package/src/headers/24/runtime_agent.h +41 -0
  201. package/src/headers/24/session.h +528 -0
  202. package/src/headers/24/sessionticket.h +108 -0
  203. package/src/headers/24/spawn_sync.h +243 -0
  204. package/src/headers/24/stream_base-inl.h +173 -0
  205. package/src/headers/24/stream_base.h +478 -0
  206. package/src/headers/24/stream_pipe.h +76 -0
  207. package/src/headers/24/stream_wrap.h +132 -0
  208. package/src/headers/24/streams.h +370 -0
  209. package/src/headers/24/string_bytes.h +109 -0
  210. package/src/headers/24/string_decoder-inl.h +31 -0
  211. package/src/headers/24/string_decoder.h +49 -0
  212. package/src/headers/24/target_agent.h +75 -0
  213. package/src/headers/24/tcp_wrap.h +105 -0
  214. package/src/headers/24/threadpoolwork-inl.h +70 -0
  215. package/src/headers/24/timer_wrap-inl.h +32 -0
  216. package/src/headers/24/timer_wrap.h +87 -0
  217. package/src/headers/24/timers.h +75 -0
  218. package/src/headers/24/tlscontext.h +228 -0
  219. package/src/headers/24/tokens.h +256 -0
  220. package/src/headers/24/trace_event.h +722 -0
  221. package/src/headers/24/trace_event_common.h +1109 -0
  222. package/src/headers/24/traced_value.h +129 -0
  223. package/src/headers/24/tracing_agent.h +43 -0
  224. package/src/headers/24/transportparams.h +166 -0
  225. package/src/headers/24/tty_wrap.h +65 -0
  226. package/src/headers/24/udp_wrap.h +230 -0
  227. package/src/headers/24/undici_version.h +6 -0
  228. package/src/headers/24/util-inl.h +711 -0
  229. package/src/headers/24/util.h +1016 -0
  230. package/src/headers/24/v8-external-memory-accounter.h +60 -0
  231. package/src/headers/24/v8-fast-api-calls.h +819 -0
  232. package/src/headers/24/v8-inspector.h +426 -0
  233. package/src/headers/24/wasi_permission.h +31 -0
  234. package/src/headers/24/worker_agent.h +40 -0
  235. package/src/headers/24/worker_inspector.h +124 -0
  236. package/src/headers/24/worker_permission.h +31 -0
  237. package/src/headers/24/zlib_version.h +6 -0
@@ -0,0 +1,598 @@
1
+ #ifndef SRC_CRYPTO_CRYPTO_UTIL_H_
2
+ #define SRC_CRYPTO_CRYPTO_UTIL_H_
3
+
4
+ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
+
6
+ #include "async_wrap.h"
7
+ #include "env.h"
8
+ #include "node_errors.h"
9
+ #include "node_external_reference.h"
10
+ #include "node_internals.h"
11
+ #include "string_bytes.h"
12
+ #include "util.h"
13
+ #include "v8.h"
14
+
15
+ #include "ncrypto.h"
16
+
17
+ #include <algorithm>
18
+ #include <climits>
19
+ #include <cstdio>
20
+ #include <memory>
21
+ #include <optional>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ namespace node::crypto {
26
+ // Currently known sizes of commonly used OpenSSL struct sizes.
27
+ // OpenSSL considers it's various structs to be opaque and the
28
+ // sizes may change from one version of OpenSSL to another, so
29
+ // these values should not be trusted to remain static. These
30
+ // are provided to allow for some close to reasonable memory
31
+ // tracking.
32
+ constexpr size_t kSizeOf_DH = 144;
33
+ constexpr size_t kSizeOf_EC_KEY = 80;
34
+ constexpr size_t kSizeOf_EVP_CIPHER_CTX = 168;
35
+ constexpr size_t kSizeOf_EVP_MD_CTX = 48;
36
+ constexpr size_t kSizeOf_EVP_PKEY = 72;
37
+ constexpr size_t kSizeOf_EVP_PKEY_CTX = 80;
38
+ constexpr size_t kSizeOf_HMAC_CTX = 32;
39
+
40
+ bool ProcessFipsOptions();
41
+
42
+ bool InitCryptoOnce(v8::Isolate* isolate);
43
+ void InitCryptoOnce();
44
+
45
+ void InitCrypto(v8::Local<v8::Object> target);
46
+
47
+ extern void UseExtraCaCerts(std::string_view file);
48
+ extern int LoadSystemCACertificatesOffThread();
49
+ void CleanupCachedRootCertificates();
50
+
51
+ int PasswordCallback(char* buf, int size, int rwflag, void* u);
52
+ int NoPasswordCallback(char* buf, int size, int rwflag, void* u);
53
+
54
+ // Decode is used by the various stream-based crypto utilities to decode
55
+ // string input.
56
+ template <typename T>
57
+ void Decode(const v8::FunctionCallbackInfo<v8::Value>& args,
58
+ void (*callback)(T*, const v8::FunctionCallbackInfo<v8::Value>&,
59
+ const char*, size_t)) {
60
+ T* ctx;
61
+ ASSIGN_OR_RETURN_UNWRAP(&ctx, args.This());
62
+
63
+ if (args[0]->IsString()) {
64
+ StringBytes::InlineDecoder decoder;
65
+ Environment* env = Environment::GetCurrent(args);
66
+ enum encoding enc = ParseEncoding(env->isolate(), args[1], UTF8);
67
+ if (decoder.Decode(env, args[0].As<v8::String>(), enc).IsNothing())
68
+ return;
69
+ callback(ctx, args, decoder.out(), decoder.size());
70
+ } else {
71
+ ArrayBufferViewContents<char> buf(args[0]);
72
+ callback(ctx, args, buf.data(), buf.length());
73
+ }
74
+ }
75
+
76
+ #define NODE_CRYPTO_ERROR_CODES_MAP(V) \
77
+ V(CIPHER_JOB_FAILED, "Cipher job failed") \
78
+ V(DERIVING_BITS_FAILED, "Deriving bits failed") \
79
+ V(ENGINE_NOT_FOUND, "Engine \"%s\" was not found") \
80
+ V(INVALID_KEY_TYPE, "Invalid key type") \
81
+ V(KEY_GENERATION_JOB_FAILED, "Key generation job failed") \
82
+ V(OK, "Ok") \
83
+
84
+ enum class NodeCryptoError {
85
+ #define V(CODE, DESCRIPTION) CODE,
86
+ NODE_CRYPTO_ERROR_CODES_MAP(V)
87
+ #undef V
88
+ };
89
+
90
+ template <typename... Args>
91
+ std::string getNodeCryptoErrorString(const NodeCryptoError error,
92
+ Args&&... args) {
93
+ const char* error_string = nullptr;
94
+ switch (error) {
95
+ #define V(CODE, DESCRIPTION) \
96
+ case NodeCryptoError::CODE: \
97
+ error_string = DESCRIPTION; \
98
+ break;
99
+ NODE_CRYPTO_ERROR_CODES_MAP(V)
100
+ #undef V
101
+ }
102
+ return SPrintF(error_string, std::forward<Args>(args)...);
103
+ }
104
+
105
+ // Utility struct used to harvest error information from openssl's error stack
106
+ struct CryptoErrorStore final : public MemoryRetainer {
107
+ public:
108
+ void Capture();
109
+
110
+ bool Empty() const;
111
+
112
+ template <typename... Args>
113
+ void Insert(const NodeCryptoError error, Args&&... args);
114
+
115
+ v8::MaybeLocal<v8::Value> ToException(
116
+ Environment* env,
117
+ v8::Local<v8::String> exception_string = v8::Local<v8::String>()) const;
118
+
119
+ SET_NO_MEMORY_INFO()
120
+ SET_MEMORY_INFO_NAME(CryptoErrorStore)
121
+ SET_SELF_SIZE(CryptoErrorStore)
122
+
123
+ private:
124
+ std::vector<std::string> errors_;
125
+ };
126
+
127
+ template <typename... Args>
128
+ void CryptoErrorStore::Insert(const NodeCryptoError error, Args&&... args) {
129
+ const char* error_string = nullptr;
130
+ switch (error) {
131
+ #define V(CODE, DESCRIPTION) \
132
+ case NodeCryptoError::CODE: error_string = DESCRIPTION; break;
133
+ NODE_CRYPTO_ERROR_CODES_MAP(V)
134
+ #undef V
135
+ }
136
+ errors_.emplace_back(SPrintF(error_string,
137
+ std::forward<Args>(args)...));
138
+ }
139
+
140
+ v8::MaybeLocal<v8::Value> cryptoErrorListToException(
141
+ Environment* env, const ncrypto::CryptoErrorList& errors);
142
+
143
+ template <typename T>
144
+ T* MallocOpenSSL(size_t count) {
145
+ void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
146
+ CHECK_IMPLIES(mem == nullptr, count == 0);
147
+ return static_cast<T*>(mem);
148
+ }
149
+
150
+ // A helper class representing a read-only byte array. When deallocated, its
151
+ // contents are zeroed.
152
+ class ByteSource final {
153
+ public:
154
+ ByteSource() = default;
155
+ ByteSource(ByteSource&& other) noexcept;
156
+ ~ByteSource();
157
+
158
+ ByteSource& operator=(ByteSource&& other) noexcept;
159
+
160
+ ByteSource(const ByteSource&) = delete;
161
+ ByteSource& operator=(const ByteSource&) = delete;
162
+
163
+ template <typename T = void>
164
+ inline const T* data() const {
165
+ return reinterpret_cast<const T*>(data_);
166
+ }
167
+
168
+ template <typename T = void>
169
+ operator ncrypto::Buffer<const T>() const {
170
+ return ncrypto::Buffer<const T>{
171
+ .data = data<T>(),
172
+ .len = size(),
173
+ };
174
+ }
175
+
176
+ inline size_t size() const { return size_; }
177
+
178
+ inline bool empty() const { return size_ == 0; }
179
+
180
+ inline operator bool() const { return data_ != nullptr; }
181
+
182
+ inline ncrypto::BignumPointer ToBN() const {
183
+ return ncrypto::BignumPointer(data<unsigned char>(), size());
184
+ }
185
+
186
+ // Creates a v8::BackingStore that takes over responsibility for
187
+ // any allocated data. The ByteSource will be reset with size = 0
188
+ // after being called.
189
+ std::unique_ptr<v8::BackingStore> ReleaseToBackingStore(Environment* env);
190
+
191
+ v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env);
192
+
193
+ v8::MaybeLocal<v8::Uint8Array> ToBuffer(Environment* env);
194
+
195
+ static ByteSource Allocated(void* data, size_t size);
196
+
197
+ template <typename T>
198
+ static ByteSource Allocated(const ncrypto::Buffer<T>& buffer) {
199
+ return Allocated(buffer.data, buffer.len);
200
+ }
201
+
202
+ static ByteSource Foreign(const void* data, size_t size);
203
+
204
+ static ByteSource FromEncodedString(Environment* env,
205
+ v8::Local<v8::String> value,
206
+ enum encoding enc = BASE64);
207
+
208
+ static ByteSource FromStringOrBuffer(Environment* env,
209
+ v8::Local<v8::Value> value);
210
+
211
+ static ByteSource FromString(Environment* env,
212
+ v8::Local<v8::String> str,
213
+ bool ntc = false);
214
+
215
+ static ByteSource FromBuffer(v8::Local<v8::Value> buffer,
216
+ bool ntc = false);
217
+
218
+ static ByteSource FromBIO(const ncrypto::BIOPointer& bio);
219
+
220
+ static ByteSource NullTerminatedCopy(Environment* env,
221
+ v8::Local<v8::Value> value);
222
+
223
+ static ByteSource FromSymmetricKeyObjectHandle(v8::Local<v8::Value> handle);
224
+
225
+ static ByteSource FromSecretKeyBytes(
226
+ Environment* env, v8::Local<v8::Value> value);
227
+
228
+ private:
229
+ const void* data_ = nullptr;
230
+ void* allocated_data_ = nullptr;
231
+ size_t size_ = 0;
232
+
233
+ ByteSource(const void* data, void* allocated_data, size_t size)
234
+ : data_(data), allocated_data_(allocated_data), size_(size) {}
235
+ };
236
+
237
+ enum CryptoJobMode {
238
+ kCryptoJobAsync,
239
+ kCryptoJobSync
240
+ };
241
+
242
+ CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args);
243
+
244
+ template <typename CryptoJobTraits>
245
+ class CryptoJob : public AsyncWrap, public ThreadPoolWork {
246
+ public:
247
+ using AdditionalParams = typename CryptoJobTraits::AdditionalParameters;
248
+
249
+ explicit CryptoJob(Environment* env,
250
+ v8::Local<v8::Object> object,
251
+ AsyncWrap::ProviderType type,
252
+ CryptoJobMode mode,
253
+ AdditionalParams&& params)
254
+ : AsyncWrap(env, object, type),
255
+ ThreadPoolWork(env, "crypto"),
256
+ mode_(mode),
257
+ params_(std::move(params)) {
258
+ // If the CryptoJob is async, then the instance will be
259
+ // cleaned up when AfterThreadPoolWork is called.
260
+ if (mode == kCryptoJobSync) MakeWeak();
261
+ }
262
+
263
+ bool IsNotIndicativeOfMemoryLeakAtExit() const override {
264
+ // CryptoJobs run a work in the libuv thread pool and may still
265
+ // exist when the event loop empties and starts to exit.
266
+ return true;
267
+ }
268
+
269
+ void AfterThreadPoolWork(int status) override {
270
+ Environment* env = AsyncWrap::env();
271
+ CHECK_EQ(mode_, kCryptoJobAsync);
272
+ CHECK(status == 0 || status == UV_ECANCELED);
273
+ std::unique_ptr<CryptoJob> ptr(this);
274
+ // If the job was canceled do not execute the callback.
275
+ // TODO(@jasnell): We should likely revisit skipping the
276
+ // callback on cancel as that could leave the JS in a pending
277
+ // state (e.g. unresolved promises...)
278
+ if (status == UV_ECANCELED) return;
279
+ v8::HandleScope handle_scope(env->isolate());
280
+ v8::Context::Scope context_scope(env->context());
281
+
282
+ v8::Local<v8::Value> exception;
283
+ v8::Local<v8::Value> args[2];
284
+ {
285
+ node::errors::TryCatchScope try_catch(env);
286
+ // If ToResult returns Nothing, then an exception should have been
287
+ // thrown and we should have caught it. Otherwise, args[0] and args[1]
288
+ // both should have been set to a value, even if the value is undefined.
289
+ if (ptr->ToResult(&args[0], &args[1]).IsNothing()) {
290
+ CHECK(try_catch.HasCaught());
291
+ CHECK(try_catch.CanContinue());
292
+ exception = try_catch.Exception();
293
+ }
294
+ }
295
+
296
+ if (!exception.IsEmpty()) {
297
+ ptr->MakeCallback(env->ondone_string(), 1, &exception);
298
+ } else {
299
+ CHECK(!args[0].IsEmpty());
300
+ CHECK(!args[1].IsEmpty());
301
+ ptr->MakeCallback(env->ondone_string(), arraysize(args), args);
302
+ }
303
+ }
304
+
305
+ virtual v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
306
+ v8::Local<v8::Value>* result) = 0;
307
+
308
+ CryptoJobMode mode() const { return mode_; }
309
+
310
+ CryptoErrorStore* errors() { return &errors_; }
311
+
312
+ AdditionalParams* params() { return &params_; }
313
+
314
+ const char* MemoryInfoName() const override {
315
+ return CryptoJobTraits::JobName;
316
+ }
317
+
318
+ void MemoryInfo(MemoryTracker* tracker) const override {
319
+ tracker->TrackField("params", params_);
320
+ tracker->TrackField("errors", errors_);
321
+ }
322
+
323
+ static void Run(const v8::FunctionCallbackInfo<v8::Value>& args) {
324
+ Environment* env = Environment::GetCurrent(args);
325
+
326
+ CryptoJob<CryptoJobTraits>* job;
327
+ ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
328
+ if (job->mode() == kCryptoJobAsync)
329
+ return job->ScheduleWork();
330
+
331
+ v8::Local<v8::Value> ret[2];
332
+ env->PrintSyncTrace();
333
+ job->DoThreadPoolWork();
334
+ if (job->ToResult(&ret[0], &ret[1]).IsJust()) {
335
+ CHECK(!ret[0].IsEmpty());
336
+ CHECK(!ret[1].IsEmpty());
337
+ args.GetReturnValue().Set(
338
+ v8::Array::New(env->isolate(), ret, arraysize(ret)));
339
+ }
340
+ }
341
+
342
+ static void Initialize(
343
+ v8::FunctionCallback new_fn,
344
+ Environment* env,
345
+ v8::Local<v8::Object> target) {
346
+ v8::Isolate* isolate = env->isolate();
347
+ v8::HandleScope scope(isolate);
348
+ v8::Local<v8::Context> context = env->context();
349
+ v8::Local<v8::FunctionTemplate> job = NewFunctionTemplate(isolate, new_fn);
350
+ job->Inherit(AsyncWrap::GetConstructorTemplate(env));
351
+ job->InstanceTemplate()->SetInternalFieldCount(
352
+ AsyncWrap::kInternalFieldCount);
353
+ SetProtoMethod(isolate, job, "run", Run);
354
+ SetConstructorFunction(context, target, CryptoJobTraits::JobName, job);
355
+ }
356
+
357
+ static void RegisterExternalReferences(v8::FunctionCallback new_fn,
358
+ ExternalReferenceRegistry* registry) {
359
+ registry->Register(new_fn);
360
+ registry->Register(Run);
361
+ }
362
+
363
+ private:
364
+ const CryptoJobMode mode_;
365
+ CryptoErrorStore errors_;
366
+ AdditionalParams params_;
367
+ };
368
+
369
+ template <typename DeriveBitsTraits>
370
+ class DeriveBitsJob final : public CryptoJob<DeriveBitsTraits> {
371
+ public:
372
+ using AdditionalParams = typename DeriveBitsTraits::AdditionalParameters;
373
+
374
+ static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
375
+ Environment* env = Environment::GetCurrent(args);
376
+
377
+ CryptoJobMode mode = GetCryptoJobMode(args[0]);
378
+
379
+ AdditionalParams params;
380
+ if (DeriveBitsTraits::AdditionalConfig(mode, args, 1, &params)
381
+ .IsNothing()) {
382
+ // The DeriveBitsTraits::AdditionalConfig is responsible for
383
+ // calling an appropriate THROW_CRYPTO_* variant reporting
384
+ // whatever error caused initialization to fail.
385
+ return;
386
+ }
387
+
388
+ new DeriveBitsJob(env, args.This(), mode, std::move(params));
389
+ }
390
+
391
+ static void Initialize(
392
+ Environment* env,
393
+ v8::Local<v8::Object> target) {
394
+ CryptoJob<DeriveBitsTraits>::Initialize(New, env, target);
395
+ }
396
+
397
+ static void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
398
+ CryptoJob<DeriveBitsTraits>::RegisterExternalReferences(New, registry);
399
+ }
400
+
401
+ DeriveBitsJob(
402
+ Environment* env,
403
+ v8::Local<v8::Object> object,
404
+ CryptoJobMode mode,
405
+ AdditionalParams&& params)
406
+ : CryptoJob<DeriveBitsTraits>(
407
+ env,
408
+ object,
409
+ DeriveBitsTraits::Provider,
410
+ mode,
411
+ std::move(params)) {}
412
+
413
+ void DoThreadPoolWork() override {
414
+ ncrypto::ClearErrorOnReturn clear_error_on_return;
415
+ if (!DeriveBitsTraits::DeriveBits(AsyncWrap::env(),
416
+ *CryptoJob<DeriveBitsTraits>::params(),
417
+ &out_,
418
+ this->mode())) {
419
+ CryptoErrorStore* errors = CryptoJob<DeriveBitsTraits>::errors();
420
+ errors->Capture();
421
+ if (errors->Empty())
422
+ errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
423
+ return;
424
+ }
425
+ success_ = true;
426
+ }
427
+
428
+ v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
429
+ v8::Local<v8::Value>* result) override {
430
+ Environment* env = AsyncWrap::env();
431
+ CryptoErrorStore* errors = CryptoJob<DeriveBitsTraits>::errors();
432
+ if (success_) {
433
+ CHECK(errors->Empty());
434
+ *err = v8::Undefined(env->isolate());
435
+ if (!DeriveBitsTraits::EncodeOutput(
436
+ env, *CryptoJob<DeriveBitsTraits>::params(), &out_)
437
+ .ToLocal(result)) {
438
+ return v8::Nothing<void>();
439
+ }
440
+ } else {
441
+ if (errors->Empty()) errors->Capture();
442
+ CHECK(!errors->Empty());
443
+ *result = v8::Undefined(env->isolate());
444
+ if (!errors->ToException(env).ToLocal(err)) {
445
+ return v8::Nothing<void>();
446
+ }
447
+ }
448
+ CHECK(!result->IsEmpty());
449
+ CHECK(!err->IsEmpty());
450
+ return v8::JustVoid();
451
+ }
452
+
453
+ SET_SELF_SIZE(DeriveBitsJob)
454
+ void MemoryInfo(MemoryTracker* tracker) const override {
455
+ tracker->TrackFieldWithSize("out", out_.size());
456
+ CryptoJob<DeriveBitsTraits>::MemoryInfo(tracker);
457
+ }
458
+
459
+ private:
460
+ ByteSource out_;
461
+ bool success_ = false;
462
+ };
463
+
464
+ void ThrowCryptoError(Environment* env,
465
+ unsigned long err, // NOLINT(runtime/int)
466
+ const char* message = nullptr);
467
+
468
+ // WebIDL AllowSharedBufferSource.
469
+ inline bool IsAnyBufferSource(v8::Local<v8::Value> arg) {
470
+ return arg->IsArrayBufferView() ||
471
+ arg->IsArrayBuffer() ||
472
+ arg->IsSharedArrayBuffer();
473
+ }
474
+
475
+ template <typename T>
476
+ class ArrayBufferOrViewContents final {
477
+ public:
478
+ ArrayBufferOrViewContents() = default;
479
+ ArrayBufferOrViewContents(const ArrayBufferOrViewContents&) = delete;
480
+ void operator=(const ArrayBufferOrViewContents&) = delete;
481
+
482
+ inline explicit ArrayBufferOrViewContents(v8::Local<v8::Value> buf) {
483
+ if (buf.IsEmpty()) {
484
+ return;
485
+ }
486
+
487
+ CHECK(IsAnyBufferSource(buf));
488
+ if (buf->IsArrayBufferView()) {
489
+ auto view = buf.As<v8::ArrayBufferView>();
490
+ offset_ = view->ByteOffset();
491
+ length_ = view->ByteLength();
492
+ data_ = view->Buffer()->Data();
493
+ } else if (buf->IsArrayBuffer()) {
494
+ auto ab = buf.As<v8::ArrayBuffer>();
495
+ offset_ = 0;
496
+ length_ = ab->ByteLength();
497
+ data_ = ab->Data();
498
+ } else {
499
+ auto sab = buf.As<v8::SharedArrayBuffer>();
500
+ offset_ = 0;
501
+ length_ = sab->ByteLength();
502
+ data_ = sab->Data();
503
+ }
504
+ }
505
+
506
+ inline const T* data() const {
507
+ // Ideally, these would return nullptr if IsEmpty() or length_ is zero,
508
+ // but some of the openssl API react badly if given a nullptr even when
509
+ // length is zero, so we have to return something.
510
+ if (empty()) return &buf;
511
+ return reinterpret_cast<T*>(data_) + offset_;
512
+ }
513
+
514
+ inline T* data() {
515
+ // Ideally, these would return nullptr if IsEmpty() or length_ is zero,
516
+ // but some of the openssl API react badly if given a nullptr even when
517
+ // length is zero, so we have to return something.
518
+ if (empty()) return &buf;
519
+ return reinterpret_cast<T*>(data_) + offset_;
520
+ }
521
+
522
+ inline size_t size() const { return length_; }
523
+
524
+ inline bool empty() const { return length_ == 0; }
525
+
526
+ // In most cases, input buffer sizes passed in to openssl need to
527
+ // be limited to <= INT_MAX. This utility method helps us check.
528
+ inline bool CheckSizeInt32() { return size() <= INT_MAX; }
529
+
530
+ inline ByteSource ToByteSource() const {
531
+ return ByteSource::Foreign(data(), size());
532
+ }
533
+
534
+ inline ByteSource ToCopy() const {
535
+ if (empty()) return {};
536
+ auto buf = ncrypto::DataPointer::Alloc(size());
537
+ memcpy(buf.get(), data(), size());
538
+ return ByteSource::Allocated(buf.release());
539
+ }
540
+
541
+ inline ByteSource ToNullTerminatedCopy() const {
542
+ if (empty()) return {};
543
+ auto buf = ncrypto::DataPointer::Alloc(size() + 1);
544
+ memcpy(buf.get(), data(), size());
545
+ static_cast<char*>(buf.get())[size()] = 0;
546
+ return ByteSource::Allocated(buf.release());
547
+ }
548
+
549
+ inline ncrypto::DataPointer ToDataPointer() const {
550
+ if (empty()) return {};
551
+ if (auto dp = ncrypto::DataPointer::Alloc(size())) {
552
+ memcpy(dp.get(), data(), size());
553
+ return dp;
554
+ }
555
+ return {};
556
+ }
557
+
558
+ template <typename M>
559
+ void CopyTo(M* dest, size_t len) const {
560
+ static_assert(sizeof(M) == 1, "sizeof(M) must equal 1");
561
+ len = std::min(len, size());
562
+ if (len > 0 && data() != nullptr) {
563
+ memcpy(dest, data(), len);
564
+ }
565
+ }
566
+
567
+ private:
568
+ T buf = 0;
569
+ size_t offset_ = 0;
570
+ size_t length_ = 0;
571
+ void* data_ = nullptr;
572
+
573
+ // Declaring operator new and delete as deleted is not spec compliant.
574
+ // Therefore declare them private instead to disable dynamic alloc
575
+ void* operator new(size_t);
576
+ void* operator new[](size_t);
577
+ void operator delete(void*);
578
+ void operator delete[](void*);
579
+ };
580
+
581
+ v8::MaybeLocal<v8::Value> EncodeBignum(Environment* env,
582
+ const BIGNUM* bn,
583
+ int size);
584
+
585
+ v8::Maybe<void> SetEncodedValue(Environment* env,
586
+ v8::Local<v8::Object> target,
587
+ v8::Local<v8::String> name,
588
+ const BIGNUM* bn,
589
+ int size = 0);
590
+
591
+ namespace Util {
592
+ void Initialize(Environment* env, v8::Local<v8::Object> target);
593
+ void RegisterExternalReferences(ExternalReferenceRegistry* registry);
594
+ } // namespace Util
595
+ } // namespace node::crypto
596
+
597
+ #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
598
+ #endif // SRC_CRYPTO_CRYPTO_UTIL_H_