forked from simplecrawler/simplecrawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookies.js
413 lines (345 loc) · 12.9 KB
/
cookies.js
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/**
* @file simplecrawler's cookie jar module
*/
var EventEmitter = require("events").EventEmitter,
util = require("util");
/**
* Creates a new cookie jar
* @class
*/
var CookieJar = function() {
EventEmitter.call(this);
/**
* The actual jar that holds the cookies
* @private
* @type {Array}
*/
this.cookies = [];
};
util.inherits(CookieJar, EventEmitter);
/**
* Called when {@link CookieJar#add} returns a result
* @callback CookieJar~addCallback
* @param {Error|null} error If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
* @param {Cookie|null} cookie The cookie that was added to the jar
*/
/**
* Adds a new cookie to the jar, either by creating a new {@link Cookie} object
* from specific details such as name, value, etc., accepting a string from a
* Set-Cookie header, or by passing in an existing {@link Cookie} object.
* @fires CookieJar#addcookie
* @param {String} name Name of the new cookie
* @param {String} value Value of the new cookie
* @param {String|Number} expiry Expiry timestamp of the new cookie in milliseconds
* @param {String} [path="/"] Limits cookie to a path
* @param {String} [domain="*"] Limits cookie to a domain
* @param {Boolean} [httponly=false] Specifies whether to include the HttpOnly flag
* @param {CookieJar~addCallback} [callback]
* @return {CookieJar} Returns the cookie jar instance to enable chained API calls
*/
CookieJar.prototype.add = function(name, value, expiry, path, domain, httponly, callback) {
var existingIndex = -1, newCookie;
if (arguments.length > 1) {
newCookie = new Cookie(name, value, expiry, path, domain, httponly);
} else if (name instanceof Cookie) {
newCookie = name;
} else {
newCookie = Cookie.fromString(name);
}
// Are we updating an existing cookie or adding a new one?
this.cookies.forEach(function(cookie, index) {
if (cookie.name === newCookie.name && cookie.matchDomain(newCookie.domain)) {
existingIndex = index;
}
});
if (existingIndex === -1) {
this.cookies.push(newCookie);
} else {
this.cookies[existingIndex] = newCookie;
}
/**
* Fired when a cookie has been added to the jar
* @event CookieJar#addcookie
* @param {Cookie} cookie The cookie that has been added
*/
this.emit("addcookie", newCookie);
if (callback instanceof Function) {
callback(null, newCookie);
}
return this;
};
/**
* Called when {@link CookieJar#remove} returns a result
* @callback CookieJar~removeCallback
* @param {Error|null} error If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
* @param {Cookie[]|null} cookiesRemoved An array of the cookies that were removed from the cookie jar
*/
/**
* Removes cookies from the cookie jar. If no domain and name are specified, all
* cookies in the jar are removed.
* @fires CookieJar#removecookie
* @param {String} [name] Name of the cookie to be removed
* @param {String} [domain] The domain that the cookie applies to
* @param {CookieJar~removeCallback} [callback]
* @return {Cookie[]} Returns an array of the cookies that were removed from the cookie jar
*/
CookieJar.prototype.remove = function(name, domain, callback) {
var cookiesRemoved = [],
jar = this;
jar.cookies.forEach(function(cookie, index) {
// If the names don't match, we're not removing this cookie
if (Boolean(name) && cookie.name !== name) {
return false;
}
// If the domains don't match, we're not removing this cookie
if (Boolean(domain) && !cookie.matchDomain(domain)) {
return false;
}
// Matched. Remove!
cookiesRemoved.push(jar.cookies.splice(index, 1));
});
/**
* Fired when one or multiple cookie have been removed from the jar
* @event CookieJar#removecookie
* @param {Cookie[]} cookie The cookies that have been removed
*/
jar.emit("removecookie", cookiesRemoved);
if (callback instanceof Function) {
callback(null, cookiesRemoved);
}
return cookiesRemoved;
};
/**
* Called when {@link CookieJar#get} returns a result
* @callback CookieJar~getCallback
* @param {Error} [error] If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
* @param {Cookie[]} [cookies] An array of cookies that matched the name and/or domain.
*/
/**
* Gets an array of cookies based on name and domain
* @param {String} [name] Name of the cookie to retrieve
* @param {String} [domain] Domain to retrieve the cookies from
* @param {CookieJar~getCallback} [callback]
* @return {Cookie[]} Returns an array of cookies that matched the name and/or domain
*/
CookieJar.prototype.get = function(name, domain, callback) {
var cookies = this.cookies.filter(function(cookie) {
// If the names don't match, we're not returning this cookie
if (Boolean(name) && cookie.name !== name) {
return false;
}
// If the domains don't match, we're not returning this cookie
if (Boolean(domain) && !cookie.matchDomain(domain)) {
return false;
}
return true;
});
if (callback instanceof Function) {
callback(null, cookies);
}
return cookies;
};
/**
* Called when {@link CookieJar#getAsHeader} returns a result
* @callback CookieJar~getAsHeaderCallback
* @param {Error} [error] If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
* @param {String[]} [cookies] An array of HTTP header formatted cookies.
*/
/**
* Generates an array of headers based on the value of the cookie jar
* @param {String} [domain] The domain from which to generate cookies
* @param {String} [path] Filter headers to cookies applicable to this path
* @param {CookieJar~getAsHeaderCallback} [callback]
* @return {String[]} Returns an array of HTTP header formatted cookies
*/
CookieJar.prototype.getAsHeader = function(domain, path, callback) {
var headers = this.cookies.filter(function(cookie) {
if (cookie.isExpired()) {
return false;
}
if (!domain && !path) {
return true;
}
if (domain) {
return cookie.matchDomain(domain);
}
if (path) {
return cookie.matchPath(path);
}
}).map(function(cookie) {
return cookie.toOutboundString();
});
if (callback instanceof Function) {
callback(null, headers);
}
return headers;
};
/**
* Called when {@link CookieJar#addFromHeaders} returns a result
* @callback CookieJar~addFromHeadersCallback
* @param {Error} [error] If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
*/
/**
* Adds cookies to the cookie jar based on an array of 'Set-Cookie' headers
* provided by a web server. Duplicate cookies are overwritten.
* @fires CookieJar#addcookie
* @param {String|String[]} headers One or multiple Set-Cookie headers to be added to the cookie jar
* @param {CookieJar~addFromHeadersCallback} [callback]
* @return {CookieJar} Returns the cookie jar instance to enable chained API calls
*/
CookieJar.prototype.addFromHeaders = function(headers, callback) {
var jar = this;
if (!Array.isArray(headers)) {
headers = [headers];
}
headers.forEach(function(header) {
jar.add(header);
});
if (callback instanceof Function) {
callback(null);
}
return jar;
};
/**
* Generates a newline-separated list of all cookies in the jar
* @return {String} Returns stringified versions of all cookies in the jar in a newline separated string
*/
CookieJar.prototype.toString = function() {
return this.getAsHeader().join("\n");
};
/**
* Creates a new cookies
* @class
* @param {String} name Name of the new cookie
* @param {String} value Value of the new cookie
* @param {String|Number} expires Expiry timestamp of the new cookie in milliseconds
* @param {String} [path="/"] Limits cookie to a path
* @param {String} [domain="*"] Limits cookie to a domain
* @param {Boolean} [httponly=false] Specifies whether to include the HttpOnly flag
*/
var Cookie = function(name, value, expires, path, domain, httponly) {
if (!name) {
throw new Error("A name is required to create a cookie.");
}
// Parse date to timestamp - consider it never expiring if timestamp is not
// passed to the function
if (expires) {
if (typeof expires !== "number") {
expires = new Date(expires).getTime();
}
} else {
expires = -1;
}
this.name = name;
this.value = value || "";
this.expires = expires;
this.path = path || "/";
this.domain = domain || "*";
this.httponly = Boolean(httponly);
};
/**
* Creates a new {@link Cookie} based on a header string
* @param {String} string A Set-Cookie header string
* @return {Cookie} Returns a newly created Cookie object
*/
Cookie.fromString = function(string) {
if (!string || typeof string !== "string") {
throw new Error("String must be supplied to generate a cookie.");
}
function parseKeyVal(input) {
var key = input.split(/=/).shift(),
val = input.split(/=/).slice(1).join("=");
return [key, val];
}
string = string.replace(/^\s*set-cookie\s*:\s*/i, "");
var parts = string.split(/\s*;\s*/i),
name = parseKeyVal(parts.shift()),
keyValParts = {};
keyValParts.name = name[0];
keyValParts.value = name[1];
parts
.filter(function(input) {
return Boolean(input.replace(/\s+/ig, "").length);
})
.map(parseKeyVal)
.forEach(function(keyval) {
var key = String(keyval[0]).toLowerCase().replace(/[^a-z0-9]/ig, "");
keyValParts[key] = keyval[1];
});
return new Cookie(
keyValParts.name,
keyValParts.value,
keyValParts.expires || keyValParts.expiry,
keyValParts.path,
keyValParts.domain,
keyValParts.hasOwnProperty("httponly")
);
};
/**
* Outputs the cookie as a string, in the form of an outbound Cookie header
* @return {String} Stringified version of the cookie
*/
Cookie.prototype.toOutboundString = function() {
return this.name + "=" + this.value;
};
/**
* Outputs the cookie as a string, in the form of a Set-Cookie header
* @param {Boolean} [includeHeader] Controls whether to include the 'Set-Cookie: ' header name at the beginning of the string.
* @return {String} Stringified version of the cookie
*/
Cookie.prototype.toString = function(includeHeader) {
var string = "";
if (includeHeader) {
string = "Set-Cookie: ";
}
string += this.name + "=" + this.value + "; ";
if (this.expires > 0) {
string += "Expires=" + new Date(this.expires).toGMTString() + "; ";
}
if (this.path) {
string += "Path=" + this.path + "; ";
}
if (this.domain) {
string += "Domain=" + this.domain + "; ";
}
if (this.httponly) {
string += "Httponly; ";
}
return string;
};
/**
* Determines whether a cookie has expired or not
* @return {Boolean} Returns true if the cookie has expired. Otherwise, it returns false.
*/
Cookie.prototype.isExpired = function() {
if (this.expires < 0) {
return false;
}
return this.expires < Date.now();
};
/**
* Determines whether a cookie matches a given domain
* @param {String} domain The domain to match against
* @return {Boolean} Returns true if the provided domain matches the cookie's domain. Otherwise, it returns false.
*/
Cookie.prototype.matchDomain = function(domain) {
if (this.domain === "*") {
return true;
}
var reverseDomain = this.domain.split("").reverse().join(""),
reverseDomainComp = domain.split("").reverse().join("");
return reverseDomain.indexOf(reverseDomainComp) === 0;
};
/**
* Determines whether a cookie matches a given path
* @param {String} path The path to match against
* @return {Boolean} Returns true if the provided path matches the cookie's path. Otherwise, it returns false.
*/
Cookie.prototype.matchPath = function(path) {
if (!this.path) {
return true;
}
return path.indexOf(this.path) === 0;
};
module.exports = CookieJar;
module.exports.Cookie = Cookie;