-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
create_cookie_agent.ts
155 lines (134 loc) · 4.62 KB
/
create_cookie_agent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import type http from 'node:http';
import liburl from 'node:url';
import type { CookieOptions } from '../cookie_options';
import { createCookieHeaderValue } from '../utils/create_cookie_header_value';
import { saveCookiesFromHeader } from '../utils/save_cookies_from_header';
import { validateCookieOptions } from '../utils/validate_cookie_options';
declare module 'http' {
interface Agent {
addRequest(req: http.ClientRequest, options: http.RequestOptions): void;
}
interface ClientRequest {
_header: string | null;
_headerSent: boolean;
_implicitHeader(): void;
_onPendingData(amount: number): void;
outputData: Array<{
callback: unknown;
data: string;
encoding: string;
}>;
outputSize: number;
}
}
export type CookieAgentOptions = {
cookies?: CookieOptions | undefined;
};
const kCookieOptions = Symbol('cookieOptions');
const kReimplicitHeader = Symbol('reimplicitHeader');
const kRecreateFirstChunk = Symbol('recreateFirstChunk');
const kOverrideRequest = Symbol('overrideRequest');
export function createCookieAgent<BaseAgent extends http.Agent = http.Agent, Params extends unknown[] = unknown[]>(
BaseAgentClass: new (...params: Params) => BaseAgent,
) {
type WithCookieAgentOptions<T> = T extends http.AgentOptions ? T & CookieAgentOptions : T;
type ConstructorParams = {
[Index in keyof Params]: WithCookieAgentOptions<Params[Index]>;
} & { length: Params['length'] };
// @ts-expect-error ...
class CookieAgent extends BaseAgentClass {
[kCookieOptions]: CookieOptions | undefined;
constructor(...params: ConstructorParams) {
const { cookies: cookieOptions } = (params.find((opt) => {
return opt != null && typeof opt === 'object' && 'cookies' in opt;
}) ?? {}) as CookieAgentOptions;
super(...(params as Params));
if (cookieOptions) {
validateCookieOptions(cookieOptions);
}
this[kCookieOptions] = cookieOptions;
}
private [kReimplicitHeader](req: http.ClientRequest): void {
const _headerSent = req._headerSent;
req._header = null;
req._implicitHeader();
req._headerSent = _headerSent;
}
private [kRecreateFirstChunk](req: http.ClientRequest): void {
const firstChunk = req.outputData[0];
if (req._header == null || firstChunk == null) {
return;
}
const prevData = firstChunk.data;
const prevHeaderLength = prevData.indexOf('\r\n\r\n');
if (prevHeaderLength === -1) {
firstChunk.data = req._header;
} else {
firstChunk.data = `${req._header}${prevData.slice(prevHeaderLength + 4)}`;
}
const diffSize = firstChunk.data.length - prevData.length;
req.outputSize += diffSize;
req._onPendingData(diffSize);
}
private [kOverrideRequest](req: http.ClientRequest, requestUrl: string, cookieOptions: CookieOptions): void {
const _implicitHeader = req._implicitHeader.bind(req);
req._implicitHeader = (): void => {
try {
const cookieHeader = createCookieHeaderValue({
cookieOptions,
passedValues: [req.getHeader('Cookie')].flat(),
requestUrl,
});
if (cookieHeader) {
req.setHeader('Cookie', cookieHeader);
}
} catch (err) {
req.destroy(err as Error);
return;
}
return _implicitHeader();
};
const emit = req.emit.bind(req);
req.emit = (event: string, ...args: unknown[]): boolean => {
if (event === 'response') {
try {
const res = args[0] as http.IncomingMessage;
saveCookiesFromHeader({
cookieOptions,
cookies: res.headers['set-cookie'],
requestUrl,
});
} catch (err) {
req.destroy(err as Error);
return false;
}
}
return emit(event, ...args);
};
}
override addRequest(req: http.ClientRequest, options: http.RequestOptions): void {
const cookieOptions = this[kCookieOptions];
if (cookieOptions) {
try {
const requestUrl = liburl.format({
host: req.host,
pathname: req.path,
protocol: req.protocol,
});
this[kOverrideRequest](req, requestUrl, cookieOptions);
if (req._header != null) {
this[kReimplicitHeader](req);
}
if (req._headerSent) {
this[kRecreateFirstChunk](req);
}
} catch (err) {
req.destroy(err as Error);
return;
}
}
return super.addRequest(req, options);
}
}
return CookieAgent;
}