typescriptaxioshttpcookiecookiejar

Access cookie from http-cookie-agent in typescript


I am trying to access a cookie from axios. I am unable to use the wrapper but can use http-cookie-agent directly.

I can set the cookie, but I am unable to retrieve it again.

The cookie is set like this:

export function setupAxios(
  basePath: string,
  config?: { initialCookie?: string | Cookie }
) {
  const jar = new CookieJar();
  if (config) {
    const { initialCookie } = config;
    if (typeof initialCookie !== "undefined") {
      jar.setCookieSync(initialCookie, basePath);
    }
  }
  const httpsCookieAgent = new HttpsCookieAgent({
    rejectUnauthorized: false,
    cookies: { jar },
  });
  const axios = Axios.create({
    withCredentials: true,
    timeout: 1000,
    httpsAgent: httpsCookieAgent,
  });

  return axios;
}

which is called like this: export const axios = setupAxios(basePath);

I have a function clearCookies in which I get the agent:

export function clearCookies() {
  const httpsAgent = axios.defaults.httpsAgent as typeof HttpsCookieAgent;
  console.log(httpsAgent);
  >>> const options = httpsAgent.[Symbol(cookieOptions)] as CookieAgentOptions; <<< This I don't know how to accomplish.
  const jar = options.cookies?.jar;
  jar?.removeAllCookiesSync();
}

I can log out the dictionary:

CookieAgent {
  _events: [Object: null prototype] {
    free: [Function (anonymous)],
    newListener: [Function: maybeEnableKeylog]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  defaultPort: 443,
  protocol: 'https:',
  options: [Object: null prototype] { rejectUnauthorized: false, path: null },
  requests: [Object: null prototype] {},
  sockets: [Object: null prototype] {
    'example.com:443::::::::false:::::::::::::': [ [TLSSocket] ]
  },
  freeSockets: [Object: null prototype] {},
  keepAliveMsecs: 1000,
  keepAlive: false,
  maxSockets: Infinity,
  maxFreeSockets: 256,
  scheduling: 'lifo',
  maxTotalSockets: Infinity,
  totalSocketCount: 1,
  maxCachedSessions: 100,
  _sessionCache: {
    map: {
      'example.com:443::::::::false:::::::::::::': <Buffer 30 82 03 1f 02 01 01 02 02 03 04 04 02 13 02 04 20 aa 87 c2 15 2c 23 f2 11 6e f0 fe ce d5 b1 a3 b4 dd 53 01 08 76 ce c0 5e 7e 18 fe cd 11 2d 7c 89 04 ... 753 more bytes>
    },
    list: [ 'example.com:443::::::::false:::::::::::::' ]
  },
  [Symbol(kCapture)]: false,
  [Symbol(cookieOptions)]: {
    jar: CookieJar {
      rejectPublicSuffixes: true,
      enableLooseMode: false,
      allowSpecialUseDomain: false,
      store: { idx: {
        'example.com': {
          '/': {
            id0: Cookie="id0=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpIjoiMTI3ZTA4NjYtNmJjZi00ZDAxLThjZTItNDRkNDg1OTI4MTRjIiwibCI6IjIwZDIxMzg4LWNjNzctNGM4Ni04N2JkLTRiNjE1NzU5OGEwYSJ9.SvP-cnS8docWhAGPKHm8YOjICmYp8BjWFFr-gv75WJE; Expires=Mon, 20 Jun 2022 19:00:59 GMT; Path=/; Secure; HttpOnly; hostOnly=true; aAge=9ms; cAge=352ms"
          }
        }
      } },
      prefixSecurity: 'silent',
      _cloneSync: [Function (anonymous)],
      _importCookiesSync: [Function (anonymous)],
      getCookiesSync: [Function (anonymous)],
      getCookieStringSync: [Function (anonymous)],
      getSetCookieStringsSync: [Function (anonymous)],
      removeAllCookiesSync: [Function (anonymous)],
      setCookieSync: [Function (anonymous)],
      serializeSync: [Function (anonymous)]
    }
  }
}

The cookie is clearly there, I am however unable to retrieve it. I have imported

import { HttpsCookieAgent, CookieAgentOptions, CookieOptions } from "http-cookie-agent/http";

and if I'd be able to set the CookieAgentOptions I could access the cookie (at least according to vscode). But I don't know how to write code that accesses [Symbol(cookieOptions)]

httpsAgent.defaultPort works fine and gets me 443, but how do I handle the symbol?


Solution

  • The idea to loop brought me on the right track. I also had to remove the typecasting. Now you can access the cookie e.g. this way:

    export function clearCookies() {
      const httpsAgent = axios.defaults.httpsAgent;
      for (let sym of Object.getOwnPropertySymbols(httpsAgent)) {
        if (sym.toString() === "Symbol(cookieOptions)") {
          const jar = httpsAgent[sym].jar as CookieJar;
          jar.removeAllCookiesSync();
        }
      }
    }
    

    Still, I'd prefer some way of accessing the symbol directly.