forked from jd1378/deno-another-cookiejar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookie_jar.ts
264 lines (240 loc) · 7.07 KB
/
cookie_jar.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import {
Cookie,
CookieOptions,
isSameDomainOrSubdomain,
parseURL,
} from "./cookie.ts";
const strictMatchProps = [
"value",
"secure",
"httpOnly",
"maxAge",
"expires",
"sameSite",
];
function cookieMatches(
options: Cookie | CookieOptions,
comparedWith: Cookie,
strictMatch = false,
): boolean {
if (
options.path !== undefined && !comparedWith.path?.startsWith(options.path)
) {
return false;
}
if (options.domain) {
if (!isSameDomainOrSubdomain(options.domain, comparedWith.domain)) {
return false;
}
}
if (
options.name !== undefined &&
options.name !== comparedWith.name
) {
return false;
}
if (
strictMatch &&
strictMatchProps.some((propKey) =>
// deno-lint-ignore ban-ts-comment
// @ts-ignore
options[propKey] !== undefined &&
// deno-lint-ignore ban-ts-comment
// @ts-ignore
options[propKey] !== comparedWith[propKey]
)
) {
return false;
}
return true;
}
// cookie compare from tough-cookie
const MAX_TIME = 2147483647000; // 31-bit max
/**
* Cookies with longer paths are listed before cookies with
* shorter paths.
*
* Among cookies that have equal-length path fields, cookies with
* earlier creation-times are listed before cookies with later
* creation-times."
*/
function cookieCompare(a: Cookie, b: Cookie) {
let cmp = 0;
// descending for length: b CMP a
const aPathLen = a.path?.length || 0;
const bPathLen = b.path?.length || 0;
cmp = bPathLen - aPathLen;
if (cmp !== 0) {
return cmp;
}
// ascending for time: a CMP b
const aTime = a.creationDate || MAX_TIME;
const bTime = b.creationDate || MAX_TIME;
cmp = aTime - bTime;
if (cmp !== 0) {
return cmp;
}
// tie breaker
cmp = a.creationIndex - b.creationIndex;
return cmp;
}
export class CookieJar {
cookies = Array<Cookie>();
/**
* @param cookies - the cookies array to initialize with
*/
constructor(cookies?: Array<Cookie> | Array<CookieOptions>) {
this.replaceCookies(cookies);
}
/**
* Sets or replaces a cookie inside the jar.
* Only sets new cookies if cookie is valid and not expired.
* Validation and expiration checks are not run when replacing a cookie.
* @param url - the url that this cookie from received from. mainly used by the fetch wrapper.
* will automatically set domain and path if provided and it was not found inside Cookie/cookiestring.
*/
setCookie(cookie: Cookie | string, url?: string | Request | URL) {
let cookieObj;
if (typeof cookie === "string") {
cookieObj = Cookie.from(cookie);
} else {
cookieObj = cookie;
}
if (url) {
if (!cookieObj.domain) {
cookieObj.setDomain(url);
}
if (!cookieObj.path) {
cookieObj.setPath(url);
}
}
if (!cookieObj.isValid()) {
return;
}
const foundCookie = this.getCookie(cookieObj);
if (foundCookie) {
const indexOfCookie = this.cookies.indexOf(foundCookie);
if (!cookieObj.isExpired()) {
this.cookies.splice(indexOfCookie, 1, cookieObj);
} else {
this.cookies.splice(indexOfCookie, 1);
}
} else if (!cookieObj.isExpired()) {
this.cookies.push(cookieObj);
}
// sort by creation date, so when searching, we get the latest created cookies.
this.cookies.sort(cookieCompare);
}
/**
* Gets the first cooking matching the defined properties of a given Cookie or CookieOptions.
* returns undefined if not found or expired. `creationDate` prop is not checked.
* Also removes the cookie and returns undefined if cookie is expired.
*/
getCookie(options: Cookie | CookieOptions): Cookie | undefined {
const strictMatch = typeof (options as Cookie).isValid !== "function";
for (const [index, cookie] of this.cookies.entries()) {
if (cookieMatches(options, cookie, strictMatch)) {
if (!cookie.isExpired()) {
return cookie;
} else {
this.cookies.splice(index, 1);
return undefined;
}
}
}
}
/**
* Returns cookies that match the options excluding expired ones, also removes expired cookies before returning.
* @param options - the options to filter cookies with, and if not provided, returnes all cookies.
* if no cookie is found with given options, an empty array is returned.
*/
getCookies(options?: CookieOptions | Cookie) {
if (options) {
const matchedCookies: Cookie[] = [];
const removeCookies: Cookie[] = [];
for (const cookie of this.cookies) {
if (cookieMatches(options, cookie)) {
if (!cookie.isExpired()) {
matchedCookies.push(cookie);
} else {
removeCookies.push(cookie);
}
}
}
if (removeCookies.length) {
this.cookies = this.cookies.filter((cookie) =>
!removeCookies.includes(cookie)
);
}
return matchedCookies;
} else {
return this.cookies;
}
}
/**
* Converts the cookies to a string that can be used in a request.
* @param url - the url to get the cookies for. if provided, will only return cookies that match the domain and path of the url.
* @returns string of all cookies that match the url, in the from of `<cookie-name>=<cookie-value>` seperated by `; `
*/
getCookieString(url: string | Request | URL) {
const searchCookie = new Cookie();
searchCookie.setDomain(url);
const cookiesToSend = this.getCookies(searchCookie)
.filter((cookie) => {
return cookie.canSendTo(parseURL(url));
})
.map((c) => c.getCookieString())
.join("; ");
return cookiesToSend;
}
toJSON() {
return this.cookies;
}
/**
* Removes first cookie that matches the given option.
*
* Returns the deleted cookie if found or undefined otherwise.
*/
removeCookie(options: CookieOptions | Cookie): Cookie | undefined {
for (const [index, cookie] of this.cookies.entries()) {
if (cookieMatches(options, cookie)) {
return this.cookies.splice(index, 1)[0];
}
}
}
/**
* Removes all cookies that matches the given option.
* If options is not given, all cookies will be deleted.
*
* Returns the deleted cookies if found or undefined otherwise.
*/
removeCookies(options?: CookieOptions | Cookie): Array<Cookie> | undefined {
if (options) {
const deletedCookies: Cookie[] = [];
this.cookies = this.cookies.filter((cookie) => {
if (cookieMatches(options, cookie)) {
deletedCookies.push(cookie);
return false;
}
return true;
});
return deletedCookies.length ? deletedCookies : undefined;
} else {
this.cookies = [];
}
}
replaceCookies(cookies?: Array<Cookie> | Array<CookieOptions>) {
if (cookies?.length) {
if (typeof (cookies[0] as Cookie).isValid === "function") {
this.cookies = cookies as Array<Cookie>;
} else {
this.cookies = [];
for (const option of cookies) {
this.cookies.push(new Cookie(option));
}
}
} else {
this.cookies = [];
}
}
}