index.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CommaAndColonSeparatedRecord = exports.ConnectionString = exports.redactConnectionString = void 0;
  4. const whatwg_url_1 = require("whatwg-url");
  5. const redact_1 = require("./redact");
  6. Object.defineProperty(exports, "redactConnectionString", { enumerable: true, get: function () { return redact_1.redactConnectionString; } });
  7. const DUMMY_HOSTNAME = '__this_is_a_placeholder__';
  8. function connectionStringHasValidScheme(connectionString) {
  9. return connectionString.startsWith('mongodb://') || connectionString.startsWith('mongodb+srv://');
  10. }
  11. const HOSTS_REGEX = /^(?<protocol>[^/]+):\/\/(?:(?<username>[^:@]*)(?::(?<password>[^@]*))?@)?(?<hosts>(?!:)[^/?@]*)(?<rest>.*)/;
  12. class CaseInsensitiveMap extends Map {
  13. delete(name) {
  14. return super.delete(this._normalizeKey(name));
  15. }
  16. get(name) {
  17. return super.get(this._normalizeKey(name));
  18. }
  19. has(name) {
  20. return super.has(this._normalizeKey(name));
  21. }
  22. set(name, value) {
  23. return super.set(this._normalizeKey(name), value);
  24. }
  25. _normalizeKey(name) {
  26. name = `${name}`;
  27. for (const key of this.keys()) {
  28. if (key.toLowerCase() === name.toLowerCase()) {
  29. name = key;
  30. break;
  31. }
  32. }
  33. return name;
  34. }
  35. }
  36. function caseInsenstiveURLSearchParams(Ctor) {
  37. return class CaseInsenstiveURLSearchParams extends Ctor {
  38. append(name, value) {
  39. return super.append(this._normalizeKey(name), value);
  40. }
  41. delete(name) {
  42. return super.delete(this._normalizeKey(name));
  43. }
  44. get(name) {
  45. return super.get(this._normalizeKey(name));
  46. }
  47. getAll(name) {
  48. return super.getAll(this._normalizeKey(name));
  49. }
  50. has(name) {
  51. return super.has(this._normalizeKey(name));
  52. }
  53. set(name, value) {
  54. return super.set(this._normalizeKey(name), value);
  55. }
  56. keys() {
  57. return super.keys();
  58. }
  59. values() {
  60. return super.values();
  61. }
  62. entries() {
  63. return super.entries();
  64. }
  65. [Symbol.iterator]() {
  66. return super[Symbol.iterator]();
  67. }
  68. _normalizeKey(name) {
  69. return CaseInsensitiveMap.prototype._normalizeKey.call(this, name);
  70. }
  71. };
  72. }
  73. class URLWithoutHost extends whatwg_url_1.URL {
  74. }
  75. class MongoParseError extends Error {
  76. get name() {
  77. return 'MongoParseError';
  78. }
  79. }
  80. class ConnectionString extends URLWithoutHost {
  81. _hosts;
  82. constructor(uri, options = {}) {
  83. const { looseValidation } = options;
  84. if (!looseValidation && !connectionStringHasValidScheme(uri)) {
  85. throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');
  86. }
  87. const match = uri.match(HOSTS_REGEX);
  88. if (!match) {
  89. throw new MongoParseError(`Invalid connection string "${uri}"`);
  90. }
  91. const { protocol, username, password, hosts, rest } = match.groups ?? {};
  92. if (!looseValidation) {
  93. if (!protocol || !hosts) {
  94. throw new MongoParseError(`Protocol and host list are required in "${uri}"`);
  95. }
  96. try {
  97. decodeURIComponent(username ?? '');
  98. decodeURIComponent(password ?? '');
  99. }
  100. catch (err) {
  101. throw new MongoParseError(err.message);
  102. }
  103. const illegalCharacters = /[:/?#[\]@]/gi;
  104. if (username?.match(illegalCharacters)) {
  105. throw new MongoParseError(`Username contains unescaped characters ${username}`);
  106. }
  107. if (!username || !password) {
  108. const uriWithoutProtocol = uri.replace(`${protocol}://`, '');
  109. if (uriWithoutProtocol.startsWith('@') || uriWithoutProtocol.startsWith(':')) {
  110. throw new MongoParseError('URI contained empty userinfo section');
  111. }
  112. }
  113. if (password?.match(illegalCharacters)) {
  114. throw new MongoParseError('Password contains unescaped characters');
  115. }
  116. }
  117. let authString = '';
  118. if (typeof username === 'string')
  119. authString += username;
  120. if (typeof password === 'string')
  121. authString += `:${password}`;
  122. if (authString)
  123. authString += '@';
  124. try {
  125. super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`);
  126. }
  127. catch (err) {
  128. if (looseValidation) {
  129. new ConnectionString(uri, {
  130. ...options,
  131. looseValidation: false
  132. });
  133. }
  134. if (typeof err.message === 'string') {
  135. err.message = err.message.replace(DUMMY_HOSTNAME, hosts);
  136. }
  137. throw err;
  138. }
  139. this._hosts = hosts.split(',');
  140. if (!looseValidation) {
  141. if (this.isSRV && this.hosts.length !== 1) {
  142. throw new MongoParseError('mongodb+srv URI cannot have multiple service names');
  143. }
  144. if (this.isSRV && this.hosts.some(host => host.includes(':'))) {
  145. throw new MongoParseError('mongodb+srv URI cannot have port number');
  146. }
  147. }
  148. if (!this.pathname) {
  149. this.pathname = '/';
  150. }
  151. Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype);
  152. }
  153. get host() {
  154. return DUMMY_HOSTNAME;
  155. }
  156. set host(_ignored) {
  157. throw new Error('No single host for connection string');
  158. }
  159. get hostname() {
  160. return DUMMY_HOSTNAME;
  161. }
  162. set hostname(_ignored) {
  163. throw new Error('No single host for connection string');
  164. }
  165. get port() {
  166. return '';
  167. }
  168. set port(_ignored) {
  169. throw new Error('No single host for connection string');
  170. }
  171. get href() {
  172. return this.toString();
  173. }
  174. set href(_ignored) {
  175. throw new Error('Cannot set href for connection strings');
  176. }
  177. get isSRV() {
  178. return this.protocol.includes('srv');
  179. }
  180. get hosts() {
  181. return this._hosts;
  182. }
  183. set hosts(list) {
  184. this._hosts = list;
  185. }
  186. toString() {
  187. return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(','));
  188. }
  189. clone() {
  190. return new ConnectionString(this.toString(), {
  191. looseValidation: true
  192. });
  193. }
  194. redact(options) {
  195. return (0, redact_1.redactValidConnectionString)(this, options);
  196. }
  197. typedSearchParams() {
  198. const _sametype = false && new (caseInsenstiveURLSearchParams(whatwg_url_1.URLSearchParams))();
  199. return this.searchParams;
  200. }
  201. [Symbol.for('nodejs.util.inspect.custom')]() {
  202. const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this;
  203. return {
  204. href,
  205. origin,
  206. protocol,
  207. username,
  208. password,
  209. hosts,
  210. pathname,
  211. search,
  212. searchParams,
  213. hash
  214. };
  215. }
  216. }
  217. exports.ConnectionString = ConnectionString;
  218. class CommaAndColonSeparatedRecord extends CaseInsensitiveMap {
  219. constructor(from) {
  220. super();
  221. for (const entry of (from ?? '').split(',')) {
  222. if (!entry)
  223. continue;
  224. const colonIndex = entry.indexOf(':');
  225. if (colonIndex === -1) {
  226. this.set(entry, '');
  227. }
  228. else {
  229. this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1));
  230. }
  231. }
  232. }
  233. toString() {
  234. return [...this].map(entry => entry.join(':')).join(',');
  235. }
  236. }
  237. exports.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord;
  238. exports.default = ConnectionString;
  239. //# sourceMappingURL=index.js.map