Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

http-cookie-agent

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

http-cookie-agent - npm Package Compare versions

Comparing version 2.0.0 to 2.1.0

dist/types/tough-cookie.d.js

224

dist/create_cookie_agent.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCookieAgent = void 0;
const url_1 = __importDefault(require("url"));
const tough_cookie_1 = require("tough-cookie");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createCookieAgent = createCookieAgent;
var _nodeUrl = _interopRequireDefault(require("node:url"));
var _toughCookie = require("tough-cookie");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const GET_REQUEST_URL = Symbol('getRequestUrl');

@@ -13,99 +18,120 @@ const SET_COOKIE_HEADER = Symbol('setCookieHeader');

const OVERWRITE_REQUEST_EMIT = Symbol('overwriteRequestEmit');
function createCookieAgent(BaseAgentClass) {
// @ts-ignore
class CookieAgent extends BaseAgentClass {
jar;
constructor(options, ...rest) {
super(options, ...rest);
this.jar = options.jar;
// @ts-expect-error ...
class CookieAgent extends BaseAgentClass {
constructor(options, ...rest) {
super(options, ...rest);
this.jar = options.jar;
}
[GET_REQUEST_URL](req) {
const requestUrl = _nodeUrl.default.format({
host: req.host,
pathname: req.path,
protocol: req.protocol
});
return requestUrl;
}
async [CREATE_COOKIE_HEADER_STRING](req) {
const requestUrl = this[GET_REQUEST_URL](req);
const cookies = await this.jar.getCookies(requestUrl);
const cookiesMap = new Map(cookies.map(cookie => [cookie.key, cookie]));
const cookieHeaderList = [req.getHeader('Cookie')].flat();
for (const header of cookieHeaderList) {
if (typeof header !== 'string') {
continue;
}
[GET_REQUEST_URL](req) {
const requestUrl = url_1.default.format({
protocol: req.protocol,
host: req.host,
pathname: req.path,
});
return requestUrl;
for (const str of header.split(';')) {
const cookie = _toughCookie.Cookie.parse(str.trim());
if (cookie === undefined) {
continue;
}
cookiesMap.set(cookie.key, cookie);
}
async [CREATE_COOKIE_HEADER_STRING](req) {
const requestUrl = this[GET_REQUEST_URL](req);
const cookies = await this.jar.getCookies(requestUrl);
const cookiesMap = new Map(cookies.map((cookie) => [cookie.key, cookie]));
const cookieHeaderList = [req.getHeader('Cookie')].flat();
for (const header of cookieHeaderList) {
if (typeof header !== 'string') {
continue;
}
for (const str of header.split(';')) {
const cookie = tough_cookie_1.Cookie.parse(str.trim());
if (cookie === undefined) {
continue;
}
cookiesMap.set(cookie.key, cookie);
}
}
const cookieHeader = Array.from(cookiesMap.values())
.map((cookie) => cookie.cookieString())
.join(';\x20');
return cookieHeader;
}
const cookieHeader = Array.from(cookiesMap.values()).map(cookie => cookie.cookieString()).join(';\x20');
return cookieHeader;
}
async [SET_COOKIE_HEADER](req) {
const cookieHeader = await this[CREATE_COOKIE_HEADER_STRING](req);
if (cookieHeader === '') {
return;
}
if (req._header === null) {
req.setHeader('Cookie', cookieHeader);
return;
}
const alreadyHeaderSent = req._headerSent;
req._header = null;
req.setHeader('Cookie', cookieHeader);
req._implicitHeader();
req._headerSent = alreadyHeaderSent;
if (alreadyHeaderSent !== true) {
return;
}
const firstChunk = req.outputData.shift();
if (firstChunk === undefined) {
return;
}
const dataWithoutHeader = firstChunk.data.split('\r\n\r\n').slice(1).join('\r\n\r\n');
const chunk = { ...firstChunk,
data: `${req._header}${dataWithoutHeader}`
};
req.outputData.unshift(chunk);
const diffSize = chunk.data.length - firstChunk.data.length;
req.outputSize += diffSize;
req._onPendingData(diffSize);
}
async [OVERWRITE_REQUEST_EMIT](req) {
const requestUrl = this[GET_REQUEST_URL](req);
const emit = req.emit.bind(req);
req.emit = (event, ...args) => {
if (event !== 'response') {
return emit(event, ...args);
}
async [SET_COOKIE_HEADER](req) {
const cookieHeader = await this[CREATE_COOKIE_HEADER_STRING](req);
if (cookieHeader === '') {
return;
const res = args[0];
(async () => {
const cookies = res.headers['set-cookie'];
if (cookies !== undefined) {
for (const cookie of cookies) {
await this.jar.setCookie(cookie, requestUrl, {
ignoreError: true
});
}
if (req._header === null) {
req.setHeader('Cookie', cookieHeader);
return;
}
const alreadyHeaderSent = req._headerSent;
req._header = null;
req.setHeader('Cookie', cookieHeader);
req._implicitHeader();
req._headerSent = alreadyHeaderSent;
if (alreadyHeaderSent !== true) {
return;
}
const firstChunk = req.outputData.shift();
const dataWithoutHeader = firstChunk.data.split('\r\n\r\n').slice(1).join('\r\n\r\n');
const chunk = {
...firstChunk,
data: `${req._header}${dataWithoutHeader}`,
};
req.outputData.unshift(chunk);
const diffSize = chunk.data.length - firstChunk.data.length;
req.outputSize += diffSize;
req._onPendingData(diffSize);
}
async [OVERWRITE_REQUEST_EMIT](req) {
const requestUrl = this[GET_REQUEST_URL](req);
const emit = req.emit.bind(req);
req.emit = (event, ...args) => {
if (event !== 'response') {
return emit(event, ...args);
}
const res = args[0];
(async () => {
const cookies = res.headers['set-cookie'];
if (cookies !== undefined) {
for (const cookie of cookies) {
await this.jar.setCookie(cookie, requestUrl, { ignoreError: true });
}
}
})()
.then(() => emit('response', res))
.catch((err) => emit('error', err));
return req.listenerCount(event) !== 0;
};
}
addRequest(req, options) {
Promise.resolve()
.then(() => this[SET_COOKIE_HEADER](req))
.then(() => this[OVERWRITE_REQUEST_EMIT](req))
.then(() => super.addRequest(req, options))
.catch((err) => req.emit('error', err));
}
}
})().then(() => emit('response', res)).catch(err => emit('error', err));
return req.listenerCount(event) !== 0;
};
}
return CookieAgent;
}
exports.createCookieAgent = createCookieAgent;
addRequest(req, options) {
Promise.resolve().then(() => this[SET_COOKIE_HEADER](req)).then(() => this[OVERWRITE_REQUEST_EMIT](req)).then(() => super.addRequest(req, options)).catch(err => req.emit('error', err));
}
}
return CookieAgent;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HttpCookieAgent = void 0;
const http_1 = __importDefault(require("http"));
const create_cookie_agent_1 = require("./create_cookie_agent");
exports.HttpCookieAgent = (0, create_cookie_agent_1.createCookieAgent)(http_1.default.Agent);
var _nodeHttp = _interopRequireDefault(require("node:http"));
var _create_cookie_agent = require("./create_cookie_agent");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const HttpCookieAgent = (0, _create_cookie_agent.createCookieAgent)(_nodeHttp.default.Agent);
exports.HttpCookieAgent = HttpCookieAgent;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HttpsCookieAgent = void 0;
const https_1 = __importDefault(require("https"));
const create_cookie_agent_1 = require("./create_cookie_agent");
exports.HttpsCookieAgent = (0, create_cookie_agent_1.createCookieAgent)(https_1.default.Agent);
var _nodeHttps = _interopRequireDefault(require("node:https"));
var _create_cookie_agent = require("./create_cookie_agent");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const HttpsCookieAgent = (0, _create_cookie_agent.createCookieAgent)(_nodeHttps.default.Agent);
exports.HttpsCookieAgent = HttpsCookieAgent;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MixedCookieAgent = exports.HttpsCookieAgent = exports.HttpCookieAgent = exports.createCookieAgent = void 0;
var create_cookie_agent_1 = require("./create_cookie_agent");
Object.defineProperty(exports, "createCookieAgent", { enumerable: true, get: function () { return create_cookie_agent_1.createCookieAgent; } });
var http_cookie_agent_1 = require("./http_cookie_agent");
Object.defineProperty(exports, "HttpCookieAgent", { enumerable: true, get: function () { return http_cookie_agent_1.HttpCookieAgent; } });
var https_cookie_agent_1 = require("./https_cookie_agent");
Object.defineProperty(exports, "HttpsCookieAgent", { enumerable: true, get: function () { return https_cookie_agent_1.HttpsCookieAgent; } });
var mixed_cookie_agent_1 = require("./mixed_cookie_agent");
Object.defineProperty(exports, "MixedCookieAgent", { enumerable: true, get: function () { return mixed_cookie_agent_1.MixedCookieAgent; } });
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "CookieAgentOptions", {
enumerable: true,
get: function () {
return _create_cookie_agent.CookieAgentOptions;
}
});
Object.defineProperty(exports, "HttpCookieAgent", {
enumerable: true,
get: function () {
return _http_cookie_agent.HttpCookieAgent;
}
});
Object.defineProperty(exports, "HttpsCookieAgent", {
enumerable: true,
get: function () {
return _https_cookie_agent.HttpsCookieAgent;
}
});
Object.defineProperty(exports, "MixedCookieAgent", {
enumerable: true,
get: function () {
return _mixed_cookie_agent.MixedCookieAgent;
}
});
Object.defineProperty(exports, "createCookieAgent", {
enumerable: true,
get: function () {
return _create_cookie_agent.createCookieAgent;
}
});
var _create_cookie_agent = require("./create_cookie_agent");
var _http_cookie_agent = require("./http_cookie_agent");
var _https_cookie_agent = require("./https_cookie_agent");
var _mixed_cookie_agent = require("./mixed_cookie_agent");
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MixedCookieAgent = void 0;
const agent_base_1 = __importDefault(require("agent-base"));
const http_cookie_agent_1 = require("./http_cookie_agent");
const https_cookie_agent_1 = require("./https_cookie_agent");
class MixedCookieAgent extends agent_base_1.default.Agent {
jar;
_httpAgent;
_httpsAgent;
constructor(options) {
super();
this._httpAgent = new http_cookie_agent_1.HttpCookieAgent(options);
this._httpsAgent = new https_cookie_agent_1.HttpsCookieAgent(options);
this.jar = options.jar;
}
callback(_req, options) {
return options.secureEndpoint ? this._httpsAgent : this._httpAgent;
}
var _agentBase = _interopRequireDefault(require("agent-base"));
var _http_cookie_agent = require("./http_cookie_agent");
var _https_cookie_agent = require("./https_cookie_agent");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class MixedCookieAgent extends _agentBase.default.Agent {
constructor(options) {
super();
this._httpAgent = new _http_cookie_agent.HttpCookieAgent(options);
this._httpsAgent = new _https_cookie_agent.HttpsCookieAgent(options);
this.jar = options.jar;
}
callback(_req, options) {
return options.secureEndpoint ? this._httpsAgent : this._httpAgent;
}
}
exports.MixedCookieAgent = MixedCookieAgent;
exports.MixedCookieAgent = MixedCookieAgent;

@@ -1,3 +0,4 @@

import * as http from 'http';
import * as https from 'https';
import * as http from 'node:http';
import * as https from 'node:https';
import { CookieJar } from 'tough-cookie';

@@ -4,0 +5,0 @@

{
"name": "http-cookie-agent",
"version": "2.0.0",
"version": "2.1.0",
"description": "Allows cookies with every Node.js HTTP clients.",
"license": "MIT",
"author": "3846masa <3846masahiro+git@gmail.com>",
"keywords": [
"agent",
"axios",
"cookies",
"fetch",
"got",
"http",
"https",
"needle",
"node-fetch",
"phin",
"request",
"superagent",
"tough-cookie",
"urllib",
"undici"
],
"homepage": "https://github.com/3846masa/http-cookie-agent#readme",
"bugs": {
"url": "https://github.com/3846masa/http-cookie-agent/issues"
},
"repository": {

@@ -12,8 +30,13 @@ "type": "git",

},
"bugs": {
"url": "https://github.com/3846masa/http-cookie-agent/issues"
"license": "MIT",
"author": "3846masa <3846masahiro+git@gmail.com>",
"exports": {
".": "./dist/index.js",
"./undici": "./undici/index.js"
},
"main": "dist/index.js",
"types": "index.d.ts",
"files": [
"dist",
"undici",
"index.d.ts",

@@ -24,24 +47,41 @@ "!**/__tests__"

"prebuild": "rimraf dist",
"build": "tsc",
"build": "npm-run-all build:*",
"build:cjs": "babel src --out-dir dist --extensions .ts --out-file-extension .js",
"build:mjs": "babel src --out-dir dist --extensions .mts --out-file-extension .mjs",
"semantic-release": "semantic-release",
"pretest": "npm run build",
"test": "ava"
"test": "ava",
"lint": "npm-run-all lint:*",
"lint:tsc": "tsc --noEmit",
"lint:eslint": "eslint --ext .js,.ts,.mjs,.mts .",
"lint:prettier": "prettier --check .",
"format": "npm-run-all format:*",
"format:eslint": "eslint --fix --ext .js,.ts,.mjs,.mts .",
"format:prettier": "prettier --write ."
},
"types": "index.d.ts",
"ava": {
"files": [
"dist/**/__tests__/*.spec.js",
"dist/**/__tests__/*.spec.mjs"
],
"workerThreads": false
},
"dependencies": {
"agent-base": "^6.0.2"
},
"peerDependencies": {
"tough-cookie": "^4.0.0"
},
"devDependencies": {
"@ava/typescript": "3.0.1",
"@3846masa/configs": "github:3846masa/configs",
"@babel/cli": "^7.17.10",
"@babel/core": "7.17.10",
"@babel/preset-env": "^7.17.10",
"@babel/preset-typescript": "^7.16.7",
"@hapi/wreck": "17.2.0",
"@semantic-release/changelog": "5.0.1",
"@semantic-release/git": "9.0.1",
"@types/http-proxy": "1.17.8",
"@semantic-release/changelog": "6.0.1",
"@semantic-release/git": "10.0.1",
"@types/deasync": "0.1.2",
"@types/http-proxy": "1.17.9",
"@types/needle": "2.5.3",
"@types/node": "14.18.16",
"@types/node-fetch": "2.6.1",
"@types/request": "2.48.8",
"@types/semver": "^7.3.9",
"@types/superagent": "4.1.15",

@@ -52,46 +92,37 @@ "@types/tough-cookie": "4.0.2",

"axios": "0.27.2",
"got": "11.8.3",
"deasync": "0.1.26",
"eslint-import-resolver-typescript": "2.7.1",
"got": "12.0.4",
"http-proxy": "1.18.1",
"http-proxy-agent": "5.0.0",
"needle": "3.1.0",
"node-fetch": "2.6.7",
"node-fetch": "3.2.4",
"npm-run-all": "4.1.5",
"phin": "3.6.1",
"request": "2.88.2",
"rimraf": "^3.0.2",
"semantic-release": "17.4.7",
"semantic-release": "19.0.2",
"semver": "^7.3.7",
"superagent": "7.1.3",
"tough-cookie": "4.0.0",
"typescript": "4.6.4",
"undici": "5.1.1",
"urllib": "2.38.0"
},
"keywords": [
"agent",
"axios",
"cookies",
"fetch",
"got",
"http",
"https",
"needle",
"node-fetch",
"phin",
"request",
"superagent",
"tough-cookie",
"urllib"
],
"peerDependencies": {
"deasync": "^0.1.26",
"tough-cookie": "^4.0.0",
"undici": "^5.1.1"
},
"peerDependenciesMeta": {
"deasync": {
"optional": true
},
"undici": {
"optional": true
}
},
"engines": {
"node": ">=14.18.0 <15.0.0 || >=16.0.0"
},
"ava": {
"files": [
"**/__tests__/*.spec.ts"
],
"typescript": {
"rewritePaths": {
"src/": "dist/"
},
"compile": false
}
}
}

@@ -9,3 +9,3 @@ # HTTP Cookie Agent

Allows cookies with every Node.js HTTP clients (e.g. axios, node-fetch).
Allows cookies with every Node.js HTTP clients (e.g. undici, axios, node-fetch).

@@ -24,3 +24,3 @@ ## Table of Contents

```
```bash
npm install http-cookie-agent tough-cookie

@@ -53,3 +53,3 @@ ```

`http` / `https` / `axios` / `node-fetch` / `got`\*\* / `superagent`\*\* / `request`\*\* / `needle` / `phin` / `@hapi/wreck` / `urllib` etc.
`undici` / `node:http` / `node:https` / `axios` / `node-fetch` / `got`\*\* / `superagent`\*\* / `request`\*\* / `needle` / `phin` / `@hapi/wreck` / `urllib` etc.

@@ -62,7 +62,23 @@ \*\* The library supports cookies by default. You may not need `http-cookie-agent`.

#### `http` / `https`
#### `undici`
```js
import https from 'https';
import { fetch, setGlobalDispatcher } from 'undici';
import { CookieJar } from 'tough-cookie';
import { CookieAgent } from 'http-cookie-agent/undici';
const jar = new CookieJar();
const agent = new CookieAgent({ cookies: { jar } });
setGlobalDispatcher(agent);
await fetch('https://example.com');
```
#### `node:http` / `node:https`
```js
import https from 'node:https';
import { CookieJar } from 'tough-cookie';
import { HttpsCookieAgent } from 'http-cookie-agent';

@@ -251,3 +267,4 @@

```js
import https from 'https';
import https from 'node:https';
import { HttpsAgent as KeepAliveAgent } from 'agentkeepalive';

@@ -267,2 +284,50 @@ import { CookieJar } from 'tough-cookie';

#### `undici`
If you want to use another undici Agent library, use `CookieClient` via factory function.
```js
import { fetch, ProxyAgent, setGlobalDispatcher } from 'undici';
import { CookieJar } from 'tough-cookie';
import { CookieClient } from 'http-cookie-agent/undici';
const jar = new CookieJar();
const agent = new ProxyAgent({
factory: (origin, opts) => {
return new CookieClient(origin, {
...opts,
cookies: { jar },
});
},
});
setGlobalDispatcher(agent);
await fetch('https://example.com');
```
If you want to use another undici Client library, wrap the client in `createCookieClient`.
```js
import { fetch, Agent, MockClient, setGlobalDispatcher } from 'undici';
import { CookieJar } from 'tough-cookie';
import { createCookieClient } from 'http-cookie-agent/undici';
const CookieClient = createCookieClient(MockClient);
const jar = new CookieJar();
const agent = new Agent({
factory: (origin, opts) => {
return new CookieClient(origin, {
...opts,
cookies: { jar },
});
},
});
setGlobalDispatcher(agent);
await fetch('https://example.com');
```
## Contributing

@@ -269,0 +334,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc