@morojs/engine 1.1.19 → 1.1.21

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.
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # @morojs/engine
2
2
 
3
3
  MoroJS's native HTTP engine: a Moro-authored C++ core with raw-V8 bindings,
4
- shipped as **prebuilt binaries per platform x Node ABI**. MIT licensed.
4
+ shipped as **prebuilt binaries per platform x Node ABI**. It serves HTTP/1.1,
5
+ HTTP/2 and WebSocket (with permessage-deflate) and terminates TLS in-process.
6
+ MIT licensed.
5
7
 
6
8
  This is the meta package. It contains only a small JavaScript loader plus the
7
9
  TypeScript types; the actual `.node` binaries are delivered by per-platform
@@ -24,7 +26,6 @@ prebuilt binary is not available:
24
26
  server: {
25
27
  engine: 'moro', // default - native engine when loadable, Node http otherwise
26
28
  // engine: 'node' - always use Node http
27
- // engine: 'uws' - opt in to uWebSockets.js
28
29
  }
29
30
  ```
30
31
 
@@ -55,6 +56,21 @@ rich, actionable error (`err.code === 'MORO_ENGINE_BINARY_MISSING'`) that names
55
56
  the expected package, the running Node ABI, and the remediation for npm's
56
57
  optional-dependency lockfile bug ([npm/cli#4828](https://github.com/npm/cli/issues/4828)).
57
58
 
59
+ ## TLS
60
+
61
+ Each platform package carries two builds of the engine per Node version. The
62
+ default terminates TLS with a bundled [BoringSSL](https://boringssl.googlesource.com/boringssl);
63
+ the other uses the OpenSSL of the running Node.js and is selected by itself
64
+ when that library is specially configured (FIPS mode, `--openssl-config`,
65
+ `OPENSSL_CONF`, ...), or with `MORO_ENGINE_TLS=openssl` /
66
+ `engine.selectTls('openssl')`. `engine.probe().tls` reports which is loaded.
67
+
68
+ The bundled library is updated by a scheduled release every time upstream
69
+ publishes a snapshot (every two to three weeks), so **keep this package
70
+ updated** the way you keep Node.js updated; a TLS server on a build more than
71
+ 180 days old says so in a process warning (`MORO_ENGINE_TLS_STALE`). Details:
72
+ [docs/TLS.md](https://github.com/Moro-JS/engine/blob/main/docs/TLS.md).
73
+
58
74
  ## Supported platforms
59
75
 
60
76
  | Package | os | cpu | libc |
package/index.d.ts CHANGED
@@ -86,6 +86,27 @@ export interface FastApiInfo {
86
86
  runtimeV8: string;
87
87
  }
88
88
 
89
+ /** The TLS library the loaded binary terminates TLS with, and why that binary. */
90
+ export interface EngineTlsInfo {
91
+ /** 'boringssl': carried inside the addon (the default since 1.1.20).
92
+ * 'openssl': the OpenSSL the running node exports. */
93
+ library: 'boringssl' | 'openssl';
94
+ /** BoringSSL: the upstream version tag the build is pinned to
95
+ * (`0.YYYYMMDD.N`). OpenSSL: that library's own version, e.g. '3.5.2'. */
96
+ version: string;
97
+ /** BoringSSL only: the day upstream cut that snapshot, 'YYYY-MM-DD' - how
98
+ * old the bundled TLS code is. */
99
+ date?: string;
100
+ /** Why this library: 'default', 'selectTls()', 'MORO_ENGINE_TLS',
101
+ * "node's OpenSSL is configured (...)" (FIPS mode, an OpenSSL config or
102
+ * provider option), 'fallback' (the BoringSSL binary could not be loaded,
103
+ * or BoringSSL did not accept the TLS configuration), or
104
+ * 'MORO_ENGINE_BINARY'. */
105
+ reason: string;
106
+ /** With reason 'fallback': why BoringSSL is not the one serving. */
107
+ fallbackReason?: string;
108
+ }
109
+
89
110
  export interface EngineProbeResult {
90
111
  /** True when a native binary loaded for this platform/ABI */
91
112
  ok: boolean;
@@ -103,6 +124,8 @@ export interface EngineProbeResult {
103
124
  notify?: 'deferred' | 'sync';
104
125
  /** Fast-call build/install diagnostics. */
105
126
  fastApi?: FastApiInfo;
127
+ /** TLS library in use (1.1.20 and later). */
128
+ tls?: EngineTlsInfo;
106
129
  /** I/O transport in use: 'epoll' (Linux default since 1.1.10: the engine's
107
130
  * own readiness loop on one uv_poll, no libuv stream per connection),
108
131
  * 'uring' (Linux 6.1+, MORO_ENGINE_TRANSPORT=uring, when the sandbox
@@ -255,8 +278,13 @@ export interface ServeOptions {
255
278
  rejectUnauthorized?: boolean;
256
279
  /** Explicit cipher/group policy for compliance baselines (PCI/FIPS/hardened
257
280
  * profiles; feature-detect via probe().capabilities.tlsPolicy). Same
258
- * semantics as Node's tls.createSecureContext; unset = the host Node's
259
- * OpenSSL defaults; invalid values THROW from serve(). */
281
+ * 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
283
+ * of AES-256-GCM, ChaCha20 for a client that lists it first. With the
284
+ * bundled BoringSSL (probe().tls.library) `ciphersuites` can name
285
+ * TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384 and
286
+ * TLS_CHACHA20_POLY1305_SHA256, and `ciphers` has no DHE or CCM suites;
287
+ * a policy that needs others selects OpenSSL (selectTls / MORO_ENGINE_TLS). */
260
288
  ciphers?: string; // TLS <= 1.2 cipher list
261
289
  ciphersuites?: string; // TLS 1.3 suites (colon-separated)
262
290
  ecdhCurve?: string; // key-share groups, e.g. 'X25519:P-256'; 'auto' = default
@@ -419,8 +447,8 @@ export function clearStaticRoutes(serverId: number): void;
419
447
  * `/user/:id` is prefix "/user/" and suffix ""; `/files/:name.json` is
420
448
  * prefix "/files/" and suffix ".json". The segment must be non-empty and
421
449
  * contain no '/', so `/user/` and `/user/1/2` still reach onRequest. It is
422
- * written as it is on the wire, undecoded (uWS's writeParameterValue does
423
- * the same); a route that needs decoding stays a JS route. The header block
450
+ * written as it is on the wire, undecoded; a route that needs decoding
451
+ * stays a JS route. The header block
424
452
  * is materialised once, so the reply is byte-identical to
425
453
  * respond(status, headersFlat, segment). Only an exact method match
426
454
  * short-circuits; re-registering (method, prefix, suffix) replaces it.
@@ -490,6 +518,36 @@ export function wsGetRemoteAddress(wsId: number): string | undefined;
490
518
 
491
519
  /** Non-throwing load diagnostics. Never throws. */
492
520
  export function probe(): EngineProbeResult;
521
+ /**
522
+ * Choose the TLS library before the engine's binary is loaded. Returns the
523
+ * library in effect.
524
+ *
525
+ * - 'boringssl': BoringSSL, carried inside the addon. The default.
526
+ * - 'openssl': the OpenSSL of the running node - for FIPS mode, OpenSSL
527
+ * providers or engines, a system crypto policy.
528
+ * - 'auto': no choice made in code. MORO_ENGINE_TLS decides if it is set;
529
+ * otherwise BoringSSL, unless node's OpenSSL is specially configured
530
+ * (--enable-fips, --force-fips, --openssl-config, --openssl-shared-config,
531
+ * --openssl-legacy-provider, OPENSSL_CONF, OPENSSL_MODULES, or FIPS mode on),
532
+ * in which case OpenSSL.
533
+ *
534
+ * The choice is per thread and must be made before the first probe() or
535
+ * serve() there: a loaded addon cannot be swapped, and asking for the other
536
+ * library afterwards throws (code 'MORO_ENGINE_TLS_LOADED'). The environment
537
+ * variable MORO_ENGINE_TLS takes the same three values and needs no code.
538
+ *
539
+ * `ssl`: the ssl options the server is about to be created with. When no
540
+ * library is named ('auto', no MORO_ENGINE_TLS), the load checks that
541
+ * BoringSSL accepts them - its set of key types, cipher suites and groups is
542
+ * narrower than OpenSSL's - and settles on OpenSSL when it does not
543
+ * (probe().tls: reason 'fallback'). Without it, serve() makes the same move
544
+ * for the first TLS server of a thread, as long as no other native function
545
+ * has been taken from the module yet.
546
+ */
547
+ export function selectTls(
548
+ library: 'boringssl' | 'openssl' | 'auto',
549
+ ssl?: ServeOptions['ssl']
550
+ ): 'boringssl' | 'openssl' | 'auto';
493
551
  // The engine version comes from this package's package.json (stamped from the
494
552
  // release tag), available without loading the addon via `probe().version` or on
495
553
  // the default export as `engine.version` — neither forces the native addon to
@@ -536,6 +594,7 @@ declare const engine: {
536
594
  wsGetQuery: typeof wsGetQuery;
537
595
  wsGetRemoteAddress: typeof wsGetRemoteAddress;
538
596
  probe: typeof probe;
597
+ selectTls: typeof selectTls;
539
598
  version: string;
540
599
  };
541
600
 
package/index.js CHANGED
@@ -6,8 +6,15 @@
6
6
  // published as an exact-version optionalDependency of this package.
7
7
  // 2. A local build/ directory (engine repo development).
8
8
  //
9
- // Binary naming: moro_engine_<platform>_<arch>[_<libc>]_<abi>.node
9
+ // Binary naming: moro_engine_<platform>_<arch>[_<libc>]_<abi>[_boringssl].node
10
10
  // (libc segment on linux only: gnu | musl)
11
+ //
12
+ // Two binaries exist per platform and ABI, and they differ in one thing: the
13
+ // TLS library. `..._boringssl.node` carries BoringSSL and is the default. The
14
+ // unsuffixed one links the OpenSSL the running node exports; it is chosen when
15
+ // the process has that library specially configured (FIPS, an OpenSSL config
16
+ // file, providers), when the app or operator asks for it, and as the fallback
17
+ // when the BoringSSL binary cannot be loaded. See tlsPreference() below.
11
18
 
12
19
  const { existsSync } = require('fs');
13
20
  const { join } = require('path');
@@ -48,17 +55,98 @@ function libcSuffix() {
48
55
  }
49
56
  }
50
57
 
51
- function binaryName() {
58
+ function binaryName(tls) {
52
59
  const libc = libcSuffix().replace('-', '_'); // '' | '_gnu' | '_musl'
53
- return `moro_engine_${process.platform}_${process.arch}${libc}_${process.versions.modules}.node`;
60
+ const variant = tls === 'boringssl' ? '_boringssl' : '';
61
+ return `moro_engine_${process.platform}_${process.arch}${libc}_${process.versions.modules}${variant}.node`;
62
+ }
63
+
64
+ // ---- which TLS library ------------------------------------------------------
65
+
66
+ // Set by selectTls() before the binding is loaded; null = not chosen in code.
67
+ let selectedTls = null;
68
+ // The ssl options the first TLS server will be created with, when the caller
69
+ // said so (selectTls(library, ssl)): lets the load itself settle on a library
70
+ // that accepts them.
71
+ let plannedSsl = null;
72
+
73
+ // Node options that configure the process's OpenSSL. An operator who passes
74
+ // one expects TLS to go through that library - a FIPS provider, an engine or
75
+ // provider module, a policy file - and the bundled BoringSSL knows none of it.
76
+ const OPENSSL_NODE_FLAGS = ['--enable-fips', '--force-fips', '--openssl-config', '--openssl-shared-config', '--openssl-legacy-provider'];
77
+
78
+ function opensslIsConfigured() {
79
+ const flags = `${process.execArgv.join(' ')} ${process.env.NODE_OPTIONS || ''}`;
80
+ for (const flag of OPENSSL_NODE_FLAGS) {
81
+ if (flags.includes(flag)) return flag;
82
+ }
83
+ if (process.env.OPENSSL_CONF) return 'OPENSSL_CONF';
84
+ if (process.env.OPENSSL_MODULES) return 'OPENSSL_MODULES';
85
+ try {
86
+ if (require('crypto').getFips()) return 'FIPS mode';
87
+ } catch {
88
+ // a node built without crypto: nothing is configured
89
+ }
90
+ return null;
91
+ }
92
+
93
+ function normalizeTls(value, source) {
94
+ const v = String(value).toLowerCase();
95
+ if (v === 'boringssl' || v === 'openssl' || v === 'auto') return v;
96
+ if (v === 'node') return 'openssl'; // "the one node ships"
97
+ const error = new Error(`@morojs/engine: ${source} must be "boringssl", "openssl" or "auto", got "${value}"`);
98
+ error.code = 'MORO_ENGINE_TLS_INVALID';
99
+ throw error;
100
+ }
101
+
102
+ /**
103
+ * The TLS library to load and why. `explicit` means someone asked for it by
104
+ * name: then a binary that cannot be loaded is an error, never a silent switch
105
+ * to the other library.
106
+ */
107
+ function tlsPreference() {
108
+ let asked = selectedTls;
109
+ let reason = 'selectTls()';
110
+ if (!asked || asked === 'auto') {
111
+ const env = process.env.MORO_ENGINE_TLS;
112
+ asked = env ? normalizeTls(env, 'MORO_ENGINE_TLS') : 'auto';
113
+ reason = 'MORO_ENGINE_TLS';
114
+ }
115
+ if (asked !== 'auto') return { library: asked, explicit: true, reason };
116
+ const configured = opensslIsConfigured();
117
+ if (configured) return { library: 'openssl', explicit: false, reason: `node's OpenSSL is configured (${configured})` };
118
+ return { library: 'boringssl', explicit: false, reason: 'default' };
54
119
  }
55
120
 
56
121
  function platformPackageName() {
57
122
  return `@morojs/engine-${process.platform}-${process.arch}${libcSuffix()}`;
58
123
  }
59
124
 
125
+ // One binary by file name: the per-platform package first, then a local build.
126
+ function loadNamed(name, attempts) {
127
+ // 1. Per-platform npm package
128
+ const pkg = platformPackageName();
129
+ try {
130
+ return { module: require(require.resolve(`${pkg}/${name}`)), from: pkg };
131
+ } catch (err) {
132
+ attempts.push(`${pkg}/${name}: ${err.message.split('\n')[0]}`);
133
+ }
134
+
135
+ // 2. Engine repo local build (development)
136
+ const local = join(__dirname, '..', '..', 'build', name);
137
+ if (existsSync(local)) {
138
+ try {
139
+ return { module: require(local), from: local };
140
+ } catch (err) {
141
+ attempts.push(`${local}: ${err.message.split('\n')[0]}`);
142
+ }
143
+ } else {
144
+ attempts.push(`${local}: not present`);
145
+ }
146
+ return null;
147
+ }
148
+
60
149
  function tryLoad() {
61
- const name = binaryName();
62
150
  const attempts = [];
63
151
 
64
152
  // 0. Explicit binary (build/diagnostics only, never needed by users): the
@@ -77,26 +165,44 @@ function tryLoad() {
77
165
  }
78
166
  }
