@morojs/engine 1.1.21 → 1.2.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 (4) hide show
  1. package/README.md +4 -0
  2. package/index.d.ts +134 -23
  3. package/index.js +258 -14
  4. package/package.json +8 -8
package/README.md CHANGED
@@ -86,6 +86,10 @@ updated** the way you keep Node.js updated; a TLS server on a build more than
86
86
  Node ABIs: 115/127/131/137/141/147 (Node 20/22/23/24/25/26). Any other
87
87
  platform/ABI falls back to Node's `http` server via MoroJS.
88
88
 
89
+ The glibc packages need glibc 2.28 or later, the same floor as Node.js's own
90
+ Linux binaries: RHEL, Rocky and Alma Linux 8 and later, Amazon Linux 2023,
91
+ Debian 10 and later, Ubuntu 20.04 and later.
92
+
89
93
  ## I/O transport
90
94
 
91
95
  On Linux the engine runs its own socket path on libuv's epoll by default
package/index.d.ts CHANGED
@@ -29,6 +29,9 @@ export interface EngineCapabilities {
29
29
  /** updateSsl() is available: the certificate/key (and policy) of a TLS
30
30
  * server can be replaced for new handshakes without a restart. */
31
31
  tlsReload: boolean;
32
+ /** ssl.crl and ssl.maxVersion are honoured (an engine without this flag
33
+ * reads neither). */
34
+ tlsCrl: boolean;
32
35
  /** setStaticRoute() / clearStaticRoutes() are available. */
33
36
  staticRoutes: boolean;
34
37
  /** setParamRoute() / clearParamRoutes() are available: a route with one
@@ -64,6 +67,21 @@ export interface EngineCapabilities {
64
67
  * exist: the engine can perform valid WebSocket upgrades itself, firing
65
68
  * onWsOpen without the request ever reaching onRequest. */
66
69
  wsAutoUpgrade: boolean;
70
+ /** Engine-side upgrades (setWsAutoUpgrade) are safe together with batched
71
+ * dispatch (onRequestBatch). Engines 1.1.15 to 1.1.21 report
72
+ * wsAutoUpgrade and batchDispatch without this flag and must not be given
73
+ * both: a process abort could occur there with pipelined WebSocket
74
+ * handshakes. */
75
+ wsAutoUpgradeBatch: boolean;
76
+ /** idleTimeoutMs does not close a connection whose response is still being
77
+ * written to a peer that is reading it, whether the handler answered
78
+ * before it returned or later; responseTimeoutMs governs delivery (and
79
+ * closes a peer that stops reading). Only with responseTimeoutMs set to 0
80
+ * does the idle timeout apply to such a connection. Engines without this
81
+ * flag (before 1.2.0) count a response given before the handler returned
82
+ * as idle from the moment it is framed, so an idle timeout shorter than a
83
+ * slow download cuts the download. */
84
+ idleSparesDrainingResponse: boolean;
67
85
  /** getBodyType() and getBodyText() exist. */
68
86
  bodyText: boolean;
69
87
  /** getBodyLent() exists. */
@@ -107,11 +125,24 @@ export interface EngineTlsInfo {
107
125
  fallbackReason?: string;
108
126
  }
109
127
 
128
+ /** The native binary that was loaded. */
129
+ export interface EngineBinaryInfo {
130
+ /** The `.node` file. */
131
+ path: string;
132
+ /** The version of the platform package it came from: the release the
133
+ * running code belongs to, always equal to `EngineProbeResult.version`
134
+ * (a platform package of another release is not loaded). Absent for a
135
+ * local build and for `MORO_ENGINE_BINARY`. */
136
+ version?: string;
137
+ }
138
+
110
139
  export interface EngineProbeResult {
111
140
  /** True when a native binary loaded for this platform/ABI */
112
141
  ok: boolean;
113
142
  /** Engine version — the published package version (always set by the loader). */
114
143
  version?: string;
144
+ /** Which binary is loaded, and from which release (`ok: true` only). */
145
+ binary?: EngineBinaryInfo;
115
146
  platform: string;
116
147
  arch: string;
117
148
  /** Node ABI (process.versions.modules) the binary was built for */
@@ -162,7 +193,11 @@ export interface ServeCallbacks {
162
193
  * that index, or return when it still equals the slot you just dispatched
163
194
  * (that handler is async; the remaining slots are delivered later). A
164
195
  * request that stands alone still arrives here with count 1; onRequest is
165
- * used only when this callback is absent. Return the slots consumed. */
196
+ * used only when this callback is absent. Return the slots consumed.
197
+ * `control[0]` at or above `count` means the batch is over: every slot was
198
+ * answered, the next request is a WebSocket handshake the engine answers
199
+ * itself (setWsAutoUpgrade), or the connection was closed from inside the
200
+ * loop - in each case, return. */
166
201
  onRequestBatch?(count: number): number;
167
202
  /** The client disconnected, or the engine tore the request down (write
168
203
  * error, responseBackpressureLimit, timeout, close()), before the response
@@ -186,7 +221,13 @@ export interface ServeCallbacks {
186
221
  * upgradeToWebSocket() call — so a client that pipelines its first frame with
187
222
  * the Upgrade is never dropped. */
188
223
  onWsMessage?(wsId: number, data: string | ArrayBuffer, isBinary: boolean): void;
189
- /** WebSocket closed (code per RFC 6455 §7.4). */
224
+ /** WebSocket closed (code per RFC 6455 §7.4): the peer's Close code (1005
225
+ * when its Close carried none), 1006 when it went away without one, the
226
+ * code of a protocol failure (1002, 1007, 1009), or the code wsClose() was
227
+ * called with, as passed. Fires exactly once per socket. Inside it the
228
+ * socket is already closing - wsSend() answers false and wsClose() does
229
+ * nothing - while wsGetHeaders(), wsGetQuery() and wsGetRemoteAddress()
230
+ * still answer. */
190
231
  onWsClose?(wsId: number, code: number): void;
191
232
  }
192
233
 
@@ -195,13 +236,17 @@ export interface ServeOptions {
195
236
  maxBodySize?: number;
196
237
  /** Close a connection after this many ms with no bytes received while not
197
238
  * running a handler (slowloris defense + keep-alive cap). 0 disables.
198
- * Default 120000. */
239
+ * Default 120000. A connection whose response is still being written to
240
+ * the peer is not idle: responseTimeoutMs governs it, unless that is 0
241
+ * (capabilities.idleSparesDrainingResponse). */
199
242
  idleTimeoutMs?: number;
200
243
  /** Max simultaneous connections; accepts beyond this are dropped
201
244
  * immediately (connection-flood defense). 0 = unlimited (default). */
202
245
  maxConnections?: number;
203
- /** Cap on bytes buffered for one connection while its response is in flight
204
- * (pipelined-flood defense). 0 = maxHeadSize + maxBodySize (default). */
246
+ /** Cap on bytes buffered for one connection while they cannot be
247
+ * dispatched: a handler is running, or the responses already given are
248
+ * waiting on the peer (pipelined-flood defense). Over it the connection is
249
+ * closed. 0 = maxHeadSize + maxBodySize (default). */
205
250
  maxPendingBytes?: number;
206
251
  /** Budget in ms for receiving one complete request (head + body), measured
207
252
  * from its first byte. Unlike idleTimeoutMs it does NOT reset on activity,
@@ -242,12 +287,26 @@ export interface ServeOptions {
242
287
  /** Cap on a complete (reassembled) WebSocket message; larger messages fail
243
288
  * the connection with close code 1009. Must be > 0. Default 16 MiB. */
244
289
  wsMaxMessageSize?: number;
245
- /** WebSocket send backpressure cap: a slow consumer whose write queue grows
246
- * past this is shed with close code 1013 rather than buffering without
247
- * bound. 0 = unlimited. Default 1 MiB. */
290
+ /** WebSocket send backpressure cap: a consumer that is not keeping up is
291
+ * shed with close code 1013 rather than buffered without bound. A socket
292
+ * is shed by a wsSend() that finds bytes of an earlier send still waiting
293
+ * and leaves more than this many bytes queued. One message sent to a
294
+ * socket with nothing waiting is never shed for its size: it is queued
295
+ * whole and the socket stays open; a peer that stops reading with it in
296
+ * flight is closed by responseTimeoutMs. A stalled peer can therefore
297
+ * hold this many bytes across sends, or the largest single message the
298
+ * application sends, whichever is larger - the engine does not cap the
299
+ * size of one message, so an application sending very large ones to
300
+ * untrusted peers should bound them. On Windows the system takes the
301
+ * first two sends outstanding on a socket whole into its buffer and
302
+ * reports them sent: they are not counted here and responseTimeoutMs does
303
+ * not time them (docs/API.md, send backpressure). 0 = unlimited. Default
304
+ * 1 MiB. */
248
305
  wsBackpressureLimit?: number;
249
306
  /** Write-queue level above which write()/wsSend() report backpressure
250
- * (false) and onWritable is armed. Must be > 0. Default 262144. */
307
+ * (false) and onWritable is armed, and at which no further pipelined
308
+ * request is taken from a connection until the peer has read. Must be
309
+ * > 0. Default 262144. */
251
310
  writeHighWaterMark?: number;
252
311
  /** TCP listen backlog handed to the kernel. Must be > 0. Default 512. */
253
312
  backlog?: number;
@@ -263,15 +322,30 @@ export interface ServeOptions {
263
322
  key?: string | ArrayBuffer | Uint8Array;
264
323
  cert?: string | ArrayBuffer | Uint8Array;
265
324
  ca?: string | ArrayBuffer | Uint8Array;
325
+ /** Certificate revocation lists (PEM, one or more) for client
326
+ * certificates, as Node's tls `crl` (feature-detect via
327
+ * probe().capabilities.tlsCrl). With any given, a client certificate is
328
+ * accepted only when the CRL of every CA in its chain is here and does
329
+ * not list it. */
330
+ crl?: string | ArrayBuffer | Uint8Array;
266
331
  /** Decrypts an encrypted private key */
267
332
  passphrase?: string;
268
333
  /** Session-ticket keys, Node tls.Server-compatible: exactly 48 bytes
269
334
  * (16-byte key name + 16-byte HMAC secret + 16-byte AES key). Share the
270
335
  * same buffer across reusePort workers / processes so TLS sessions
271
- * resume across all of them. Rotation is the caller's job. */
336
+ * resume across all of them. Rotation is the caller's job. A session
337
+ * is resumed only by a server with the same policy as the one that
338
+ * issued it - minVersion, ciphers, ciphersuites, and requestCert /
339
+ * rejectUnauthorized / the CA certificates: sharing the keys with a
340
+ * listener that asks for no client certificate does not let its
341
+ * sessions into one that requires them. */
272
342
  ticketKeys?: string | ArrayBuffer | Uint8Array;
273
- /** Protocol floor. Default 'TLSv1.2'. */
343
+ /** Protocol floor. Default 'TLSv1.2' - or 'TLSv1.3' when node was
344
+ * started with --tls-min-v1.3 (tls.DEFAULT_MIN_VERSION). */
274
345
  minVersion?: 'TLSv1.2' | 'TLSv1.3';
346
+ /** Protocol ceiling. Default: the newest the TLS library has - or
347
+ * 'TLSv1.2' when node was started with --tls-max-v1.2. */
348
+ maxVersion?: 'TLSv1.2' | 'TLSv1.3';
275
349
  /** Request a client certificate (mutual TLS) */
276
350
  requestCert?: boolean;
277
351
  /** Fail the handshake when the client cert doesn't verify (default true) */
@@ -279,7 +353,10 @@ export interface ServeOptions {
279
353
  /** Explicit cipher/group policy for compliance baselines (PCI/FIPS/hardened
280
354
  * profiles; feature-detect via probe().capabilities.tlsPolicy). Same
281
355
  * semantics as Node's tls.createSecureContext; invalid values THROW from
282
- * serve(). Unset: the TLS library's own set of ciphers, AES-128-GCM ahead
356
+ * serve(). A value of the wrong type throws too, here and for every
357
+ * other policy option (`requestCert: 1` is an error, not "off").
358
+ * Unset: the list node was started with (--tls-cipher-list), else the
359
+ * TLS library's own set of ciphers, AES-128-GCM ahead
283
360
  * of AES-256-GCM, ChaCha20 for a client that lists it first. With the
284
361
  * bundled BoringSSL (probe().tls.library) `ciphersuites` can name
285
362
  * TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384 and
@@ -318,8 +395,11 @@ export interface ServeOptions {
318
395
  | {
319
396
  serverNoContextTakeover?: boolean;
320
397
  clientNoContextTakeover?: boolean;
321
- serverMaxWindowBits?: number; // 8..15
322
- clientMaxWindowBits?: number; // 8..15
398
+ /** 9..15. An 8-bit window is never negotiated: zlib's raw deflate
399
+ * has none, so an offer asking for one is declined. */
400
+ serverMaxWindowBits?: number;
401
+ /** 9..15 (see serverMaxWindowBits). */
402
+ clientMaxWindowBits?: number;
323
403
  /** Min message bytes before a send is compressed. Default 1024. */
324
404
  threshold?: number;
325
405
  /** Hard cap on an inflated message (zip-bomb defense).
@@ -341,7 +421,9 @@ type BodyInit = string | ArrayBuffer | Uint8Array | Buffer;
341
421
 
342
422
  /** Register callbacks and create a server. Sockets open only at listen(). */
343
423
  export function serve(callbacks: ServeCallbacks, options?: ServeOptions): number;
344
- /** Bind + listen; returns the actual bound port (supports port 0). Throws on failure. */
424
+ /** Bind + listen; returns the actual bound port (supports port 0). Throws on
425
+ * failure, with a libuv-style `code`. A server listens once: EINVAL for one
426
+ * that is already listening, has stopped listening or is closing. */
345
427
  export function listen(serverId: number, host: string, port: number): number;
346
428
  /** Tear down the server: stop accepting AND close every live connection
347
429
  * (in-flight requests get onAborted). For a graceful shutdown, call
@@ -354,7 +436,9 @@ export function stopListening(serverId: number): void;
354
436
  * handshake from now on, without restarting the listener (feature-detect via
355
437
  * probe().capabilities.tlsReload). `ssl` is the full ServeOptions.ssl shape,
356
438
  * not a diff; ticketKeys carry over when omitted so session resumption
357
- * survives a rotation. Established connections keep the context they
439
+ * survives a rotation of the certificate (an update that changes the
440
+ * policy - minVersion, ciphers, the client-certificate settings or CAs -
441
+ * ends it: those clients get a full handshake). Established connections keep the context they
358
442
  * handshaked with. Throws (leaving the current context in place) on invalid
359
443
  * material, and for a server that was not started with ssl. */
360
444
  export function updateSsl(serverId: number, ssl: NonNullable<ServeOptions['ssl']>): void;
@@ -398,7 +482,14 @@ export function getBodyText(reqId: number): string | null;
398
482
  * rate out of back-to-back full collections. For a handler that relays,
399
483
  * hashes or echoes a body and keeps none of it. Code that keeps the body
400
484
  * past the response reads it with getBody (a copy, during a loan) or
401
- * transfers the lent buffer. Null when there is no body. */
485
+ * transfers the lent buffer. Null when there is no body.
486
+ *
487
+ * "Keeps none of it" includes work in progress. An asynchronous operation
488
+ * that was handed the bytes - fs.write, a socket or stream write that did
489
+ * not go out at once, a zlib or crypto job - keeps a pointer to the memory,
490
+ * not the buffer: if the response is completed before it has finished, it
491
+ * reads memory that is free or already holds another request's body. Wait
492
+ * for it before responding, or read the body with getBody. */
402
493
  export function getBodyLent(reqId: number): ArrayBuffer | null;
403
494
  export function getRemoteAddress(reqId: number): string;
404
495
  export function isAborted(reqId: number): boolean;
@@ -495,17 +586,37 @@ export function endWith(reqId: number, chunk: BodyInit): void;
495
586
  // ---- WebSocket (RFC 6455) ----
496
587
  /** Upgrade the request's connection; returns wsId, or -1 if not a valid upgrade.
497
588
  * onWsOpen (and any early frames pipelined in the handshake's TCP segment, via
498
- * onWsMessage) fire SYNCHRONOUSLY during this call, before it returns. */
589
+ * onWsMessage) fire SYNCHRONOUSLY during this call, before it returns.
590
+ * A valid upgrade (RFC 6455 §4.2.1) is a GET over HTTP/1.1 with
591
+ * `Upgrade: websocket`, `Connection: Upgrade`, exactly one Sec-WebSocket-Key
592
+ * (16 bytes, base64) and exactly one `Sec-WebSocket-Version: 13`. After -1
593
+ * the request is still open and the caller answers it (a handshake whose
594
+ * only fault is its version is owed a 426 with `Sec-WebSocket-Version: 13`,
595
+ * which setWsAutoUpgrade sends by itself). */
499
596
  export function upgradeToWebSocket(reqId: number): number;
500
- /** Send a frame; returns false on backpressure. */
597
+ /** Send a frame. false when it did not go out - the socket is gone or
598
+ * closing, or `data` is not a string or bytes - and on backpressure (the
599
+ * frame is queued, the write queue is over writeHighWaterMark). */
501
600
  export function wsSend(wsId: number, data: string | ArrayBuffer | Uint8Array | Buffer, isBinary: boolean): boolean;
502
- /** Send a Close frame and close the connection. */
601
+ /** Send a Close frame (code 1000 unless given) and end the connection: the
602
+ * server half-closes and reads until the peer has closed too (at most two
603
+ * seconds), so the peer receives the Close even while it is still sending;
604
+ * a TLS connection is closed after its close_notify. The frame is legal
605
+ * whatever is passed: a `code` that may not appear on the wire (RFC 6455
606
+ * §7.4) is replaced - 1005 by a Close without a status, any other
607
+ * (1004, 1006, 1015, below 1000, 1016-2999, 5000 and up) by 1011 - and
608
+ * `reason` is cut to 123 bytes of UTF-8 at a character boundary. onWsClose
609
+ * reports `code` as passed. */
503
610
  export function wsClose(wsId: number, code?: number, reason?: string): void;
504
611
  /** With `on`, every valid WebSocket handshake is answered by the engine itself:
505
612
  * the 101 goes out, onWsOpen fires (and any frames pipelined with the
506
- * handshake reach onWsMessage), and onRequest is never called for it. An
507
- * invalid handshake is surfaced to onRequest as any other request. Applies
508
- * to this server only; register it again after close() + serve(). */
613
+ * handshake reach onWsMessage), and onRequest is never called for it. A
614
+ * handshake that is valid except for its Sec-WebSocket-Version is answered
615
+ * too: 426 with `Sec-WebSocket-Version: 13` (RFC 6455 §4.4). Any other
616
+ * request - not a GET, HTTP/1.0, a missing or repeated key - is surfaced to
617
+ * onRequest as an ordinary request. Applies to this server only; register
618
+ * it again after close() + serve(). Together with onRequestBatch only on an
619
+ * engine that reports capabilities.wsAutoUpgradeBatch. */
509
620
  export function setWsAutoUpgrade(serverId: number, on: boolean): void;
510
621
  /** The handshake request's headers, flat [name, value, ...] with names
511
622
  * lowercased (the shape getHeaders() gives), kept for the socket's lifetime;
package/index.js CHANGED
@@ -4,7 +4,8 @@
4
4
  // Resolution order:
5
5
  // 1. The matching per-platform package (@morojs/engine-<platform>-<arch>[-libc])
6
6
  // published as an exact-version optionalDependency of this package.
7
- // 2. A local build/ directory (engine repo development).
7
+ // 2. A local build/ directory, when running from the engine repository
8
+ // itself (development).
8
9
  //
9
10
  // Binary naming: moro_engine_<platform>_<arch>[_<libc>]_<abi>[_boringssl].node
10
11
  // (libc segment on linux only: gnu | musl)
@@ -17,7 +18,7 @@
17
18
  // when the BoringSSL binary cannot be loaded. See tlsPreference() below.
18
19
 
19
20
  const { existsSync } = require('fs');
20
- const { join } = require('path');
21
+ const { join, dirname, sep } = require('path');
21
22
 
22
23
  // The engine version is whatever this package publishes: tools/prepare-release.mjs
23
24
  // stamps package.json from the release tag, so reading it here keeps probe() and
@@ -75,11 +76,35 @@ let plannedSsl = null;
75
76
  // provider module, a policy file - and the bundled BoringSSL knows none of it.
76
77
  const OPENSSL_NODE_FLAGS = ['--enable-fips', '--force-fips', '--openssl-config', '--openssl-shared-config', '--openssl-legacy-provider'];
77
78
 
79
+ // The same options given through node's configuration file
80
+ // (--experimental-config-file=<path>, or node.config.json in the working
81
+ // directory with --experimental-default-config-file): they take effect like
82
+ // the flags and appear in neither execArgv nor NODE_OPTIONS.
83
+ function opensslOptionInNodeConfigFile(flags) {
84
+ let file = null;
85
+ const named = /--experimental-config-file(?:=|\s+)("[^"]+"|'[^']+'|\S+)/.exec(flags);
86
+ if (named) file = named[1].replace(/^["']|["']$/g, '');
87
+ else if (flags.includes('--experimental-default-config-file')) file = 'node.config.json';
88
+ if (!file) return null;
89
+ try {
90
+ const options = JSON.parse(require('fs').readFileSync(file, 'utf8')).nodeOptions || {};
91
+ for (const flag of OPENSSL_NODE_FLAGS) {
92
+ const value = options[flag.slice(2)];
93
+ if (value !== undefined && value !== false) return `${flag} in ${file}`;
94
+ }
95
+ } catch {
96
+ // unreadable here: node has already refused to start on a file it cannot read
97
+ }
98
+ return null;
99
+ }
100
+
78
101
  function opensslIsConfigured() {
79
102
  const flags = `${process.execArgv.join(' ')} ${process.env.NODE_OPTIONS || ''}`;
80
103
  for (const flag of OPENSSL_NODE_FLAGS) {
81
104
  if (flags.includes(flag)) return flag;
82
105
  }
106
+ const fromFile = opensslOptionInNodeConfigFile(flags);
107
+ if (fromFile) return fromFile;
83
108
  if (process.env.OPENSSL_CONF) return 'OPENSSL_CONF';
84
109
  if (process.env.OPENSSL_MODULES) return 'OPENSSL_MODULES';
85
110
  try {
@@ -127,16 +152,26 @@ function loadNamed(name, attempts) {
127
152
  // 1. Per-platform npm package
128
153
  const pkg = platformPackageName();
129
154
  try {
130
- return { module: require(require.resolve(`${pkg}/${name}`)), from: pkg };
155
+ const path = resolveInInstall(pkg, name);
156
+ const packageVersion = packageVersionAt(dirname(path));
157
+ // The binaries of another release are not this package's to run: the
158
+ // two are published together and pinned to each other.
159
+ if (packageVersion && packageVersion !== ENGINE_VERSION) {
160
+ throw new Error(`found ${path}, which is ${pkg} ${packageVersion}, not ${ENGINE_VERSION}: not loaded`);
161
+ }
162
+ return { module: require(path), from: pkg, path, packageVersion };
131
163
  } catch (err) {
132
164
  attempts.push(`${pkg}/${name}: ${err.message.split('\n')[0]}`);
133
165
  }
134
166
 
135
- // 2. Engine repo local build (development)
167
+ // 2. Engine repo local build (development). Only inside the engine
168
+ // repository: installed, the same relative path is node_modules/build,
169
+ // which belongs to whatever package is called "build".
170
+ if (!inEngineRepo()) return null;
136
171
  const local = join(__dirname, '..', '..', 'build', name);
137
172
  if (existsSync(local)) {
138
173
  try {
139
- return { module: require(local), from: local };
174
+ return { module: require(local), from: local, path: local };
140
175
  } catch (err) {
141
176
  attempts.push(`${local}: ${err.message.split('\n')[0]}`);
142
177
  }
@@ -146,6 +181,55 @@ function loadNamed(name, attempts) {
146
181
  return null;
147
182
  }
148
183
 
184
+ // Where a file of the platform package is, looked for only inside the
185
+ // node_modules tree this package was installed into: the node_modules of each
186
+ // directory from this one up to the outermost node_modules on this file's
187
+ // path. That is every place a package manager puts a dependency of this
188
+ // package (beside it, nested under it, hoisted above it, or linked next to it
189
+ // in a store). Plain module resolution would go on from there to the
190
+ // node_modules of every directory above the application, to NODE_PATH and to
191
+ // the home directory's module folders, and a native binary is not taken from
192
+ // a place the installation does not own. Outside a node_modules tree (the
193
+ // engine repository, a bundle), and under Yarn Plug'n'Play, where resolution
194
+ // is already limited to declared dependencies, it is plain resolution.
195
+ function resolveInInstall(pkg, name) {
196
+ const request = `${pkg}/${name}`;
197
+ const marker = `${sep}node_modules${sep}`;
198
+ const at = `${__dirname}${sep}`.indexOf(marker);
199
+ if (at === -1 || process.versions.pnp) return require.resolve(request);
200
+ const top = __dirname.slice(0, at + marker.length - 1); // .../node_modules
201
+ for (const dir of require.resolve.paths(request) || []) {
202
+ if (dir !== top && !dir.startsWith(top + sep)) continue;
203
+ const file = join(dir, pkg, name);
204
+ if (existsSync(file)) return file;
205
+ }
206
+ throw new Error(`not installed in ${top}`);
207
+ }
208
+
209
+ // The version stamped into the platform package in `dir` (the release
210
+ // assembler writes it; this package pins it exactly in optionalDependencies).
211
+ function packageVersionAt(dir) {
212
+ try {
213
+ return String(require(join(dir, 'package.json')).version || '') || null;
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+
219
+ // Whether this file is running from a checkout of the engine repository
220
+ // (packages/engine under the monorepo root), as opposed to an install.
221
+ let engineRepo;
222
+ function inEngineRepo() {
223
+ if (engineRepo === undefined) {
224
+ try {
225
+ engineRepo = require(join(__dirname, '..', '..', 'package.json')).name === '@morojs/engine-monorepo';
226
+ } catch {
227
+ engineRepo = false;
228
+ }
229
+ }
230
+ return engineRepo;
231
+ }
232
+
149
233
  function tryLoad() {
150
234
  const attempts = [];
151
235
 
@@ -157,7 +241,7 @@ function tryLoad() {
157
241
  const explicit = process.env.MORO_ENGINE_BINARY;
158
242
  if (explicit) {
159
243
  try {
160
- return { module: require(explicit), from: explicit };
244
+ return { module: require(explicit), from: explicit, path: explicit };
161
245
  } catch (err) {
162
246
  const error = new Error(`@morojs/engine: MORO_ENGINE_BINARY=${explicit} failed to load: ${err.message}`);
163
247
  error.code = 'MORO_ENGINE_BINARY_MISSING';
@@ -179,10 +263,11 @@ function tryLoad() {
179
263
  // for - an Ed448 or DSA key, a CCM suite, a brainpool group - worked on
180
264
  // node's OpenSSL up to 1.1.19, and keeps working there now.
181
265
  if (pref.library === 'boringssl' && !pref.explicit && plannedSsl) {
182
- const refused = tlsRefusal(first.module, plannedSsl);
266
+ const planned = withNodeTlsPolicy(plannedSsl);
267
+ const refused = tlsRefusal(first.module, planned);
183
268
  if (refused) {
184
269
  const other = loadNamed(binaryName('openssl'), []);
185
- if (other && !tlsRefusal(other.module, plannedSsl)) {
270
+ if (other && !tlsRefusal(other.module, planned)) {
186
271
  return { ...other, tls: { reason: 'fallback', fallbackReason: notAccepted(refused) } };
187
272
  }
188
273
  // Neither library takes it: the configuration is simply wrong, and
@@ -233,6 +318,14 @@ function loadBinding() {
233
318
  return loaded.module;
234
319
  }
235
320
 
321
+ // probe().binary: the file that was loaded and, when it came from a platform
322
+ // package, that package's version - the release the running code belongs to.
323
+ function binaryInfo() {
324
+ const info = { path: loaded.path };
325
+ if (loaded.packageVersion) info.version = loaded.packageVersion;
326
+ return info;
327
+ }
328
+
236
329
  /**
237
330
  * Non-throwing diagnostics: can the engine load here, and what is it?
238
331
  * MoroJS's preflight uses this instead of exception-driven detection.
@@ -252,7 +345,7 @@ function probe() {
252
345
  // package.json is the source of truth for the version (see ENGINE_VERSION);
253
346
  // override the binding's build-time constant so the two can never disagree.
254
347
  const native = loaded.module.probe();
255
- return { ...native, version: ENGINE_VERSION, tls: tlsInfo(native) };
348
+ return { ...native, version: ENGINE_VERSION, tls: tlsInfo(native), binary: binaryInfo() };
256
349
  }
257
350
 
258
351
  // `0.YYYYMMDD.N`, BoringSSL's version tags: the day upstream cut the snapshot.
@@ -350,7 +443,7 @@ function warnIfBundledTlsIsOld(binding) {
350
443
  let serversCreated = 0;
351
444
  const handedOut = new Set();
352
445
 
353
- function serveOnOpenSslInstead(error, self, args) {
446
+ function serveOnOpenSslInstead(error, self, argsFor) {
354
447
  if (!loaded.tls || loaded.tls.reason !== 'default') return undefined; // chosen by name, or not BoringSSL
355
448
  if (serversCreated > 0 || handedOut.size > 0) {
356
449
  error.message += ` [TLS library: the bundled BoringSSL. If node's OpenSSL accepts this configuration, MORO_ENGINE_TLS=openssl selects it.]`;
@@ -360,7 +453,7 @@ function serveOnOpenSslInstead(error, self, args) {
360
453
  if (!other) return undefined;
361
454
  let serverId;
362
455
  try {
363
- serverId = other.module.serve.apply(self, args);
456
+ serverId = other.module.serve.apply(self, argsFor(other.module));
364
457
  } catch {
365
458
  return undefined; // wrong for both libraries: the first error stands
366
459
  }
@@ -370,14 +463,159 @@ function serveOnOpenSslInstead(error, self, args) {
370
463
 
371
464
  let tlsAgeChecked = false;
372
465
 
466
+ // What the operator told node about every TLS server of the process, applied
467
+ // to an ssl options object that does not say otherwise: `node --tls-min-v1.3`
468
+ // (tls.DEFAULT_MIN_VERSION) raises the protocol floor, `node --tls-max-v1.2`
469
+ // (tls.DEFAULT_MAX_VERSION) lowers the ceiling, and
470
+ // `node --tls-cipher-list=...` (tls.DEFAULT_CIPHERS) is the cipher list, its
471
+ // TLS 1.3 suite names going to `ciphersuites` as node itself splits them.
472
+ // node's own servers obey both; a server here that did not would accept what
473
+ // the operator ruled out, and say nothing. The app's own minVersion,
474
+ // maxVersion, ciphers or ciphersuites win, as they do for node. Returns `ssl`
475
+ // itself when there is nothing to add.
476
+ function withNodeTlsPolicy(ssl) {
477
+ if (!ssl || typeof ssl !== 'object') return ssl;
478
+ let nodeTls;
479
+ try {
480
+ nodeTls = require('tls');
481
+ } catch {
482
+ return ssl; // a node built without crypto
483
+ }
484
+ let out = ssl;
485
+ if (ssl.minVersion == null && nodeTls.DEFAULT_MIN_VERSION === 'TLSv1.3') {
486
+ out = { ...out, minVersion: 'TLSv1.3' };
487
+ }
488
+ if (ssl.maxVersion == null && ssl.minVersion !== 'TLSv1.3' && nodeTls.DEFAULT_MAX_VERSION === 'TLSv1.2') {
489
+ out = { ...out, maxVersion: 'TLSv1.2' };
490
+ }
491
+ // A list other than the one compiled into node: the flag was given (or
492
+ // the app assigned tls.DEFAULT_CIPHERS). Asked this way and not of
493
+ // execArgv, where a test runner repeats every option with its default.
494
+ let builtIn;
495
+ try {
496
+ builtIn = require('crypto').constants.defaultCoreCipherList;
497
+ } catch {
498
+ builtIn = undefined;
499
+ }
500
+ const listed = nodeTls.DEFAULT_CIPHERS;
501
+ if (ssl.ciphers == null && ssl.ciphersuites == null && typeof listed === 'string' && typeof builtIn === 'string' && listed !== builtIn) {
502
+ const names = listed.split(':').filter(Boolean);
503
+ const suites = names.filter((name) => name.startsWith('TLS_'));
504
+ const list = names.filter((name) => !name.startsWith('TLS_'));
505
+ if (suites.length) out = { ...out, ciphersuites: suites.join(':') };
506
+ if (list.length) out = { ...out, ciphers: list.join(':') };
507
+ }
508
+ return out;
509
+ }
510
+
511
+ // ---- dispatch trampolines ---------------------------------------------------
512
+ //
513
+ // onRequest, onRequestBatch, onAborted and onWritable reach the engine wrapped
514
+ // in one of the functions below. The engine enters them through
515
+ // node::MakeCallback, which keeps Node's callback scope on the native stack
516
+ // (a scope opened around a plain call is allocated per call), and for that
517
+ // has no exception handler of its own around the call. So the wrapper does
518
+ // what the engine's native handler did: an exception the application's
519
+ // callback throws is reported on stderr (the same line) and goes no further,
520
+ // and the batch wrapper tells the engine that the application has left its
521
+ // loop over the batch before anything queued by the handlers runs. Nothing
522
+ // else changes for the callback: it is called with the same arguments and
523
+ // with `this` the global object, and what a nextTick callback or a microtask
524
+ // it queued throws is the process's uncaught exception, as before. A stack
525
+ // trace taken inside it has this file's frame below it.
526
+ //
527
+ // MORO_ENGINE_DISPATCH=scope turns the wrapping off (diagnostics): the engine
528
+ // then opens the scope and catches natively, as it does for callbacks handed
529
+ // to the binding directly.
530
+ const DISPATCH_TRAMPOLINES = process.env.MORO_ENGINE_DISPATCH !== 'scope';
531
+ const ReflectApply = Reflect.apply;
532
+ const FunctionPrototypeBind = Function.prototype.bind;
533
+ // The callback, called on the global object whatever it is called on.
534
+ const onGlobal = (cb) => ReflectApply(FunctionPrototypeBind, cb, [globalThis]);
535
+
536
+ function requestTrampoline(cb, report) {
537
+ const call = onGlobal(cb);
538
+ return function dispatchRequest(reqId, methodIdx, path) {
539
+ try {
540
+ call(reqId, methodIdx, path);
541
+ } catch (error) {
542
+ report(0, error);
543
+ }
544
+ };
545
+ }
546
+
547
+ function noticeTrampoline(cb, report) {
548
+ const call = onGlobal(cb);
549
+ return function dispatchNotice(reqId) {
550
+ try {
551
+ call(reqId);
552
+ } catch (error) {
553
+ report(0, error);
554
+ }
555
+ };
556
+ }
557
+
558
+ function batchTrampoline(cb, report, batchDone) {
559
+ const call = onGlobal(cb);
560
+ return function dispatchBatch(count) {
561
+ try {
562
+ call(count);
563
+ } catch (error) {
564
+ batchDone();
565
+ report(1, error);
566
+ return;
567
+ }
568
+ batchDone();
569
+ };
570
+ }
571
+
572
+ // The callbacks object serve() hands to `binding`: each property read once,
573
+ // in the order the binding reads them, the four above wrapped.
574
+ function readCallbacks(callbacks) {
575
+ return {
576
+ onRequest: callbacks.onRequest,
577
+ onRequestBatch: callbacks.onRequestBatch,
578
+ onAborted: callbacks.onAborted,
579
+ onWritable: callbacks.onWritable,
580
+ onWsOpen: callbacks.onWsOpen,
581
+ onWsMessage: callbacks.onWsMessage,
582
+ onWsClose: callbacks.onWsClose,
583
+ };
584
+ }
585
+ function withTrampolines(binding, read) {
586
+ const report = binding._reportCaught;
587
+ const batchDone = binding._batchDone;
588
+ const out = { ...read };
589
+ if (typeof read.onRequest === 'function') out.onRequest = requestTrampoline(read.onRequest, report);
590
+ if (typeof read.onRequestBatch === 'function') out.onRequestBatch = batchTrampoline(read.onRequestBatch, report, batchDone);
591
+ if (typeof read.onAborted === 'function') out.onAborted = noticeTrampoline(read.onAborted, report);
592
+ if (typeof read.onWritable === 'function') out.onWritable = noticeTrampoline(read.onWritable, report);
593
+ return out;
594
+ }
595
+ const canTrampoline = (binding) => typeof binding._reportCaught === 'function' && typeof binding._batchDone === 'function';
596
+
373
597
  function serve(callbacks, options) {
374
598
  const tls = Boolean(options && options.ssl);
375
599
  const binding = loaded.module;
600
+ const args = Array.prototype.slice.call(arguments);
601
+ if (tls) {
602
+ const ssl = withNodeTlsPolicy(options.ssl);
603
+ if (ssl !== options.ssl) args[1] = { ...options, ssl };
604
+ }
605
+ // (A callbacks argument that is not an object goes to the binding as it
606
+ // is, and is refused there.)
607
+ const wrap = DISPATCH_TRAMPOLINES && callbacks !== null && (typeof callbacks === 'object' || typeof callbacks === 'function');
608
+ const read = wrap ? readCallbacks(callbacks) : null;
609
+ const argsFor = (mod) => {
610
+ // The third argument says "these are trampolines"; nothing else may.
611
+ if (!wrap || !canTrampoline(mod)) return args.slice(0, 2);
612
+ return [withTrampolines(mod, read), args[1], true];
613
+ };
376
614
  let serverId;
377
615
  try {
378
- serverId = binding.serve.apply(this, arguments);
616
+ serverId = binding.serve.apply(this, argsFor(binding));
379
617
  } catch (error) {
380
- serverId = tls ? serveOnOpenSslInstead(error, this, arguments) : undefined;
618
+ serverId = tls ? serveOnOpenSslInstead(error, this, argsFor) : undefined;
381
619
  if (serverId === undefined) throw error;
382
620
  }
383
621
  serversCreated++;
@@ -388,6 +626,12 @@ function serve(callbacks, options) {
388
626
  return serverId;
389
627
  }
390
628
 
629
+ // updateSsl() builds a whole new context from the options it is given, so
630
+ // the process-wide policy above goes into it the same way.
631
+ function updateSsl(serverId, ssl) {
632
+ return loaded.module.updateSsl(serverId, withNodeTlsPolicy(ssl));
633
+ }
634
+
391
635
  // The native binding's function exports (src/binding.cpp Initialize; mirrored by
392
636
  // the ESM named exports in index.mjs). ONLY these names force a native load —
393
637
  // anything else reads as undefined without loading, so `require`/`import` of
@@ -457,7 +701,7 @@ module.exports = new Proxy(
457
701
  return serve;
458
702
  }
459
703
  handedOut.add(prop);
460
- const fn = binding[prop];
704
+ const fn = prop === 'updateSsl' && typeof binding.updateSsl === 'function' ? updateSsl : binding[prop];
461
705
  target[prop] = fn;
462
706
  return fn;
463
707
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morojs/engine",
3
- "version": "1.1.21",
3
+ "version": "1.2.0",
4
4
  "description": "MoroJS native HTTP engine - Moro-authored C++ core with per-platform prebuilt binaries and automatic Node.js fallback in MoroJS",
5
5
  "license": "MIT",
6
6
  "author": "CM Ventures Inc.",
@@ -38,13 +38,13 @@
38
38
  "provenance": true
39
39
  },
40
40
  "optionalDependencies": {
41
- "@morojs/engine-darwin-arm64": "1.1.21",
42
- "@morojs/engine-darwin-x64": "1.1.21",
43
- "@morojs/engine-linux-x64-gnu": "1.1.21",
44
- "@morojs/engine-linux-arm64-gnu": "1.1.21",
45
- "@morojs/engine-linux-x64-musl": "1.1.21",
46
- "@morojs/engine-linux-arm64-musl": "1.1.21",
47
- "@morojs/engine-win32-x64": "1.1.21"
41
+ "@morojs/engine-darwin-arm64": "1.2.0",
42
+ "@morojs/engine-darwin-x64": "1.2.0",
43
+ "@morojs/engine-linux-x64-gnu": "1.2.0",
44
+ "@morojs/engine-linux-arm64-gnu": "1.2.0",
45
+ "@morojs/engine-linux-x64-musl": "1.2.0",
46
+ "@morojs/engine-linux-arm64-musl": "1.2.0",
47
+ "@morojs/engine-win32-x64": "1.2.0"
48
48
  },
49
49
  "keywords": [
50
50
  "morojs",