@morojs/engine 1.1.18 → 1.1.20

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
@@ -55,6 +55,21 @@ rich, actionable error (`err.code === 'MORO_ENGINE_BINARY_MISSING'`) that names
55
55
  the expected package, the running Node ABI, and the remediation for npm's
56
56
  optional-dependency lockfile bug ([npm/cli#4828](https://github.com/npm/cli/issues/4828)).
57
57
 
58
+ ## TLS
59
+
60
+ Each platform package carries two builds of the engine per Node version. The
61
+ default terminates TLS with a bundled [BoringSSL](https://boringssl.googlesource.com/boringssl);
62
+ the other uses the OpenSSL of the running Node.js and is selected by itself
63
+ when that library is specially configured (FIPS mode, `--openssl-config`,
64
+ `OPENSSL_CONF`, ...), or with `MORO_ENGINE_TLS=openssl` /
65
+ `engine.selectTls('openssl')`. `engine.probe().tls` reports which is loaded.
66
+
67
+ The bundled library is updated by a scheduled release every time upstream
68
+ publishes a snapshot (every two to three weeks), so **keep this package
69
+ updated** the way you keep Node.js updated; a TLS server on a build more than
70
+ 180 days old says so in a process warning (`MORO_ENGINE_TLS_STALE`). Details:
71
+ [docs/TLS.md](https://github.com/Moro-JS/engine/blob/main/docs/TLS.md).
72
+
58
73
  ## Supported platforms
59
74
 
60
75
  | Package | os | cpu | libc |
package/index.d.ts CHANGED
@@ -14,8 +14,9 @@ export interface EngineCapabilities {
14
14
  limits: boolean;
15
15
  /** In-process TLS termination via ServeOptions.ssl. */
16
16
  tls: boolean;
17
- /** ALPN-negotiated HTTP/2 alongside HTTP/1.1 — reserved for a future
18
- * release; not yet configurable (no ServeOptions field). */
17
+ /** HTTP/2 via ServeOptions.http2 (engine >= 1.1.19): negotiated by ALPN on
18
+ * a TLS listener, by prior knowledge on a cleartext one, with HTTP/1.1
19
+ * served beside it on the same port. */
19
20
  http2: boolean;
20
21
  /** WebSocket permessage-deflate (RFC 7692) via ServeOptions.wsDeflate. */
21
22
  wsDeflate: boolean;
@@ -63,6 +64,10 @@ export interface EngineCapabilities {
63
64
  * exist: the engine can perform valid WebSocket upgrades itself, firing
64
65
  * onWsOpen without the request ever reaching onRequest. */
65
66
  wsAutoUpgrade: boolean;
67
+ /** getBodyType() and getBodyText() exist. */
68
+ bodyText: boolean;
69
+ /** getBodyLent() exists. */
70
+ bodyLent: boolean;
66
71
  }
67
72
 
68
73
  export interface FastApiInfo {
@@ -81,6 +86,27 @@ export interface FastApiInfo {
81
86
  runtimeV8: string;
82
87
  }
83
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
+
84
110
  export interface EngineProbeResult {
85
111
  /** True when a native binary loaded for this platform/ABI */
86
112
  ok: boolean;
@@ -98,6 +124,8 @@ export interface EngineProbeResult {
98
124
  notify?: 'deferred' | 'sync';
99
125
  /** Fast-call build/install diagnostics. */
100
126
  fastApi?: FastApiInfo;
127
+ /** TLS library in use (1.1.20 and later). */
128
+ tls?: EngineTlsInfo;
101
129
  /** I/O transport in use: 'epoll' (Linux default since 1.1.10: the engine's
102
130
  * own readiness loop on one uv_poll, no libuv stream per connection),
103
131
  * 'uring' (Linux 6.1+, MORO_ENGINE_TRANSPORT=uring, when the sandbox
@@ -250,12 +278,39 @@ export interface ServeOptions {
250
278
  rejectUnauthorized?: boolean;
251
279
  /** Explicit cipher/group policy for compliance baselines (PCI/FIPS/hardened
252
280
  * profiles; feature-detect via probe().capabilities.tlsPolicy). Same
253
- * semantics as Node's tls.createSecureContext; unset = the host Node's
254
- * 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). */
255
288
  ciphers?: string; // TLS <= 1.2 cipher list
256
289
  ciphersuites?: string; // TLS 1.3 suites (colon-separated)
257
290
  ecdhCurve?: string; // key-share groups, e.g. 'X25519:P-256'; 'auto' = default
258
291
  };
292
+ /** HTTP/2 (RFC 9113). Off by default. `true`, or an object of settings to
293
+ * advertise. With `ssl` the listener offers "h2" ahead of "http/1.1" in
294
+ * ALPN; without it a client speaks HTTP/2 by opening with the connection
295
+ * preface (prior knowledge, e.g. `curl --http2-prior-knowledge`). Every
296
+ * other client is served HTTP/1.1 on the same port. A request arriving on
297
+ * an HTTP/2 stream is delivered exactly as an HTTP/1 request is - the same
298
+ * callbacks, the same accessors, the same response calls. Not served over
299
+ * HTTP/2: WebSocket upgrades (RFC 8441), server push, CONNECT. */
300
+ http2?:
301
+ | boolean
302
+ | {
303
+ /** Streams a client may have open at once. Default 256. */
304
+ maxConcurrentStreams?: number;
305
+ /** Per-stream receive window, in bytes. Default 1 MiB. */
306
+ initialWindowSize?: number;
307
+ /** Largest frame payload accepted. Default (and minimum) 16,384. */
308
+ maxFrameSize?: number;
309
+ /** Largest decoded request header list. Default: maxHeadSize. */
310
+ maxHeaderListSize?: number;
311
+ /** HPACK dynamic table size offered to the client. Default 4,096. */
312
+ headerTableSize?: number;
313
+ };
259
314
  /** WebSocket permessage-deflate (RFC 7692). Off by default.
260
315
  * boolean to enable with defaults, or an options object. */
261
316
  wsDeflate?:
@@ -326,6 +381,25 @@ export function getHeader(reqId: number, lowercaseName: string): string | undefi
326
381
  * without a copy and stay valid for as long as JS holds the buffer; a second
327
382
  * call during the same request returns the same storage, not a snapshot. */
328
383
  export function getBody(reqId: number): ArrayBuffer | null;
384
+ /** The request's Content-Type: '' when it has a body but no such header,
385
+ * null when it has no body (or the request is gone). */
386
+ export function getBodyType(reqId: number): string | null;
387
+ /** The body as a string when every byte of it is ASCII, null otherwise (read
388
+ * it with getBody then). The string is the exact bytes received - decoded
389
+ * as UTF-8 or as Latin-1 it is the same text - and lives on the JS heap
390
+ * like any other string, where getBody's ArrayBuffer counts as external
391
+ * memory until a collection frees it. Null once getBody has taken the
392
+ * bytes. */
393
+ export function getBodyText(reqId: number): string | null;
394
+ /** The body as an ArrayBuffer that is detached when the response is complete
395
+ * or the request is aborted (byteLength 0, every view empty). The bytes are
396
+ * moved into it, not copied, and released at that moment instead of at some
397
+ * later collection - which is what keeps a server reading bodies at a high
398
+ * rate out of back-to-back full collections. For a handler that relays,
399
+ * hashes or echoes a body and keeps none of it. Code that keeps the body
400
+ * past the response reads it with getBody (a copy, during a loan) or
401
+ * transfers the lent buffer. Null when there is no body. */
402
+ export function getBodyLent(reqId: number): ArrayBuffer | null;
329
403
  export function getRemoteAddress(reqId: number): string;
330
404
  export function isAborted(reqId: number): boolean;
331
405
 
@@ -444,6 +518,36 @@ export function wsGetRemoteAddress(wsId: number): string | undefined;
444
518
 
445
519
  /** Non-throwing load diagnostics. Never throws. */
446
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';
447
551
  // The engine version comes from this package's package.json (stamped from the
448
552
  // release tag), available without loading the addon via `probe().version` or on
449
553
  // the default export as `engine.version` — neither forces the native addon to
@@ -463,6 +567,9 @@ declare const engine: {
463
567
  getHeaders: typeof getHeaders;
464
568
  getHeader: typeof getHeader;
465
569
  getBody: typeof getBody;
570
+ getBodyType: typeof getBodyType;
571
+ getBodyText: typeof getBodyText;
572
+ getBodyLent: typeof getBodyLent;
466
573
  getRemoteAddress: typeof getRemoteAddress;
467
574
  isAborted: typeof isAborted;
468
575
  respond: typeof respond;
@@ -487,6 +594,7 @@ declare const engine: {
487
594
  wsGetQuery: typeof wsGetQuery;
488
595
  wsGetRemoteAddress: typeof wsGetRemoteAddress;
489
596
  probe: typeof probe;
597
+ selectTls: typeof selectTls;
490
598
  version: string;
491
599
  };
492
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
@@ -161,6 +409,9 @@ const NATIVE_API = new Set([
161
409
  'getHeaders',
162
410
  'getHeader',
163
411
  'getBody',
412
+ 'getBodyType',
413
+ 'getBodyText',
414
+ 'getBodyLent',
164
415
  'getRemoteAddress',
165
416
  'isAborted',
166
417
  'respond',
@@ -187,7 +438,7 @@ const NATIVE_API = new Set([
187
438
  ]);
188
439
 
189
440
  module.exports = new Proxy(
190
- { probe, version: ENGINE_VERSION },
441
+ { probe, selectTls, version: ENGINE_VERSION },
191
442
  {
192
443
  get(target, prop) {
193
444
  if (prop in target) return target[prop];
@@ -200,7 +451,13 @@ module.exports = new Proxy(
200
451
  // short-circuits on `prop in target` above: the call site then sees
201
452
  // one constant function (inline-cacheable, fast-call eligible)
202
453
  // instead of a fresh trap invocation per call.
203
- 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];
204
461
  target[prop] = fn;
205
462
  return fn;
206
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);
@@ -38,6 +40,9 @@ export let getQuery = (...a) => (getQuery = engine.getQuery)(...a);
38
40
  export let getHeaders = (...a) => (getHeaders = engine.getHeaders)(...a);
39
41
  export let getHeader = (...a) => (getHeader = engine.getHeader)(...a);
40
42
  export let getBody = (...a) => (getBody = engine.getBody)(...a);
43
+ export let getBodyType = (...a) => (getBodyType = engine.getBodyType)(...a);
44
+ export let getBodyText = (...a) => (getBodyText = engine.getBodyText)(...a);
45
+ export let getBodyLent = (...a) => (getBodyLent = engine.getBodyLent)(...a);
41
46
  export let getRemoteAddress = (...a) => (getRemoteAddress = engine.getRemoteAddress)(...a);
42
47
  export let isAborted = (...a) => (isAborted = engine.isAborted)(...a);
43
48
  export let respond = (...a) => (respond = engine.respond)(...a);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morojs/engine",
3
- "version": "1.1.18",
3
+ "version": "1.1.20",
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.18",
42
- "@morojs/engine-darwin-x64": "1.1.18",
43
- "@morojs/engine-linux-x64-gnu": "1.1.18",
44
- "@morojs/engine-linux-arm64-gnu": "1.1.18",
45
- "@morojs/engine-linux-x64-musl": "1.1.18",
46
- "@morojs/engine-linux-arm64-musl": "1.1.18",
47
- "@morojs/engine-win32-x64": "1.1.18"
41
+ "@morojs/engine-darwin-arm64": "1.1.20",
42
+ "@morojs/engine-darwin-x64": "1.1.20",
43
+ "@morojs/engine-linux-x64-gnu": "1.1.20",
44
+ "@morojs/engine-linux-arm64-gnu": "1.1.20",
45
+ "@morojs/engine-linux-x64-musl": "1.1.20",
46
+ "@morojs/engine-linux-arm64-musl": "1.1.20",
47
+ "@morojs/engine-win32-x64": "1.1.20"
48
48
  },
49
49
  "keywords": [
50
50
  "morojs",