index.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268
  1. // lib/pathMatch.ts
  2. function pathMatch(reqPath, cookiePath) {
  3. if (cookiePath === reqPath) {
  4. return true;
  5. }
  6. const idx = reqPath.indexOf(cookiePath);
  7. if (idx === 0) {
  8. if (cookiePath[cookiePath.length - 1] === "/") {
  9. return true;
  10. }
  11. if (reqPath.startsWith(cookiePath) && reqPath[cookiePath.length] === "/") {
  12. return true;
  13. }
  14. }
  15. return false;
  16. }
  17. // lib/getPublicSuffix.ts
  18. import { getDomain } from "tldts";
  19. var SPECIAL_USE_DOMAINS = ["local", "example", "invalid", "localhost", "test"];
  20. var SPECIAL_TREATMENT_DOMAINS = ["localhost", "invalid"];
  21. var defaultGetPublicSuffixOptions = {
  22. allowSpecialUseDomain: false,
  23. ignoreError: false
  24. };
  25. function getPublicSuffix(domain, options = {}) {
  26. options = { ...defaultGetPublicSuffixOptions, ...options };
  27. const domainParts = domain.split(".");
  28. const topLevelDomain = domainParts[domainParts.length - 1];
  29. const allowSpecialUseDomain = !!options.allowSpecialUseDomain;
  30. const ignoreError = !!options.ignoreError;
  31. if (allowSpecialUseDomain && topLevelDomain !== void 0 && SPECIAL_USE_DOMAINS.includes(topLevelDomain)) {
  32. if (domainParts.length > 1) {
  33. const secondLevelDomain = domainParts[domainParts.length - 2];
  34. return `${secondLevelDomain}.${topLevelDomain}`;
  35. } else if (SPECIAL_TREATMENT_DOMAINS.includes(topLevelDomain)) {
  36. return topLevelDomain;
  37. }
  38. }
  39. if (!ignoreError && topLevelDomain !== void 0 && SPECIAL_USE_DOMAINS.includes(topLevelDomain)) {
  40. throw new Error(
  41. `Cookie has domain set to the public suffix "${topLevelDomain}" which is a special use domain. To allow this, configure your CookieJar with {allowSpecialUseDomain: true, rejectPublicSuffixes: false}.`
  42. );
  43. }
  44. const publicSuffix = getDomain(domain, {
  45. allowIcannDomains: true,
  46. allowPrivateDomains: true
  47. });
  48. if (publicSuffix) return publicSuffix;
  49. }
  50. // lib/permuteDomain.ts
  51. function permuteDomain(domain, allowSpecialUseDomain) {
  52. const pubSuf = getPublicSuffix(domain, {
  53. allowSpecialUseDomain
  54. });
  55. if (!pubSuf) {
  56. return void 0;
  57. }
  58. if (pubSuf == domain) {
  59. return [domain];
  60. }
  61. if (domain.slice(-1) == ".") {
  62. domain = domain.slice(0, -1);
  63. }
  64. const prefix = domain.slice(0, -(pubSuf.length + 1));
  65. const parts = prefix.split(".").reverse();
  66. let cur = pubSuf;
  67. const permutations = [cur];
  68. while (parts.length) {
  69. const part = parts.shift();
  70. cur = `${part}.${cur}`;
  71. permutations.push(cur);
  72. }
  73. return permutations;
  74. }
  75. // lib/store.ts
  76. var Store = class {
  77. constructor() {
  78. this.synchronous = false;
  79. }
  80. /**
  81. * @internal No doc because this is an overload that supports the implementation
  82. */
  83. findCookie(_domain, _path, _key, _callback) {
  84. throw new Error("findCookie is not implemented");
  85. }
  86. /**
  87. * @internal No doc because this is an overload that supports the implementation
  88. */
  89. findCookies(_domain, _path, _allowSpecialUseDomain = false, _callback) {
  90. throw new Error("findCookies is not implemented");
  91. }
  92. /**
  93. * @internal No doc because this is an overload that supports the implementation
  94. */
  95. putCookie(_cookie, _callback) {
  96. throw new Error("putCookie is not implemented");
  97. }
  98. /**
  99. * @internal No doc because this is an overload that supports the implementation
  100. */
  101. updateCookie(_oldCookie, _newCookie, _callback) {
  102. throw new Error("updateCookie is not implemented");
  103. }
  104. /**
  105. * @internal No doc because this is an overload that supports the implementation
  106. */
  107. removeCookie(_domain, _path, _key, _callback) {
  108. throw new Error("removeCookie is not implemented");
  109. }
  110. /**
  111. * @internal No doc because this is an overload that supports the implementation
  112. */
  113. removeCookies(_domain, _path, _callback) {
  114. throw new Error("removeCookies is not implemented");
  115. }
  116. /**
  117. * @internal No doc because this is an overload that supports the implementation
  118. */
  119. removeAllCookies(_callback) {
  120. throw new Error("removeAllCookies is not implemented");
  121. }
  122. /**
  123. * @internal No doc because this is an overload that supports the implementation
  124. */
  125. getAllCookies(_callback) {
  126. throw new Error(
  127. "getAllCookies is not implemented (therefore jar cannot be serialized)"
  128. );
  129. }
  130. };
  131. // lib/utils.ts
  132. var objectToString = (obj) => Object.prototype.toString.call(obj);
  133. var safeArrayToString = (arr, seenArrays) => {
  134. if (typeof arr.join !== "function") return objectToString(arr);
  135. seenArrays.add(arr);
  136. const mapped = arr.map(
  137. (val) => val === null || val === void 0 || seenArrays.has(val) ? "" : safeToStringImpl(val, seenArrays)
  138. );
  139. return mapped.join();
  140. };
  141. var safeToStringImpl = (val, seenArrays = /* @__PURE__ */ new WeakSet()) => {
  142. if (typeof val !== "object" || val === null) {
  143. return String(val);
  144. } else if (typeof val.toString === "function") {
  145. return Array.isArray(val) ? (
  146. // Arrays have a weird custom toString that we need to replicate
  147. safeArrayToString(val, seenArrays)
  148. ) : (
  149. // eslint-disable-next-line @typescript-eslint/no-base-to-string
  150. String(val)
  151. );
  152. } else {
  153. return objectToString(val);
  154. }
  155. };
  156. var safeToString = (val) => safeToStringImpl(val);
  157. function createPromiseCallback(cb) {
  158. let callback;
  159. let resolve;
  160. let reject;
  161. const promise = new Promise((_resolve, _reject) => {
  162. resolve = _resolve;
  163. reject = _reject;
  164. });
  165. if (typeof cb === "function") {
  166. callback = (err, result) => {
  167. try {
  168. if (err) cb(err);
  169. else cb(null, result);
  170. } catch (e) {
  171. reject(e instanceof Error ? e : new Error());
  172. }
  173. };
  174. } else {
  175. callback = (err, result) => {
  176. try {
  177. if (err) reject(err);
  178. else resolve(result);
  179. } catch (e) {
  180. reject(e instanceof Error ? e : new Error());
  181. }
  182. };
  183. }
  184. return {
  185. promise,
  186. callback,
  187. resolve: (value) => {
  188. callback(null, value);
  189. return promise;
  190. },
  191. reject: (error) => {
  192. callback(error);
  193. return promise;
  194. }
  195. };
  196. }
  197. function inOperator(k, o) {
  198. return k in o;
  199. }
  200. // lib/memstore.ts
  201. var MemoryCookieStore = class extends Store {
  202. /**
  203. * Create a new {@link MemoryCookieStore}.
  204. */
  205. constructor() {
  206. super();
  207. this.synchronous = true;
  208. this.idx = /* @__PURE__ */ Object.create(null);
  209. }
  210. /**
  211. * @internal No doc because this is an overload that supports the implementation
  212. */
  213. findCookie(domain, path, key, callback) {
  214. const promiseCallback = createPromiseCallback(callback);
  215. if (domain == null || path == null || key == null) {
  216. return promiseCallback.resolve(void 0);
  217. }
  218. const result = this.idx[domain]?.[path]?.[key];
  219. return promiseCallback.resolve(result);
  220. }
  221. /**
  222. * @internal No doc because this is an overload that supports the implementation
  223. */
  224. findCookies(domain, path, allowSpecialUseDomain = false, callback) {
  225. if (typeof allowSpecialUseDomain === "function") {
  226. callback = allowSpecialUseDomain;
  227. allowSpecialUseDomain = true;
  228. }
  229. const results = [];
  230. const promiseCallback = createPromiseCallback(callback);
  231. if (!domain) {
  232. return promiseCallback.resolve([]);
  233. }
  234. let pathMatcher;
  235. if (!path) {
  236. pathMatcher = function matchAll(domainIndex) {
  237. for (const curPath in domainIndex) {
  238. const pathIndex = domainIndex[curPath];
  239. for (const key in pathIndex) {
  240. const value = pathIndex[key];
  241. if (value) {
  242. results.push(value);
  243. }
  244. }
  245. }
  246. };
  247. } else {
  248. pathMatcher = function matchRFC(domainIndex) {
  249. for (const cookiePath in domainIndex) {
  250. if (pathMatch(path, cookiePath)) {
  251. const pathIndex = domainIndex[cookiePath];
  252. for (const key in pathIndex) {
  253. const value = pathIndex[key];
  254. if (value) {
  255. results.push(value);
  256. }
  257. }
  258. }
  259. }
  260. };
  261. }
  262. const domains = permuteDomain(domain, allowSpecialUseDomain) || [domain];
  263. const idx = this.idx;
  264. domains.forEach((curDomain) => {
  265. const domainIndex = idx[curDomain];
  266. if (!domainIndex) {
  267. return;
  268. }
  269. pathMatcher(domainIndex);
  270. });
  271. return promiseCallback.resolve(results);
  272. }
  273. /**
  274. * @internal No doc because this is an overload that supports the implementation
  275. */
  276. putCookie(cookie, callback) {
  277. const promiseCallback = createPromiseCallback(callback);
  278. const { domain, path, key } = cookie;
  279. if (domain == null || path == null || key == null) {
  280. return promiseCallback.resolve(void 0);
  281. }
  282. const domainEntry = this.idx[domain] ?? /* @__PURE__ */ Object.create(null);
  283. this.idx[domain] = domainEntry;
  284. const pathEntry = domainEntry[path] ?? /* @__PURE__ */ Object.create(null);
  285. domainEntry[path] = pathEntry;
  286. pathEntry[key] = cookie;
  287. return promiseCallback.resolve(void 0);
  288. }
  289. /**
  290. * @internal No doc because this is an overload that supports the implementation
  291. */
  292. updateCookie(_oldCookie, newCookie, callback) {
  293. if (callback) this.putCookie(newCookie, callback);
  294. else return this.putCookie(newCookie);
  295. }
  296. /**
  297. * @internal No doc because this is an overload that supports the implementation
  298. */
  299. removeCookie(domain, path, key, callback) {
  300. const promiseCallback = createPromiseCallback(callback);
  301. delete this.idx[domain]?.[path]?.[key];
  302. return promiseCallback.resolve(void 0);
  303. }
  304. /**
  305. * @internal No doc because this is an overload that supports the implementation
  306. */
  307. removeCookies(domain, path, callback) {
  308. const promiseCallback = createPromiseCallback(callback);
  309. const domainEntry = this.idx[domain];
  310. if (domainEntry) {
  311. if (path) {
  312. delete domainEntry[path];
  313. } else {
  314. delete this.idx[domain];
  315. }
  316. }
  317. return promiseCallback.resolve(void 0);
  318. }
  319. /**
  320. * @internal No doc because this is an overload that supports the implementation
  321. */
  322. removeAllCookies(callback) {
  323. const promiseCallback = createPromiseCallback(callback);
  324. this.idx = /* @__PURE__ */ Object.create(null);
  325. return promiseCallback.resolve(void 0);
  326. }
  327. /**
  328. * @internal No doc because this is an overload that supports the implementation
  329. */
  330. getAllCookies(callback) {
  331. const promiseCallback = createPromiseCallback(callback);
  332. const cookies = [];
  333. const idx = this.idx;
  334. const domains = Object.keys(idx);
  335. domains.forEach((domain) => {
  336. const domainEntry = idx[domain] ?? {};
  337. const paths = Object.keys(domainEntry);
  338. paths.forEach((path) => {
  339. const pathEntry = domainEntry[path] ?? {};
  340. const keys = Object.keys(pathEntry);
  341. keys.forEach((key) => {
  342. const keyEntry = pathEntry[key];
  343. if (keyEntry != null) {
  344. cookies.push(keyEntry);
  345. }
  346. });
  347. });
  348. });
  349. cookies.sort((a, b) => {
  350. return (a.creationIndex || 0) - (b.creationIndex || 0);
  351. });
  352. return promiseCallback.resolve(cookies);
  353. }
  354. };
  355. // lib/validators.ts
  356. function isNonEmptyString(data) {
  357. return isString(data) && data !== "";
  358. }
  359. function isEmptyString(data) {
  360. return data === "" || data instanceof String && data.toString() === "";
  361. }
  362. function isString(data) {
  363. return typeof data === "string" || data instanceof String;
  364. }
  365. function isObject(data) {
  366. return objectToString(data) === "[object Object]";
  367. }
  368. function validate(bool, cbOrMessage, message) {
  369. if (bool) return;
  370. const cb = typeof cbOrMessage === "function" ? cbOrMessage : void 0;
  371. let options = typeof cbOrMessage === "function" ? message : cbOrMessage;
  372. if (!isObject(options)) options = "[object Object]";
  373. const err = new ParameterError(safeToString(options));
  374. if (cb) cb(err);
  375. else throw err;
  376. }
  377. var ParameterError = class extends Error {
  378. };
  379. // lib/version.ts
  380. var version = "6.0.0";
  381. // lib/cookie/constants.ts
  382. var PrefixSecurityEnum = {
  383. SILENT: "silent",
  384. STRICT: "strict",
  385. DISABLED: "unsafe-disabled"
  386. };
  387. Object.freeze(PrefixSecurityEnum);
  388. var IP_V6_REGEX = `
  389. \\[?(?:
  390. (?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)|
  391. (?:[a-fA-F\\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|:[a-fA-F\\d]{1,4}|:)|
  392. (?:[a-fA-F\\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,2}|:)|
  393. (?:[a-fA-F\\d]{1,4}:){4}(?:(?::[a-fA-F\\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,3}|:)|
  394. (?:[a-fA-F\\d]{1,4}:){3}(?:(?::[a-fA-F\\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,4}|:)|
  395. (?:[a-fA-F\\d]{1,4}:){2}(?:(?::[a-fA-F\\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,5}|:)|
  396. (?:[a-fA-F\\d]{1,4}:){1}(?:(?::[a-fA-F\\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,6}|:)|
  397. (?::(?:(?::[a-fA-F\\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,7}|:))
  398. )(?:%[0-9a-zA-Z]{1,})?\\]?
  399. `.replace(/\s*\/\/.*$/gm, "").replace(/\n/g, "").trim();
  400. var IP_V6_REGEX_OBJECT = new RegExp(`^${IP_V6_REGEX}$`);
  401. var IP_V4_REGEX = `(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])`;
  402. var IP_V4_REGEX_OBJECT = new RegExp(`^${IP_V4_REGEX}$`);
  403. // lib/cookie/canonicalDomain.ts
  404. function domainToASCII(domain) {
  405. return new URL(`http://${domain}`).hostname;
  406. }
  407. function canonicalDomain(domainName) {
  408. if (domainName == null) {
  409. return void 0;
  410. }
  411. let str = domainName.trim().replace(/^\./, "");
  412. if (IP_V6_REGEX_OBJECT.test(str)) {
  413. if (!str.startsWith("[")) {
  414. str = "[" + str;
  415. }
  416. if (!str.endsWith("]")) {
  417. str = str + "]";
  418. }
  419. return domainToASCII(str).slice(1, -1);
  420. }
  421. if (/[^\u0001-\u007f]/.test(str)) {
  422. return domainToASCII(str);
  423. }
  424. return str.toLowerCase();
  425. }
  426. // lib/cookie/formatDate.ts
  427. function formatDate(date) {
  428. return date.toUTCString();
  429. }
  430. // lib/cookie/parseDate.ts
  431. var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
  432. var MONTH_TO_NUM = {
  433. jan: 0,
  434. feb: 1,
  435. mar: 2,
  436. apr: 3,
  437. may: 4,
  438. jun: 5,
  439. jul: 6,
  440. aug: 7,
  441. sep: 8,
  442. oct: 9,
  443. nov: 10,
  444. dec: 11
  445. };
  446. function parseDigits(token, minDigits, maxDigits, trailingOK) {
  447. let count = 0;
  448. while (count < token.length) {
  449. const c = token.charCodeAt(count);
  450. if (c <= 47 || c >= 58) {
  451. break;
  452. }
  453. count++;
  454. }
  455. if (count < minDigits || count > maxDigits) {
  456. return;
  457. }
  458. if (!trailingOK && count != token.length) {
  459. return;
  460. }
  461. return parseInt(token.slice(0, count), 10);
  462. }
  463. function parseTime(token) {
  464. const parts = token.split(":");
  465. const result = [0, 0, 0];
  466. if (parts.length !== 3) {
  467. return;
  468. }
  469. for (let i = 0; i < 3; i++) {
  470. const trailingOK = i == 2;
  471. const numPart = parts[i];
  472. if (numPart === void 0) {
  473. return;
  474. }
  475. const num = parseDigits(numPart, 1, 2, trailingOK);
  476. if (num === void 0) {
  477. return;
  478. }
  479. result[i] = num;
  480. }
  481. return result;
  482. }
  483. function parseMonth(token) {
  484. token = String(token).slice(0, 3).toLowerCase();
  485. switch (token) {
  486. case "jan":
  487. return MONTH_TO_NUM.jan;
  488. case "feb":
  489. return MONTH_TO_NUM.feb;
  490. case "mar":
  491. return MONTH_TO_NUM.mar;
  492. case "apr":
  493. return MONTH_TO_NUM.apr;
  494. case "may":
  495. return MONTH_TO_NUM.may;
  496. case "jun":
  497. return MONTH_TO_NUM.jun;
  498. case "jul":
  499. return MONTH_TO_NUM.jul;
  500. case "aug":
  501. return MONTH_TO_NUM.aug;
  502. case "sep":
  503. return MONTH_TO_NUM.sep;
  504. case "oct":
  505. return MONTH_TO_NUM.oct;
  506. case "nov":
  507. return MONTH_TO_NUM.nov;
  508. case "dec":
  509. return MONTH_TO_NUM.dec;
  510. default:
  511. return;
  512. }
  513. }
  514. function parseDate(cookieDate) {
  515. if (!cookieDate) {
  516. return;
  517. }
  518. const tokens = cookieDate.split(DATE_DELIM);
  519. let hour;
  520. let minute;
  521. let second;
  522. let dayOfMonth;
  523. let month;
  524. let year;
  525. for (let i = 0; i < tokens.length; i++) {
  526. const token = (tokens[i] ?? "").trim();
  527. if (!token.length) {
  528. continue;
  529. }
  530. if (second === void 0) {
  531. const result = parseTime(token);
  532. if (result) {
  533. hour = result[0];
  534. minute = result[1];
  535. second = result[2];
  536. continue;
  537. }
  538. }
  539. if (dayOfMonth === void 0) {
  540. const result = parseDigits(token, 1, 2, true);
  541. if (result !== void 0) {
  542. dayOfMonth = result;
  543. continue;
  544. }
  545. }
  546. if (month === void 0) {
  547. const result = parseMonth(token);
  548. if (result !== void 0) {
  549. month = result;
  550. continue;
  551. }
  552. }
  553. if (year === void 0) {
  554. const result = parseDigits(token, 2, 4, true);
  555. if (result !== void 0) {
  556. year = result;
  557. if (year >= 70 && year <= 99) {
  558. year += 1900;
  559. } else if (year >= 0 && year <= 69) {
  560. year += 2e3;
  561. }
  562. }
  563. }
  564. }
  565. if (dayOfMonth === void 0 || month === void 0 || year === void 0 || hour === void 0 || minute === void 0 || second === void 0 || dayOfMonth < 1 || dayOfMonth > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59) {
  566. return;
  567. }
  568. return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
  569. }
  570. // lib/cookie/cookie.ts
  571. var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
  572. var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
  573. var CONTROL_CHARS = /[\x00-\x1F]/;
  574. var TERMINATORS = ["\n", "\r", "\0"];
  575. function trimTerminator(str) {
  576. if (isEmptyString(str)) return str;
  577. for (let t = 0; t < TERMINATORS.length; t++) {
  578. const terminator = TERMINATORS[t];
  579. const terminatorIdx = terminator ? str.indexOf(terminator) : -1;
  580. if (terminatorIdx !== -1) {
  581. str = str.slice(0, terminatorIdx);
  582. }
  583. }
  584. return str;
  585. }
  586. function parseCookiePair(cookiePair, looseMode) {
  587. cookiePair = trimTerminator(cookiePair);
  588. let firstEq = cookiePair.indexOf("=");
  589. if (looseMode) {
  590. if (firstEq === 0) {
  591. cookiePair = cookiePair.substring(1);
  592. firstEq = cookiePair.indexOf("=");
  593. }
  594. } else {
  595. if (firstEq <= 0) {
  596. return void 0;
  597. }
  598. }
  599. let cookieName, cookieValue;
  600. if (firstEq <= 0) {
  601. cookieName = "";
  602. cookieValue = cookiePair.trim();
  603. } else {
  604. cookieName = cookiePair.slice(0, firstEq).trim();
  605. cookieValue = cookiePair.slice(firstEq + 1).trim();
  606. }
  607. if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
  608. return void 0;
  609. }
  610. const c = new Cookie();
  611. c.key = cookieName;
  612. c.value = cookieValue;
  613. return c;
  614. }
  615. function parse(str, options) {
  616. if (isEmptyString(str) || !isString(str)) {
  617. return void 0;
  618. }
  619. str = str.trim();
  620. const firstSemi = str.indexOf(";");
  621. const cookiePair = firstSemi === -1 ? str : str.slice(0, firstSemi);
  622. const c = parseCookiePair(cookiePair, options?.loose ?? false);
  623. if (!c) {
  624. return void 0;
  625. }
  626. if (firstSemi === -1) {
  627. return c;
  628. }
  629. const unparsed = str.slice(firstSemi + 1).trim();
  630. if (unparsed.length === 0) {
  631. return c;
  632. }
  633. const cookie_avs = unparsed.split(";");
  634. while (cookie_avs.length) {
  635. const av = (cookie_avs.shift() ?? "").trim();
  636. if (av.length === 0) {
  637. continue;
  638. }
  639. const av_sep = av.indexOf("=");
  640. let av_key, av_value;
  641. if (av_sep === -1) {
  642. av_key = av;
  643. av_value = null;
  644. } else {
  645. av_key = av.slice(0, av_sep);
  646. av_value = av.slice(av_sep + 1);
  647. }
  648. av_key = av_key.trim().toLowerCase();
  649. if (av_value) {
  650. av_value = av_value.trim();
  651. }
  652. switch (av_key) {
  653. case "expires":
  654. if (av_value) {
  655. const exp = parseDate(av_value);
  656. if (exp) {
  657. c.expires = exp;
  658. }
  659. }
  660. break;
  661. case "max-age":
  662. if (av_value) {
  663. if (/^-?[0-9]+$/.test(av_value)) {
  664. const delta = parseInt(av_value, 10);
  665. c.setMaxAge(delta);
  666. }
  667. }
  668. break;
  669. case "domain":
  670. if (av_value) {
  671. const domain = av_value.trim().replace(/^\./, "");
  672. if (domain) {
  673. c.domain = domain.toLowerCase();
  674. }
  675. }
  676. break;
  677. case "path":
  678. c.path = av_value && av_value[0] === "/" ? av_value : null;
  679. break;
  680. case "secure":
  681. c.secure = true;
  682. break;
  683. case "httponly":
  684. c.httpOnly = true;
  685. break;
  686. case "samesite":
  687. switch (av_value ? av_value.toLowerCase() : "") {
  688. case "strict":
  689. c.sameSite = "strict";
  690. break;
  691. case "lax":
  692. c.sameSite = "lax";
  693. break;
  694. case "none":
  695. c.sameSite = "none";
  696. break;
  697. default:
  698. c.sameSite = void 0;
  699. break;
  700. }
  701. break;
  702. default:
  703. c.extensions = c.extensions || [];
  704. c.extensions.push(av);
  705. break;
  706. }
  707. }
  708. return c;
  709. }
  710. function fromJSON(str) {
  711. if (!str || isEmptyString(str)) {
  712. return void 0;
  713. }
  714. let obj;
  715. if (typeof str === "string") {
  716. try {
  717. obj = JSON.parse(str);
  718. } catch {
  719. return void 0;
  720. }
  721. } else {
  722. obj = str;
  723. }
  724. const c = new Cookie();
  725. Cookie.serializableProperties.forEach((prop) => {
  726. if (obj && typeof obj === "object" && inOperator(prop, obj)) {
  727. const val = obj[prop];
  728. if (val === void 0) {
  729. return;
  730. }
  731. if (inOperator(prop, cookieDefaults) && val === cookieDefaults[prop]) {
  732. return;
  733. }
  734. switch (prop) {
  735. case "key":
  736. case "value":
  737. case "sameSite":
  738. if (typeof val === "string") {
  739. c[prop] = val;
  740. }
  741. break;
  742. case "expires":
  743. case "creation":
  744. case "lastAccessed":
  745. if (typeof val === "number" || typeof val === "string" || val instanceof Date) {
  746. c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(val);
  747. } else if (val === null) {
  748. c[prop] = null;
  749. }
  750. break;
  751. case "maxAge":
  752. if (typeof val === "number" || val === "Infinity" || val === "-Infinity") {
  753. c[prop] = val;
  754. }
  755. break;
  756. case "domain":
  757. case "path":
  758. if (typeof val === "string" || val === null) {
  759. c[prop] = val;
  760. }
  761. break;
  762. case "secure":
  763. case "httpOnly":
  764. if (typeof val === "boolean") {
  765. c[prop] = val;
  766. }
  767. break;
  768. case "extensions":
  769. if (Array.isArray(val) && val.every((item) => typeof item === "string")) {
  770. c[prop] = val;
  771. }
  772. break;
  773. case "hostOnly":
  774. case "pathIsDefault":
  775. if (typeof val === "boolean" || val === null) {
  776. c[prop] = val;
  777. }
  778. break;
  779. }
  780. }
  781. });
  782. return c;
  783. }
  784. var cookieDefaults = {
  785. // the order in which the RFC has them:
  786. key: "",
  787. value: "",
  788. expires: "Infinity",
  789. maxAge: null,
  790. domain: null,
  791. path: null,
  792. secure: false,
  793. httpOnly: false,
  794. extensions: null,
  795. // set by the CookieJar:
  796. hostOnly: null,
  797. pathIsDefault: null,
  798. creation: null,
  799. lastAccessed: null,
  800. sameSite: void 0
  801. };
  802. var _Cookie = class _Cookie {
  803. /**
  804. * Create a new Cookie instance.
  805. * @public
  806. * @param options - The attributes to set on the cookie
  807. */
  808. constructor(options = {}) {
  809. this.key = options.key ?? cookieDefaults.key;
  810. this.value = options.value ?? cookieDefaults.value;
  811. this.expires = options.expires ?? cookieDefaults.expires;
  812. this.maxAge = options.maxAge ?? cookieDefaults.maxAge;
  813. this.domain = options.domain ?? cookieDefaults.domain;
  814. this.path = options.path ?? cookieDefaults.path;
  815. this.secure = options.secure ?? cookieDefaults.secure;
  816. this.httpOnly = options.httpOnly ?? cookieDefaults.httpOnly;
  817. this.extensions = options.extensions ?? cookieDefaults.extensions;
  818. this.creation = options.creation ?? cookieDefaults.creation;
  819. this.hostOnly = options.hostOnly ?? cookieDefaults.hostOnly;
  820. this.pathIsDefault = options.pathIsDefault ?? cookieDefaults.pathIsDefault;
  821. this.lastAccessed = options.lastAccessed ?? cookieDefaults.lastAccessed;
  822. this.sameSite = options.sameSite ?? cookieDefaults.sameSite;
  823. this.creation = options.creation ?? /* @__PURE__ */ new Date();
  824. Object.defineProperty(this, "creationIndex", {
  825. configurable: false,
  826. enumerable: false,
  827. // important for assert.deepEqual checks
  828. writable: true,
  829. value: ++_Cookie.cookiesCreated
  830. });
  831. this.creationIndex = _Cookie.cookiesCreated;
  832. }
  833. [Symbol.for("nodejs.util.inspect.custom")]() {
  834. const now = Date.now();
  835. const hostOnly = this.hostOnly != null ? this.hostOnly.toString() : "?";
  836. const createAge = this.creation && this.creation !== "Infinity" ? `${String(now - this.creation.getTime())}ms` : "?";
  837. const accessAge = this.lastAccessed && this.lastAccessed !== "Infinity" ? `${String(now - this.lastAccessed.getTime())}ms` : "?";
  838. return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`;
  839. }
  840. /**
  841. * For convenience in using `JSON.stringify(cookie)`. Returns a plain-old Object that can be JSON-serialized.
  842. *
  843. * @remarks
  844. * - Any `Date` properties (such as {@link Cookie.expires}, {@link Cookie.creation}, and {@link Cookie.lastAccessed}) are exported in ISO format (`Date.toISOString()`).
  845. *
  846. * - Custom Cookie properties are discarded. In tough-cookie 1.x, since there was no {@link Cookie.toJSON} method explicitly defined, all enumerable properties were captured.
  847. * If you want a property to be serialized, add the property name to {@link Cookie.serializableProperties}.
  848. */
  849. toJSON() {
  850. const obj = {};
  851. for (const prop of _Cookie.serializableProperties) {
  852. const val = this[prop];
  853. if (val === cookieDefaults[prop]) {
  854. continue;
  855. }
  856. switch (prop) {
  857. case "key":
  858. case "value":
  859. case "sameSite":
  860. if (typeof val === "string") {
  861. obj[prop] = val;
  862. }
  863. break;
  864. case "expires":
  865. case "creation":
  866. case "lastAccessed":
  867. if (typeof val === "number" || typeof val === "string" || val instanceof Date) {
  868. obj[prop] = val == "Infinity" ? "Infinity" : new Date(val).toISOString();
  869. } else if (val === null) {
  870. obj[prop] = null;
  871. }
  872. break;
  873. case "maxAge":
  874. if (typeof val === "number" || val === "Infinity" || val === "-Infinity") {
  875. obj[prop] = val;
  876. }
  877. break;
  878. case "domain":
  879. case "path":
  880. if (typeof val === "string" || val === null) {
  881. obj[prop] = val;
  882. }
  883. break;
  884. case "secure":
  885. case "httpOnly":
  886. if (typeof val === "boolean") {
  887. obj[prop] = val;
  888. }
  889. break;
  890. case "extensions":
  891. if (Array.isArray(val)) {
  892. obj[prop] = val;
  893. }
  894. break;
  895. case "hostOnly":
  896. case "pathIsDefault":
  897. if (typeof val === "boolean" || val === null) {
  898. obj[prop] = val;
  899. }
  900. break;
  901. }
  902. }
  903. return obj;
  904. }
  905. /**
  906. * Does a deep clone of this cookie, implemented exactly as `Cookie.fromJSON(cookie.toJSON())`.
  907. * @public
  908. */
  909. clone() {
  910. return fromJSON(this.toJSON());
  911. }
  912. /**
  913. * Validates cookie attributes for semantic correctness. Useful for "lint" checking any `Set-Cookie` headers you generate.
  914. * For now, it returns a boolean, but eventually could return a reason string.
  915. *
  916. * @remarks
  917. * Works for a few things, but is by no means comprehensive.
  918. *
  919. * @beta
  920. */
  921. validate() {
  922. if (!this.value || !COOKIE_OCTETS.test(this.value)) {
  923. return false;
  924. }
  925. if (this.expires != "Infinity" && !(this.expires instanceof Date) && !parseDate(this.expires)) {
  926. return false;
  927. }
  928. if (this.maxAge != null && this.maxAge !== "Infinity" && (this.maxAge === "-Infinity" || this.maxAge <= 0)) {
  929. return false;
  930. }
  931. if (this.path != null && !PATH_VALUE.test(this.path)) {
  932. return false;
  933. }
  934. const cdomain = this.cdomain();
  935. if (cdomain) {
  936. if (cdomain.match(/\.$/)) {
  937. return false;
  938. }
  939. const suffix = getPublicSuffix(cdomain);
  940. if (suffix == null) {
  941. return false;
  942. }
  943. }
  944. return true;
  945. }
  946. /**
  947. * Sets the 'Expires' attribute on a cookie.
  948. *
  949. * @remarks
  950. * When given a `string` value it will be parsed with {@link parseDate}. If the value can't be parsed as a cookie date
  951. * then the 'Expires' attribute will be set to `"Infinity"`.
  952. *
  953. * @param exp - the new value for the 'Expires' attribute of the cookie.
  954. */
  955. setExpires(exp) {
  956. if (exp instanceof Date) {
  957. this.expires = exp;
  958. } else {
  959. this.expires = parseDate(exp) || "Infinity";
  960. }
  961. }
  962. /**
  963. * Sets the 'Max-Age' attribute (in seconds) on a cookie.
  964. *
  965. * @remarks
  966. * Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it can be serialized to JSON.
  967. *
  968. * @param age - the new value for the 'Max-Age' attribute (in seconds).
  969. */
  970. setMaxAge(age) {
  971. if (age === Infinity) {
  972. this.maxAge = "Infinity";
  973. } else if (age === -Infinity) {
  974. this.maxAge = "-Infinity";
  975. } else {
  976. this.maxAge = age;
  977. }
  978. }
  979. /**
  980. * Encodes to a `Cookie` header value (specifically, the {@link Cookie.key} and {@link Cookie.value} properties joined with "=").
  981. * @public
  982. */
  983. cookieString() {
  984. const val = this.value || "";
  985. if (this.key) {
  986. return `${this.key}=${val}`;
  987. }
  988. return val;
  989. }
  990. /**
  991. * Encodes to a `Set-Cookie header` value.
  992. * @public
  993. */
  994. toString() {
  995. let str = this.cookieString();
  996. if (this.expires != "Infinity") {
  997. if (this.expires instanceof Date) {
  998. str += `; Expires=${formatDate(this.expires)}`;
  999. }
  1000. }
  1001. if (this.maxAge != null && this.maxAge != Infinity) {
  1002. str += `; Max-Age=${String(this.maxAge)}`;
  1003. }
  1004. if (this.domain && !this.hostOnly) {
  1005. str += `; Domain=${this.domain}`;
  1006. }
  1007. if (this.path) {
  1008. str += `; Path=${this.path}`;
  1009. }
  1010. if (this.secure) {
  1011. str += "; Secure";
  1012. }
  1013. if (this.httpOnly) {
  1014. str += "; HttpOnly";
  1015. }
  1016. if (this.sameSite && this.sameSite !== "none") {
  1017. if (this.sameSite.toLowerCase() === _Cookie.sameSiteCanonical.lax.toLowerCase()) {
  1018. str += `; SameSite=${_Cookie.sameSiteCanonical.lax}`;
  1019. } else if (this.sameSite.toLowerCase() === _Cookie.sameSiteCanonical.strict.toLowerCase()) {
  1020. str += `; SameSite=${_Cookie.sameSiteCanonical.strict}`;
  1021. } else {
  1022. str += `; SameSite=${this.sameSite}`;
  1023. }
  1024. }
  1025. if (this.extensions) {
  1026. this.extensions.forEach((ext) => {
  1027. str += `; ${ext}`;
  1028. });
  1029. }
  1030. return str;
  1031. }
  1032. /**
  1033. * Computes the TTL relative to now (milliseconds).
  1034. *
  1035. * @remarks
  1036. * - `Infinity` is returned for cookies without an explicit expiry
  1037. *
  1038. * - `0` is returned if the cookie is expired.
  1039. *
  1040. * - Otherwise a time-to-live in milliseconds is returned.
  1041. *
  1042. * @param now - passing an explicit value is mostly used for testing purposes since this defaults to the `Date.now()`
  1043. * @public
  1044. */
  1045. TTL(now = Date.now()) {
  1046. if (this.maxAge != null && typeof this.maxAge === "number") {
  1047. return this.maxAge <= 0 ? 0 : this.maxAge * 1e3;
  1048. }
  1049. const expires = this.expires;
  1050. if (expires === "Infinity") {
  1051. return Infinity;
  1052. }
  1053. return (expires?.getTime() ?? now) - (now || Date.now());
  1054. }
  1055. /**
  1056. * Computes the absolute unix-epoch milliseconds that this cookie expires.
  1057. *
  1058. * The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
  1059. * (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
  1060. *
  1061. * If Expires ({@link Cookie.expires}) is set, that's returned.
  1062. *
  1063. * @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
  1064. */
  1065. expiryTime(now) {
  1066. if (this.maxAge != null) {
  1067. const relativeTo = now || this.lastAccessed || /* @__PURE__ */ new Date();
  1068. const maxAge = typeof this.maxAge === "number" ? this.maxAge : -Infinity;
  1069. const age = maxAge <= 0 ? -Infinity : maxAge * 1e3;
  1070. if (relativeTo === "Infinity") {
  1071. return Infinity;
  1072. }
  1073. return relativeTo.getTime() + age;
  1074. }
  1075. if (this.expires == "Infinity") {
  1076. return Infinity;
  1077. }
  1078. return this.expires ? this.expires.getTime() : void 0;
  1079. }
  1080. /**
  1081. * Similar to {@link Cookie.expiryTime}, computes the absolute unix-epoch milliseconds that this cookie expires and returns it as a Date.
  1082. *
  1083. * The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
  1084. * (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
  1085. *
  1086. * If Expires ({@link Cookie.expires}) is set, that's returned.
  1087. *
  1088. * @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
  1089. */
  1090. expiryDate(now) {
  1091. const millisec = this.expiryTime(now);
  1092. if (millisec == Infinity) {
  1093. return /* @__PURE__ */ new Date(2147483647e3);
  1094. } else if (millisec == -Infinity) {
  1095. return /* @__PURE__ */ new Date(0);
  1096. } else {
  1097. return millisec == void 0 ? void 0 : new Date(millisec);
  1098. }
  1099. }
  1100. /**
  1101. * Indicates if the cookie has been persisted to a store or not.
  1102. * @public
  1103. */
  1104. isPersistent() {
  1105. return this.maxAge != null || this.expires != "Infinity";
  1106. }
  1107. /**
  1108. * Calls {@link canonicalDomain} with the {@link Cookie.domain} property.
  1109. * @public
  1110. */
  1111. canonicalizedDomain() {
  1112. return canonicalDomain(this.domain);
  1113. }
  1114. /**
  1115. * Alias for {@link Cookie.canonicalizedDomain}
  1116. * @public
  1117. */
  1118. cdomain() {
  1119. return canonicalDomain(this.domain);
  1120. }
  1121. /**
  1122. * Parses a string into a Cookie object.
  1123. *
  1124. * @remarks
  1125. * Note: when parsing a `Cookie` header it must be split by ';' before each Cookie string can be parsed.
  1126. *
  1127. * @example
  1128. * ```
  1129. * // parse a `Set-Cookie` header
  1130. * const setCookieHeader = 'a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT'
  1131. * const cookie = Cookie.parse(setCookieHeader)
  1132. * cookie.key === 'a'
  1133. * cookie.value === 'bcd'
  1134. * cookie.expires === new Date(Date.parse('Tue, 18 Oct 2011 07:05:03 GMT'))
  1135. * ```
  1136. *
  1137. * @example
  1138. * ```
  1139. * // parse a `Cookie` header
  1140. * const cookieHeader = 'name=value; name2=value2; name3=value3'
  1141. * const cookies = cookieHeader.split(';').map(Cookie.parse)
  1142. * cookies[0].name === 'name'
  1143. * cookies[0].value === 'value'
  1144. * cookies[1].name === 'name2'
  1145. * cookies[1].value === 'value2'
  1146. * cookies[2].name === 'name3'
  1147. * cookies[2].value === 'value3'
  1148. * ```
  1149. *
  1150. * @param str - The `Set-Cookie` header or a Cookie string to parse.
  1151. * @param options - Configures `strict` or `loose` mode for cookie parsing
  1152. */
  1153. static parse(str, options) {
  1154. return parse(str, options);
  1155. }
  1156. /**
  1157. * Does the reverse of {@link Cookie.toJSON}.
  1158. *
  1159. * @remarks
  1160. * Any Date properties (such as .expires, .creation, and .lastAccessed) are parsed via Date.parse, not tough-cookie's parseDate, since ISO timestamps are being handled at this layer.
  1161. *
  1162. * @example
  1163. * ```
  1164. * const json = JSON.stringify({
  1165. * key: 'alpha',
  1166. * value: 'beta',
  1167. * domain: 'example.com',
  1168. * path: '/foo',
  1169. * expires: '2038-01-19T03:14:07.000Z',
  1170. * })
  1171. * const cookie = Cookie.fromJSON(json)
  1172. * cookie.key === 'alpha'
  1173. * cookie.value === 'beta'
  1174. * cookie.domain === 'example.com'
  1175. * cookie.path === '/foo'
  1176. * cookie.expires === new Date(Date.parse('2038-01-19T03:14:07.000Z'))
  1177. * ```
  1178. *
  1179. * @param str - An unparsed JSON string or a value that has already been parsed as JSON
  1180. */
  1181. static fromJSON(str) {
  1182. return fromJSON(str);
  1183. }
  1184. };
  1185. _Cookie.cookiesCreated = 0;
  1186. /**
  1187. * @internal
  1188. */
  1189. _Cookie.sameSiteLevel = {
  1190. strict: 3,
  1191. lax: 2,
  1192. none: 1
  1193. };
  1194. /**
  1195. * @internal
  1196. */
  1197. _Cookie.sameSiteCanonical = {
  1198. strict: "Strict",
  1199. lax: "Lax"
  1200. };
  1201. /**
  1202. * Cookie properties that will be serialized when using {@link Cookie.fromJSON} and {@link Cookie.toJSON}.
  1203. * @public
  1204. */
  1205. _Cookie.serializableProperties = [
  1206. "key",
  1207. "value",
  1208. "expires",
  1209. "maxAge",
  1210. "domain",
  1211. "path",
  1212. "secure",
  1213. "httpOnly",
  1214. "extensions",
  1215. "hostOnly",
  1216. "pathIsDefault",
  1217. "creation",
  1218. "lastAccessed",
  1219. "sameSite"
  1220. ];
  1221. var Cookie = _Cookie;
  1222. // lib/cookie/cookieCompare.ts
  1223. var MAX_TIME = 2147483647e3;
  1224. function cookieCompare(a, b) {
  1225. let cmp;
  1226. const aPathLen = a.path ? a.path.length : 0;
  1227. const bPathLen = b.path ? b.path.length : 0;
  1228. cmp = bPathLen - aPathLen;
  1229. if (cmp !== 0) {
  1230. return cmp;
  1231. }
  1232. const aTime = a.creation && a.creation instanceof Date ? a.creation.getTime() : MAX_TIME;
  1233. const bTime = b.creation && b.creation instanceof Date ? b.creation.getTime() : MAX_TIME;
  1234. cmp = aTime - bTime;
  1235. if (cmp !== 0) {
  1236. return cmp;
  1237. }
  1238. cmp = (a.creationIndex || 0) - (b.creationIndex || 0);
  1239. return cmp;
  1240. }
  1241. // lib/cookie/defaultPath.ts
  1242. function defaultPath(path) {
  1243. if (!path || path.slice(0, 1) !== "/") {
  1244. return "/";
  1245. }
  1246. if (path === "/") {
  1247. return path;
  1248. }
  1249. const rightSlash = path.lastIndexOf("/");
  1250. if (rightSlash === 0) {
  1251. return "/";
  1252. }
  1253. return path.slice(0, rightSlash);
  1254. }
  1255. // lib/cookie/domainMatch.ts
  1256. var IP_REGEX_LOWERCASE = /(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/;
  1257. function domainMatch(domain, cookieDomain, canonicalize) {
  1258. if (domain == null || cookieDomain == null) {
  1259. return void 0;
  1260. }
  1261. let _str;
  1262. let _domStr;
  1263. if (canonicalize !== false) {
  1264. _str = canonicalDomain(domain);
  1265. _domStr = canonicalDomain(cookieDomain);
  1266. } else {
  1267. _str = domain;
  1268. _domStr = cookieDomain;
  1269. }
  1270. if (_str == null || _domStr == null) {
  1271. return void 0;
  1272. }
  1273. if (_str == _domStr) {
  1274. return true;
  1275. }
  1276. const idx = _str.lastIndexOf(_domStr);
  1277. if (idx <= 0) {
  1278. return false;
  1279. }
  1280. if (_str.length !== _domStr.length + idx) {
  1281. return false;
  1282. }
  1283. if (_str.substring(idx - 1, idx) !== ".") {
  1284. return false;
  1285. }
  1286. return !IP_REGEX_LOWERCASE.test(_str);
  1287. }
  1288. // lib/cookie/secureContext.ts
  1289. function isLoopbackV4(address) {
  1290. const octets = address.split(".");
  1291. return octets.length === 4 && octets[0] !== void 0 && parseInt(octets[0], 10) === 127;
  1292. }
  1293. function isLoopbackV6(address) {
  1294. return address === "::1";
  1295. }
  1296. function isNormalizedLocalhostTLD(lowerHost) {
  1297. return lowerHost.endsWith(".localhost");
  1298. }
  1299. function isLocalHostname(host) {
  1300. const lowerHost = host.toLowerCase();
  1301. return lowerHost === "localhost" || isNormalizedLocalhostTLD(lowerHost);
  1302. }
  1303. function hostNoBrackets(host) {
  1304. if (host.length >= 2 && host.startsWith("[") && host.endsWith("]")) {
  1305. return host.substring(1, host.length - 1);
  1306. }
  1307. return host;
  1308. }
  1309. function isPotentiallyTrustworthy(inputUrl, allowSecureOnLocal = true) {
  1310. let url;
  1311. if (typeof inputUrl === "string") {
  1312. try {
  1313. url = new URL(inputUrl);
  1314. } catch {
  1315. return false;
  1316. }
  1317. } else {
  1318. url = inputUrl;
  1319. }
  1320. const scheme = url.protocol.replace(":", "").toLowerCase();
  1321. const hostname = hostNoBrackets(url.hostname).replace(/\.+$/, "");
  1322. if (scheme === "https" || scheme === "wss") {
  1323. return true;
  1324. }
  1325. if (!allowSecureOnLocal) {
  1326. return false;
  1327. }
  1328. if (IP_V4_REGEX_OBJECT.test(hostname)) {
  1329. return isLoopbackV4(hostname);
  1330. }
  1331. if (IP_V6_REGEX_OBJECT.test(hostname)) {
  1332. return isLoopbackV6(hostname);
  1333. }
  1334. return isLocalHostname(hostname);
  1335. }
  1336. // lib/cookie/cookieJar.ts
  1337. var defaultSetCookieOptions = {
  1338. loose: false,
  1339. sameSiteContext: void 0,
  1340. ignoreError: false,
  1341. http: true
  1342. };
  1343. var defaultGetCookieOptions = {
  1344. http: true,
  1345. expire: true,
  1346. allPaths: false,
  1347. sameSiteContext: void 0,
  1348. sort: void 0
  1349. };
  1350. var SAME_SITE_CONTEXT_VAL_ERR = 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"';
  1351. function getCookieContext(url) {
  1352. if (url && typeof url === "object" && "hostname" in url && typeof url.hostname === "string" && "pathname" in url && typeof url.pathname === "string" && "protocol" in url && typeof url.protocol === "string") {
  1353. return {
  1354. hostname: url.hostname,
  1355. pathname: url.pathname,
  1356. protocol: url.protocol
  1357. };
  1358. } else if (typeof url === "string") {
  1359. try {
  1360. return new URL(decodeURI(url));
  1361. } catch {
  1362. return new URL(url);
  1363. }
  1364. } else {
  1365. throw new ParameterError("`url` argument is not a string or URL.");
  1366. }
  1367. }
  1368. function checkSameSiteContext(value) {
  1369. const context = String(value).toLowerCase();
  1370. if (context === "none" || context === "lax" || context === "strict") {
  1371. return context;
  1372. } else {
  1373. return void 0;
  1374. }
  1375. }
  1376. function isSecurePrefixConditionMet(cookie) {
  1377. const startsWithSecurePrefix = typeof cookie.key === "string" && cookie.key.startsWith("__Secure-");
  1378. return !startsWithSecurePrefix || cookie.secure;
  1379. }
  1380. function isHostPrefixConditionMet(cookie) {
  1381. const startsWithHostPrefix = typeof cookie.key === "string" && cookie.key.startsWith("__Host-");
  1382. return !startsWithHostPrefix || Boolean(
  1383. cookie.secure && cookie.hostOnly && cookie.path != null && cookie.path === "/"
  1384. );
  1385. }
  1386. function getNormalizedPrefixSecurity(prefixSecurity) {
  1387. const normalizedPrefixSecurity = prefixSecurity.toLowerCase();
  1388. switch (normalizedPrefixSecurity) {
  1389. case PrefixSecurityEnum.STRICT:
  1390. case PrefixSecurityEnum.SILENT:
  1391. case PrefixSecurityEnum.DISABLED:
  1392. return normalizedPrefixSecurity;
  1393. default:
  1394. return PrefixSecurityEnum.SILENT;
  1395. }
  1396. }
  1397. var CookieJar = class _CookieJar {
  1398. /**
  1399. * Creates a new `CookieJar` instance.
  1400. *
  1401. * @remarks
  1402. * - If a custom store is not passed to the constructor, an in-memory store ({@link MemoryCookieStore} will be created and used.
  1403. * - If a boolean value is passed as the `options` parameter, this is equivalent to passing `{ rejectPublicSuffixes: <value> }`
  1404. *
  1405. * @param store - a custom {@link Store} implementation (defaults to {@link MemoryCookieStore})
  1406. * @param options - configures how cookies are processed by the cookie jar
  1407. */
  1408. constructor(store, options) {
  1409. if (typeof options === "boolean") {
  1410. options = { rejectPublicSuffixes: options };
  1411. }
  1412. this.rejectPublicSuffixes = options?.rejectPublicSuffixes ?? true;
  1413. this.enableLooseMode = options?.looseMode ?? false;
  1414. this.allowSpecialUseDomain = options?.allowSpecialUseDomain ?? true;
  1415. this.allowSecureOnLocal = options?.allowSecureOnLocal ?? true;
  1416. this.prefixSecurity = getNormalizedPrefixSecurity(
  1417. options?.prefixSecurity ?? "silent"
  1418. );
  1419. this.store = store ?? new MemoryCookieStore();
  1420. }
  1421. callSync(fn) {
  1422. if (!this.store.synchronous) {
  1423. throw new Error(
  1424. "CookieJar store is not synchronous; use async API instead."
  1425. );
  1426. }
  1427. let syncErr = null;
  1428. let syncResult = void 0;
  1429. try {
  1430. fn.call(this, (error, result) => {
  1431. syncErr = error;
  1432. syncResult = result;
  1433. });
  1434. } catch (err) {
  1435. syncErr = err;
  1436. }
  1437. if (syncErr) throw syncErr;
  1438. return syncResult;
  1439. }
  1440. /**
  1441. * @internal No doc because this is the overload implementation
  1442. */
  1443. setCookie(cookie, url, options, callback) {
  1444. if (typeof options === "function") {
  1445. callback = options;
  1446. options = void 0;
  1447. }
  1448. const promiseCallback = createPromiseCallback(callback);
  1449. const cb = promiseCallback.callback;
  1450. let context;
  1451. try {
  1452. if (typeof url === "string") {
  1453. validate(
  1454. isNonEmptyString(url),
  1455. callback,
  1456. safeToString(options)
  1457. );
  1458. }
  1459. context = getCookieContext(url);
  1460. if (typeof url === "function") {
  1461. return promiseCallback.reject(new Error("No URL was specified"));
  1462. }
  1463. if (typeof options === "function") {
  1464. options = defaultSetCookieOptions;
  1465. }
  1466. validate(typeof cb === "function", cb);
  1467. if (!isNonEmptyString(cookie) && !isObject(cookie) && cookie instanceof String && cookie.length == 0) {
  1468. return promiseCallback.resolve(void 0);
  1469. }
  1470. } catch (err) {
  1471. return promiseCallback.reject(err);
  1472. }
  1473. const host = canonicalDomain(context.hostname) ?? null;
  1474. const loose = options?.loose || this.enableLooseMode;
  1475. let sameSiteContext = null;
  1476. if (options?.sameSiteContext) {
  1477. sameSiteContext = checkSameSiteContext(options.sameSiteContext);
  1478. if (!sameSiteContext) {
  1479. return promiseCallback.reject(new Error(SAME_SITE_CONTEXT_VAL_ERR));
  1480. }
  1481. }
  1482. if (typeof cookie === "string" || cookie instanceof String) {
  1483. const parsedCookie = Cookie.parse(cookie.toString(), { loose });
  1484. if (!parsedCookie) {
  1485. const err = new Error("Cookie failed to parse");
  1486. return options?.ignoreError ? promiseCallback.resolve(void 0) : promiseCallback.reject(err);
  1487. }
  1488. cookie = parsedCookie;
  1489. } else if (!(cookie instanceof Cookie)) {
  1490. const err = new Error(
  1491. "First argument to setCookie must be a Cookie object or string"
  1492. );
  1493. return options?.ignoreError ? promiseCallback.resolve(void 0) : promiseCallback.reject(err);
  1494. }
  1495. const now = options?.now || /* @__PURE__ */ new Date();
  1496. if (this.rejectPublicSuffixes && cookie.domain) {
  1497. try {
  1498. const cdomain = cookie.cdomain();
  1499. const suffix = typeof cdomain === "string" ? getPublicSuffix(cdomain, {
  1500. allowSpecialUseDomain: this.allowSpecialUseDomain,
  1501. ignoreError: options?.ignoreError
  1502. }) : null;
  1503. if (suffix == null && !IP_V6_REGEX_OBJECT.test(cookie.domain)) {
  1504. const err = new Error("Cookie has domain set to a public suffix");
  1505. return options?.ignoreError ? promiseCallback.resolve(void 0) : promiseCallback.reject(err);
  1506. }
  1507. } catch (err) {
  1508. return options?.ignoreError ? promiseCallback.resolve(void 0) : (
  1509. // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
  1510. promiseCallback.reject(err)
  1511. );
  1512. }
  1513. }
  1514. if (cookie.domain) {
  1515. if (!domainMatch(host ?? void 0, cookie.cdomain() ?? void 0, false)) {
  1516. const err = new Error(
  1517. `Cookie not in this host's domain. Cookie:${cookie.cdomain() ?? "null"} Request:${host ?? "null"}`
  1518. );
  1519. return options?.ignoreError ? promiseCallback.resolve(void 0) : promiseCallback.reject(err);
  1520. }
  1521. if (cookie.hostOnly == null) {
  1522. cookie.hostOnly = false;
  1523. }
  1524. } else {
  1525. cookie.hostOnly = true;
  1526. cookie.domain = host;
  1527. }
  1528. if (!cookie.path || cookie.path[0] !== "/") {
  1529. cookie.path = defaultPath(context.pathname);
  1530. cookie.pathIsDefault = true;
  1531. }
  1532. if (options?.http === false && cookie.httpOnly) {
  1533. const err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
  1534. return options.ignoreError ? promiseCallback.resolve(void 0) : promiseCallback.reject(err);
  1535. }
  1536. if (cookie.sameSite !== "none" && cookie.sameSite !== void 0 && sameSiteContext) {
  1537. if (sameSiteContext === "none") {
  1538. const err = new Error(
  1539. "Cookie is SameSite but this is a cross-origin request"
  1540. );
  1541. return options?.ignoreError ? promiseCallback.resolve(void 0) : promiseCallback.reject(err);
  1542. }
  1543. }
  1544. const ignoreErrorForPrefixSecurity = this.prefixSecurity === PrefixSecurityEnum.SILENT;
  1545. const prefixSecurityDisabled = this.prefixSecurity === PrefixSecurityEnum.DISABLED;
  1546. if (!prefixSecurityDisabled) {
  1547. let errorFound = false;
  1548. let errorMsg;
  1549. if (!isSecurePrefixConditionMet(cookie)) {
  1550. errorFound = true;
  1551. errorMsg = "Cookie has __Secure prefix but Secure attribute is not set";
  1552. } else if (!isHostPrefixConditionMet(cookie)) {
  1553. errorFound = true;
  1554. errorMsg = "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'";
  1555. }
  1556. if (errorFound) {
  1557. return options?.ignoreError || ignoreErrorForPrefixSecurity ? promiseCallback.resolve(void 0) : promiseCallback.reject(new Error(errorMsg));
  1558. }
  1559. }
  1560. const store = this.store;
  1561. if (!store.updateCookie) {
  1562. store.updateCookie = async function(_oldCookie, newCookie, cb2) {
  1563. return this.putCookie(newCookie).then(
  1564. () => cb2?.(null),
  1565. (error) => cb2?.(error)
  1566. );
  1567. };
  1568. }
  1569. const withCookie = function withCookie2(err, oldCookie) {
  1570. if (err) {
  1571. cb(err);
  1572. return;
  1573. }
  1574. const next = function(err2) {
  1575. if (err2) {
  1576. cb(err2);
  1577. } else if (typeof cookie === "string") {
  1578. cb(null, void 0);
  1579. } else {
  1580. cb(null, cookie);
  1581. }
  1582. };
  1583. if (oldCookie) {
  1584. if (options && "http" in options && options.http === false && oldCookie.httpOnly) {
  1585. err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
  1586. if (options.ignoreError) cb(null, void 0);
  1587. else cb(err);
  1588. return;
  1589. }
  1590. if (cookie instanceof Cookie) {
  1591. cookie.creation = oldCookie.creation;
  1592. cookie.creationIndex = oldCookie.creationIndex;
  1593. cookie.lastAccessed = now;
  1594. store.updateCookie(oldCookie, cookie, next);
  1595. }
  1596. } else {
  1597. if (cookie instanceof Cookie) {
  1598. cookie.creation = cookie.lastAccessed = now;
  1599. store.putCookie(cookie, next);
  1600. }
  1601. }
  1602. };
  1603. store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
  1604. return promiseCallback.promise;
  1605. }
  1606. /**
  1607. * Synchronously attempt to set the {@link Cookie} in the {@link CookieJar}.
  1608. *
  1609. * <strong>Note:</strong> Only works if the configured {@link Store} is also synchronous.
  1610. *
  1611. * @remarks
  1612. * - If successfully persisted, the {@link Cookie} will have updated
  1613. * {@link Cookie.creation}, {@link Cookie.lastAccessed} and {@link Cookie.hostOnly}
  1614. * properties.
  1615. *
  1616. * - As per the RFC, the {@link Cookie.hostOnly} flag is set if there was no `Domain={value}`
  1617. * attribute on the cookie string. The {@link Cookie.domain} property is set to the
  1618. * fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an
  1619. * exact hostname match (not a {@link domainMatch} as per usual)
  1620. *
  1621. * @param cookie - The cookie object or cookie string to store. A string value will be parsed into a cookie using {@link Cookie.parse}.
  1622. * @param url - The domain to store the cookie with.
  1623. * @param options - Configuration settings to use when storing the cookie.
  1624. * @public
  1625. */
  1626. setCookieSync(cookie, url, options) {
  1627. const setCookieFn = options ? this.setCookie.bind(this, cookie, url, options) : this.setCookie.bind(this, cookie, url);
  1628. return this.callSync(setCookieFn);
  1629. }
  1630. /**
  1631. * @internal No doc because this is the overload implementation
  1632. */
  1633. getCookies(url, options, callback) {
  1634. if (typeof options === "function") {
  1635. callback = options;
  1636. options = defaultGetCookieOptions;
  1637. } else if (options === void 0) {
  1638. options = defaultGetCookieOptions;
  1639. }
  1640. const promiseCallback = createPromiseCallback(callback);
  1641. const cb = promiseCallback.callback;
  1642. let context;
  1643. try {
  1644. if (typeof url === "string") {
  1645. validate(isNonEmptyString(url), cb, url);
  1646. }
  1647. context = getCookieContext(url);
  1648. validate(
  1649. isObject(options),
  1650. cb,
  1651. safeToString(options)
  1652. );
  1653. validate(typeof cb === "function", cb);
  1654. } catch (parameterError) {
  1655. return promiseCallback.reject(parameterError);
  1656. }
  1657. const host = canonicalDomain(context.hostname);
  1658. const path = context.pathname || "/";
  1659. const potentiallyTrustworthy = isPotentiallyTrustworthy(
  1660. url,
  1661. this.allowSecureOnLocal
  1662. );
  1663. let sameSiteLevel = 0;
  1664. if (options.sameSiteContext) {
  1665. const sameSiteContext = checkSameSiteContext(options.sameSiteContext);
  1666. if (sameSiteContext == null) {
  1667. return promiseCallback.reject(new Error(SAME_SITE_CONTEXT_VAL_ERR));
  1668. }
  1669. sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext];
  1670. if (!sameSiteLevel) {
  1671. return promiseCallback.reject(new Error(SAME_SITE_CONTEXT_VAL_ERR));
  1672. }
  1673. }
  1674. const http = options.http ?? true;
  1675. const now = Date.now();
  1676. const expireCheck = options.expire ?? true;
  1677. const allPaths = options.allPaths ?? false;
  1678. const store = this.store;
  1679. function matchingCookie(c) {
  1680. if (c.hostOnly) {
  1681. if (c.domain != host) {
  1682. return false;
  1683. }
  1684. } else {
  1685. if (!domainMatch(host ?? void 0, c.domain ?? void 0, false)) {
  1686. return false;
  1687. }
  1688. }
  1689. if (!allPaths && typeof c.path === "string" && !pathMatch(path, c.path)) {
  1690. return false;
  1691. }
  1692. if (c.secure && !potentiallyTrustworthy) {
  1693. return false;
  1694. }
  1695. if (c.httpOnly && !http) {
  1696. return false;
  1697. }
  1698. if (sameSiteLevel) {
  1699. let cookieLevel;
  1700. if (c.sameSite === "lax") {
  1701. cookieLevel = Cookie.sameSiteLevel.lax;
  1702. } else if (c.sameSite === "strict") {
  1703. cookieLevel = Cookie.sameSiteLevel.strict;
  1704. } else {
  1705. cookieLevel = Cookie.sameSiteLevel.none;
  1706. }
  1707. if (cookieLevel > sameSiteLevel) {
  1708. return false;
  1709. }
  1710. }
  1711. const expiryTime = c.expiryTime();
  1712. if (expireCheck && expiryTime != void 0 && expiryTime <= now) {
  1713. store.removeCookie(c.domain, c.path, c.key, () => {
  1714. });
  1715. return false;
  1716. }
  1717. return true;
  1718. }
  1719. store.findCookies(
  1720. host,
  1721. allPaths ? null : path,
  1722. this.allowSpecialUseDomain,
  1723. (err, cookies) => {
  1724. if (err) {
  1725. cb(err);
  1726. return;
  1727. }
  1728. if (cookies == null) {
  1729. cb(null, []);
  1730. return;
  1731. }
  1732. cookies = cookies.filter(matchingCookie);
  1733. if ("sort" in options && options.sort !== false) {
  1734. cookies = cookies.sort(cookieCompare);
  1735. }
  1736. const now2 = /* @__PURE__ */ new Date();
  1737. for (const cookie of cookies) {
  1738. cookie.lastAccessed = now2;
  1739. }
  1740. cb(null, cookies);
  1741. }
  1742. );
  1743. return promiseCallback.promise;
  1744. }
  1745. /**
  1746. * Synchronously retrieve the list of cookies that can be sent in a Cookie header for the
  1747. * current URL.
  1748. *
  1749. * <strong>Note</strong>: Only works if the configured Store is also synchronous.
  1750. *
  1751. * @remarks
  1752. * - The array of cookies returned will be sorted according to {@link cookieCompare}.
  1753. *
  1754. * - The {@link Cookie.lastAccessed} property will be updated on all returned cookies.
  1755. *
  1756. * @param url - The domain to store the cookie with.
  1757. * @param options - Configuration settings to use when retrieving the cookies.
  1758. */
  1759. getCookiesSync(url, options) {
  1760. return this.callSync(this.getCookies.bind(this, url, options)) ?? [];
  1761. }
  1762. /**
  1763. * @internal No doc because this is the overload implementation
  1764. */
  1765. getCookieString(url, options, callback) {
  1766. if (typeof options === "function") {
  1767. callback = options;
  1768. options = void 0;
  1769. }
  1770. const promiseCallback = createPromiseCallback(callback);
  1771. const next = function(err, cookies) {
  1772. if (err) {
  1773. promiseCallback.callback(err);
  1774. } else {
  1775. promiseCallback.callback(
  1776. null,
  1777. cookies?.sort(cookieCompare).map((c) => c.cookieString()).join("; ")
  1778. );
  1779. }
  1780. };
  1781. this.getCookies(url, options, next);
  1782. return promiseCallback.promise;
  1783. }
  1784. /**
  1785. * Synchronous version of `.getCookieString()`. Accepts the same options as `.getCookies()` but returns a string suitable for a
  1786. * `Cookie` header rather than an Array.
  1787. *
  1788. * <strong>Note</strong>: Only works if the configured Store is also synchronous.
  1789. *
  1790. * @param url - The domain to store the cookie with.
  1791. * @param options - Configuration settings to use when retrieving the cookies.
  1792. */
  1793. getCookieStringSync(url, options) {
  1794. return this.callSync(
  1795. options ? this.getCookieString.bind(this, url, options) : this.getCookieString.bind(this, url)
  1796. ) ?? "";
  1797. }
  1798. /**
  1799. * @internal No doc because this is the overload implementation
  1800. */
  1801. getSetCookieStrings(url, options, callback) {
  1802. if (typeof options === "function") {
  1803. callback = options;
  1804. options = void 0;
  1805. }
  1806. const promiseCallback = createPromiseCallback(
  1807. callback
  1808. );
  1809. const next = function(err, cookies) {
  1810. if (err) {
  1811. promiseCallback.callback(err);
  1812. } else {
  1813. promiseCallback.callback(
  1814. null,
  1815. cookies?.map((c) => {
  1816. return c.toString();
  1817. })
  1818. );
  1819. }
  1820. };
  1821. this.getCookies(url, options, next);
  1822. return promiseCallback.promise;
  1823. }
  1824. /**
  1825. * Synchronous version of `.getSetCookieStrings()`. Returns an array of strings suitable for `Set-Cookie` headers.
  1826. * Accepts the same options as `.getCookies()`.
  1827. *
  1828. * <strong>Note</strong>: Only works if the configured Store is also synchronous.
  1829. *
  1830. * @param url - The domain to store the cookie with.
  1831. * @param options - Configuration settings to use when retrieving the cookies.
  1832. */
  1833. getSetCookieStringsSync(url, options = {}) {
  1834. return this.callSync(this.getSetCookieStrings.bind(this, url, options)) ?? [];
  1835. }
  1836. /**
  1837. * @internal No doc because this is the overload implementation
  1838. */
  1839. serialize(callback) {
  1840. const promiseCallback = createPromiseCallback(callback);
  1841. let type = this.store.constructor.name;
  1842. if (isObject(type)) {
  1843. type = null;
  1844. }
  1845. const serialized = {
  1846. // The version of tough-cookie that serialized this jar. Generally a good
  1847. // practice since future versions can make data import decisions based on
  1848. // known past behavior. When/if this matters, use `semver`.
  1849. version: `tough-cookie@${version}`,
  1850. // add the store type, to make humans happy:
  1851. storeType: type,
  1852. // CookieJar configuration:
  1853. rejectPublicSuffixes: this.rejectPublicSuffixes,
  1854. enableLooseMode: this.enableLooseMode,
  1855. allowSpecialUseDomain: this.allowSpecialUseDomain,
  1856. prefixSecurity: getNormalizedPrefixSecurity(this.prefixSecurity),
  1857. // this gets filled from getAllCookies:
  1858. cookies: []
  1859. };
  1860. if (typeof this.store.getAllCookies !== "function") {
  1861. return promiseCallback.reject(
  1862. new Error(
  1863. "store does not support getAllCookies and cannot be serialized"
  1864. )
  1865. );
  1866. }
  1867. this.store.getAllCookies((err, cookies) => {
  1868. if (err) {
  1869. promiseCallback.callback(err);
  1870. return;
  1871. }
  1872. if (cookies == null) {
  1873. promiseCallback.callback(null, serialized);
  1874. return;
  1875. }
  1876. serialized.cookies = cookies.map((cookie) => {
  1877. const serializedCookie = cookie.toJSON();
  1878. delete serializedCookie.creationIndex;
  1879. return serializedCookie;
  1880. });
  1881. promiseCallback.callback(null, serialized);
  1882. });
  1883. return promiseCallback.promise;
  1884. }
  1885. /**
  1886. * Serialize the CookieJar if the underlying store supports `.getAllCookies`.
  1887. *
  1888. * <strong>Note</strong>: Only works if the configured Store is also synchronous.
  1889. */
  1890. serializeSync() {
  1891. return this.callSync((callback) => {
  1892. this.serialize(callback);
  1893. });
  1894. }
  1895. /**
  1896. * Alias of {@link CookieJar.serializeSync}. Allows the cookie to be serialized
  1897. * with `JSON.stringify(cookieJar)`.
  1898. */
  1899. toJSON() {
  1900. return this.serializeSync();
  1901. }
  1902. /**
  1903. * Use the class method CookieJar.deserialize instead of calling this directly
  1904. * @internal
  1905. */
  1906. _importCookies(serialized, callback) {
  1907. let cookies = void 0;
  1908. if (serialized && typeof serialized === "object" && inOperator("cookies", serialized) && Array.isArray(serialized.cookies)) {
  1909. cookies = serialized.cookies;
  1910. }
  1911. if (!cookies) {
  1912. callback(new Error("serialized jar has no cookies array"), void 0);
  1913. return;
  1914. }
  1915. cookies = cookies.slice();
  1916. const putNext = (err) => {
  1917. if (err) {
  1918. callback(err, void 0);
  1919. return;
  1920. }
  1921. if (Array.isArray(cookies)) {
  1922. if (!cookies.length) {
  1923. callback(err, this);
  1924. return;
  1925. }
  1926. let cookie;
  1927. try {
  1928. cookie = Cookie.fromJSON(cookies.shift());
  1929. } catch (e) {
  1930. callback(e instanceof Error ? e : new Error(), void 0);
  1931. return;
  1932. }
  1933. if (cookie === void 0) {
  1934. putNext(null);
  1935. return;
  1936. }
  1937. this.store.putCookie(cookie, putNext);
  1938. }
  1939. };
  1940. putNext(null);
  1941. }
  1942. /**
  1943. * @internal
  1944. */
  1945. _importCookiesSync(serialized) {
  1946. this.callSync(this._importCookies.bind(this, serialized));
  1947. }
  1948. /**
  1949. * @internal No doc because this is the overload implementation
  1950. */
  1951. clone(newStore, callback) {
  1952. if (typeof newStore === "function") {
  1953. callback = newStore;
  1954. newStore = void 0;
  1955. }
  1956. const promiseCallback = createPromiseCallback(callback);
  1957. const cb = promiseCallback.callback;
  1958. this.serialize((err, serialized) => {
  1959. if (err) {
  1960. return promiseCallback.reject(err);
  1961. }
  1962. return _CookieJar.deserialize(serialized ?? "", newStore, cb);
  1963. });
  1964. return promiseCallback.promise;
  1965. }
  1966. /**
  1967. * @internal
  1968. */
  1969. _cloneSync(newStore) {
  1970. const cloneFn = newStore && typeof newStore !== "function" ? this.clone.bind(this, newStore) : this.clone.bind(this);
  1971. return this.callSync((callback) => {
  1972. cloneFn(callback);
  1973. });
  1974. }
  1975. /**
  1976. * Produces a deep clone of this CookieJar. Modifications to the original do
  1977. * not affect the clone, and vice versa.
  1978. *
  1979. * <strong>Note</strong>: Only works if both the configured Store and destination
  1980. * Store are synchronous.
  1981. *
  1982. * @remarks
  1983. * - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
  1984. *
  1985. * - Transferring between store types is supported so long as the source
  1986. * implements `.getAllCookies()` and the destination implements `.putCookie()`.
  1987. *
  1988. * @param newStore - The target {@link Store} to clone cookies into.
  1989. */
  1990. cloneSync(newStore) {
  1991. if (!newStore) {
  1992. return this._cloneSync();
  1993. }
  1994. if (!newStore.synchronous) {
  1995. throw new Error(
  1996. "CookieJar clone destination store is not synchronous; use async API instead."
  1997. );
  1998. }
  1999. return this._cloneSync(newStore);
  2000. }
  2001. /**
  2002. * @internal No doc because this is the overload implementation
  2003. */
  2004. removeAllCookies(callback) {
  2005. const promiseCallback = createPromiseCallback(callback);
  2006. const cb = promiseCallback.callback;
  2007. const store = this.store;
  2008. if (typeof store.removeAllCookies === "function" && store.removeAllCookies !== Store.prototype.removeAllCookies) {
  2009. store.removeAllCookies(cb);
  2010. return promiseCallback.promise;
  2011. }
  2012. store.getAllCookies((err, cookies) => {
  2013. if (err) {
  2014. cb(err);
  2015. return;
  2016. }
  2017. if (!cookies) {
  2018. cookies = [];
  2019. }
  2020. if (cookies.length === 0) {
  2021. cb(null, void 0);
  2022. return;
  2023. }
  2024. let completedCount = 0;
  2025. const removeErrors = [];
  2026. const removeCookieCb = function removeCookieCb2(removeErr) {
  2027. if (removeErr) {
  2028. removeErrors.push(removeErr);
  2029. }
  2030. completedCount++;
  2031. if (completedCount === cookies.length) {
  2032. if (removeErrors[0]) cb(removeErrors[0]);
  2033. else cb(null, void 0);
  2034. return;
  2035. }
  2036. };
  2037. cookies.forEach((cookie) => {
  2038. store.removeCookie(
  2039. cookie.domain,
  2040. cookie.path,
  2041. cookie.key,
  2042. removeCookieCb
  2043. );
  2044. });
  2045. });
  2046. return promiseCallback.promise;
  2047. }
  2048. /**
  2049. * Removes all cookies from the CookieJar.
  2050. *
  2051. * <strong>Note</strong>: Only works if the configured Store is also synchronous.
  2052. *
  2053. * @remarks
  2054. * - This is a new backwards-compatible feature of tough-cookie version 2.5,
  2055. * so not all Stores will implement it efficiently. For Stores that do not
  2056. * implement `removeAllCookies`, the fallback is to call `removeCookie` after
  2057. * `getAllCookies`.
  2058. *
  2059. * - If `getAllCookies` fails or isn't implemented in the Store, an error is returned.
  2060. *
  2061. * - If one or more of the `removeCookie` calls fail, only the first error is returned.
  2062. */
  2063. removeAllCookiesSync() {
  2064. this.callSync((callback) => {
  2065. this.removeAllCookies(callback);
  2066. });
  2067. }
  2068. /**
  2069. * @internal No doc because this is the overload implementation
  2070. */
  2071. static deserialize(strOrObj, store, callback) {
  2072. if (typeof store === "function") {
  2073. callback = store;
  2074. store = void 0;
  2075. }
  2076. const promiseCallback = createPromiseCallback(callback);
  2077. let serialized;
  2078. if (typeof strOrObj === "string") {
  2079. try {
  2080. serialized = JSON.parse(strOrObj);
  2081. } catch (e) {
  2082. return promiseCallback.reject(e instanceof Error ? e : new Error());
  2083. }
  2084. } else {
  2085. serialized = strOrObj;
  2086. }
  2087. const readSerializedProperty = (property) => {
  2088. return serialized && typeof serialized === "object" && inOperator(property, serialized) ? serialized[property] : void 0;
  2089. };
  2090. const readSerializedBoolean = (property) => {
  2091. const value = readSerializedProperty(property);
  2092. return typeof value === "boolean" ? value : void 0;
  2093. };
  2094. const readSerializedString = (property) => {
  2095. const value = readSerializedProperty(property);
  2096. return typeof value === "string" ? value : void 0;
  2097. };
  2098. const jar = new _CookieJar(store, {
  2099. rejectPublicSuffixes: readSerializedBoolean("rejectPublicSuffixes"),
  2100. looseMode: readSerializedBoolean("enableLooseMode"),
  2101. allowSpecialUseDomain: readSerializedBoolean("allowSpecialUseDomain"),
  2102. prefixSecurity: getNormalizedPrefixSecurity(
  2103. readSerializedString("prefixSecurity") ?? "silent"
  2104. )
  2105. });
  2106. jar._importCookies(serialized, (err) => {
  2107. if (err) {
  2108. promiseCallback.callback(err);
  2109. return;
  2110. }
  2111. promiseCallback.callback(null, jar);
  2112. });
  2113. return promiseCallback.promise;
  2114. }
  2115. /**
  2116. * A new CookieJar is created and the serialized {@link Cookie} values are added to
  2117. * the underlying store. Each {@link Cookie} is added via `store.putCookie(...)` in
  2118. * the order in which they appear in the serialization.
  2119. *
  2120. * <strong>Note</strong>: Only works if the configured Store is also synchronous.
  2121. *
  2122. * @remarks
  2123. * - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
  2124. *
  2125. * - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
  2126. *
  2127. * @param strOrObj - A JSON string or object representing the deserialized cookies.
  2128. * @param store - The underlying store to persist the deserialized cookies into.
  2129. */
  2130. static deserializeSync(strOrObj, store) {
  2131. const serialized = typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj;
  2132. const readSerializedProperty = (property) => {
  2133. return serialized && typeof serialized === "object" && inOperator(property, serialized) ? serialized[property] : void 0;
  2134. };
  2135. const readSerializedBoolean = (property) => {
  2136. const value = readSerializedProperty(property);
  2137. return typeof value === "boolean" ? value : void 0;
  2138. };
  2139. const readSerializedString = (property) => {
  2140. const value = readSerializedProperty(property);
  2141. return typeof value === "string" ? value : void 0;
  2142. };
  2143. const jar = new _CookieJar(store, {
  2144. rejectPublicSuffixes: readSerializedBoolean("rejectPublicSuffixes"),
  2145. looseMode: readSerializedBoolean("enableLooseMode"),
  2146. allowSpecialUseDomain: readSerializedBoolean("allowSpecialUseDomain"),
  2147. prefixSecurity: getNormalizedPrefixSecurity(
  2148. readSerializedString("prefixSecurity") ?? "silent"
  2149. )
  2150. });
  2151. if (!jar.store.synchronous) {
  2152. throw new Error(
  2153. "CookieJar store is not synchronous; use async API instead."
  2154. );
  2155. }
  2156. jar._importCookiesSync(serialized);
  2157. return jar;
  2158. }
  2159. /**
  2160. * Alias of {@link CookieJar.deserializeSync}.
  2161. *
  2162. * @remarks
  2163. * - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
  2164. *
  2165. * - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
  2166. *
  2167. * @param jsonString - A JSON string or object representing the deserialized cookies.
  2168. * @param store - The underlying store to persist the deserialized cookies into.
  2169. */
  2170. static fromJSON(jsonString, store) {
  2171. return _CookieJar.deserializeSync(jsonString, store);
  2172. }
  2173. };
  2174. // lib/cookie/permutePath.ts
  2175. function permutePath(path) {
  2176. if (path === "/") {
  2177. return ["/"];
  2178. }
  2179. const permutations = [path];
  2180. while (path.length > 1) {
  2181. const lindex = path.lastIndexOf("/");
  2182. if (lindex === 0) {
  2183. break;
  2184. }
  2185. path = path.slice(0, lindex);
  2186. permutations.push(path);
  2187. }
  2188. permutations.push("/");
  2189. return permutations;
  2190. }
  2191. // lib/cookie/index.ts
  2192. function parse2(str, options) {
  2193. return Cookie.parse(str, options);
  2194. }
  2195. function fromJSON2(str) {
  2196. return Cookie.fromJSON(str);
  2197. }
  2198. export {
  2199. Cookie,
  2200. CookieJar,
  2201. MemoryCookieStore,
  2202. ParameterError,
  2203. PrefixSecurityEnum,
  2204. Store,
  2205. canonicalDomain,
  2206. cookieCompare,
  2207. defaultPath,
  2208. domainMatch,
  2209. formatDate,
  2210. fromJSON2 as fromJSON,
  2211. getPublicSuffix,
  2212. parse2 as parse,
  2213. parseDate,
  2214. pathMatch,
  2215. permuteDomain,
  2216. permutePath,
  2217. version
  2218. };
  2219. /*!
  2220. * Copyright (c) 2015-2020, Salesforce.com, Inc.
  2221. * All rights reserved.
  2222. *
  2223. * Redistribution and use in source and binary forms, with or without
  2224. * modification, are permitted provided that the following conditions are met:
  2225. *
  2226. * 1. Redistributions of source code must retain the above copyright notice,
  2227. * this list of conditions and the following disclaimer.
  2228. *
  2229. * 2. Redistributions in binary form must reproduce the above copyright notice,
  2230. * this list of conditions and the following disclaimer in the documentation
  2231. * and/or other materials provided with the distribution.
  2232. *
  2233. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  2234. * be used to endorse or promote products derived from this software without
  2235. * specific prior written permission.
  2236. *
  2237. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  2238. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  2239. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  2240. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  2241. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  2242. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  2243. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  2244. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  2245. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  2246. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  2247. * POSSIBILITY OF SUCH DAMAGE.
  2248. */
  2249. //# sourceMappingURL=index.js.map