forked from Horat1us/node-cookiefile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-cookiefile.js
361 lines (321 loc) · 11.1 KB
/
http-cookiefile.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
/**
* Created by horat1us on 09.10.16.
*/
"use strict";
module.exports = {
Cookie: class Cookie {
constructor({domain, httpOnly = false, crossDomain = false, path = '/', https = false, expire = 0, name, value}) {
if (!(expire instanceof Date || require('isnumeric')(expire))) {
throw new module.exports.CookieError();
}
this.domain = domain;
this.crossDomain = crossDomain;
this.path = path;
this.https = https;
this.expire = ~~expire ? ~~expire : 0;
this.value = value;
this.cookieName = name;
this.httpOnly = httpOnly
}
/** @return {String} */
get name() {
return this.cookieName;
}
get isCrossDomain() {
return this.crossDomain.toString().toUpperCase();
}
get isHttps() {
return this.https.toString().toUpperCase();
}
/**
* @return {Cookie}
*/
clone() {
return new Cookie(this);
}
/** @return {String} */
toString() {
let _this = this,
string = this.httpOnly ? "#HttpOnly_" : "";
['domain', 'isCrossDomain', 'path', 'isHttps', 'expire', 'name', 'value']
.forEach(prop => string += _this[prop] + '\t');
return string.trim() + '\n';
}
toHeader() {
return `${this.name}=${this.value}; `;
}
toResponseHeader() {
return `Set-Cookie: ${this.name}=${this.value}; ` +
[['Domain', 'domain'], ['Path', 'path']]
.map(([name, prop]) => `${name}=${this[prop]}`)
.join('; ') + '; ' +
`expires=${new Date(this.expire).toUTCString()}; ` +
[['Secure', 'https'], ['HttpOnly', 'httpOnly']]
.filter(([,property]) => this[property])
.map(([name]) => ` ${name}`)
.join('; ');
}
/**
* @param {Cookie} cookie
* @return {Boolean}
*/
is(cookie) {
for (let prop in ['domain', 'crossDomain', 'path', 'https', 'expire', 'name', 'value']) {
if (this[prop] !== cookie[prop]) {
return false;
}
}
return true;
}
},
CookieMap: class CookieMap extends Map {
constructor(file = []) {
if (Array.isArray(file)) {
super();
file.forEach(cookie => {
if (!(cookie instanceof module.exports.Cookie)) {
throw new module.exports.CookieError(4);
}
this.set(cookie);
});
this.file = false;
} else if (typeof(file) === 'string') {
super();
this.file = file;
return this.readFile();
} else {
throw new TypeError("Wrong argument supplied for CookieMap construtor");
}
}
/**
* @param {String} nameValue a=b=c
* @returns {Array} [ 'a', 'b=c' ]
*/
static split(nameValue) {
let parts = nameValue
.trim()
.split('=');
if (parts.length == 1) {
return parts;
}
parts = [parts[0], (nameValue.replace(`${parts[0]}=`, ''))];
return parts;
}
/**
* @param {String} header HTTP Header like Set-Cookie: ...
* @param {Object} props
* @return {CookieMap}
*/
header(header, props = {}) {
if (!CookieMap.validateHeader(header)) {
return this;
}
let CookieInfo = {};
header
.replace('Set-Cookie: ', '')
.split(';')
.map(CookieMap.split)
.map(parts => parts.map(part => part.trim()))
.filter(part => {
if (part.length === 2) {
return true;
}
switch (part[0]) {
case "Secure":
CookieInfo.https = true;
break;
case "HttpOnly":
CookieInfo.httpOnly = true;
break;
}
return false;
})
.forEach(([name, value]) => {
switch (name.toLowerCase()) {
case "domain":
return CookieInfo.domain = value;
case "path":
return CookieInfo.path = value;
case "expires":
return CookieInfo.expire = new Date(value);
case "same-Site":
case "max-Age":
// TODO: Integrate support for Max-Age and Same-Site directives
return;
default:
CookieInfo.name = name;
CookieInfo.value = value;
}
});
CookieInfo = Object.assign(props, CookieInfo);
['name', 'value', 'domain']
.forEach(prop => {
if (!CookieInfo.hasOwnProperty(prop)) {
throw new module.exports.CookieError(5);
}
});
this.set(new module.exports.Cookie(CookieInfo));
return this;
}
/**
* @param {String} requestHeader: Cookie: a=b; d=c
* @param {Object} params
* @return {CookieMap}
*/
generate(requestHeader, params = {}) {
requestHeader
.replace('Cookie: ', '')
.trim()
.split(';')
.map(cookie => cookie.trim())
.filter(cookie => cookie.length > 0)
.map(CookieMap.split)
.filter(cookie => cookie.length === 2)
.map(([name, value]) => Object.assign({name, value}, params))
.map(params => new module.exports.Cookie(params))
.forEach(cookie => this.set(cookie));
return this;
}
/**
* Takes sample HTTP Cookie and return true if set-cookie header given
* @param {String} header HTTP Header like Set-Cookie: ...
*/
static validateHeader(header) {
return header
.trim()
.substr(0, 11) === "Set-Cookie:";
}
/**
* @param {Cookie} cookie
* @return {CookieMap}
*/
set(cookie) {
if (!(cookie instanceof module.exports.Cookie)) {
throw new TypeError(`Cookie must be type of cookie, ${typeof(cookie)} given`);
}
super.set(cookie.name, cookie);
return this;
}
/**
* @return {CookieMap}
*/
save(file = false) {
if (file === false || typeof(file) !== 'string') {
file = this.file;
}
if (file === false) {
throw new module.exports.CookieError(2);
}
require('fs').writeFileSync(file, this.toString());
return this;
}
/**
* @returns {CookieMap}
*/
clone() {
let cookieMap = new CookieMap();
for ([, cookie] of this) {
cookieMap.set(cookie.clone());
}
return cookieMap;
}
toString() {
let cookieContent = module.exports.CookieFile.Header;
/** @var {Cookie} cookie */
for (let cookie of this.values()) {
cookieContent += cookie.toString();
}
return cookieContent.trim();
}
/**
* @return {String} HTTP User header
*/
toRequestHeader({http = true, secure = true} = {}) {
let string = 'Cookie: ';
/**
* @var {String} name
* @var {Cookie} cookie
*/
for (let [, cookie] of this) {
string += cookie.toHeader();
}
return string.replace(/;\s*$/, '');
}
/**
* @return {String} HTTP Server header
*/
toResponseHeader() {
let headers = [];
for (let [,cookie] of this) {
headers.push(cookie.toResponseHeader());
}
return headers;
}
/**
* @return {CookieMap}
*/
readFile() {
if (!require('file-exists')(this.file)) {
throw new module.exports.CookieError(1);
}
const fs = require('fs');
let cookieFileContents = fs.readFileSync(this.file, {encoding: 'UTF-8'})
const cookies = cookieFileContents
.split('\n')
.map(line => line.split("\t").map((word) => word.trim()))
.filter(line => line.length === 7)
.map(cookieData => ({
name: cookieData[5],
value: cookieData[6],
domain: cookieData[0],
crossDomain: cookieData[1] === 'TRUE',
path: cookieData[2],
https: cookieData[3] === 'TRUE',
expire: ~~cookieData[4] ? ~~cookieData[4] : 0,
}))
.map(cookie => {
if (cookie.domain.substr(0, 10) === "#HttpOnly_") {
cookie.httpOnly = true;
cookie.domain = cookie.domain.substr(10);
}
return cookie;
})
.forEach(cookie => this.set(
new module.exports.Cookie(cookie)
));
return this;
}
get size() {
return super.size;
}
},
CookieError: class CookieError extends Error {
constructor(code = 0) {
const message = (() => {
switch (code) {
case 5:
return "Wrong header passed for creating cookie";
case 4:
return "Cookie passed to constructor is incorrect";
case 3:
return "Cookie file writing error";
case 2:
return 'You can not save this object because is initialized by Map, not file';
case 1:
return 'Cookie File doesn\'t exists';
default:
return "Cookie expire must be instance of Date or integer";
}
})();
super(message);
}
}
,
CookieFile: {
Header: `# Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by node-httpcookie! Edit at your own risk
`,
}
}
;