@zero-server/sdk 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,398 +1,398 @@
1
- /**
2
- * @module grpc/credentials
3
- * @description Channel credentials for gRPC connections.
4
- * Provides factory functions for creating insecure, SSL/TLS,
5
- * and metadata-based credentials. Supports certificate rotation
6
- * and credential composition.
7
- *
8
- * Uses only Node.js built-in `tls` and `fs` — no external packages.
9
- *
10
- * @example | Insecure (plaintext)
11
- * const { ChannelCredentials, GrpcClient } = require('@zero-server/sdk');
12
- * const creds = ChannelCredentials.createInsecure();
13
- * const client = new GrpcClient({ address: 'http://localhost:50051', credentials: creds }, schema, 'Greeter');
14
- *
15
- * @example | Server-only TLS
16
- * const creds = ChannelCredentials.createSsl(fs.readFileSync('ca.pem'));
17
- *
18
- * @example | Mutual TLS (mTLS)
19
- * const creds = ChannelCredentials.createSsl(
20
- * fs.readFileSync('ca.pem'),
21
- * fs.readFileSync('client-key.pem'),
22
- * fs.readFileSync('client-cert.pem'),
23
- * );
24
- *
25
- * @example | Metadata credentials (e.g. Bearer token)
26
- * const creds = ChannelCredentials.createFromMetadata((params) => ({
27
- * authorization: 'Bearer ' + getToken(),
28
- * }));
29
- *
30
- * @example | Composed credentials (TLS + per-call metadata)
31
- * const creds = ChannelCredentials.combine(
32
- * ChannelCredentials.createSsl(ca),
33
- * ChannelCredentials.createFromMetadata(() => ({ authorization: 'Bearer ' + token })),
34
- * );
35
- */
36
-
37
- const fs = require('fs');
38
- const log = require('../debug')('zero:grpc:credentials');
39
-
40
- // -- Credential Types ----------------------------------------
41
-
42
- /** @enum {string} */
43
- const CredentialType = {
44
- INSECURE: 'insecure',
45
- SSL: 'ssl',
46
- METADATA: 'metadata',
47
- COMPOSITE: 'composite',
48
- };
49
-
50
- // -- ChannelCredentials Class --------------------------------
51
-
52
- /**
53
- * Channel credentials define how a gRPC client authenticates to the server.
54
- *
55
- * @class
56
- */
57
- class ChannelCredentials
58
- {
59
- /**
60
- * @param {string} type - Credential type.
61
- * @param {object} [config] - Type-specific configuration.
62
- * @private
63
- */
64
- constructor(type, config = {})
65
- {
66
- /** @type {string} */
67
- this.type = type;
68
- /** @private */
69
- this._config = config;
70
- }
71
-
72
- /**
73
- * Create insecure (plaintext) credentials.
74
- * No TLS — suitable for development or service-mesh environments
75
- * where transport security is handled by the infrastructure.
76
- *
77
- * @returns {ChannelCredentials}
78
- */
79
- static createInsecure()
80
- {
81
- return new ChannelCredentials(CredentialType.INSECURE);
82
- }
83
-
84
- /**
85
- * Create SSL/TLS credentials.
86
- *
87
- * @param {Buffer|string|null} [rootCerts] - Root CA certificate(s) in PEM format.
88
- * If null, uses the system default trust store.
89
- * @param {Buffer|string|null} [clientKey] - Client private key in PEM format (for mTLS).
90
- * @param {Buffer|string|null} [clientCert] - Client certificate in PEM format (for mTLS).
91
- * @param {object} [opts] - Additional options.
92
- * @param {boolean} [opts.rejectUnauthorized=true] - Reject connections with invalid certs.
93
- * @returns {ChannelCredentials}
94
- *
95
- * @example | Server-only TLS
96
- * const creds = ChannelCredentials.createSsl(fs.readFileSync('ca.pem'));
97
- *
98
- * @example | Mutual TLS
99
- * const creds = ChannelCredentials.createSsl(caPem, keyPem, certPem);
100
- */
101
- static createSsl(rootCerts, clientKey, clientCert, opts = {})
102
- {
103
- const config = {
104
- rejectUnauthorized: opts.rejectUnauthorized !== false,
105
- };
106
-
107
- if (rootCerts)
108
- {
109
- config.ca = Buffer.isBuffer(rootCerts) ? rootCerts : Buffer.from(rootCerts);
110
- }
111
- if (clientKey)
112
- {
113
- config.key = Buffer.isBuffer(clientKey) ? clientKey : Buffer.from(clientKey);
114
- }
115
- if (clientCert)
116
- {
117
- config.cert = Buffer.isBuffer(clientCert) ? clientCert : Buffer.from(clientCert);
118
- }
119
-
120
- if (config.key && !config.cert)
121
- throw new Error('Client key provided without client certificate');
122
- if (config.cert && !config.key)
123
- throw new Error('Client certificate provided without client key');
124
-
125
- return new ChannelCredentials(CredentialType.SSL, config);
126
- }
127
-
128
- /**
129
- * Create SSL credentials from PEM file paths.
130
- * Files are read once at creation time.
131
- *
132
- * @param {string|null} [caPath] - Path to CA certificate file.
133
- * @param {string|null} [keyPath] - Path to client key file.
134
- * @param {string|null} [certPath] - Path to client certificate file.
135
- * @param {object} [opts] - Additional options.
136
- * @returns {ChannelCredentials}
137
- *
138
- * @example
139
- * const creds = ChannelCredentials.createSslFromFiles('./certs/ca.pem', './certs/client.key', './certs/client.pem');
140
- */
141
- static createSslFromFiles(caPath, keyPath, certPath, opts = {})
142
- {
143
- const ca = caPath ? fs.readFileSync(caPath) : null;
144
- const key = keyPath ? fs.readFileSync(keyPath) : null;
145
- const cert = certPath ? fs.readFileSync(certPath) : null;
146
- return ChannelCredentials.createSsl(ca, key, cert, opts);
147
- }
148
-
149
- /**
150
- * Create per-call metadata credentials.
151
- * The generator function is called before each RPC to produce
152
- * metadata headers (e.g. authorization tokens).
153
- *
154
- * @param {Function} metadataGenerator - `(params?) => object|Promise<object>`.
155
- * Returns key-value pairs to merge into call metadata.
156
- * `params` includes `{ serviceUrl, methodName }`.
157
- * @returns {ChannelCredentials}
158
- *
159
- * @example
160
- * const creds = ChannelCredentials.createFromMetadata(async () => ({
161
- * authorization: 'Bearer ' + await getAccessToken(),
162
- * }));
163
- */
164
- static createFromMetadata(metadataGenerator)
165
- {
166
- if (typeof metadataGenerator !== 'function')
167
- throw new Error('createFromMetadata requires a function');
168
-
169
- return new ChannelCredentials(CredentialType.METADATA, {
170
- generator: metadataGenerator,
171
- });
172
- }
173
-
174
- /**
175
- * Combine multiple credentials into one.
176
- * At most one channel credential (insecure/SSL) and any number
177
- * of call credentials (metadata) can be combined.
178
- *
179
- * @param {...ChannelCredentials} credentials - Credentials to combine.
180
- * @returns {ChannelCredentials}
181
- *
182
- * @example
183
- * const creds = ChannelCredentials.combine(
184
- * ChannelCredentials.createSsl(ca),
185
- * ChannelCredentials.createFromMetadata(() => ({ 'x-api-key': apiKey })),
186
- * ChannelCredentials.createFromMetadata(async () => ({ authorization: 'Bearer ' + token })),
187
- * );
188
- */
189
- static combine(...credentials)
190
- {
191
- let channelCred = null;
192
- const metadataGens = [];
193
-
194
- for (const cred of credentials)
195
- {
196
- if (!(cred instanceof ChannelCredentials))
197
- throw new Error('combine() arguments must be ChannelCredentials instances');
198
-
199
- if (cred.type === CredentialType.COMPOSITE)
200
- {
201
- // Flatten nested composites
202
- if (cred._config.channelCred) channelCred = cred._config.channelCred;
203
- metadataGens.push(...cred._config.metadataGenerators);
204
- }
205
- else if (cred.type === CredentialType.INSECURE || cred.type === CredentialType.SSL)
206
- {
207
- if (channelCred)
208
- throw new Error('Cannot combine multiple channel credentials (use at most one insecure/SSL)');
209
- channelCred = cred;
210
- }
211
- else if (cred.type === CredentialType.METADATA)
212
- {
213
- metadataGens.push(cred._config.generator);
214
- }
215
- }
216
-
217
- return new ChannelCredentials(CredentialType.COMPOSITE, {
218
- channelCred,
219
- metadataGenerators: metadataGens,
220
- });
221
- }
222
-
223
- /**
224
- * Whether this credential uses TLS.
225
- * @returns {boolean}
226
- */
227
- isSecure()
228
- {
229
- if (this.type === CredentialType.INSECURE) return false;
230
- if (this.type === CredentialType.SSL) return true;
231
- if (this.type === CredentialType.METADATA) return false;
232
- if (this.type === CredentialType.COMPOSITE)
233
- {
234
- const ch = this._config.channelCred;
235
- return ch ? ch.isSecure() : false;
236
- }
237
- return false;
238
- }
239
-
240
- /**
241
- * Get the TLS connection options for `http2.connect()`.
242
- * Returns `null` for insecure/metadata-only credentials.
243
- *
244
- * @returns {object|null} TLS options `{ ca, key, cert, rejectUnauthorized }`.
245
- */
246
- getConnectionOptions()
247
- {
248
- if (this.type === CredentialType.SSL)
249
- {
250
- const opts = {};
251
- if (this._config.ca) opts.ca = this._config.ca;
252
- if (this._config.key) opts.key = this._config.key;
253
- if (this._config.cert) opts.cert = this._config.cert;
254
- opts.rejectUnauthorized = this._config.rejectUnauthorized;
255
- return opts;
256
- }
257
-
258
- if (this.type === CredentialType.COMPOSITE && this._config.channelCred)
259
- {
260
- return this._config.channelCred.getConnectionOptions();
261
- }
262
-
263
- return null;
264
- }
265
-
266
- /**
267
- * Generate per-call metadata by running all metadata generators.
268
- *
269
- * @param {object} [params] - Call parameters `{ serviceUrl, methodName }`.
270
- * @returns {Promise<object>} Merged metadata key-value pairs.
271
- */
272
- async generateMetadata(params)
273
- {
274
- const generators = [];
275
-
276
- if (this.type === CredentialType.METADATA)
277
- {
278
- generators.push(this._config.generator);
279
- }
280
- else if (this.type === CredentialType.COMPOSITE)
281
- {
282
- generators.push(...this._config.metadataGenerators);
283
- }
284
-
285
- if (generators.length === 0) return {};
286
-
287
- const merged = {};
288
- for (const gen of generators)
289
- {
290
- const md = await gen(params);
291
- if (md && typeof md === 'object')
292
- {
293
- Object.assign(merged, md);
294
- }
295
- }
296
-
297
- return merged;
298
- }
299
- }
300
-
301
- // -- Certificate Rotation Helper ---------------------------------
302
-
303
- /**
304
- * Create SSL credentials with automatic certificate rotation.
305
- * Watches certificate files for changes and reloads them.
306
- *
307
- * Returns a credentials-like object with `getCurrent()` to get
308
- * the latest credentials and `stop()` to cease watching.
309
- *
310
- * @param {object} opts - Options.
311
- * @param {string} opts.caPath - Path to CA certificate file.
312
- * @param {string} [opts.keyPath] - Path to client key file (for mTLS).
313
- * @param {string} [opts.certPath] - Path to client certificate file (for mTLS).
314
- * @param {number} [opts.pollInterval=30000] - Check interval in ms (default 30s).
315
- * @param {object} [opts.sslOpts] - Additional SSL options.
316
- * @returns {{ getCurrent: () => ChannelCredentials, stop: () => void }}
317
- *
318
- * @example
319
- * const rotating = createRotatingCredentials({
320
- * caPath: '/certs/ca.pem',
321
- * keyPath: '/certs/client.key',
322
- * certPath: '/certs/client.pem',
323
- * });
324
- * // Use rotating.getCurrent() when creating clients
325
- * const client = new GrpcClient({ address, credentials: rotating.getCurrent() }, schema, service);
326
- * // Stop watching on shutdown
327
- * rotating.stop();
328
- */
329
- function createRotatingCredentials(opts)
330
- {
331
- if (!opts || !opts.caPath)
332
- throw new Error('createRotatingCredentials requires caPath');
333
-
334
- let current = ChannelCredentials.createSslFromFiles(
335
- opts.caPath, opts.keyPath || null, opts.certPath || null, opts.sslOpts || {}
336
- );
337
-
338
- /** @private */ let lastMtimes = _getMtimes(opts);
339
-
340
- const timer = setInterval(() =>
341
- {
342
- try
343
- {
344
- const mtimes = _getMtimes(opts);
345
- if (mtimes.ca !== lastMtimes.ca ||
346
- mtimes.key !== lastMtimes.key ||
347
- mtimes.cert !== lastMtimes.cert)
348
- {
349
- current = ChannelCredentials.createSslFromFiles(
350
- opts.caPath, opts.keyPath || null, opts.certPath || null, opts.sslOpts || {}
351
- );
352
- lastMtimes = mtimes;
353
- log.info('SSL credentials rotated');
354
- }
355
- }
356
- catch (err)
357
- {
358
- log.error('credential rotation check failed: %s', err.message);
359
- }
360
- }, opts.pollInterval || 30000);
361
-
362
- if (timer.unref) timer.unref();
363
-
364
- return {
365
- getCurrent() { return current; },
366
- stop() { clearInterval(timer); },
367
- };
368
- }
369
-
370
- /**
371
- * Get file modification times.
372
- * @private
373
- */
374
- function _getMtimes(opts)
375
- {
376
- return {
377
- ca: opts.caPath ? _safeMtime(opts.caPath) : 0,
378
- key: opts.keyPath ? _safeMtime(opts.keyPath) : 0,
379
- cert: opts.certPath ? _safeMtime(opts.certPath) : 0,
380
- };
381
- }
382
-
383
- /**
384
- * @private
385
- */
386
- function _safeMtime(filePath)
387
- {
388
- try { return fs.statSync(filePath).mtimeMs; }
389
- catch (_) { return 0; }
390
- }
391
-
392
- // -- Exports -------------------------------------------------
393
-
394
- module.exports = {
395
- ChannelCredentials,
396
- CredentialType,
397
- createRotatingCredentials,
398
- };
1
+ /**
2
+ * @module grpc/credentials
3
+ * @description Channel credentials for gRPC connections.
4
+ * Provides factory functions for creating insecure, SSL/TLS,
5
+ * and metadata-based credentials. Supports certificate rotation
6
+ * and credential composition.
7
+ *
8
+ * Uses only Node.js built-in `tls` and `fs` — no external packages.
9
+ *
10
+ * @example | Insecure (plaintext)
11
+ * const { ChannelCredentials, GrpcClient } = require('@zero-server/sdk');
12
+ * const creds = ChannelCredentials.createInsecure();
13
+ * const client = new GrpcClient({ address: 'http://localhost:50051', credentials: creds }, schema, 'Greeter');
14
+ *
15
+ * @example | Server-only TLS
16
+ * const creds = ChannelCredentials.createSsl(fs.readFileSync('ca.pem'));
17
+ *
18
+ * @example | Mutual TLS (mTLS)
19
+ * const creds = ChannelCredentials.createSsl(
20
+ * fs.readFileSync('ca.pem'),
21
+ * fs.readFileSync('client-key.pem'),
22
+ * fs.readFileSync('client-cert.pem'),
23
+ * );
24
+ *
25
+ * @example | Metadata credentials (e.g. Bearer token)
26
+ * const creds = ChannelCredentials.createFromMetadata((params) => ({
27
+ * authorization: 'Bearer ' + getToken(),
28
+ * }));
29
+ *
30
+ * @example | Composed credentials (TLS + per-call metadata)
31
+ * const creds = ChannelCredentials.combine(
32
+ * ChannelCredentials.createSsl(ca),
33
+ * ChannelCredentials.createFromMetadata(() => ({ authorization: 'Bearer ' + token })),
34
+ * );
35
+ */
36
+
37
+ const fs = require('fs');
38
+ const log = require('../debug')('zero:grpc:credentials');
39
+
40
+ // -- Credential Types ----------------------------------------
41
+
42
+ /** @enum {string} */
43
+ const CredentialType = {
44
+ INSECURE: 'insecure',
45
+ SSL: 'ssl',
46
+ METADATA: 'metadata',
47
+ COMPOSITE: 'composite',
48
+ };
49
+
50
+ // -- ChannelCredentials Class --------------------------------
51
+
52
+ /**
53
+ * Channel credentials define how a gRPC client authenticates to the server.
54
+ *
55
+ * @class
56
+ */
57
+ class ChannelCredentials
58
+ {
59
+ /**
60
+ * @param {string} type - Credential type.
61
+ * @param {object} [config] - Type-specific configuration.
62
+ * @private
63
+ */
64
+ constructor(type, config = {})
65
+ {
66
+ /** @type {string} */
67
+ this.type = type;
68
+ /** @private */
69
+ this._config = config;
70
+ }
71
+
72
+ /**
73
+ * Create insecure (plaintext) credentials.
74
+ * No TLS — suitable for development or service-mesh environments
75
+ * where transport security is handled by the infrastructure.
76
+ *
77
+ * @returns {ChannelCredentials}
78
+ */
79
+ static createInsecure()
80
+ {
81
+ return new ChannelCredentials(CredentialType.INSECURE);
82
+ }
83
+
84
+ /**
85
+ * Create SSL/TLS credentials.
86
+ *
87
+ * @param {Buffer|string|null} [rootCerts] - Root CA certificate(s) in PEM format.
88
+ * If null, uses the system default trust store.
89
+ * @param {Buffer|string|null} [clientKey] - Client private key in PEM format (for mTLS).
90
+ * @param {Buffer|string|null} [clientCert] - Client certificate in PEM format (for mTLS).
91
+ * @param {object} [opts] - Additional options.
92
+ * @param {boolean} [opts.rejectUnauthorized=true] - Reject connections with invalid certs.
93
+ * @returns {ChannelCredentials}
94
+ *
95
+ * @example | Server-only TLS
96
+ * const creds = ChannelCredentials.createSsl(fs.readFileSync('ca.pem'));
97
+ *
98
+ * @example | Mutual TLS
99
+ * const creds = ChannelCredentials.createSsl(caPem, keyPem, certPem);
100
+ */
101
+ static createSsl(rootCerts, clientKey, clientCert, opts = {})
102
+ {
103
+ const config = {
104
+ rejectUnauthorized: opts.rejectUnauthorized !== false,
105
+ };
106
+
107
+ if (rootCerts)
108
+ {
109
+ config.ca = Buffer.isBuffer(rootCerts) ? rootCerts : Buffer.from(rootCerts);
110
+ }
111
+ if (clientKey)
112
+ {
113
+ config.key = Buffer.isBuffer(clientKey) ? clientKey : Buffer.from(clientKey);
114
+ }
115
+ if (clientCert)
116
+ {
117
+ config.cert = Buffer.isBuffer(clientCert) ? clientCert : Buffer.from(clientCert);
118
+ }
119
+
120
+ if (config.key && !config.cert)
121
+ throw new Error('Client key provided without client certificate');
122
+ if (config.cert && !config.key)
123
+ throw new Error('Client certificate provided without client key');
124
+
125
+ return new ChannelCredentials(CredentialType.SSL, config);
126
+ }
127
+
128
+ /**
129
+ * Create SSL credentials from PEM file paths.
130
+ * Files are read once at creation time.
131
+ *
132
+ * @param {string|null} [caPath] - Path to CA certificate file.
133
+ * @param {string|null} [keyPath] - Path to client key file.
134
+ * @param {string|null} [certPath] - Path to client certificate file.
135
+ * @param {object} [opts] - Additional options.
136
+ * @returns {ChannelCredentials}
137
+ *
138
+ * @example
139
+ * const creds = ChannelCredentials.createSslFromFiles('./certs/ca.pem', './certs/client.key', './certs/client.pem');
140
+ */
141
+ static createSslFromFiles(caPath, keyPath, certPath, opts = {})
142
+ {
143
+ const ca = caPath ? fs.readFileSync(caPath) : null;
144
+ const key = keyPath ? fs.readFileSync(keyPath) : null;
145
+ const cert = certPath ? fs.readFileSync(certPath) : null;
146
+ return ChannelCredentials.createSsl(ca, key, cert, opts);
147
+ }
148
+
149
+ /**
150
+ * Create per-call metadata credentials.
151
+ * The generator function is called before each RPC to produce
152
+ * metadata headers (e.g. authorization tokens).
153
+ *
154
+ * @param {Function} metadataGenerator - `(params?) => object|Promise<object>`.
155
+ * Returns key-value pairs to merge into call metadata.
156
+ * `params` includes `{ serviceUrl, methodName }`.
157
+ * @returns {ChannelCredentials}
158
+ *
159
+ * @example
160
+ * const creds = ChannelCredentials.createFromMetadata(async () => ({
161
+ * authorization: 'Bearer ' + await getAccessToken(),
162
+ * }));
163
+ */
164
+ static createFromMetadata(metadataGenerator)
165
+ {
166
+ if (typeof metadataGenerator !== 'function')
167
+ throw new Error('createFromMetadata requires a function');
168
+
169
+ return new ChannelCredentials(CredentialType.METADATA, {
170
+ generator: metadataGenerator,
171
+ });
172
+ }
173
+
174
+ /**
175
+ * Combine multiple credentials into one.
176
+ * At most one channel credential (insecure/SSL) and any number
177
+ * of call credentials (metadata) can be combined.
178
+ *
179
+ * @param {...ChannelCredentials} credentials - Credentials to combine.
180
+ * @returns {ChannelCredentials}
181
+ *
182
+ * @example
183
+ * const creds = ChannelCredentials.combine(
184
+ * ChannelCredentials.createSsl(ca),
185
+ * ChannelCredentials.createFromMetadata(() => ({ 'x-api-key': apiKey })),
186
+ * ChannelCredentials.createFromMetadata(async () => ({ authorization: 'Bearer ' + token })),
187
+ * );
188
+ */
189
+ static combine(...credentials)
190
+ {
191
+ let channelCred = null;
192
+ const metadataGens = [];
193
+
194
+ for (const cred of credentials)
195
+ {
196
+ if (!(cred instanceof ChannelCredentials))
197
+ throw new Error('combine() arguments must be ChannelCredentials instances');
198
+
199
+ if (cred.type === CredentialType.COMPOSITE)
200
+ {
201
+ // Flatten nested composites
202
+ if (cred._config.channelCred) channelCred = cred._config.channelCred;
203
+ metadataGens.push(...cred._config.metadataGenerators);
204
+ }
205
+ else if (cred.type === CredentialType.INSECURE || cred.type === CredentialType.SSL)
206
+ {
207
+ if (channelCred)
208
+ throw new Error('Cannot combine multiple channel credentials (use at most one insecure/SSL)');
209
+ channelCred = cred;
210
+ }
211
+ else if (cred.type === CredentialType.METADATA)
212
+ {
213
+ metadataGens.push(cred._config.generator);
214
+ }
215
+ }
216
+
217
+ return new ChannelCredentials(CredentialType.COMPOSITE, {
218
+ channelCred,
219
+ metadataGenerators: metadataGens,
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Whether this credential uses TLS.
225
+ * @returns {boolean}
226
+ */
227
+ isSecure()
228
+ {
229
+ if (this.type === CredentialType.INSECURE) return false;
230
+ if (this.type === CredentialType.SSL) return true;
231
+ if (this.type === CredentialType.METADATA) return false;
232
+ if (this.type === CredentialType.COMPOSITE)
233
+ {
234
+ const ch = this._config.channelCred;
235
+ return ch ? ch.isSecure() : false;
236
+ }
237
+ return false;
238
+ }
239
+
240
+ /**
241
+ * Get the TLS connection options for `http2.connect()`.
242
+ * Returns `null` for insecure/metadata-only credentials.
243
+ *
244
+ * @returns {object|null} TLS options `{ ca, key, cert, rejectUnauthorized }`.
245
+ */
246
+ getConnectionOptions()
247
+ {
248
+ if (this.type === CredentialType.SSL)
249
+ {
250
+ const opts = {};
251
+ if (this._config.ca) opts.ca = this._config.ca;
252
+ if (this._config.key) opts.key = this._config.key;
253
+ if (this._config.cert) opts.cert = this._config.cert;
254
+ opts.rejectUnauthorized = this._config.rejectUnauthorized;
255
+ return opts;
256
+ }
257
+
258
+ if (this.type === CredentialType.COMPOSITE && this._config.channelCred)
259
+ {
260
+ return this._config.channelCred.getConnectionOptions();
261
+ }
262
+
263
+ return null;
264
+ }
265
+
266
+ /**
267
+ * Generate per-call metadata by running all metadata generators.
268
+ *
269
+ * @param {object} [params] - Call parameters `{ serviceUrl, methodName }`.
270
+ * @returns {Promise<object>} Merged metadata key-value pairs.
271
+ */
272
+ async generateMetadata(params)
273
+ {
274
+ const generators = [];
275
+
276
+ if (this.type === CredentialType.METADATA)
277
+ {
278
+ generators.push(this._config.generator);
279
+ }
280
+ else if (this.type === CredentialType.COMPOSITE)
281
+ {
282
+ generators.push(...this._config.metadataGenerators);
283
+ }
284
+
285
+ if (generators.length === 0) return {};
286
+
287
+ const merged = {};
288
+ for (const gen of generators)
289
+ {
290
+ const md = await gen(params);
291
+ if (md && typeof md === 'object')
292
+ {
293
+ Object.assign(merged, md);
294
+ }
295
+ }
296
+
297
+ return merged;
298
+ }
299
+ }
300
+
301
+ // -- Certificate Rotation Helper ---------------------------------
302
+
303
+ /**
304
+ * Create SSL credentials with automatic certificate rotation.
305
+ * Watches certificate files for changes and reloads them.
306
+ *
307
+ * Returns a credentials-like object with `getCurrent()` to get
308
+ * the latest credentials and `stop()` to cease watching.
309
+ *
310
+ * @param {object} opts - Options.
311
+ * @param {string} opts.caPath - Path to CA certificate file.
312
+ * @param {string} [opts.keyPath] - Path to client key file (for mTLS).
313
+ * @param {string} [opts.certPath] - Path to client certificate file (for mTLS).
314
+ * @param {number} [opts.pollInterval=30000] - Check interval in ms (default 30s).
315
+ * @param {object} [opts.sslOpts] - Additional SSL options.
316
+ * @returns {{ getCurrent: () => ChannelCredentials, stop: () => void }}
317
+ *
318
+ * @example
319
+ * const rotating = createRotatingCredentials({
320
+ * caPath: '/certs/ca.pem',
321
+ * keyPath: '/certs/client.key',
322
+ * certPath: '/certs/client.pem',
323
+ * });
324
+ * // Use rotating.getCurrent() when creating clients
325
+ * const client = new GrpcClient({ address, credentials: rotating.getCurrent() }, schema, service);
326
+ * // Stop watching on shutdown
327
+ * rotating.stop();
328
+ */
329
+ function createRotatingCredentials(opts)
330
+ {
331
+ if (!opts || !opts.caPath)
332
+ throw new Error('createRotatingCredentials requires caPath');
333
+
334
+ let current = ChannelCredentials.createSslFromFiles(
335
+ opts.caPath, opts.keyPath || null, opts.certPath || null, opts.sslOpts || {}
336
+ );
337
+
338
+ /** @private */ let lastMtimes = _getMtimes(opts);
339
+
340
+ const timer = setInterval(() =>
341
+ {
342
+ try
343
+ {
344
+ const mtimes = _getMtimes(opts);
345
+ if (mtimes.ca !== lastMtimes.ca ||
346
+ mtimes.key !== lastMtimes.key ||
347
+ mtimes.cert !== lastMtimes.cert)
348
+ {
349
+ current = ChannelCredentials.createSslFromFiles(
350
+ opts.caPath, opts.keyPath || null, opts.certPath || null, opts.sslOpts || {}
351
+ );
352
+ lastMtimes = mtimes;
353
+ log.info('SSL credentials rotated');
354
+ }
355
+ }
356
+ catch (err)
357
+ {
358
+ log.error('credential rotation check failed: %s', err.message);
359
+ }
360
+ }, opts.pollInterval || 30000);
361
+
362
+ if (timer.unref) timer.unref();
363
+
364
+ return {
365
+ getCurrent() { return current; },
366
+ stop() { clearInterval(timer); },
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Get file modification times.
372
+ * @private
373
+ */
374
+ function _getMtimes(opts)
375
+ {
376
+ return {
377
+ ca: opts.caPath ? _safeMtime(opts.caPath) : 0,
378
+ key: opts.keyPath ? _safeMtime(opts.keyPath) : 0,
379
+ cert: opts.certPath ? _safeMtime(opts.certPath) : 0,
380
+ };
381
+ }
382
+
383
+ /**
384
+ * @private
385
+ */
386
+ function _safeMtime(filePath)
387
+ {
388
+ try { return fs.statSync(filePath).mtimeMs; }
389
+ catch (_) { return 0; }
390
+ }
391
+
392
+ // -- Exports -------------------------------------------------
393
+
394
+ module.exports = {
395
+ ChannelCredentials,
396
+ CredentialType,
397
+ createRotatingCredentials,
398
+ };