cf-workers-native 0.1.4 → 0.1.5

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 (161) hide show
  1. package/dist/browser/documents/page-source.js +1 -1
  2. package/dist/browser/fetch/host-call.js +6 -1
  3. package/dist/browser/fetch/native-network.d.ts +1 -1
  4. package/dist/browser/fetch/relay.js +2 -0
  5. package/dist/browser/isolated/transport.js +3 -2
  6. package/dist/browser/request/index.js +3 -2
  7. package/dist/cloudflare/workers/worker-runtime.js +2 -1
  8. package/dist/compat/console/index.d.ts +35 -0
  9. package/dist/compat/console/index.js +92 -0
  10. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +19 -0
  11. package/dist/compat/crypto/LICENSE-APACHE +177 -0
  12. package/dist/compat/crypto/LICENSE.emscripten +102 -0
  13. package/dist/compat/crypto/LICENSE.musl +193 -0
  14. package/dist/compat/crypto/LICENSE.openssl +177 -0
  15. package/dist/compat/crypto/asymmetric.d.ts +13 -0
  16. package/dist/compat/crypto/asymmetric.js +239 -0
  17. package/dist/compat/crypto/brorand.cjs +74 -0
  18. package/dist/compat/crypto/brorand.d.cts +6 -0
  19. package/dist/compat/crypto/certificate.d.ts +14 -0
  20. package/dist/compat/crypto/certificate.js +66 -0
  21. package/dist/compat/crypto/ecdh.d.ts +15 -0
  22. package/dist/compat/crypto/ecdh.js +109 -0
  23. package/dist/compat/crypto/hkdf.d.ts +2 -0
  24. package/dist/compat/crypto/hkdf.js +52 -0
  25. package/dist/compat/crypto/index.cjs +2 -0
  26. package/dist/compat/crypto/index.d.cts +2 -0
  27. package/dist/compat/crypto/index.d.ts +30 -0
  28. package/dist/compat/crypto/index.js +83 -0
  29. package/dist/compat/crypto/key-formats.d.ts +6 -0
  30. package/dist/compat/crypto/key-formats.js +120 -0
  31. package/dist/compat/crypto/key-state.d.ts +9 -0
  32. package/dist/compat/crypto/key-state.js +4 -0
  33. package/dist/compat/crypto/keys.d.ts +50 -0
  34. package/dist/compat/crypto/keys.js +209 -0
  35. package/dist/compat/crypto/metadata.d.ts +4 -0
  36. package/dist/compat/crypto/metadata.js +22 -0
  37. package/dist/compat/crypto/native-crypto.d.ts +68 -0
  38. package/dist/compat/crypto/native-crypto.js +569 -0
  39. package/dist/compat/crypto/prime.d.ts +19 -0
  40. package/dist/compat/crypto/prime.js +146 -0
  41. package/dist/compat/crypto/random.d.ts +7 -0
  42. package/dist/compat/crypto/random.js +123 -0
  43. package/dist/compat/crypto/rsa.d.ts +5 -0
  44. package/dist/compat/crypto/rsa.js +173 -0
  45. package/dist/compat/crypto/scrypt.d.ts +25 -0
  46. package/dist/compat/crypto/scrypt.js +150 -0
  47. package/dist/compat/crypto/sign-errors.d.ts +8 -0
  48. package/dist/compat/crypto/sign-errors.js +13 -0
  49. package/dist/compat/crypto/sign-handle.d.ts +22 -0
  50. package/dist/compat/crypto/sign-handle.js +105 -0
  51. package/dist/compat/crypto/signatures.d.ts +28 -0
  52. package/dist/compat/crypto/signatures.js +252 -0
  53. package/dist/compat/crypto/symmetric.d.ts +29 -0
  54. package/dist/compat/crypto/symmetric.js +104 -0
  55. package/dist/compat/crypto/validation.d.ts +3 -0
  56. package/dist/compat/crypto/validation.js +19 -0
  57. package/dist/compat/crypto/x509.d.ts +30 -0
  58. package/dist/compat/crypto/x509.js +406 -0
  59. package/dist/compat/events/errors.d.ts +8 -0
  60. package/dist/compat/events/errors.js +39 -0
  61. package/dist/compat/events/index.cjs +2 -0
  62. package/dist/compat/events/index.d.cts +2 -0
  63. package/dist/compat/events/index.d.ts +64 -0
  64. package/dist/compat/events/index.js +792 -0
  65. package/dist/compat/events/intrinsics.d.ts +1 -0
  66. package/dist/compat/events/intrinsics.js +2 -0
  67. package/dist/compat/fs/embedded.d.ts +85 -0
  68. package/dist/compat/fs/embedded.js +255 -0
  69. package/dist/compat/fs/index.d.ts +7 -84
  70. package/dist/compat/fs/index.js +218 -252
  71. package/dist/compat/fs/mode.d.ts +1 -0
  72. package/dist/compat/fs/mode.js +13 -0
  73. package/dist/compat/fs/promises/index.d.ts +1 -1
  74. package/dist/compat/fs/promises/index.js +1 -1
  75. package/dist/compat/fs/writable.d.ts +6 -0
  76. package/dist/compat/fs/writable.js +142 -0
  77. package/dist/compat/http/symbols.d.ts +5 -0
  78. package/dist/compat/http/symbols.js +9 -0
  79. package/dist/compat/http-common/index.d.ts +37 -0
  80. package/dist/compat/http-common/index.js +43 -0
  81. package/dist/compat/http-outgoing/index.d.ts +13 -0
  82. package/dist/compat/http-outgoing/index.js +32 -0
  83. package/dist/compat/http-server/index.d.ts +18 -0
  84. package/dist/compat/http-server/index.js +107 -0
  85. package/dist/compat/module/builtins.d.ts +1 -0
  86. package/dist/compat/module/builtins.js +101 -0
  87. package/dist/compat/module/index.d.ts +4 -2
  88. package/dist/compat/module/index.js +22 -17
  89. package/dist/compat/module/metadata.d.ts +44 -0
  90. package/dist/compat/module/metadata.js +127 -0
  91. package/dist/compat/net/internal-net.js +4 -0
  92. package/dist/compat/net/sockets.d.ts +5 -0
  93. package/dist/compat/net/sockets.js +74 -13
  94. package/dist/compat/process/index.cjs +2 -0
  95. package/dist/compat/process/index.d.cts +4 -0
  96. package/dist/compat/process/index.d.ts +18 -0
  97. package/dist/compat/process/index.js +140 -0
  98. package/dist/compat/process/metadata.d.ts +135 -0
  99. package/dist/compat/process/metadata.js +251 -0
  100. package/dist/compat/process/state.d.ts +4 -0
  101. package/dist/compat/process/state.js +4 -0
  102. package/dist/compat/stream-web/LICENSE +22 -0
  103. package/dist/compat/stream-web/ponyfill.d.ts +1 -1
  104. package/dist/compat/stream-web/ponyfill.js +2369 -1775
  105. package/dist/compat/stream-web/runtime.d.ts +1 -1
  106. package/dist/compat/stream-web/runtime.js +3 -2
  107. package/dist/compat/stream-wrap/LICENSE-3RD-PARTY.md +11 -0
  108. package/dist/compat/stream-wrap/LICENSE-APACHE +177 -0
  109. package/dist/compat/stream-wrap/index.d.ts +1 -0
  110. package/dist/compat/stream-wrap/index.js +1 -0
  111. package/dist/compat/tls/LICENSE-3RD-PARTY.md +11 -0
  112. package/dist/compat/tls/LICENSE-APACHE +177 -0
  113. package/dist/compat/tls/constants.d.ts +7 -0
  114. package/dist/compat/tls/constants.js +14 -0
  115. package/dist/compat/tls/errors.d.ts +35 -0
  116. package/dist/compat/tls/errors.js +68 -0
  117. package/dist/compat/tls/helpers.d.ts +9 -0
  118. package/dist/compat/tls/helpers.js +207 -0
  119. package/dist/compat/tls/index.d.ts +26 -0
  120. package/dist/compat/tls/index.js +50 -0
  121. package/dist/compat/tls/jsstream.d.ts +19 -0
  122. package/dist/compat/tls/jsstream.js +186 -0
  123. package/dist/compat/tls/native-session.d.ts +3 -0
  124. package/dist/compat/tls/native-session.js +187 -0
  125. package/dist/compat/tls/wrap.d.ts +65 -0
  126. package/dist/compat/tls/wrap.js +544 -0
  127. package/dist/compat/tls-wrap/LICENSE-3RD-PARTY.md +11 -0
  128. package/dist/compat/tls-wrap/LICENSE-APACHE +177 -0
  129. package/dist/compat/tls-wrap/index.d.ts +7 -0
  130. package/dist/compat/tls-wrap/index.js +3 -0
  131. package/dist/compat/util/index.js +43 -1
  132. package/dist/compat/util/types/index.d.ts +3 -0
  133. package/dist/compat/util/types/index.js +5 -0
  134. package/dist/compat/zlib/LICENSE.brotli +19 -0
  135. package/dist/compat/zlib/LICENSE.emscripten +102 -0
  136. package/dist/compat/zlib/LICENSE.musl +193 -0
  137. package/dist/compat/zlib/LICENSE.zstd +30 -0
  138. package/dist/compat/zlib/compression.d.ts +55 -0
  139. package/dist/compat/zlib/compression.js +259 -0
  140. package/dist/compat/zlib/constants.d.ts +172 -0
  141. package/dist/compat/zlib/constants.js +173 -0
  142. package/dist/compat/zlib/index.d.ts +180 -0
  143. package/dist/compat/zlib/index.js +177 -0
  144. package/dist/compat/zlib/native-codecs.d.ts +17 -0
  145. package/dist/compat/zlib/native-codecs.js +168 -0
  146. package/dist/shared/globals/inject.d.ts +2 -1
  147. package/dist/shared/globals/inject.js +2 -1
  148. package/dist/shared/globals/runtime.d.ts +1 -2
  149. package/dist/shared/globals/runtime.js +1 -2
  150. package/dist/shared/request-scope.d.ts +4 -0
  151. package/dist/shared/request-scope.js +11 -0
  152. package/dist/tooling/async.js +36 -14
  153. package/dist/tooling/shared.d.ts +1 -0
  154. package/dist/tooling/shared.js +20 -1
  155. package/dist/tooling/vite.js +4 -3
  156. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +56 -8
  157. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkersCapacitorPlugin.java +4 -2
  158. package/native/ios/NetworkBridge.swift +11 -1
  159. package/native/ios/SocketBridge.swift +37 -2
  160. package/native/ios/WorkersCapacitorPlugin.swift +4 -0
  161. package/package.json +3 -1
