connection_string.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.DEFAULT_OPTIONS = exports.OPTIONS = void 0;
  4. exports.resolveSRVRecord = resolveSRVRecord;
  5. exports.parseOptions = parseOptions;
  6. const dns = require("dns");
  7. const mongodb_connection_string_url_1 = require("mongodb-connection-string-url");
  8. const url_1 = require("url");
  9. const mongo_credentials_1 = require("./cmap/auth/mongo_credentials");
  10. const providers_1 = require("./cmap/auth/providers");
  11. const compression_1 = require("./cmap/wire_protocol/compression");
  12. const encrypter_1 = require("./encrypter");
  13. const error_1 = require("./error");
  14. const mongo_client_1 = require("./mongo_client");
  15. const mongo_logger_1 = require("./mongo_logger");
  16. const read_concern_1 = require("./read_concern");
  17. const read_preference_1 = require("./read_preference");
  18. const monitor_1 = require("./sdam/monitor");
  19. const utils_1 = require("./utils");
  20. const write_concern_1 = require("./write_concern");
  21. const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced'];
  22. const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI';
  23. const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option';
  24. const LB_DIRECT_CONNECTION_ERROR = 'loadBalanced option not supported when directConnection is provided';
  25. function retryDNSTimeoutFor(api) {
  26. return async function dnsReqRetryTimeout(lookupAddress) {
  27. try {
  28. return await dns.promises[api](lookupAddress);
  29. }
  30. catch (firstDNSError) {
  31. if (firstDNSError.code === dns.TIMEOUT) {
  32. return await dns.promises[api](lookupAddress);
  33. }
  34. else {
  35. throw firstDNSError;
  36. }
  37. }
  38. };
  39. }
  40. const resolveSrv = retryDNSTimeoutFor('resolveSrv');
  41. const resolveTxt = retryDNSTimeoutFor('resolveTxt');
  42. /**
  43. * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal
  44. * connection string.
  45. *
  46. * @param uri - The connection string to parse
  47. * @param options - Optional user provided connection string options
  48. */
  49. async function resolveSRVRecord(options) {
  50. if (typeof options.srvHost !== 'string') {
  51. throw new error_1.MongoAPIError('Option "srvHost" must not be empty');
  52. }
  53. // Asynchronously start TXT resolution so that we do not have to wait until
  54. // the SRV record is resolved before starting a second DNS query.
  55. const lookupAddress = options.srvHost;
  56. const txtResolutionPromise = resolveTxt(lookupAddress);
  57. txtResolutionPromise.then(undefined, utils_1.squashError); // rejections will be handled later
  58. const hostname = `_${options.srvServiceName}._tcp.${lookupAddress}`;
  59. // Resolve the SRV record and use the result as the list of hosts to connect to.
  60. const addresses = await resolveSrv(hostname);
  61. if (addresses.length === 0) {
  62. throw new error_1.MongoAPIError('No addresses found at host');
  63. }
  64. for (const { name } of addresses) {
  65. (0, utils_1.checkParentDomainMatch)(name, lookupAddress);
  66. }
  67. const hostAddresses = addresses.map(r => utils_1.HostAddress.fromString(`${r.name}:${r.port ?? 27017}`));
  68. validateLoadBalancedOptions(hostAddresses, options, true);
  69. // Use the result of resolving the TXT record and add options from there if they exist.
  70. let record;
  71. try {
  72. record = await txtResolutionPromise;
  73. }
  74. catch (error) {
  75. if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') {
  76. throw error;
  77. }
  78. return hostAddresses;
  79. }
  80. if (record.length > 1) {
  81. throw new error_1.MongoParseError('Multiple text records not allowed');
  82. }
  83. const txtRecordOptions = new url_1.URLSearchParams(record[0].join(''));
  84. const txtRecordOptionKeys = [...txtRecordOptions.keys()];
  85. if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) {
  86. throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`);
  87. }
  88. if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) {
  89. throw new error_1.MongoParseError('Cannot have empty URI params in DNS TXT Record');
  90. }
  91. const source = txtRecordOptions.get('authSource') ?? undefined;
  92. const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined;
  93. const loadBalanced = txtRecordOptions.get('loadBalanced') ?? undefined;
  94. if (!options.userSpecifiedAuthSource &&
  95. source &&
  96. options.credentials &&
  97. !providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism)) {
  98. options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source });
  99. }
  100. if (!options.userSpecifiedReplicaSet && replicaSet) {
  101. options.replicaSet = replicaSet;
  102. }
  103. if (loadBalanced === 'true') {
  104. options.loadBalanced = true;
  105. }
  106. if (options.replicaSet && options.srvMaxHosts > 0) {
  107. throw new error_1.MongoParseError('Cannot combine replicaSet option with srvMaxHosts');
  108. }
  109. validateLoadBalancedOptions(hostAddresses, options, true);
  110. return hostAddresses;
  111. }
  112. /**
  113. * Checks if TLS options are valid
  114. *
  115. * @param allOptions - All options provided by user or included in default options map
  116. * @throws MongoAPIError if TLS options are invalid
  117. */
  118. function checkTLSOptions(allOptions) {
  119. if (!allOptions)
  120. return;
  121. const check = (a, b) => {
  122. if (allOptions.has(a) && allOptions.has(b)) {
  123. throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`);
  124. }
  125. };
  126. check('tlsInsecure', 'tlsAllowInvalidCertificates');
  127. check('tlsInsecure', 'tlsAllowInvalidHostnames');
  128. }
  129. function getBoolean(name, value) {
  130. if (typeof value === 'boolean')
  131. return value;
  132. switch (value) {
  133. case 'true':
  134. return true;
  135. case 'false':
  136. return false;
  137. default:
  138. throw new error_1.MongoParseError(`${name} must be either "true" or "false"`);
  139. }
  140. }
  141. function getIntFromOptions(name, value) {
  142. const parsedInt = (0, utils_1.parseInteger)(value);
  143. if (parsedInt != null) {
  144. return parsedInt;
  145. }
  146. throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`);
  147. }
  148. function getUIntFromOptions(name, value) {
  149. const parsedValue = getIntFromOptions(name, value);
  150. if (parsedValue < 0) {
  151. throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`);
  152. }
  153. return parsedValue;
  154. }
  155. function* entriesFromString(value) {
  156. if (value === '') {
  157. return;
  158. }
  159. const keyValuePairs = value.split(',');
  160. for (const keyValue of keyValuePairs) {
  161. const [key, value] = keyValue.split(/:(.*)/);
  162. if (value == null) {
  163. throw new error_1.MongoParseError('Cannot have undefined values in key value pairs');
  164. }
  165. yield [key, value];
  166. }
  167. }
  168. class CaseInsensitiveMap extends Map {
  169. constructor(entries = []) {
  170. super(entries.map(([k, v]) => [k.toLowerCase(), v]));
  171. }
  172. has(k) {
  173. return super.has(k.toLowerCase());
  174. }
  175. get(k) {
  176. return super.get(k.toLowerCase());
  177. }
  178. set(k, v) {
  179. return super.set(k.toLowerCase(), v);
  180. }
  181. delete(k) {
  182. return super.delete(k.toLowerCase());
  183. }
  184. }
  185. function parseOptions(uri, mongoClient = undefined, options = {}) {
  186. if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) {
  187. options = mongoClient;
  188. mongoClient = undefined;
  189. }
  190. // validate BSONOptions
  191. if (options.useBigInt64 && typeof options.promoteLongs === 'boolean' && !options.promoteLongs) {
  192. throw new error_1.MongoAPIError('Must request either bigint or Long for int64 deserialization');
  193. }
  194. if (options.useBigInt64 && typeof options.promoteValues === 'boolean' && !options.promoteValues) {
  195. throw new error_1.MongoAPIError('Must request either bigint or Long for int64 deserialization');
  196. }
  197. const url = new mongodb_connection_string_url_1.default(uri);
  198. const { hosts, isSRV } = url;
  199. const mongoOptions = Object.create(null);
  200. mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString);
  201. const urlOptions = new CaseInsensitiveMap();
  202. if (url.pathname !== '/' && url.pathname !== '') {
  203. const dbName = decodeURIComponent(url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname);
  204. if (dbName) {
  205. urlOptions.set('dbName', [dbName]);
  206. }
  207. }
  208. if (url.username !== '') {
  209. const auth = {
  210. username: decodeURIComponent(url.username)
  211. };
  212. if (typeof url.password === 'string') {
  213. auth.password = decodeURIComponent(url.password);
  214. }
  215. urlOptions.set('auth', [auth]);
  216. }
  217. for (const key of url.searchParams.keys()) {
  218. const values = url.searchParams.getAll(key);
  219. const isReadPreferenceTags = /readPreferenceTags/i.test(key);
  220. if (!isReadPreferenceTags && values.length > 1) {
  221. throw new error_1.MongoInvalidArgumentError(`URI option "${key}" cannot appear more than once in the connection string`);
  222. }
  223. if (!isReadPreferenceTags && values.includes('')) {
  224. throw new error_1.MongoAPIError(`URI option "${key}" cannot be specified with no value`);
  225. }
  226. if (!urlOptions.has(key)) {
  227. urlOptions.set(key, values);
  228. }
  229. }
  230. const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null));
  231. // Validate options that can only be provided by one of uri or object
  232. if (urlOptions.has('serverApi')) {
  233. throw new error_1.MongoParseError('URI cannot contain `serverApi`, it can only be passed to the client');
  234. }
  235. const uriMechanismProperties = urlOptions.get('authMechanismProperties');
  236. if (uriMechanismProperties) {
  237. for (const property of uriMechanismProperties) {
  238. if (/(^|,)ALLOWED_HOSTS:/.test(property)) {
  239. throw new error_1.MongoParseError('Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.');
  240. }
  241. }
  242. }
  243. if (objectOptions.has('loadBalanced')) {
  244. throw new error_1.MongoParseError('loadBalanced is only a valid option in the URI');
  245. }
  246. // All option collection
  247. const allProvidedOptions = new CaseInsensitiveMap();
  248. const allProvidedKeys = new Set([...urlOptions.keys(), ...objectOptions.keys()]);
  249. for (const key of allProvidedKeys) {
  250. const values = [];
  251. const objectOptionValue = objectOptions.get(key);
  252. if (objectOptionValue != null) {
  253. values.push(objectOptionValue);
  254. }
  255. const urlValues = urlOptions.get(key) ?? [];
  256. values.push(...urlValues);
  257. allProvidedOptions.set(key, values);
  258. }
  259. if (allProvidedOptions.has('tls') || allProvidedOptions.has('ssl')) {
  260. const tlsAndSslOpts = (allProvidedOptions.get('tls') || [])
  261. .concat(allProvidedOptions.get('ssl') || [])
  262. .map(getBoolean.bind(null, 'tls/ssl'));
  263. if (new Set(tlsAndSslOpts).size !== 1) {
  264. throw new error_1.MongoParseError('All values of tls/ssl must be the same.');
  265. }
  266. }
  267. checkTLSOptions(allProvidedOptions);
  268. const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports.OPTIONS)).map(s => s.toLowerCase()));
  269. if (unsupportedOptions.size !== 0) {
  270. const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option';
  271. const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is';
  272. throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`);
  273. }
  274. // Option parsing and setting
  275. for (const [key, descriptor] of Object.entries(exports.OPTIONS)) {
  276. const values = allProvidedOptions.get(key);
  277. if (!values || values.length === 0) {
  278. if (exports.DEFAULT_OPTIONS.has(key)) {
  279. setOption(mongoOptions, key, descriptor, [exports.DEFAULT_OPTIONS.get(key)]);
  280. }
  281. }
  282. else {
  283. const { deprecated } = descriptor;
  284. if (deprecated) {
  285. const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : '';
  286. (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`);
  287. }
  288. setOption(mongoOptions, key, descriptor, values);
  289. }
  290. }
  291. if (mongoOptions.credentials) {
  292. const isGssapi = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI;
  293. const isX509 = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_X509;
  294. const isAws = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_AWS;
  295. const isOidc = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_OIDC;
  296. if ((isGssapi || isX509) &&
  297. allProvidedOptions.has('authSource') &&
  298. mongoOptions.credentials.source !== '$external') {
  299. // If authSource was explicitly given and its incorrect, we error
  300. throw new error_1.MongoParseError(`authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'`);
  301. }
  302. if (!(isGssapi || isX509 || isAws || isOidc) &&
  303. mongoOptions.dbName &&
  304. !allProvidedOptions.has('authSource')) {
  305. // inherit the dbName unless GSSAPI or X509, then silently ignore dbName
  306. // and there was no specific authSource given
  307. mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, {
  308. source: mongoOptions.dbName
  309. });
  310. }
  311. if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) {
  312. throw new error_1.MongoMissingCredentialsError(`When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified`);
  313. }
  314. mongoOptions.credentials.validate();
  315. // Check if the only auth related option provided was authSource, if so we can remove credentials
  316. if (mongoOptions.credentials.password === '' &&
  317. mongoOptions.credentials.username === '' &&
  318. mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT &&
  319. Object.keys(mongoOptions.credentials.mechanismProperties).length === 0) {
  320. delete mongoOptions.credentials;
  321. }
  322. }
  323. if (!mongoOptions.dbName) {
  324. // dbName default is applied here because of the credential validation above
  325. mongoOptions.dbName = 'test';
  326. }
  327. validateLoadBalancedOptions(hosts, mongoOptions, isSRV);
  328. if (mongoClient && mongoOptions.autoEncryption) {
  329. encrypter_1.Encrypter.checkForMongoCrypt();
  330. mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options);
  331. mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter;
  332. }
  333. // Potential SRV Overrides and SRV connection string validations
  334. mongoOptions.userSpecifiedAuthSource =
  335. objectOptions.has('authSource') || urlOptions.has('authSource');
  336. mongoOptions.userSpecifiedReplicaSet =
  337. objectOptions.has('replicaSet') || urlOptions.has('replicaSet');
  338. if (isSRV) {
  339. // SRV Record is resolved upon connecting
  340. mongoOptions.srvHost = hosts[0];
  341. if (mongoOptions.directConnection) {
  342. throw new error_1.MongoAPIError('SRV URI does not support directConnection');
  343. }
  344. if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') {
  345. throw new error_1.MongoParseError('Cannot use srvMaxHosts option with replicaSet');
  346. }
  347. // SRV turns on TLS by default, but users can override and turn it off
  348. const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls');
  349. const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl');
  350. if (noUserSpecifiedTLS && noUserSpecifiedSSL) {
  351. mongoOptions.tls = true;
  352. }
  353. }
  354. else {
  355. const userSpecifiedSrvOptions = urlOptions.has('srvMaxHosts') ||
  356. objectOptions.has('srvMaxHosts') ||
  357. urlOptions.has('srvServiceName') ||
  358. objectOptions.has('srvServiceName');
  359. if (userSpecifiedSrvOptions) {
  360. throw new error_1.MongoParseError('Cannot use srvMaxHosts or srvServiceName with a non-srv connection string');
  361. }
  362. }
  363. if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) {
  364. throw new error_1.MongoParseError('directConnection option requires exactly one host');
  365. }
  366. if (!mongoOptions.proxyHost &&
  367. (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword)) {
  368. throw new error_1.MongoParseError('Must specify proxyHost if other proxy options are passed');
  369. }
  370. if ((mongoOptions.proxyUsername && !mongoOptions.proxyPassword) ||
  371. (!mongoOptions.proxyUsername && mongoOptions.proxyPassword)) {
  372. throw new error_1.MongoParseError('Can only specify both of proxy username/password or neither');
  373. }
  374. const proxyOptions = ['proxyHost', 'proxyPort', 'proxyUsername', 'proxyPassword'].map(key => urlOptions.get(key) ?? []);
  375. if (proxyOptions.some(options => options.length > 1)) {
  376. throw new error_1.MongoParseError('Proxy options cannot be specified multiple times in the connection string');
  377. }
  378. mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions({
  379. MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND,
  380. MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY,
  381. MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION,
  382. MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION,
  383. MONGODB_LOG_CLIENT: process.env.MONGODB_LOG_CLIENT,
  384. MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL,
  385. MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH,
  386. MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH
  387. }, {
  388. mongodbLogPath: mongoOptions.mongodbLogPath,
  389. mongodbLogComponentSeverities: mongoOptions.mongodbLogComponentSeverities,
  390. mongodbLogMaxDocumentLength: mongoOptions.mongodbLogMaxDocumentLength
  391. });
  392. return mongoOptions;
  393. }
  394. /**
  395. * #### Throws if LB mode is true:
  396. * - hosts contains more than one host
  397. * - there is a replicaSet name set
  398. * - directConnection is set
  399. * - if srvMaxHosts is used when an srv connection string is passed in
  400. *
  401. * @throws MongoParseError
  402. */
  403. function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) {
  404. if (mongoOptions.loadBalanced) {
  405. if (hosts.length > 1) {
  406. throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR);
  407. }
  408. if (mongoOptions.replicaSet) {
  409. throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR);
  410. }
  411. if (mongoOptions.directConnection) {
  412. throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR);
  413. }
  414. if (isSrv && mongoOptions.srvMaxHosts > 0) {
  415. throw new error_1.MongoParseError('Cannot limit srv hosts with loadBalanced enabled');
  416. }
  417. }
  418. return;
  419. }
  420. function setOption(mongoOptions, key, descriptor, values) {
  421. const { target, type, transform } = descriptor;
  422. const name = target ?? key;
  423. switch (type) {
  424. case 'boolean':
  425. mongoOptions[name] = getBoolean(name, values[0]);
  426. break;
  427. case 'int':
  428. mongoOptions[name] = getIntFromOptions(name, values[0]);
  429. break;
  430. case 'uint':
  431. mongoOptions[name] = getUIntFromOptions(name, values[0]);
  432. break;
  433. case 'string':
  434. if (values[0] == null) {
  435. break;
  436. }
  437. // The value should always be a string here, but since the array is typed as unknown
  438. // there still needs to be an explicit cast.
  439. // eslint-disable-next-line @typescript-eslint/no-base-to-string
  440. mongoOptions[name] = String(values[0]);
  441. break;
  442. case 'record':
  443. if (!(0, utils_1.isRecord)(values[0])) {
  444. throw new error_1.MongoParseError(`${name} must be an object`);
  445. }
  446. mongoOptions[name] = values[0];
  447. break;
  448. case 'any':
  449. mongoOptions[name] = values[0];
  450. break;
  451. default: {
  452. if (!transform) {
  453. throw new error_1.MongoParseError('Descriptors missing a type must define a transform');
  454. }
  455. const transformValue = transform({ name, options: mongoOptions, values });
  456. mongoOptions[name] = transformValue;
  457. break;
  458. }
  459. }
  460. }
  461. exports.OPTIONS = {
  462. appName: {
  463. type: 'string'
  464. },
  465. auth: {
  466. target: 'credentials',
  467. transform({ name, options, values: [value] }) {
  468. if (!(0, utils_1.isRecord)(value, ['username', 'password'])) {
  469. throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`);
  470. }
  471. return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
  472. username: value.username,
  473. password: value.password
  474. });
  475. }
  476. },
  477. authMechanism: {
  478. target: 'credentials',
  479. transform({ options, values: [value] }) {
  480. const mechanisms = Object.values(providers_1.AuthMechanism);
  481. const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw `\b${value}\b`, 'i')));
  482. if (!mechanism) {
  483. throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`);
  484. }
  485. let source = options.credentials?.source;
  486. if (mechanism === providers_1.AuthMechanism.MONGODB_PLAIN ||
  487. providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism)) {
  488. // some mechanisms have '$external' as the Auth Source
  489. source = '$external';
  490. }
  491. let password = options.credentials?.password;
  492. if (mechanism === providers_1.AuthMechanism.MONGODB_X509 && password === '') {
  493. password = undefined;
  494. }
  495. return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
  496. mechanism,
  497. source,
  498. password
  499. });
  500. }
  501. },
  502. // Note that if the authMechanismProperties contain a TOKEN_RESOURCE that has a
  503. // comma in it, it MUST be supplied as a MongoClient option instead of in the
  504. // connection string.
  505. authMechanismProperties: {
  506. target: 'credentials',
  507. transform({ options, values }) {
  508. // We can have a combination of options passed in the URI and options passed
  509. // as an object to the MongoClient. So we must transform the string options
  510. // as well as merge them together with a potentially provided object.
  511. let mechanismProperties = Object.create(null);
  512. for (const optionValue of values) {
  513. if (typeof optionValue === 'string') {
  514. for (const [key, value] of entriesFromString(optionValue)) {
  515. try {
  516. mechanismProperties[key] = getBoolean(key, value);
  517. }
  518. catch {
  519. mechanismProperties[key] = value;
  520. }
  521. }
  522. }
  523. else {
  524. if (!(0, utils_1.isRecord)(optionValue)) {
  525. throw new error_1.MongoParseError('AuthMechanismProperties must be an object');
  526. }
  527. mechanismProperties = { ...optionValue };
  528. }
  529. }
  530. return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
  531. mechanismProperties
  532. });
  533. }
  534. },
  535. authSource: {
  536. target: 'credentials',
  537. transform({ options, values: [value] }) {
  538. const source = String(value);
  539. return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source });
  540. }
  541. },
  542. autoEncryption: {
  543. type: 'record'
  544. },
  545. autoSelectFamily: {
  546. type: 'boolean',
  547. default: true
  548. },
  549. autoSelectFamilyAttemptTimeout: {
  550. type: 'uint'
  551. },
  552. bsonRegExp: {
  553. type: 'boolean'
  554. },
  555. serverApi: {
  556. target: 'serverApi',
  557. transform({ values: [version] }) {
  558. const serverApiToValidate = typeof version === 'string' ? { version } : version;
  559. const versionToValidate = serverApiToValidate && serverApiToValidate.version;
  560. if (!versionToValidate) {
  561. throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`);
  562. }
  563. if (!Object.values(mongo_client_1.ServerApiVersion).some(v => v === versionToValidate)) {
  564. throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`);
  565. }
  566. return serverApiToValidate;
  567. }
  568. },
  569. checkKeys: {
  570. type: 'boolean'
  571. },
  572. compressors: {
  573. default: 'none',
  574. target: 'compressors',
  575. transform({ values }) {
  576. const compressionList = new Set();
  577. for (const compVal of values) {
  578. const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal;
  579. if (!Array.isArray(compValArray)) {
  580. throw new error_1.MongoInvalidArgumentError('compressors must be an array or a comma-delimited list of strings');
  581. }
  582. for (const c of compValArray) {
  583. if (Object.keys(compression_1.Compressor).includes(String(c))) {
  584. compressionList.add(String(c));
  585. }
  586. else {
  587. throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`);
  588. }
  589. }
  590. }
  591. return [...compressionList];
  592. }
  593. },
  594. connectTimeoutMS: {
  595. default: 30000,
  596. type: 'uint'
  597. },
  598. dbName: {
  599. type: 'string'
  600. },
  601. directConnection: {
  602. default: false,
  603. type: 'boolean'
  604. },
  605. driverInfo: {
  606. default: {},
  607. type: 'record'
  608. },
  609. enableUtf8Validation: { type: 'boolean', default: true },
  610. family: {
  611. transform({ name, values: [value] }) {
  612. const transformValue = getIntFromOptions(name, value);
  613. if (transformValue === 4 || transformValue === 6) {
  614. return transformValue;
  615. }
  616. throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`);
  617. }
  618. },
  619. fieldsAsRaw: {
  620. type: 'record'
  621. },
  622. forceServerObjectId: {
  623. default: false,
  624. type: 'boolean'
  625. },
  626. fsync: {
  627. deprecated: 'Please use journal instead',
  628. target: 'writeConcern',
  629. transform({ name, options, values: [value] }) {
  630. const wc = write_concern_1.WriteConcern.fromOptions({
  631. writeConcern: {
  632. ...options.writeConcern,
  633. fsync: getBoolean(name, value)
  634. }
  635. });
  636. if (!wc)
  637. throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`);
  638. return wc;
  639. }
  640. },
  641. heartbeatFrequencyMS: {
  642. default: 10000,
  643. type: 'uint'
  644. },
  645. ignoreUndefined: {
  646. type: 'boolean'
  647. },
  648. j: {
  649. deprecated: 'Please use journal instead',
  650. target: 'writeConcern',
  651. transform({ name, options, values: [value] }) {
  652. const wc = write_concern_1.WriteConcern.fromOptions({
  653. writeConcern: {
  654. ...options.writeConcern,
  655. journal: getBoolean(name, value)
  656. }
  657. });
  658. if (!wc)
  659. throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`);
  660. return wc;
  661. }
  662. },
  663. journal: {
  664. target: 'writeConcern',
  665. transform({ name, options, values: [value] }) {
  666. const wc = write_concern_1.WriteConcern.fromOptions({
  667. writeConcern: {
  668. ...options.writeConcern,
  669. journal: getBoolean(name, value)
  670. }
  671. });
  672. if (!wc)
  673. throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`);
  674. return wc;
  675. }
  676. },
  677. loadBalanced: {
  678. default: false,
  679. type: 'boolean'
  680. },
  681. localThresholdMS: {
  682. default: 15,
  683. type: 'uint'
  684. },
  685. maxConnecting: {
  686. default: 2,
  687. transform({ name, values: [value] }) {
  688. const maxConnecting = getUIntFromOptions(name, value);
  689. if (maxConnecting === 0) {
  690. throw new error_1.MongoInvalidArgumentError('maxConnecting must be > 0 if specified');
  691. }
  692. return maxConnecting;
  693. }
  694. },
  695. maxIdleTimeMS: {
  696. default: 0,
  697. type: 'uint'
  698. },
  699. maxPoolSize: {
  700. default: 100,
  701. type: 'uint'
  702. },
  703. maxStalenessSeconds: {
  704. target: 'readPreference',
  705. transform({ name, options, values: [value] }) {
  706. const maxStalenessSeconds = getUIntFromOptions(name, value);
  707. if (options.readPreference) {
  708. return read_preference_1.ReadPreference.fromOptions({
  709. readPreference: { ...options.readPreference, maxStalenessSeconds }
  710. });
  711. }
  712. else {
  713. return new read_preference_1.ReadPreference('secondary', undefined, { maxStalenessSeconds });
  714. }
  715. }
  716. },
  717. minInternalBufferSize: {
  718. type: 'uint'
  719. },
  720. minPoolSize: {
  721. default: 0,
  722. type: 'uint'
  723. },
  724. minHeartbeatFrequencyMS: {
  725. default: 500,
  726. type: 'uint'
  727. },
  728. monitorCommands: {
  729. default: false,
  730. type: 'boolean'
  731. },
  732. name: {
  733. target: 'driverInfo',
  734. transform({ values: [value], options }) {
  735. return { ...options.driverInfo, name: String(value) };
  736. }
  737. },
  738. noDelay: {
  739. default: true,
  740. type: 'boolean'
  741. },
  742. pkFactory: {
  743. default: utils_1.DEFAULT_PK_FACTORY,
  744. transform({ values: [value] }) {
  745. if ((0, utils_1.isRecord)(value, ['createPk']) && typeof value.createPk === 'function') {
  746. return value;
  747. }
  748. throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`);
  749. }
  750. },
  751. promoteBuffers: {
  752. type: 'boolean'
  753. },
  754. promoteLongs: {
  755. type: 'boolean'
  756. },
  757. promoteValues: {
  758. type: 'boolean'
  759. },
  760. useBigInt64: {
  761. type: 'boolean'
  762. },
  763. proxyHost: {
  764. type: 'string'
  765. },
  766. proxyPassword: {
  767. type: 'string'
  768. },
  769. proxyPort: {
  770. type: 'uint'
  771. },
  772. proxyUsername: {
  773. type: 'string'
  774. },
  775. raw: {
  776. default: false,
  777. type: 'boolean'
  778. },
  779. readConcern: {
  780. transform({ values: [value], options }) {
  781. if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ['level'])) {
  782. return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value });
  783. }
  784. throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`);
  785. }
  786. },
  787. readConcernLevel: {
  788. target: 'readConcern',
  789. transform({ values: [level], options }) {
  790. return read_concern_1.ReadConcern.fromOptions({
  791. ...options.readConcern,
  792. level: level
  793. });
  794. }
  795. },
  796. readPreference: {
  797. default: read_preference_1.ReadPreference.primary,
  798. transform({ values: [value], options }) {
  799. if (value instanceof read_preference_1.ReadPreference) {
  800. return read_preference_1.ReadPreference.fromOptions({
  801. readPreference: { ...options.readPreference, ...value },
  802. ...value
  803. });
  804. }
  805. if ((0, utils_1.isRecord)(value, ['mode'])) {
  806. const rp = read_preference_1.ReadPreference.fromOptions({
  807. readPreference: { ...options.readPreference, ...value },
  808. ...value
  809. });
  810. if (rp)
  811. return rp;
  812. else
  813. throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`);
  814. }
  815. if (typeof value === 'string') {
  816. const rpOpts = {
  817. hedge: options.readPreference?.hedge,
  818. maxStalenessSeconds: options.readPreference?.maxStalenessSeconds
  819. };
  820. return new read_preference_1.ReadPreference(value, options.readPreference?.tags, rpOpts);
  821. }
  822. throw new error_1.MongoParseError(`Unknown ReadPreference value: ${value}`);
  823. }
  824. },
  825. readPreferenceTags: {
  826. target: 'readPreference',
  827. transform({ values, options }) {
  828. const tags = Array.isArray(values[0])
  829. ? values[0]
  830. : values;
  831. const readPreferenceTags = [];
  832. for (const tag of tags) {
  833. const readPreferenceTag = Object.create(null);
  834. if (typeof tag === 'string') {
  835. for (const [k, v] of entriesFromString(tag)) {
  836. readPreferenceTag[k] = v;
  837. }
  838. }
  839. if ((0, utils_1.isRecord)(tag)) {
  840. for (const [k, v] of Object.entries(tag)) {
  841. readPreferenceTag[k] = v;
  842. }
  843. }
  844. readPreferenceTags.push(readPreferenceTag);
  845. }
  846. return read_preference_1.ReadPreference.fromOptions({
  847. readPreference: options.readPreference,
  848. readPreferenceTags
  849. });
  850. }
  851. },
  852. replicaSet: {
  853. type: 'string'
  854. },
  855. retryReads: {
  856. default: true,
  857. type: 'boolean'
  858. },
  859. retryWrites: {
  860. default: true,
  861. type: 'boolean'
  862. },
  863. serializeFunctions: {
  864. type: 'boolean'
  865. },
  866. serverMonitoringMode: {
  867. default: 'auto',
  868. transform({ values: [value] }) {
  869. if (!Object.values(monitor_1.ServerMonitoringMode).includes(value)) {
  870. throw new error_1.MongoParseError('serverMonitoringMode must be one of `auto`, `poll`, or `stream`');
  871. }
  872. return value;
  873. }
  874. },
  875. serverSelectionTimeoutMS: {
  876. default: 30000,
  877. type: 'uint'
  878. },
  879. servername: {
  880. type: 'string'
  881. },
  882. socketTimeoutMS: {
  883. // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead',
  884. default: 0,
  885. type: 'uint'
  886. },
  887. srvMaxHosts: {
  888. type: 'uint',
  889. default: 0
  890. },
  891. srvServiceName: {
  892. type: 'string',
  893. default: 'mongodb'
  894. },
  895. ssl: {
  896. target: 'tls',
  897. type: 'boolean'
  898. },
  899. timeoutMS: {
  900. type: 'uint'
  901. },
  902. tls: {
  903. type: 'boolean'
  904. },
  905. tlsAllowInvalidCertificates: {
  906. target: 'rejectUnauthorized',
  907. transform({ name, values: [value] }) {
  908. // allowInvalidCertificates is the inverse of rejectUnauthorized
  909. return !getBoolean(name, value);
  910. }
  911. },
  912. tlsAllowInvalidHostnames: {
  913. target: 'checkServerIdentity',
  914. transform({ name, values: [value] }) {
  915. // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop
  916. return getBoolean(name, value) ? () => undefined : undefined;
  917. }
  918. },
  919. tlsCAFile: {
  920. type: 'string'
  921. },
  922. tlsCRLFile: {
  923. type: 'string'
  924. },
  925. tlsCertificateKeyFile: {
  926. type: 'string'
  927. },
  928. tlsCertificateKeyFilePassword: {
  929. target: 'passphrase',
  930. type: 'any'
  931. },
  932. tlsInsecure: {
  933. transform({ name, options, values: [value] }) {
  934. const tlsInsecure = getBoolean(name, value);
  935. if (tlsInsecure) {
  936. options.checkServerIdentity = () => undefined;
  937. options.rejectUnauthorized = false;
  938. }
  939. else {
  940. options.checkServerIdentity = options.tlsAllowInvalidHostnames
  941. ? () => undefined
  942. : undefined;
  943. options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true;
  944. }
  945. return tlsInsecure;
  946. }
  947. },
  948. w: {
  949. target: 'writeConcern',
  950. transform({ values: [value], options }) {
  951. return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } });
  952. }
  953. },
  954. waitQueueTimeoutMS: {
  955. // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead',
  956. default: 0,
  957. type: 'uint'
  958. },
  959. writeConcern: {
  960. target: 'writeConcern',
  961. transform({ values: [value], options }) {
  962. if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) {
  963. return write_concern_1.WriteConcern.fromOptions({
  964. writeConcern: {
  965. ...options.writeConcern,
  966. ...value
  967. }
  968. });
  969. }
  970. else if (value === 'majority' || typeof value === 'number') {
  971. return write_concern_1.WriteConcern.fromOptions({
  972. writeConcern: {
  973. ...options.writeConcern,
  974. w: value
  975. }
  976. });
  977. }
  978. throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`);
  979. }
  980. },
  981. wtimeout: {
  982. deprecated: 'Please use wtimeoutMS instead',
  983. target: 'writeConcern',
  984. transform({ values: [value], options }) {
  985. const wc = write_concern_1.WriteConcern.fromOptions({
  986. writeConcern: {
  987. ...options.writeConcern,
  988. wtimeout: getUIntFromOptions('wtimeout', value)
  989. }
  990. });
  991. if (wc)
  992. return wc;
  993. throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`);
  994. }
  995. },
  996. wtimeoutMS: {
  997. target: 'writeConcern',
  998. transform({ values: [value], options }) {
  999. const wc = write_concern_1.WriteConcern.fromOptions({
  1000. writeConcern: {
  1001. ...options.writeConcern,
  1002. wtimeoutMS: getUIntFromOptions('wtimeoutMS', value)
  1003. }
  1004. });
  1005. if (wc)
  1006. return wc;
  1007. throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`);
  1008. }
  1009. },
  1010. zlibCompressionLevel: {
  1011. default: 0,
  1012. type: 'int'
  1013. },
  1014. mongodbLogPath: {
  1015. transform({ values: [value] }) {
  1016. if (!((typeof value === 'string' && ['stderr', 'stdout'].includes(value)) ||
  1017. (value &&
  1018. typeof value === 'object' &&
  1019. 'write' in value &&
  1020. typeof value.write === 'function'))) {
  1021. throw new error_1.MongoAPIError(`Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable`);
  1022. }
  1023. return value;
  1024. }
  1025. },
  1026. mongodbLogComponentSeverities: {
  1027. transform({ values: [value] }) {
  1028. if (typeof value !== 'object' || !value) {
  1029. throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' must be a non-null object`);
  1030. }
  1031. for (const [k, v] of Object.entries(value)) {
  1032. if (typeof v !== 'string' || typeof k !== 'string') {
  1033. throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value`);
  1034. }
  1035. if (!Object.values(mongo_logger_1.MongoLoggableComponent).some(val => val === k) && k !== 'default') {
  1036. throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${k}`);
  1037. }
  1038. if (!Object.values(mongo_logger_1.SeverityLevel).some(val => val === v)) {
  1039. throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${v} as a value for ${k}`);
  1040. }
  1041. }
  1042. return value;
  1043. }
  1044. },
  1045. mongodbLogMaxDocumentLength: { type: 'uint' },
  1046. // Custom types for modifying core behavior
  1047. connectionType: { type: 'any' },
  1048. srvPoller: { type: 'any' },
  1049. // Accepted Node.js Options
  1050. allowPartialTrustChain: { type: 'any' },
  1051. minDHSize: { type: 'any' },
  1052. pskCallback: { type: 'any' },
  1053. secureContext: { type: 'any' },
  1054. enableTrace: { type: 'any' },
  1055. requestCert: { type: 'any' },
  1056. rejectUnauthorized: { type: 'any' },
  1057. checkServerIdentity: { type: 'any' },
  1058. keepAliveInitialDelay: { type: 'any' },
  1059. ALPNProtocols: { type: 'any' },
  1060. SNICallback: { type: 'any' },
  1061. session: { type: 'any' },
  1062. requestOCSP: { type: 'any' },
  1063. localAddress: { type: 'any' },
  1064. localPort: { type: 'any' },
  1065. hints: { type: 'any' },
  1066. lookup: { type: 'any' },
  1067. ca: { type: 'any' },
  1068. cert: { type: 'any' },
  1069. ciphers: { type: 'any' },
  1070. crl: { type: 'any' },
  1071. ecdhCurve: { type: 'any' },
  1072. key: { type: 'any' },
  1073. passphrase: { type: 'any' },
  1074. pfx: { type: 'any' },
  1075. secureProtocol: { type: 'any' },
  1076. index: { type: 'any' },
  1077. // Legacy options from v3 era
  1078. useNewUrlParser: {
  1079. type: 'boolean',
  1080. deprecated: 'useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version'
  1081. },
  1082. useUnifiedTopology: {
  1083. type: 'boolean',
  1084. deprecated: 'useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version'
  1085. },
  1086. __skipPingOnConnect: { type: 'boolean' }
  1087. };
  1088. exports.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports.OPTIONS)
  1089. .filter(([, descriptor]) => descriptor.default != null)
  1090. .map(([k, d]) => [k, d.default]));
  1091. //# sourceMappingURL=connection_string.js.map