cookies.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import utils from '../utils.js';
  2. import platform from '../platform/index.js';
  3. const decodeCookieValue = (value) => {
  4. try {
  5. return decodeURIComponent(value);
  6. } catch (e) {
  7. return value;
  8. }
  9. };
  10. export default platform.hasStandardBrowserEnv
  11. ? // Standard browser envs support document.cookie
  12. {
  13. write(name, value, expires, path, domain, secure, sameSite) {
  14. if (typeof document === 'undefined') return;
  15. const cookie = [`${name}=${encodeURIComponent(value)}`];
  16. if (utils.isNumber(expires)) {
  17. cookie.push(`expires=${new Date(expires).toUTCString()}`);
  18. }
  19. if (utils.isString(path)) {
  20. cookie.push(`path=${path}`);
  21. }
  22. if (utils.isString(domain)) {
  23. cookie.push(`domain=${domain}`);
  24. }
  25. if (secure === true) {
  26. cookie.push('secure');
  27. }
  28. if (utils.isString(sameSite)) {
  29. cookie.push(`SameSite=${sameSite}`);
  30. }
  31. document.cookie = cookie.join('; ');
  32. },
  33. read(name) {
  34. if (typeof document === 'undefined') return null;
  35. const cookieString = document.cookie;
  36. if (!cookieString) return null;
  37. // Match name=value by splitting on the semicolon separator instead of building a
  38. // RegExp from `name` — interpolating an unescaped string into a RegExp would let
  39. // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
  40. // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
  41. // "; ", so ignore optional whitespace before each cookie name.
  42. const cookies = cookieString.split(';');
  43. for (let i = 0; i < cookies.length; i++) {
  44. const cookie = cookies[i].replace(/^\s+/, '');
  45. const eq = cookie.indexOf('=');
  46. if (eq !== -1 && cookie.slice(0, eq) === name) {
  47. return decodeCookieValue(cookie.slice(eq + 1));
  48. }
  49. }
  50. return null;
  51. },
  52. async readAsync(name) {
  53. try {
  54. const store = typeof window !== 'undefined' && window.cookieStore;
  55. if (store && utils.isFunction(store.get)) {
  56. const cookie = await store.get(name);
  57. // Both APIs expose stored bytes; preserve Axios's existing URI decoding.
  58. return cookie ? decodeCookieValue(cookie.value) : null;
  59. }
  60. } catch (e) {
  61. // Restricted or unavailable storage retains the synchronous fallback.
  62. }
  63. return this.read(name);
  64. },
  65. remove(name) {
  66. this.write(name, '', Date.now() - 86400000, '/');
  67. },
  68. }
  69. : // Non-standard browser env (web workers, react-native) lack needed support.
  70. {
  71. write() {},
  72. read() {
  73. return null;
  74. },
  75. async readAsync() {
  76. return null;
  77. },
  78. remove() {},
  79. };