@@ -0,0 +1,65 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Socket, type SocketOptions } from "../net/internal-net.js";
3
+ import type { ConnectionOptions, TlsOptions, TLSSocket as TLSSocketType } from "node:tls";
4
+ import type { OnReadOpts, TcpSocketConnectOpts } from "node:net";
5
+ declare const kConnectOptions: unique symbol;
6
+ declare const kErrorEmitted: unique symbol;
7
+ declare const kRes: unique symbol;
8
+ declare const kPendingSession: unique symbol;
9
+ declare const kIsVerified: unique symbol;
10
+ export declare class TLSSocket extends Socket {
11
+ _hadError: boolean;
12
+ _handle: Socket["_handle"];
13
+ _init(): void;
14
+ _tlsOptions: TlsOptions & ConnectionOptions & SocketOptions & TcpSocketConnectOpts & {
15
+ isServer?: boolean;
16
+ requestOCSP?: boolean;
17
+ server?: unknown;
18
+ onread?: OnReadOpts;
19
+ };
20
+ _secureEstablished: boolean;
21
+ _securePending: boolean;
22
+ _newSessionPending: boolean;
23
+ _controlReleased: boolean;
24
+ authorized: boolean;
25
+ encrypted: boolean;
26
+ handle: ReturnType<TLSSocket["_wrapHandle"]>;
27
+ servername: null | string;
28
+ secureConnecting: boolean;
29
+ ssl: TLSSocket["_handle"];
30
+ [kRes]: null | Socket["_handle"];
31
+ [kIsVerified]: boolean;
32
+ [kPendingSession]: null | Buffer;
33
+ [kErrorEmitted]: boolean;
34
+ [kConnectOptions]?: NormalizedConnectionOptions;
35
+ constructor(socket: Socket | Duplex | undefined, opts: TLSSocket["_tlsOptions"]);
36
+ prototype: TLSSocket;
37
+ _destroySSL(): void;
38
+ _emitTLSError(error: Error): void;
39
+ _finishInit(): void;
40
+ _handleTimeout(): void;
41
+ _releaseControl(): boolean;
42
+ _start(): void;
43
+ _tlsError(error: Error): Error | null;
44
+ _wrapHandle(wrap: null | Socket, handle: Socket["_handle"] | null | undefined, wrapHasActiveWriteFromPrevOwner: boolean): unknown;
45
+ disableRenegotiation(): void;
46
+ getX509Certificate(): ReturnType<TLSSocketType["getX509Certificate"]>;
47
+ setKeyCert(context: unknown): void;
48
+ setServername(name: string): void;
49
+ setSession(session: string | Buffer): void;
50
+ setMaxSendFragment(size: number): boolean;
51
+ getCertificate(): ReturnType<TLSSocketType["getCertificate"]>;
52
+ getPeerX509Certificate(): ReturnType<TLSSocketType["getPeerX509Certificate"]>;
53
+ renegotiate(options: {
54
+ rejectUnauthorized?: boolean | undefined;
55
+ requestCert?: boolean | undefined;
56
+ }, callback?: (error: Error | null) => void): boolean;
57
+ exportKeyingMaterial(length: number, label: string, context?: Buffer): Buffer;
58
+ }
59
+ export declare function TLSSocket(this: TLSSocket, socket: Socket | Duplex | undefined, opts: TLSSocket["_tlsOptions"]): void;
60
+ type NormalizedConnectionOptions = ConnectionOptions & SocketOptions & TlsOptions & {
61
+ host?: string;
62
+ port: number;
63
+ };
64
+ export declare function connect(...args: unknown[]): TLSSocket;
65
+ export {};
@@ -0,0 +1,544 @@
1
+ // @ts-nocheck
2
+ import { ERR_INVALID_ARG_TYPE } from "../net/errors.js";
3
+ import { isArrayBufferView } from "../util/types/index.js";
4
+ function validateBuffer(value, name) {
5
+ if (!isArrayBufferView(value))
6
+ throw new ERR_INVALID_ARG_TYPE(name, ["Buffer", "TypedArray", "DataView"], value);
7
+ }
8
+ import { socketReader } from "../net/reader.js";
9
+ // Copyright (c) 2017-2022 Cloudflare, Inc.
10
+ // Licensed under the Apache 2.0 license found in the LICENSE file or at:
11
+ // https://opensource.org/licenses/Apache-2.0
12
+ //
13
+ // Copyright Joyent, Inc. and other Node contributors.
14
+ //
15
+ // Permission is hereby granted, free of charge, to any person obtaining a
16
+ // copy of this software and associated documentation files (the
17
+ // "Software"), to deal in the Software without restriction, including
18
+ // without limitation the rights to use, copy, modify, merge, publish,
19
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
20
+ // persons to whom the Software is furnished to do so, subject to the
21
+ // following conditions:
22
+ //
23
+ // The above copyright notice and this permission notice shall be included
24
+ // in all copies or substantial portions of the Software.
25
+ //
26
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
27
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
29
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
30
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
31
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
32
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
33
+ import { Socket, _normalizeArgs, onConnectionOpened, onConnectionClosed, tryReadStart, } from "../net/internal-net.js";
34
+ import { JSStreamSocket } from "./jsstream.js";
35
+ import { validateString, validateObject, validateNumber, validateFunction, validateInt32, validateUint32, } from "../net/validators.js";
36
+ import { ConnResetException, ERR_TLS_HANDSHAKE_TIMEOUT, ERR_OPTION_NOT_IMPLEMENTED, ERR_TLS_INVALID_CONTEXT, ERR_METHOD_NOT_IMPLEMENTED, } from "./errors.js";
37
+ import { SecureContext } from "../tls-common/index.js";
38
+ const processImpl = { shouldThrowOnNotImplementedTlsOption: () => true };
39
+ import { ok } from "../assert/index.js";
40
+ const kConnectOptions = Symbol("connect-options");
41
+ const kErrorEmitted = Symbol("error-emitted");
42
+ const kRes = Symbol("res");
43
+ const kPendingSession = Symbol("pendingSession");
44
+ const kIsVerified = Symbol("verified");
45
+ function onnewsessionclient(_sessionId, session) {
46
+ if (this[kIsVerified]) {
47
+ this.emit("session", session);
48
+ }
49
+ else {
50
+ this[kPendingSession] = session;
51
+ }
52
+ }
53
+ function onerror(err) {
54
+ if (this._hadError)
55
+ return;
56
+ this._hadError = true;
57
+ // Destroy socket if error happened before handshake's finish
58
+ if (!this._secureEstablished) {
59
+ // When handshake fails control is not yet released,
60
+ // so self._tlsError will return null instead of actual error
61
+ // Set closing the socket after emitting an event since the socket needs to
62
+ // be accessible when the `tlsClientError` event is emitted.
63
+ this.destroy(err);
64
+ }
65
+ else {
66
+ // Emit error
67
+ this._emitTLSError(err);
68
+ }
69
+ }
70
+ // We are using old style function classes for node.js compat.
71
+ // @ts-expect-error TS2323 Cannot redeclare error.
72
+ export function TLSSocket(socket, opts) {
73
+ const tlsOptions = { ...opts };
74
+ if (tlsOptions.enableTrace) {
75
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.enableTrace");
76
+ }
77
+ if (tlsOptions.isServer) {
78
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.isServer");
79
+ }
80
+ if (tlsOptions.server) {
81
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.server");
82
+ }
83
+ if (tlsOptions.requestCert) {
84
+ // Servers will request certificate from clients.
85
+ // Does not apply to Cloudflare Workers.
86
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.requestCert");
87
+ }
88
+ if (tlsOptions.rejectUnauthorized === false) {
89
+ // TODO(soon): We don't support rejectUnauthorized=false
90
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.rejectUnauthorized");
91
+ }
92
+ if (tlsOptions.ALPNProtocols !== undefined) {
93
+ // Does not apply to Cloudflare Workers.
94
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.ALPNProtocols");
95
+ }
96
+ if (tlsOptions.SNICallback !== undefined) {
97
+ // Does not apply to Cloudflare Workers.
98
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.SNICallback");
99
+ }
100
+ if (tlsOptions.requestOCSP) {
101
+ // Not yet supported. Can be implemented in the future.
102
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.requestOCSP");
103
+ }
104
+ if (tlsOptions.secureContext !== undefined &&
105
+ !(tlsOptions.secureContext instanceof SecureContext)) {
106
+ throw new ERR_TLS_INVALID_CONTEXT("context");
107
+ }
108
+ if (tlsOptions.pskCallback !== undefined) {
109
+ // Used for TLS-PSK negotiation. We do not support it.
110
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.pskCallback");
111
+ }
112
+ // checkServerIdentity requires access to the peer certificate via
113
+ // getPeerCertificate(), which is not yet implemented. When the
114
+ // throw_on_not_implemented_tls_options compat flag is enabled we throw;
115
+ // otherwise we silently continue so that existing workers are not broken.
116
+ if (tlsOptions.checkServerIdentity !== undefined) {
117
+ validateFunction(tlsOptions.checkServerIdentity, "options.checkServerIdentity");
118
+ if (processImpl.shouldThrowOnNotImplementedTlsOption()) {
119
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.checkServerIdentity");
120
+ }
121
+ }
122
+ if (socket != null && !(socket instanceof Socket)) {
123
+ throw new ERR_METHOD_NOT_IMPLEMENTED("TLS upgrade of a custom Duplex");
124
+ }
125
+ if (socket instanceof Socket &&
126
+ (socket.destroyed ||
127
+ (socket._handle &&
128
+ (socket._handle.handedOver ||
129
+ socket._handle.socket.secureTransport !== "starttls")))) {
130
+ throw new ERR_METHOD_NOT_IMPLEMENTED("TLS upgrade of an unavailable socket");
131
+ }
132
+ this._tlsOptions = tlsOptions;
133
+ this._secureEstablished = false;
134
+ this._securePending = false;
135
+ this._newSessionPending = false;
136
+ this._controlReleased = false;
137
+ this.secureConnecting = true;
138
+ this.servername = tlsOptions.servername ?? null;
139
+ this.authorized = false;
140
+ this[kRes] = null;
141
+ this[kIsVerified] = false;
142
+ this[kPendingSession] = null;
143
+ this[kErrorEmitted] = false;
144
+ let wrap = null;
145
+ let handle = null;
146
+ let wrapHasActiveWriteFromPrevOwner = false;
147
+ if (socket) {
148
+ if (socket instanceof Socket) {
149
+ wrap = socket;
150
+ }
151
+ else {
152
+ wrap = new JSStreamSocket(socket);
153
+ }
154
+ handle = wrap._handle;
155
+ wrapHasActiveWriteFromPrevOwner = wrap.writableLength > 0;
156
+ }
157
+ // Just a documented property to make secure sockets
158
+ // distinguishable from regular ones.
159
+ this.encrypted = true;
160
+ Reflect.apply(Socket, this, [
161
+ {
162
+ handle: this._wrapHandle(wrap, handle, wrapHasActiveWriteFromPrevOwner),
163
+ allowHalfOpen: socket ? socket.allowHalfOpen : tlsOptions.allowHalfOpen,
164
+ pauseOnCreate: tlsOptions.pauseOnConnect,
165
+ manualStart: true,
166
+ highWaterMark: tlsOptions.highWaterMark,
167
+ onread: !socket ? tlsOptions.onread : null,
168
+ signal: tlsOptions.signal,
169
+ lookup: tlsOptions.lookup,
170
+ },
171
+ ]);
172
+ this._parent = handle;
173
+ this._parentWrap = wrap;
174
+ // Proxy for API compatibility
175
+ this.ssl = this._handle; // C++ TLSWrap object
176
+ this.on("error", this._tlsError.bind(this));
177
+ this._init();
178
+ if (socket != null) {
179
+ this.connecting = true;
180
+ queueMicrotask(() => {
181
+ this.connecting = false;
182
+ this._start();
183
+ });
184
+ }
185
+ }
186
+ Object.setPrototypeOf(TLSSocket.prototype, Socket.prototype);
187
+ Object.setPrototypeOf(TLSSocket, Socket);
188
+ TLSSocket.prototype.disableRenegotiation = function disableRenegotiation() {
189
+ // Do nothing.
190
+ };
191
+ TLSSocket.prototype._wrapHandle = function _wrapHandle(wrap, handle, _wrapHasActiveWriteFromPrevOwner) {
192
+ if (!handle) {
193
+ return null;
194
+ }
195
+ this[kRes] = handle;
196
+ // Guard against adding multiple listeners, as this method may be called
197
+ // repeatedly on the same socket by reinitializeHandle
198
+ if (this.listenerCount("close", onSocketCloseDestroySSL) === 0) {
199
+ this.once("close", onSocketCloseDestroySSL);
200
+ }
201
+ wrap?.once("close", () => this.destroy());
202
+ return handle;
203
+ };
204
+ function onSocketCloseDestroySSL() {
205
+ // We call destroySSL directly because it is already an async process.
206
+ this._destroySSL();
207
+ this[kRes] = null;
208
+ }
209
+ TLSSocket.prototype._destroySSL = function _destroySSL() {
210
+ // We disable floating promises rule because we don't want to change the
211
+ // function signature and return Promise<void>
212
+ //
213
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
214
+ this._handle?.socket.close().then(() => {
215
+ this[kPendingSession] = null;
216
+ this[kIsVerified] = false;
217
+ });
218
+ };
219
+ TLSSocket.prototype._init = function _init() {
220
+ const options = this._tlsOptions;
221
+ this.on("error", onerror.bind(this));
222
+ // This is emitted from net.Socket class.
223
+ this.on("connectionAttempt", onnewsessionclient.bind(this));
224
+ if (options.handshakeTimeout && options.handshakeTimeout > 0)
225
+ this.setTimeout(options.handshakeTimeout, this._handleTimeout.bind(this));
226
+ // TLSSocket can be initialized with 2 different handles.
227
+ //
228
+ // 1. Socket instance created by "node:net". In this scenario, we need
229
+ // to wait for 'connect' event to be emitted in order to trigger _finishInit().
230
+ // 2. Duplex stream. Duplex streams are initialized through JSStreamSocket class.
231
+ // If that's the scenario, we can trigger _finishInit() immediately. Since, there
232
+ // is no async calls required to wait.
233
+ if (this._parentWrap != null && this._parentWrap instanceof JSStreamSocket) {
234
+ queueMicrotask(() => {
235
+ this._finishInit();
236
+ ok(this._parentWrap instanceof JSStreamSocket);
237
+ this._parentWrap.readStart();
238
+ tryReadStart(this);
239
+ });
240
+ }
241
+ else {
242
+ this.on("connect", () => {
243
+ this._finishInit();
244
+ });
245
+ }
246
+ };
247
+ TLSSocket.prototype.renegotiate = function (options, callback) {
248
+ validateObject(options, "options");
249
+ if (callback !== undefined) {
250
+ validateFunction(callback, "callback");
251
+ }
252
+ // TLS renegotiation is not supported.
253
+ return false;
254
+ };
255
+ TLSSocket.prototype.exportKeyingMaterial = function exportKeyingMaterial(length, label, context) {
256
+ validateUint32(length, "length", true);
257
+ validateString(label, "label");
258
+ if (context !== undefined) {
259
+ validateBuffer(context, "context");
260
+ }
261
+ throw new Error("exportKeyingMaterial is not implemented");
262
+ };
263
+ TLSSocket.prototype.setMaxSendFragment = function setMaxSendFragment(size) {
264
+ validateInt32(size, "size");
265
+ // Setting maximum TLS fragment size is not supported.
266
+ return false;
267
+ };
268
+ TLSSocket.prototype._handleTimeout = function _handleTimeout() {
269
+ this._emitTLSError(new ERR_TLS_HANDSHAKE_TIMEOUT());
270
+ };
271
+ TLSSocket.prototype._emitTLSError = function _emitTLSError(err) {
272
+ const e = this._tlsError(err);
273
+ if (e)
274
+ this.emit("error", e);
275
+ };
276
+ TLSSocket.prototype._tlsError = function _tlsError(err) {
277
+ this.emit("_tlsError", err);
278
+ if (this._controlReleased)
279
+ return err;
280
+ return null;
281
+ };
282
+ TLSSocket.prototype._releaseControl = function _releaseControl() {
283
+ if (this._controlReleased)
284
+ return false;
285
+ this._controlReleased = true;
286
+ this.removeListener("error", this._tlsError.bind(this));
287
+ return true;
288
+ };
289
+ // This function is called from net.Socket onConnectionOpened() handler.
290
+ TLSSocket.prototype._finishInit = function _finishInit() {
291
+ // Guard against getting onhandshakedone() after .destroy().
292
+ // * 1.2: If destroy() during onocspresponse(), then write of next handshake
293
+ // record fails, the handshake done info callbacks does not occur, and the
294
+ // socket closes.
295
+ // * 1.3: The OCSP response comes in the same record that finishes handshake,
296
+ // so even after .destroy(), the handshake done info callback occurs
297
+ // immediately after onocspresponse(). Ignore it.
298
+ if (!this._handle)
299
+ return;
300
+ this._secureEstablished = true;
301
+ if (this._tlsOptions.handshakeTimeout &&
302
+ this._tlsOptions.handshakeTimeout > 0) {
303
+ this.setTimeout(0, this._handleTimeout.bind(this));
304
+ }
305
+ this.emit("secure");
306
+ };
307
+ TLSSocket.prototype._start = function _start() {
308
+ if (this.destroyed)
309
+ return;
310
+ if (this.connecting) {
311
+ this.once("connect", this._start.bind(this));
312
+ return;
313
+ }
314
+ // If a user calls tls.connect({ socket }) with a socket that is not initialized
315
+ // and the socket is not connected, we need to wait for the socket to connect
316
+ // before we can complete the process.
317
+ //
318
+ // Take a look at the following test for this particular edge case:
319
+ // https://github.com/nodejs/node/blob/91d8a524ada001103a2d1c6825ca17b8393c183f/test/parallel/test-tls-on-empty-socket.js
320
+ if (this._parentWrap != null && this._parentWrap._handle == null) {
321
+ this._parentWrap.once("connect", () => {
322
+ // We need to update the Socket handle of this TLSSocket
323
+ // since it was created after TLSSocket is initialized.
324
+ if (this._parentWrap?._handle != null) {
325
+ this._handle = this._parentWrap._handle;
326
+ }
327
+ this._start();
328
+ });
329
+ return;
330
+ }
331
+ // Guard against the following cases:
332
+ // - Socket was destroyed before the connection was established
333
+ // - TLSSocket can not be upgraded if the secureTransport does not support 'starttls'
334
+ if (this._handle?.socket.secureTransport !== "starttls") {
335
+ return;
336
+ }
337
+ // The connection moves to a new handle: the read loop's pending read on
338
+ // this one is about to reject, which it must not take for a failure.
339
+ this._handle.handedOver = true;
340
+ this._handle.writer.releaseLock();
341
+ this._handle.reader.releaseLock();
342
+ try {
343
+ const { host, port, addressType } = this._handle.options;
344
+ const tlsOpts = this.servername != null
345
+ ? { expectedServerHostname: this.servername }
346
+ : undefined;
347
+ const socket = this._handle.socket.startTls(tlsOpts);
348
+ this._handle = {
349
+ socket: socket,
350
+ writer: socket.writable.getWriter(),
351
+ reader: socketReader(socket.readable),
352
+ bytesRead: 0,
353
+ bytesWritten: 0,
354
+ reading: false,
355
+ options: this._handle.options,
356
+ };
357
+ // This is now an encrypted connection.
358
+ // There are cases where in node:net we have to distinguish between
359
+ // encrypted and unencrypted connections.
360
+ this.encrypted = true;
361
+ this._handle.socket.opened.then(onConnectionOpened.bind(this), (err) => {
362
+ this.emit("connectionAttemptFailed", host, port, addressType, err);
363
+ this.destroy(err);
364
+ });
365
+ this._handle.socket.closed.then(onConnectionClosed.bind(this), (error) => {
366
+ // Do not call this.destroy.bind(this) since user can override it.
367
+ this.destroy(error);
368
+ });
369
+ }
370
+ catch (error) {
371
+ this.destroy(error);
372
+ }
373
+ };
374
+ TLSSocket.prototype.setServername = function setServername(name) {
375
+ validateString(name, "name");
376
+ this.servername = name;
377
+ };
378
+ TLSSocket.prototype.setSession = function (_session) {
379
+ // Do nothing. We don't support setting session.
380
+ };
381
+ // @ts-expect-error TS2322 Inconsistencies between @types/node
382
+ TLSSocket.prototype.getPeerCertificate = function (_detailed) {
383
+ // Returns an object representing a peer certificate.
384
+ // This function is not supported.
385
+ throw new Error("getPeerCertificate is not implemented");
386
+ };
387
+ TLSSocket.prototype.getCertificate = function () {
388
+ // Returns an object representing the local certificate.
389
+ // This function is not supported.
390
+ throw new Error("TLSSocket.getCertificate is not implemented");
391
+ };
392
+ TLSSocket.prototype.getPeerX509Certificate = function (_detailed) {
393
+ // Returns the peer certificate as an X509 certificate.
394
+ // This function is not supported.
395
+ throw new Error("TLSSocket.getPeerX509Certificate is not implemented");
396
+ };
397
+ TLSSocket.prototype.getX509Certificate = function () {
398
+ // Returns the local certificate as an X509 certificate.
399
+ // This function is not supported.
400
+ throw new Error("TLSSocket.getX509Certificate is not implemented");
401
+ };
402
+ TLSSocket.prototype.setKeyCert = function (_context) {
403
+ // Changing private key and certificate to be used with TCP connection
404
+ // is not supported due to the limitations of connect() api.
405
+ throw new Error("TLSSocket.setKeyCert is not implemented");
406
+ };
407
+ // We have this syntax because of the original Node.js implementation.
408
+ // They are not supported by Cloudflare Workers but in Node.js
409
+ // they are all properties of this._handle[PROP_NAME]
410
+ [
411
+ "getCipher",
412
+ "getSharedSigalgs",
413
+ "getEphemeralKeyInfo",
414
+ "getFinished",
415
+ "getPeerFinished",
416
+ "getProtocol",
417
+ "getSession",
418
+ "getTLSTicket",
419
+ "isSessionReused",
420
+ "enableTrace",
421
+ ].forEach((method) => {
422
+ // @ts-expect-error TS7053 Omitting...
423
+ TLSSocket.prototype[method] = function () {
424
+ // None of these functions are supported by connect() api.
425
+ return null;
426
+ };
427
+ });
428
+ function normalizeConnectArgs(listArgs) {
429
+ const args = _normalizeArgs(listArgs);
430
+ const options = args[0];
431
+ const cb = args[1];
432
+ // If args[0] was options, then normalize dealt with it.
433
+ // If args[0] is port, or args[0], args[1] is host, port, we need to
434
+ // find the options and merge them in, normalize's options has only
435
+ // the host/port/path args that it knows about, not the tls options.
436
+ // This means that options.host overrides a host arg.
437
+ if (listArgs[1] !== null && typeof listArgs[1] === "object") {
438
+ Object.assign(options, listArgs[1]);
439
+ }
440
+ else if (listArgs[2] !== null && typeof listArgs[2] === "object") {
441
+ Object.assign(options, listArgs[2]);
442
+ }
443
+ return cb ? [options, cb] : [options];
444
+ }
445
+ function onConnectSecure() {
446
+ this.authorized = true;
447
+ this.secureConnecting = false;
448
+ this.emit("secureConnect");
449
+ this[kIsVerified] = true;
450
+ const session = this[kPendingSession];
451
+ this[kPendingSession] = null;
452
+ if (session)
453
+ this.emit("session", session);
454
+ this.removeListener("end", onConnectEnd);
455
+ }
456
+ function onConnectEnd() {
457
+ // NOTE: This logic is shared with _http_client.js
458
+ if (!this._hadError) {
459
+ const options = this[kConnectOptions];
460
+ this._hadError = true;
461
+ const error = new ConnResetException("Client network socket disconnected " +
462
+ "before secure TLS connection was " +
463
+ "established");
464
+ error.path = options?.path;
465
+ error.host = options?.host;
466
+ error.port = options?.port;
467
+ // @ts-expect-error TS2339 Missing types
468
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
469
+ error.localAddress = options?.localAddress;
470
+ this.destroy(error);
471
+ }
472
+ }
473
+ // Arguments: [port,] [host,] [options,] [cb]
474
+ export function connect(...args) {
475
+ args = normalizeConnectArgs(args);
476
+ const options = args[0];
477
+ const cb = args[1];
478
+ if (options.minDHSize !== undefined) {
479
+ // We leave this validation for node.js compat.
480
+ validateNumber(options.minDHSize, "options.minDHSize", 1);
481
+ // Not supported.
482
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.minDHSize");
483
+ }
484
+ if (options.rejectUnauthorized === false) {
485
+ // TODO(soon): We don't support rejectUnauthorized=false
486
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.rejectUnauthorized");
487
+ }
488
+ if (options.pskCallback !== undefined) {
489
+ // Used for TLS-PSK negotiation.
490
+ // Does not make sense for Cloudflare Workers.
491
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.pskCallback");
492
+ }
493
+ if (options.checkServerIdentity !== undefined) {
494
+ validateFunction(options.checkServerIdentity, "options.checkServerIdentity");
495
+ if (processImpl.shouldThrowOnNotImplementedTlsOption()) {
496
+ throw new ERR_OPTION_NOT_IMPLEMENTED("options.checkServerIdentity");
497
+ }
498
+ }
499
+ // @ts-expect-error TS2345 Type incompatibility between Node.js Duplex and internal Duplex
500
+ const tlssock = new TLSSocket(options.socket, {
501
+ allowHalfOpen: options.allowHalfOpen,
502
+ pipe: !!options.path,
503
+ ALPNProtocols: options.ALPNProtocols,
504
+ enableTrace: options.enableTrace,
505
+ highWaterMark: options.highWaterMark,
506
+ secureContext: options.secureContext,
507
+ onread: options.onread,
508
+ signal: options.signal,
509
+ lookup: options.lookup,
510
+ rejectUnauthorized: options.rejectUnauthorized !== undefined
511
+ ? Boolean(options.rejectUnauthorized) // eslint-disable-line @typescript-eslint/no-unnecessary-type-conversion
512
+ : true,
513
+ });
514
+ tlssock[kConnectOptions] = options;
515
+ // In Node.js, servername defaults to options.host when not explicitly set.
516
+ // Store it on the TLSSocket so _start() can pass it as expectedServerHostname
517
+ // to the native Socket.startTls() call for correct TLS certificate identity
518
+ // validation.
519
+ if (options.servername !== undefined) {
520
+ tlssock.servername = options.servername;
521
+ }
522
+ if (cb) {
523
+ tlssock.once("secureConnect", cb);
524
+ }
525
+ if (!options.socket) {
526
+ // If user provided the socket, it's their responsibility to manage its
527
+ // connectivity. If we created one internally, we connect it.
528
+ if (options.timeout) {
529
+ tlssock.setTimeout(options.timeout);
530
+ }
531
+ tlssock.connect(options, tlssock._start.bind(tlssock));
532
+ }
533
+ tlssock._releaseControl();
534
+ if (options.session) {
535
+ tlssock.setSession(options.session);
536
+ }
537
+ if (options.socket) {
538
+ tlssock._start();
539
+ }
540
+ // The 'secure' event is emitted by the SecurePair object once a secure connection has been established.
541
+ tlssock.on("secure", onConnectSecure);
542
+ tlssock.prependListener("end", onConnectEnd);
543
+ return tlssock;
544
+ }
@@ -0,0 +1,11 @@
1
+ # Upstream notices
2
+
3
+ This module ports Cloudflare workerd tag `v1.20261012.1`, revision
4
+ `5358e3d337336eaf696a48bc1563d808b10feba5`:
5
+
6
+ - `src/node/_tls_common.ts`
7
+ - `src/node/internal/internal_tls_common.ts`
8
+
9
+ Copyright Cloudflare, Inc.; Apache License 2.0. Node.js/Joyent MIT notices
10
+ are preserved in the source files. Imports, resource-management symbols and
11
+ host constructor references are adapted for the Capacitor runtime.