Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import { Cookie, CookieJar, MemoryCookieStore } from 'tough-cookie';
let header = '';
const cb = () => { };
const cookie = Cookie.parse(header)!;
cookie.value = 'somethingdifferent';
header = cookie.toString();
const cookiejar = new CookieJar();
cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb);
// ...
cookiejar.getCookies('http://example.com/otherpath', (err, cookies) => {
// res.headers['cookie'] = cookies.join('; ');
});
// All option are optional.
cookiejar.getCookies('http://example.com/otherpath', {}, () => {});
cookiejar.getCookies('http://example.com/otherpath', {
now: new Date(),
allPaths: true,
return cookies.reduce((resultCookies, cookieStr) => {
let cookie;
if (!isClient) {
if (cookieStr.length > BYTES_PER_COOKIE_LIMIT)
return resultCookies;
cookie = Cookie.parse(cookieStr, { loose: true });
if (!cookie)
return resultCookies;
}
else
cookie = cookieStr;
// NOTE: If cookie.domain and url hostname are equal to localhost/127.0.0.1,
// we should remove 'Domain=...' form cookieStr (GH-1491)
if (Cookies._hasLocalhostDomain(cookie) && (isClient || parseUrl(url).hostname === cookie.domain))
cookie.domain = '';
const parsedCookie = this._cookieJar.setCookieSync(cookie, url, {
http: !isClient,
ignoreError: true,
loose: true
cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb);
// ...
cookiejar.getCookies('http://example.com/otherpath', (err, cookies) => {
// res.headers['cookie'] = cookies.join('; ');
});
// All option are optional.
cookiejar.getCookies('http://example.com/otherpath', {}, () => {});
cookiejar.getCookies('http://example.com/otherpath', {
now: new Date(),
allPaths: true,
}, () => {});
CookieJar.deserializeSync("test cookie with store", new MemoryCookieStore());
CookieJar.deserializeSync("test cookie");
const cookiejar = new CookieJar();
cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb);
// ...
cookiejar.getCookies('http://example.com/otherpath', (err, cookies) => {
// res.headers['cookie'] = cookies.join('; ');
});
// All option are optional.
cookiejar.getCookies('http://example.com/otherpath', {}, () => {});
cookiejar.getCookies('http://example.com/otherpath', {
now: new Date(),
allPaths: true,
}, () => {});
CookieJar.deserializeSync("test cookie with store", new MemoryCookieStore());
CookieJar.deserializeSync("test cookie");
export function polyfill(options) {
const opts = { ...defaultOptions, ...options };
let root = null;
try {
root = window || global;
} catch (e) {
root = global;
}
if (opts.isomorphicFetch) {
const Tough = require('tough-cookie');
const Store = new Tough.MemoryCookieStore();
const rejectPublicSuffixes = false; // See https://github.com/salesforce/tough-cookie#cookiejarstoreoptions
const cookieJar = new Tough.CookieJar(Store, rejectPublicSuffixes);
const fetch = require('fetch-cookie')(require('@yeutech-lab/isomorphic-fetch'), cookieJar);
root.fetch = fetch;
root.cookieJar = cookieJar;
}
if (opts.fetch && !opts.isomorphicFetch) {
require('whatwg-fetch');
root.fetchMock = require('fetch-mock');
}
if (opts.localStorage && !root.localStorage) {
root.localStorage = require('localStorage');
}
'use strict';
const axios = require('axios').default;
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
cookieJar.setCookieSync('key=value; domain=mockbin.org', 'https://mockbin.org');
axios
.get('https://mockbin.org/request', {
jar: cookieJar,
withCredentials: true, // IMPORTANT!
})
.then((response) => {
const data = response.data;
console.log(data.headers.cookie);
})
.catch((err) => {
console.error(err.stack || err);
});
module.exports.jarFromCookies = function(cookies) {
let jar;
try {
// For some reason, fromJSON modifies `cookies`. Create a copy first
// just to be sure
const copy = JSON.stringify({ cookies });
jar = CookieJar.fromJSON(copy);
} catch (e) {
console.log('[cookies] Failed to initialize cookie jar', e);
jar = new CookieJar();
}
jar.rejectPublicSuffixes = false;
jar.looseMode = true;
return jar;
};
const axiosCookieJarSupport = require('node-axios-cookiejar');
const {
getUrls, CODES, SP_ACCOUNTS, PUSH_HOST_LIST,
} = require('./conf');
Promise.promisifyAll(Datastore.prototype);
const debug = Debug('weixinbot');
let URLS = getUrls({});
const logo = fs.readFileSync(path.join(__dirname, 'logo.txt'), 'utf8');
// try persistent cookie
const cookiePath = path.join(process.cwd(), '.cookie.json');
touch.sync(cookiePath);
const jar = new tough.CookieJar(new FileCookieStore(cookiePath));
const req = axios.create({
timeout: 35e3,
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2652.0 Safari/537.36',
'Referer': 'https://wx2.qq.com/',
},
jar,
withCredentials: true,
xsrfCookieName: null,
xsrfHeaderName: null,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
});
httpAgent?: http.Agent;
httpsAgent?: https.Agent;
}
function getCachedAgent(
isHttps: boolean,
agentCache: AgentCache
): http.Agent | https.Agent | undefined {
return isHttps ? agentCache.httpsAgent : agentCache.httpAgent;
}
export class NodeFetchHttpClient extends FetchHttpClient {
private proxyAgents: AgentCache = {};
private keepAliveAgents: AgentCache = {};
private readonly cookieJar = new tough.CookieJar(undefined, { looseMode: true });
private getOrCreateAgent(httpRequest: WebResource): http.Agent | https.Agent {
const isHttps = isUrlHttps(httpRequest.url);
// At the moment, proxy settings and keepAlive are mutually
// exclusive because the 'tunnel' library currently lacks the
// ability to create a proxy with keepAlive turned on.
if (httpRequest.proxySettings) {
let agent = getCachedAgent(isHttps, this.proxyAgents);
if (agent) {
return agent;
}
const tunnel: ProxyAgent = createProxyAgent(
httpRequest.url,
httpRequest.proxySettings,
if (opts.scheme) {
this.repo.index.scheme = opts.scheme;
} else if (common.isLocalhost(this.repo.index.name)) {
// Per docker.git:registry/config.go#NewServiceConfig we special
// case localhost to allow HTTP. Note that this lib doesn't do
// the "try HTTPS, then fallback to HTTP if allowed" thing that
// docker-docker does, we'll just prefer HTTP for localhost.
this.repo.index.scheme = 'http';
}
if (opts.username && opts.password) {
var buffer = new Buffer(opts.username + ':' + opts.password, 'utf8');
this._authorization = 'Basic ' + buffer.toString('base64');
}
this._ensuredSession = false;
this._cookieJar = new tough.CookieJar();
this._indexUrl = common.urlFromIndex(this.repo.index);
this._commonHttpClientOpts = {
log: this.log,
agent: opts.agent,
proxy: opts.proxy,
rejectUnauthorized: !this.insecure,
userAgent: opts.userAgent || common.DEFAULT_USERAGENT
};
this._clientsToClose = [];
Object.defineProperty(this, '_indexApi', {
get: function () {
if (self.__indexApi === undefined) {
self.__indexApi = self._createClient('json', self._indexUrl);