79
167
 
80
- // 1. Per-platform npm package
81
- const pkg = platformPackageName();
168
+ let pref;
82
169
  try {
83
- return { module: require(require.resolve(`${pkg}/${name}`)), from: pkg };
84
- } catch (err) {
85
- attempts.push(`${pkg}/${name}: ${err.message.split('\n')[0]}`);
170
+ pref = tlsPreference();
171
+ } catch (error) {
172
+ return { error };
86
173
  }
87
174
 
88
- // 2. Engine repo local build (development)
89
- const local = join(__dirname, '..', '..', 'build', name);
90
- if (existsSync(local)) {
91
- try {
92
- return { module: require(local), from: local };
93
- } catch (err) {
94
- attempts.push(`${local}: ${err.message.split('\n')[0]}`);
175
+ const first = loadNamed(binaryName(pref.library), attempts);
176
+ if (first) {
177
+ // BoringSSL by default, and the caller told us the TLS configuration it
178
+ // is about to serve: make sure BoringSSL takes it. One it has no support
179
+ // for - an Ed448 or DSA key, a CCM suite, a brainpool group - worked on
180
+ // node's OpenSSL up to 1.1.19, and keeps working there now.
181
+ if (pref.library === 'boringssl' && !pref.explicit && plannedSsl) {
182
+ const refused = tlsRefusal(first.module, plannedSsl);
183
+ if (refused) {
184
+ const other = loadNamed(binaryName('openssl'), []);
185
+ if (other && !tlsRefusal(other.module, plannedSsl)) {
186
+ return { ...other, tls: { reason: 'fallback', fallbackReason: notAccepted(refused) } };
187
+ }
188
+ // Neither library takes it: the configuration is simply wrong, and
189
+ // serve() will say so.
190
+ }
95
191
  }
96
- } else {
97
- attempts.push(`${local}: not present`);
192
+ return { ...first, tls: { reason: pref.reason } };
98
193
  }
99
194
 
195
+ // The BoringSSL binary is the default, not a requirement: when nobody asked
196
+ // for it by name and it is not there (a platform package from before 1.1.20,
197
+ // a local build made with --tls=openssl) or will not load, the binary on
198
+ // node's OpenSSL serves instead, and probe().tls says so.
199
+ if (pref.library === 'boringssl' && !pref.explicit) {
200
+ const fallbackReason = attempts.join('; ');
201
+ const second = loadNamed(binaryName('openssl'), attempts);
202
+ if (second) return { ...second, tls: { reason: 'fallback', fallbackReason } };
203
+ }
204
+
205
+ const pkg = platformPackageName();
100
206
  const error = new Error(
101
207
  `@morojs/engine: no prebuilt binary for ${process.platform}/${process.arch} ` +
102
208
  `on Node ABI ${process.versions.modules} (Node ${process.versions.node}).\n` +
@@ -111,6 +217,14 @@ function tryLoad() {
111
217
  return { error };
112
218
  }
113
219
 
220
+ // "" when the binary's TLS library can build a context from these ssl options,
221
+ // otherwise why not (the message serve() would throw). Older binaries have no
222
+ // such check and are taken to accept.
223
+ function tlsRefusal(binding, ssl) {
224
+ return typeof binding._tlsCheck === 'function' ? binding._tlsCheck(ssl) : '';
225
+ }
226
+ const notAccepted = (why) => `BoringSSL did not accept the TLS configuration (${String(why).split('\n')[0]})`;
227
+
114
228
  let loaded = null;
115
229
 
116
230
  function loadBinding() {
@@ -137,7 +251,141 @@ function probe() {
137
251
  }
138
252
  // package.json is the source of truth for the version (see ENGINE_VERSION);
139
253
  // override the binding's build-time constant so the two can never disagree.
140
- return { ...loaded.module.probe(), version: ENGINE_VERSION };
254
+ const native = loaded.module.probe();
255
+ return { ...native, version: ENGINE_VERSION, tls: tlsInfo(native) };
256
+ }
257
+
258
+ // `0.YYYYMMDD.N`, BoringSSL's version tags: the day upstream cut the snapshot.
259
+ function boringSslDate(version) {
260
+ const m = /^0\.(\d{4})(\d{2})(\d{2})\.\d+$/.exec(version || '');
261
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
262
+ }
263
+
264
+ // probe().tls: what the binary reports (library, version) plus what only the
265
+ // loader knows - why this binary was the one loaded.
266
+ function tlsInfo(native) {
267
+ // A binary from before 1.1.20 reports nothing: it links node's OpenSSL.
268
+ const base = native.tls || { library: 'openssl', version: process.versions.openssl || '' };
269
+ const info = { library: base.library, version: base.version, reason: loaded.tls ? loaded.tls.reason : 'MORO_ENGINE_BINARY' };
270
+ const date = base.library === 'boringssl' ? boringSslDate(base.version) : null;
271
+ if (date) info.date = date;
272
+ if (loaded.tls && loaded.tls.fallbackReason) info.fallbackReason = loaded.tls.fallbackReason;
273
+ return info;
274
+ }
275
+
276
+ /**
277
+ * Choose the TLS library before the binding is loaded: 'boringssl' (bundled),
278
+ * 'openssl' (the running node's) or 'auto'. The choice is per thread and has
279
+ * to come before the first probe()/serve() there; asking for the other library
280
+ * once a binary is loaded throws, because a loaded addon cannot be swapped.
281
+ * Operators can set MORO_ENGINE_TLS instead and change no code.
282
+ *
283
+ * `ssl` (optional): the ssl options the server will be created with. When the
284
+ * library is not named, the load then checks that BoringSSL accepts them and
285
+ * settles on OpenSSL if it does not.
286
+ */
287
+ function selectTls(library, ssl) {
288
+ const want = normalizeTls(library, 'selectTls()');
289
+ if (ssl && typeof ssl === 'object') plannedSsl = ssl;
290
+ if (loaded && !loaded.error) {
291
+ const have = tlsInfo(loaded.module.probe()).library;
292
+ if (want === 'auto' || want === have) return have;
293
+ const error = new Error(
294
+ `@morojs/engine: selectTls('${want}') came after the binding was loaded with ${have}. ` +
295
+ `Call it before the first probe() or serve(), or set MORO_ENGINE_TLS=${want}.`
296
+ );
297
+ error.code = 'MORO_ENGINE_TLS_LOADED';
298
+ throw error;
299
+ }
300
+ selectedTls = want;
301
+ loaded = null; // a failed earlier attempt may succeed with the other library
302
+ return want;
303
+ }
304
+
305
+ // ---- how old is the bundled TLS code ----------------------------------------
306
+
307
+ // A bundled TLS library gets its fixes through engine releases, and a server
308
+ // that nobody updates would otherwise never say so. Past this age the first
309
+ // TLS server of the process emits one warning (code MORO_ENGINE_TLS_STALE).
310
+ // The engine re-pins BoringSSL about every three weeks, so a build this old
311
+ // has missed several of them. MORO_ENGINE_TLS_AGE_WARNING=0 turns it off.
312
+ const TLS_STALE_DAYS = 180;
313
+
314
+ function warnIfBundledTlsIsOld(binding) {
315
+ if (process.env.MORO_ENGINE_TLS_AGE_WARNING === '0') return;
316
+ const tls = tlsInfo(binding.probe());
317
+ if (tls.library !== 'boringssl' || !tls.date) return;
318
+ const ageDays = Math.floor((Date.now() - Date.parse(`${tls.date}T00:00:00Z`)) / 86_400_000);
319
+ if (!(ageDays > TLS_STALE_DAYS)) return;
320
+ // Once per process, whichever thread gets here first - and in a cluster,
321
+ // from the first worker only, not once per worker process.
322
+ try {
323
+ const cluster = require('cluster');
324
+ if (cluster.isWorker && cluster.worker && cluster.worker.id !== 1) return;
325
+ } catch {
326
+ // no cluster module: not a cluster
327
+ }
328
+ if (typeof binding._tlsAgeNoticeOnce === 'function' && !binding._tlsAgeNoticeOnce()) return;
329
+ process.emitWarning(
330
+ `the TLS library bundled with @morojs/engine ${ENGINE_VERSION} (BoringSSL ${tls.version}) is ${ageDays} days old. ` +
331
+ `Its security fixes arrive only with engine releases: update @morojs/engine. ` +
332
+ `(MORO_ENGINE_TLS_AGE_WARNING=0 silences this; MORO_ENGINE_TLS=openssl uses node's OpenSSL instead.)`,
333
+ { code: 'MORO_ENGINE_TLS_STALE' }
334
+ );
335
+ }
336
+
337
+ // serve() as the loader hands it out. Creating a server is not a hot path;
338
+ // everything per request stays the raw native call.
339
+ //
340
+ // Two things happen here that the native function cannot do. A server that
341
+ // terminates TLS gets one look at the age of the bundled TLS library. And the
342
+ // first TLS server of a thread that is on BoringSSL only because nobody chose
343
+ // - not by name, not through MORO_ENGINE_TLS - is retried on node's OpenSSL
344
+ // when BoringSSL refuses its configuration: a key type or cipher BoringSSL
345
+ // does not have was accepted up to 1.1.19, and an update must not turn it
346
+ // into a server that will not start. The retry needs the thread to hold
347
+ // nothing of the first binary yet (no server, no other native function handed
348
+ // out), because ids and functions of two binaries do not mix; when it does
349
+ // hold something, the error is thrown as it is, with the way out appended.
350
+ let serversCreated = 0;
351
+ const handedOut = new Set();
352
+
353
+ function serveOnOpenSslInstead(error, self, args) {
354
+ if (!loaded.tls || loaded.tls.reason !== 'default') return undefined; // chosen by name, or not BoringSSL
355
+ if (serversCreated > 0 || handedOut.size > 0) {
356
+ error.message += ` [TLS library: the bundled BoringSSL. If node's OpenSSL accepts this configuration, MORO_ENGINE_TLS=openssl selects it.]`;
357
+ return undefined;
358
+ }
359
+ const other = loadNamed(binaryName('openssl'), []);
360
+ if (!other) return undefined;
361
+ let serverId;
362
+ try {
363
+ serverId = other.module.serve.apply(self, args);
364
+ } catch {
365
+ return undefined; // wrong for both libraries: the first error stands
366
+ }
367
+ loaded = { ...other, tls: { reason: 'fallback', fallbackReason: notAccepted(error.message) } };
368
+ return serverId;
369
+ }
370
+
371
+ let tlsAgeChecked = false;
372
+
373
+ function serve(callbacks, options) {
374
+ const tls = Boolean(options && options.ssl);
375
+ const binding = loaded.module;
376
+ let serverId;
377
+ try {
378
+ serverId = binding.serve.apply(this, arguments);
379
+ } catch (error) {
380
+ serverId = tls ? serveOnOpenSslInstead(error, this, arguments) : undefined;
381
+ if (serverId === undefined) throw error;
382
+ }
383
+ serversCreated++;
384
+ if (tls && !tlsAgeChecked) {
385
+ tlsAgeChecked = true;
386
+ warnIfBundledTlsIsOld(loaded.module);
387
+ }
388
+ return serverId;
141
389
  }
142
390
 
143
391
  // The native binding's function exports (src/binding.cpp Initialize; mirrored by
@@ -190,7 +438,7 @@ const NATIVE_API = new Set([
190
438
  ]);
191
439
 
192
440
  module.exports = new Proxy(
193
- { probe, version: ENGINE_VERSION },
441
+ { probe, selectTls, version: ENGINE_VERSION },
194
442
  {
195
443
  get(target, prop) {
196
444
  if (prop in target) return target[prop];
@@ -203,7 +451,13 @@ module.exports = new Proxy(
203
451
  // short-circuits on `prop in target` above: the call site then sees
204
452
  // one constant function (inline-cacheable, fast-call eligible)
205
453
  // instead of a fresh trap invocation per call.
206
- const fn = loadBinding()[prop];
454
+ const binding = loadBinding();
455
+ if (prop === 'serve') {
456
+ target.serve = serve;
457
+ return serve;
458
+ }
459
+ handedOut.add(prop);
460
+ const fn = binding[prop];
207
461
  target[prop] = fn;
208
462
  return fn;
209
463
  }
package/index.mjs CHANGED
@@ -25,6 +25,8 @@ export default engine;
25
25
 
26
26
  // probe() lives on the loader itself (never loads the binding) - safe to alias.
27
27
  export const probe = engine.probe;
28
+ // selectTls() is the loader's too: it decides which binary gets loaded.
29
+ export const selectTls = engine.selectTls;
28
30
 
29
31
  export let serve = (...a) => (serve = engine.serve)(...a);
30
32
  export let listen = (...a) => (listen = engine.listen)(...a);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morojs/engine",
3
- "version": "1.1.19",
3
+ "version": "1.1.21",
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,17 +38,20 @@
38
38
  "provenance": true
39
39
  },
40
40
  "optionalDependencies": {
41
- "@morojs/engine-darwin-arm64": "1.1.19",
42
- "@morojs/engine-darwin-x64": "1.1.19",
43
- "@morojs/engine-linux-x64-gnu": "1.1.19",
44
- "@morojs/engine-linux-arm64-gnu": "1.1.19",
45
- "@morojs/engine-linux-x64-musl": "1.1.19",
46
- "@morojs/engine-linux-arm64-musl": "1.1.19",
47
- "@morojs/engine-win32-x64": "1.1.19"
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"
48
48
  },
49
49
  "keywords": [
50
50
  "morojs",
51
51
  "http",
52
+ "http2",
53
+ "websocket",
54
+ "tls",
52
55
  "server",
53
56
  "native",
54
57
  "performance"