-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathconnection_string.ts
1056 lines (996 loc) · 30.8 KB
/
connection_string.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as dns from 'dns';
import * as fs from 'fs';
import ConnectionString from 'mongodb-connection-string-url';
import { URLSearchParams } from 'url';
import { AuthMechanism } from './cmap/auth/defaultAuthProviders';
import { ReadPreference, ReadPreferenceMode } from './read_preference';
import { ReadConcern, ReadConcernLevel } from './read_concern';
import { W, WriteConcern } from './write_concern';
import { MongoParseError } from './error';
import {
AnyOptions,
Callback,
DEFAULT_PK_FACTORY,
isRecord,
makeClientMetadata,
setDifference,
HostAddress,
emitWarning
} from './utils';
import type { Document } from './bson';
import {
DriverInfo,
MongoClient,
MongoClientOptions,
MongoOptions,
PkFactory,
ServerApi,
ServerApiVersion
} from './mongo_client';
import { MongoCredentials } from './cmap/auth/mongo_credentials';
import type { TagSet } from './sdam/server_description';
import { Logger, LoggerLevel } from './logger';
import { PromiseProvider } from './promise_provider';
import { Encrypter } from './encrypter';
/**
* Determines whether a provided address matches the provided parent domain in order
* to avoid certain attack vectors.
*
* @param srvAddress - The address to check against a domain
* @param parentDomain - The domain to check the provided address against
* @returns Whether the provided address matches the parent domain
*/
function matchesParentDomain(srvAddress: string, parentDomain: string): boolean {
const regex = /^.*?\./;
const srv = `.${srvAddress.replace(regex, '')}`;
const parent = `.${parentDomain.replace(regex, '')}`;
return srv.endsWith(parent);
}
/**
* Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal
* connection string.
*
* @param uri - The connection string to parse
* @param options - Optional user provided connection string options
*/
export function resolveSRVRecord(options: MongoOptions, callback: Callback<HostAddress[]>): void {
if (typeof options.srvHost !== 'string') {
return callback(new MongoParseError('Cannot resolve empty srv string'));
}
if (options.srvHost.split('.').length < 3) {
return callback(new MongoParseError('URI does not have hostname, domain name and tld'));
}
// Resolve the SRV record and use the result as the list of hosts to connect to.
const lookupAddress = options.srvHost;
dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => {
if (err) return callback(err);
if (addresses.length === 0) {
return callback(new MongoParseError('No addresses found at host'));
}
for (const { name } of addresses) {
if (!matchesParentDomain(name, lookupAddress)) {
return callback(
new MongoParseError('Server record does not share hostname with parent URI')
);
}
}
const hostAddresses = addresses.map(r =>
HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)
);
// Resolve TXT record and add options from there if they exist.
dns.resolveTxt(lookupAddress, (err, record) => {
if (err) {
if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') {
return callback(err);
}
} else {
if (record.length > 1) {
return callback(new MongoParseError('Multiple text records not allowed'));
}
const txtRecordOptions = new URLSearchParams(record[0].join(''));
const txtRecordOptionKeys = [...txtRecordOptions.keys()];
if (txtRecordOptionKeys.some(key => key !== 'authSource' && key !== 'replicaSet')) {
return callback(
new MongoParseError('Text record must only set `authSource` or `replicaSet`')
);
}
const source = txtRecordOptions.get('authSource') ?? undefined;
const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined;
if (source === '' || replicaSet === '') {
return callback(new MongoParseError('Cannot have empty URI params in DNS TXT Record'));
}
if (!options.userSpecifiedAuthSource && source) {
options.credentials = MongoCredentials.merge(options.credentials, { source });
}
if (!options.userSpecifiedReplicaSet && replicaSet) {
options.replicaSet = replicaSet;
}
}
callback(undefined, hostAddresses);
});
});
}
/**
* Checks if TLS options are valid
*
* @param options - The options used for options parsing
* @throws MongoParseError if TLS options are invalid
*/
export function checkTLSOptions(options: AnyOptions): void {
if (!options) return;
const check = (a: string, b: string) => {
if (Reflect.has(options, a) && Reflect.has(options, b)) {
throw new MongoParseError(`The '${a}' option cannot be used with '${b}'`);
}
};
check('tlsInsecure', 'tlsAllowInvalidCertificates');
check('tlsInsecure', 'tlsAllowInvalidHostnames');
check('tlsInsecure', 'tlsDisableCertificateRevocationCheck');
check('tlsInsecure', 'tlsDisableOCSPEndpointCheck');
check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck');
check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck');
check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck');
}
const TRUTHS = new Set(['true', 't', '1', 'y', 'yes']);
const FALSEHOODS = new Set(['false', 'f', '0', 'n', 'no', '-1']);
function getBoolean(name: string, value: unknown): boolean {
if (typeof value === 'boolean') return value;
const valueString = String(value).toLowerCase();
if (TRUTHS.has(valueString)) return true;
if (FALSEHOODS.has(valueString)) return false;
throw new MongoParseError(`For ${name} Expected stringified boolean value, got: ${value}`);
}
function getInt(name: string, value: unknown): number {
if (typeof value === 'number') return Math.trunc(value);
const parsedValue = Number.parseInt(String(value), 10);
if (!Number.isNaN(parsedValue)) return parsedValue;
throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`);
}
function getUint(name: string, value: unknown): number {
const parsedValue = getInt(name, value);
if (parsedValue < 0) {
throw new MongoParseError(`${name} can only be a positive int value, got: ${value}`);
}
return parsedValue;
}
function toRecord(value: string): Record<string, any> {
const record = Object.create(null);
const keyValuePairs = value.split(',');
for (const keyValue of keyValuePairs) {
const [key, value] = keyValue.split(':');
if (value == null) {
throw new MongoParseError('Cannot have undefined values in key value pairs');
}
try {
// try to get a boolean
record[key] = getBoolean('', value);
} catch {
try {
// try to get a number
record[key] = getInt('', value);
} catch {
// keep value as a string
record[key] = value;
}
}
}
return record;
}
class CaseInsensitiveMap extends Map<string, any> {
constructor(entries: Array<[string, any]> = []) {
super(entries.map(([k, v]) => [k.toLowerCase(), v]));
}
has(k: string) {
return super.has(k.toLowerCase());
}
get(k: string) {
return super.get(k.toLowerCase());
}
set(k: string, v: any) {
return super.set(k.toLowerCase(), v);
}
delete(k: string): boolean {
return super.delete(k.toLowerCase());
}
}
export function parseOptions(
uri: string,
mongoClient: MongoClient | MongoClientOptions | undefined = undefined,
options: MongoClientOptions = {}
): MongoOptions {
if (mongoClient != null && !(mongoClient instanceof MongoClient)) {
options = mongoClient;
mongoClient = undefined;
}
const url = new ConnectionString(uri);
const { hosts, isSRV } = url;
const mongoOptions = Object.create(null);
mongoOptions.hosts = isSRV ? [] : hosts.map(HostAddress.fromString);
if (isSRV) {
// SRV Record is resolved upon connecting
mongoOptions.srvHost = hosts[0];
if (!url.searchParams.has('tls') && !url.searchParams.has('ssl')) {
options.tls = true;
}
}
const urlOptions = new CaseInsensitiveMap();
if (url.pathname !== '/' && url.pathname !== '') {
const dbName = decodeURIComponent(
url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname
);
if (dbName) {
urlOptions.set('dbName', [dbName]);
}
}
if (url.username !== '') {
const auth: Document = {
username: decodeURIComponent(url.username)
};
if (typeof url.password === 'string') {
auth.password = decodeURIComponent(url.password);
}
urlOptions.set('auth', [auth]);
}
for (const key of url.searchParams.keys()) {
const values = [...url.searchParams.getAll(key)];
if (values.includes('')) {
throw new MongoParseError('URI cannot contain options with no value');
}
if (key.toLowerCase() === 'serverapi') {
throw new MongoParseError(
'URI cannot contain `serverApi`, it can only be passed to the client'
);
}
if (key.toLowerCase() === 'authsource' && urlOptions.has('authSource')) {
// If authSource is an explicit key in the urlOptions we need to remove the implicit dbName
urlOptions.delete('authSource');
}
if (!urlOptions.has(key)) {
urlOptions.set(key, values);
}
}
const objectOptions = new CaseInsensitiveMap(
Object.entries(options).filter(([, v]) => v != null)
);
const allOptions = new CaseInsensitiveMap();
const allKeys = new Set<string>([
...urlOptions.keys(),
...objectOptions.keys(),
...DEFAULT_OPTIONS.keys()
]);
for (const key of allKeys) {
const values = [];
if (objectOptions.has(key)) {
values.push(objectOptions.get(key));
}
if (urlOptions.has(key)) {
values.push(...urlOptions.get(key));
}
if (DEFAULT_OPTIONS.has(key)) {
values.push(DEFAULT_OPTIONS.get(key));
}
allOptions.set(key, values);
}
const unsupportedOptions = setDifference(
allKeys,
Array.from(Object.keys(OPTIONS)).map(s => s.toLowerCase())
);
if (unsupportedOptions.size !== 0) {
const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option';
const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is';
throw new MongoParseError(
`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`
);
}
for (const [key, descriptor] of Object.entries(OPTIONS)) {
const values = allOptions.get(key);
if (!values || values.length === 0) continue;
setOption(mongoOptions, key, descriptor, values);
}
if (mongoOptions.credentials) {
const isGssapi = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_GSSAPI;
const isX509 = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_X509;
const isAws = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_AWS;
if (
(isGssapi || isX509) &&
allOptions.has('authSource') &&
mongoOptions.credentials.source !== '$external'
) {
// If authSource was explicitly given and its incorrect, we error
throw new MongoParseError(
`${mongoOptions.credentials} can only have authSource set to '$external'`
);
}
if (!(isGssapi || isX509 || isAws) && mongoOptions.dbName && !allOptions.has('authSource')) {
// inherit the dbName unless GSSAPI or X509, then silently ignore dbName
// and there was no specific authSource given
mongoOptions.credentials = MongoCredentials.merge(mongoOptions.credentials, {
source: mongoOptions.dbName
});
}
mongoOptions.credentials.validate();
}
if (!mongoOptions.dbName) {
// dbName default is applied here because of the credential validation above
mongoOptions.dbName = 'test';
}
if (allOptions.has('tls')) {
if (new Set(allOptions.get('tls')?.map(getBoolean)).size !== 1) {
throw new MongoParseError('All values of tls must be the same.');
}
}
if (allOptions.has('ssl')) {
if (new Set(allOptions.get('ssl')?.map(getBoolean)).size !== 1) {
throw new MongoParseError('All values of ssl must be the same.');
}
}
checkTLSOptions(mongoOptions);
if (options.promiseLibrary) PromiseProvider.set(options.promiseLibrary);
if (mongoOptions.directConnection && typeof mongoOptions.srvHost === 'string') {
throw new MongoParseError('directConnection not supported with SRV URI');
}
// Potential SRV Overrides
mongoOptions.userSpecifiedAuthSource =
objectOptions.has('authSource') || urlOptions.has('authSource');
mongoOptions.userSpecifiedReplicaSet =
objectOptions.has('replicaSet') || urlOptions.has('replicaSet');
if (mongoClient && mongoOptions.autoEncryption) {
Encrypter.checkForMongoCrypt();
mongoOptions.encrypter = new Encrypter(mongoClient, uri, options);
mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter;
}
return mongoOptions;
}
function setOption(
mongoOptions: any,
key: string,
descriptor: OptionDescriptor,
values: unknown[]
) {
const { target, type, transform, deprecated } = descriptor;
const name = target ?? key;
if (deprecated) {
const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : '';
emitWarning(`${key} is a deprecated option${deprecatedMsg}`);
}
switch (type) {
case 'boolean':
mongoOptions[name] = getBoolean(name, values[0]);
break;
case 'int':
mongoOptions[name] = getInt(name, values[0]);
break;
case 'uint':
mongoOptions[name] = getUint(name, values[0]);
break;
case 'string':
if (values[0] == null) {
break;
}
mongoOptions[name] = String(values[0]);
break;
case 'record':
if (!isRecord(values[0])) {
throw new MongoParseError(`${name} must be an object`);
}
mongoOptions[name] = values[0];
break;
case 'any':
mongoOptions[name] = values[0];
break;
default: {
if (!transform) {
throw new MongoParseError('Descriptors missing a type must define a transform');
}
const transformValue = transform({ name, options: mongoOptions, values });
mongoOptions[name] = transformValue;
break;
}
}
}
interface OptionDescriptor {
target?: string;
type?: 'boolean' | 'int' | 'uint' | 'record' | 'string' | 'any';
default?: any;
deprecated?: boolean | string;
/**
* @param name - the original option name
* @param options - the options so far for resolution
* @param values - the possible values in precedence order
*/
transform?: (args: { name: string; options: MongoOptions; values: unknown[] }) => unknown;
}
export const OPTIONS = {
appName: {
target: 'metadata',
transform({ options, values: [value] }): DriverInfo {
return makeClientMetadata({ ...options.driverInfo, appName: String(value) });
}
},
auth: {
target: 'credentials',
transform({ name, options, values: [value] }): MongoCredentials {
if (!isRecord(value, ['username', 'password'] as const)) {
throw new MongoParseError(
`${name} must be an object with 'username' and 'password' properties`
);
}
return MongoCredentials.merge(options.credentials, {
username: value.username,
password: value.password
});
}
},
authMechanism: {
target: 'credentials',
transform({ options, values: [value] }): MongoCredentials {
const mechanisms = Object.values(AuthMechanism);
const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw`\b${value}\b`, 'i')));
if (!mechanism) {
throw new MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`);
}
let source = options.credentials?.source;
if (
mechanism === AuthMechanism.MONGODB_PLAIN ||
mechanism === AuthMechanism.MONGODB_GSSAPI ||
mechanism === AuthMechanism.MONGODB_AWS ||
mechanism === AuthMechanism.MONGODB_X509
) {
// some mechanisms have '$external' as the Auth Source
source = '$external';
}
let password = options.credentials?.password;
if (mechanism === AuthMechanism.MONGODB_X509 && password === '') {
password = undefined;
}
return MongoCredentials.merge(options.credentials, {
mechanism,
source,
password
});
}
},
authMechanismProperties: {
target: 'credentials',
transform({ options, values: [value] }): MongoCredentials {
if (typeof value === 'string') {
value = toRecord(value);
}
if (!isRecord(value)) {
throw new MongoParseError('AuthMechanismProperties must be an object');
}
return MongoCredentials.merge(options.credentials, { mechanismProperties: value });
}
},
authSource: {
target: 'credentials',
transform({ options, values: [value] }): MongoCredentials {
const source = String(value);
return MongoCredentials.merge(options.credentials, { source });
}
},
autoEncryption: {
type: 'record'
},
bsonRegExp: {
type: 'boolean'
},
serverApi: {
target: 'serverApi',
transform({ values: [version] }): ServerApi {
const serverApiToValidate =
typeof version === 'string' ? ({ version } as ServerApi) : (version as ServerApi);
const versionToValidate = serverApiToValidate && serverApiToValidate.version;
if (!versionToValidate) {
throw new MongoParseError(
`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(
ServerApiVersion
).join('", "')}"]`
);
}
if (!Object.values(ServerApiVersion).some(v => v === versionToValidate)) {
throw new MongoParseError(
`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(
ServerApiVersion
).join('", "')}"]`
);
}
return serverApiToValidate;
}
},
checkKeys: {
type: 'boolean'
},
compressors: {
default: 'none',
target: 'compressors',
transform({ values }) {
const compressionList = new Set();
for (const compVal of values as string[]) {
for (const c of compVal.split(',')) {
if (['none', 'snappy', 'zlib'].includes(String(c))) {
compressionList.add(String(c));
} else {
throw new MongoParseError(`${c} is not a valid compression mechanism`);
}
}
}
return [...compressionList];
}
},
connectTimeoutMS: {
default: 30000,
type: 'uint'
},
dbName: {
type: 'string'
},
directConnection: {
default: false,
type: 'boolean'
},
driverInfo: {
target: 'metadata',
default: makeClientMetadata(),
transform({ options, values: [value] }) {
if (!isRecord(value)) throw new MongoParseError('DriverInfo must be an object');
return makeClientMetadata({
driverInfo: value,
appName: options.metadata?.application?.name
});
}
},
family: {
transform({ name, values: [value] }): 4 | 6 {
const transformValue = getInt(name, value);
if (transformValue === 4 || transformValue === 6) {
return transformValue;
}
throw new MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`);
}
},
fieldsAsRaw: {
type: 'record'
},
forceServerObjectId: {
default: false,
type: 'boolean'
},
fsync: {
deprecated: 'Please use journal instead',
target: 'writeConcern',
transform({ name, options, values: [value] }): WriteConcern {
const wc = WriteConcern.fromOptions({
writeConcern: {
...options.writeConcern,
fsync: getBoolean(name, value)
}
});
if (!wc) throw new MongoParseError(`Unable to make a writeConcern from fsync=${value}`);
return wc;
}
} as OptionDescriptor,
heartbeatFrequencyMS: {
default: 10000,
type: 'uint'
},
ignoreUndefined: {
type: 'boolean'
},
j: {
deprecated: 'Please use journal instead',
target: 'writeConcern',
transform({ name, options, values: [value] }): WriteConcern {
const wc = WriteConcern.fromOptions({
writeConcern: {
...options.writeConcern,
journal: getBoolean(name, value)
}
});
if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`);
return wc;
}
} as OptionDescriptor,
journal: {
target: 'writeConcern',
transform({ name, options, values: [value] }): WriteConcern {
const wc = WriteConcern.fromOptions({
writeConcern: {
...options.writeConcern,
journal: getBoolean(name, value)
}
});
if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`);
return wc;
}
},
keepAlive: {
default: true,
type: 'boolean'
},
keepAliveInitialDelay: {
default: 120000,
type: 'uint'
},
localThresholdMS: {
default: 15,
type: 'uint'
},
logger: {
default: new Logger('MongoClient'),
transform({ values: [value] }) {
if (value instanceof Logger) {
return value;
}
emitWarning('Alternative loggers might not be supported');
// TODO: make Logger an interface that others can implement, make usage consistent in driver
// DRIVERS-1204
}
},
loggerLevel: {
target: 'logger',
transform({ values: [value] }) {
return new Logger('MongoClient', { loggerLevel: value as LoggerLevel });
}
},
maxIdleTimeMS: {
default: 0,
type: 'uint'
},
maxPoolSize: {
default: 100,
type: 'uint'
},
maxStalenessSeconds: {
target: 'readPreference',
transform({ name, options, values: [value] }) {
const maxStalenessSeconds = getUint(name, value);
if (options.readPreference) {
return ReadPreference.fromOptions({
readPreference: { ...options.readPreference, maxStalenessSeconds }
});
} else {
return new ReadPreference('secondary', undefined, { maxStalenessSeconds });
}
}
},
minInternalBufferSize: {
type: 'uint'
},
minPoolSize: {
default: 0,
type: 'uint'
},
minHeartbeatFrequencyMS: {
default: 500,
type: 'uint'
},
monitorCommands: {
default: true,
type: 'boolean'
},
name: {
target: 'driverInfo',
transform({ values: [value], options }) {
return { ...options.driverInfo, name: String(value) };
}
} as OptionDescriptor,
noDelay: {
default: true,
type: 'boolean'
},
pkFactory: {
default: DEFAULT_PK_FACTORY,
transform({ values: [value] }): PkFactory {
if (isRecord(value, ['createPk'] as const) && typeof value.createPk === 'function') {
return value as PkFactory;
}
throw new MongoParseError(
`Option pkFactory must be an object with a createPk function, got ${value}`
);
}
},
promiseLibrary: {
deprecated: true,
type: 'any'
},
promoteBuffers: {
type: 'boolean'
},
promoteLongs: {
type: 'boolean'
},
promoteValues: {
type: 'boolean'
},
raw: {
default: false,
type: 'boolean'
},
readConcern: {
transform({ values: [value], options }) {
if (value instanceof ReadConcern || isRecord(value, ['level'] as const)) {
return ReadConcern.fromOptions({ ...options.readConcern, ...value } as any);
}
throw new MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`);
}
},
readConcernLevel: {
target: 'readConcern',
transform({ values: [level], options }) {
return ReadConcern.fromOptions({
...options.readConcern,
level: level as ReadConcernLevel
});
}
},
readPreference: {
default: ReadPreference.primary,
transform({ values: [value], options }) {
if (value instanceof ReadPreference) {
return ReadPreference.fromOptions({
readPreference: { ...options.readPreference, ...value },
...value
} as any);
}
if (isRecord(value, ['mode'] as const)) {
const rp = ReadPreference.fromOptions({
readPreference: { ...options.readPreference, ...value },
...value
} as any);
if (rp) return rp;
else throw new MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`);
}
if (typeof value === 'string') {
const rpOpts = {
hedge: options.readPreference?.hedge,
maxStalenessSeconds: options.readPreference?.maxStalenessSeconds
};
return new ReadPreference(
value as ReadPreferenceMode,
options.readPreference?.tags,
rpOpts
);
}
}
},
readPreferenceTags: {
target: 'readPreference',
transform({ values, options }) {
const readPreferenceTags = [];
for (const tag of values) {
const readPreferenceTag: TagSet = Object.create(null);
if (typeof tag === 'string') {
for (const [k, v] of Object.entries(toRecord(tag))) {
readPreferenceTag[k] = v;
}
}
if (isRecord(tag)) {
for (const [k, v] of Object.entries(tag)) {
readPreferenceTag[k] = v;
}
}
readPreferenceTags.push(readPreferenceTag);
}
return ReadPreference.fromOptions({
readPreference: options.readPreference,
readPreferenceTags
});
}
},
replicaSet: {
type: 'string'
},
retryReads: {
default: true,
type: 'boolean'
},
retryWrites: {
default: true,
type: 'boolean'
},
serializeFunctions: {
type: 'boolean'
},
serverSelectionTimeoutMS: {
default: 30000,
type: 'uint'
},
servername: {
type: 'string'
},
socketTimeoutMS: {
default: 0,
type: 'uint'
},
ssl: {
target: 'tls',
type: 'boolean'
},
sslCA: {
target: 'ca',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
sslCRL: {
target: 'crl',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
sslCert: {
target: 'cert',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
sslKey: {
target: 'key',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
sslPass: {
deprecated: true,
target: 'passphrase',
type: 'string'
},
sslValidate: {
target: 'rejectUnauthorized',
type: 'boolean'
},
tls: {
type: 'boolean'
},
tlsAllowInvalidCertificates: {
target: 'rejectUnauthorized',
transform({ name, values: [value] }) {
// allowInvalidCertificates is the inverse of rejectUnauthorized
return !getBoolean(name, value);
}
},
tlsAllowInvalidHostnames: {
target: 'checkServerIdentity',
transform({ name, values: [value] }) {
// tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop
return getBoolean(name, value) ? () => undefined : undefined;
}
},
tlsCAFile: {
target: 'ca',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
tlsCertificateFile: {
target: 'cert',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
tlsCertificateKeyFile: {
target: 'key',
transform({ values: [value] }) {
return fs.readFileSync(String(value), { encoding: 'ascii' });
}
},
tlsCertificateKeyFilePassword: {
target: 'passphrase',
type: 'any'
},
tlsInsecure: {
transform({ name, options, values: [value] }) {
const tlsInsecure = getBoolean(name, value);
if (tlsInsecure) {
options.checkServerIdentity = () => undefined;
options.rejectUnauthorized = false;
} else {
options.checkServerIdentity = options.tlsAllowInvalidHostnames
? () => undefined
: undefined;
options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true;
}
return tlsInsecure;
}
},
w: {
target: 'writeConcern',
transform({ values: [value], options }) {
return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value as W } });
}
},
waitQueueTimeoutMS: {
default: 0,
type: 'uint'
},
writeConcern: {
target: 'writeConcern',
transform({ values: [value], options }) {
if (isRecord(value) || value instanceof WriteConcern) {
return WriteConcern.fromOptions({
writeConcern: {
...options.writeConcern,
...value
}
});
} else if (value === 'majority' || typeof value === 'number') {
return WriteConcern.fromOptions({
writeConcern: {
...options.writeConcern,
w: value
}
});
}
throw new MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`);
}
} as OptionDescriptor,
wtimeout: {
deprecated: 'Please use wtimeoutMS instead',
target: 'writeConcern',
transform({ values: [value], options }) {
const wc = WriteConcern.fromOptions({
writeConcern: {
...options.writeConcern,
wtimeout: getUint('wtimeout', value)
}
});
if (wc) return wc;
throw new MongoParseError(`Cannot make WriteConcern from wtimeout`);
}
} as OptionDescriptor,