-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
cookies.js
executable file
·611 lines (551 loc) · 18.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import { Meteor } from 'meteor/meteor';
let fetch;
let WebApp;
if (Meteor.isServer) {
WebApp = require('meteor/webapp').WebApp;
} else {
fetch = require('meteor/fetch').fetch;
}
const NoOp = () => {};
const urlRE = /\/___cookie___\/set/;
const rootUrl = Meteor.isServer ? process.env.ROOT_URL : (window.__meteor_runtime_config__.ROOT_URL || window.__meteor_runtime_config__.meteorEnv.ROOT_URL || false);
const mobileRootUrl = Meteor.isServer ? process.env.MOBILE_ROOT_URL : (window.__meteor_runtime_config__.MOBILE_ROOT_URL || window.__meteor_runtime_config__.meteorEnv.MOBILE_ROOT_URL || false);
const helpers = {
isUndefined(obj) {
return obj === void 0;
},
isArray(obj) {
return Array.isArray(obj);
},
clone(obj) {
if (!this.isObject(obj)) return obj;
return this.isArray(obj) ? obj.slice() : Object.assign({}, obj);
}
};
const _helpers = ['Number', 'Object', 'Function'];
for (let i = 0; i < _helpers.length; i++) {
helpers['is' + _helpers[i]] = function (obj) {
return Object.prototype.toString.call(obj) === '[object ' + _helpers[i] + ']';
};
}
/**
* @url https://github.com/jshttp/cookie/blob/master/index.js
* @name cookie
* @author jshttp
* @license
* (The MIT License)
*
* Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com>
* Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const decode = decodeURIComponent;
const encode = encodeURIComponent;
const pairSplitRegExp = /; */;
/**
* RegExp to match field-content in RFC 7230 sec 3.2
*
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* obs-text = %x80-FF
*/
const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
/**
* @function
* @name tryDecode
* @param {String} str
* @param {Function} d
* @summary Try decoding a string using a decoding function.
* @private
*/
const tryDecode = (str, d) => {
try {
return d(str);
} catch (e) {
return str;
}
};
/**
* @function
* @name parse
* @param {String} str
* @param {Object} [options]
* @return {Object}
* @summary
* Parse a cookie header.
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
* @private
*/
const parse = (str, options) => {
if (typeof str !== 'string') {
throw new Meteor.Error(404, 'argument str must be a string');
}
const obj = {};
const opt = options || {};
let val;
let key;
let eqIndx;
str.split(pairSplitRegExp).forEach((pair) => {
eqIndx = pair.indexOf('=');
if (eqIndx < 0) {
return;
}
key = pair.substr(0, eqIndx).trim();
key = tryDecode(unescape(key), (opt.decode || decode));
val = pair.substr(++eqIndx, pair.length).trim();
if (val[0] === '"') {
val = val.slice(1, -1);
}
if (void 0 === obj[key]) {
obj[key] = tryDecode(val, (opt.decode || decode));
}
});
return obj;
};
/**
* @function
* @name antiCircular
* @param data {Object} - Circular or any other object which needs to be non-circular
* @private
*/
const antiCircular = (_obj) => {
const object = helpers.clone(_obj);
const cache = new Map();
return JSON.stringify(object, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.get(value)) {
return void 0;
}
cache.set(value, true);
}
return value;
});
};
/**
* @function
* @name serialize
* @param {String} name
* @param {String} val
* @param {Object} [options]
* @return { cookieString: String, sanitizedValue: Mixed }
* @summary
* Serialize data into a cookie header.
* Serialize the a name value pair into a cookie string suitable for
* http headers. An optional options object specified cookie parameters.
* serialize('foo', 'bar', { httpOnly: true }) => "foo=bar; httpOnly"
* @private
*/
const serialize = (key, val, opt = {}) => {
let name;
if (!fieldContentRegExp.test(key)) {
name = escape(key);
} else {
name = key;
}
let sanitizedValue = val;
let value = val;
if (!helpers.isUndefined(value)) {
if (helpers.isObject(value) || helpers.isArray(value)) {
const stringified = antiCircular(value);
value = encode(`JSON.parse(${stringified})`);
sanitizedValue = JSON.parse(stringified);
} else {
value = encode(value);
if (value && !fieldContentRegExp.test(value)) {
value = escape(value);
}
}
} else {
value = '';
}
const pairs = [`${name}=${value}`];
if (helpers.isNumber(opt.maxAge)) {
pairs.push(`Max-Age=${opt.maxAge}`);
}
if (opt.domain && typeof opt.domain === 'string') {
if (!fieldContentRegExp.test(opt.domain)) {
throw new Meteor.Error(404, 'option domain is invalid');
}
pairs.push(`Domain=${opt.domain}`);
}
if (opt.path && typeof opt.path === 'string') {
if (!fieldContentRegExp.test(opt.path)) {
throw new Meteor.Error(404, 'option path is invalid');
}
pairs.push(`Path=${opt.path}`);
} else {
pairs.push('Path=/');
}
opt.expires = opt.expires || opt.expire || false;
if (opt.expires === Infinity) {
pairs.push('Expires=Fri, 31 Dec 9999 23:59:59 GMT');
} else if (opt.expires instanceof Date) {
pairs.push(`Expires=${opt.expires.toUTCString()}`);
} else if (opt.expires === 0) {
pairs.push('Expires=0');
} else if (helpers.isNumber(opt.expires)) {
pairs.push(`Expires=${(new Date(opt.expires)).toUTCString()}`);
}
if (opt.httpOnly) {
pairs.push('HttpOnly');
}
if (opt.secure) {
pairs.push('Secure');
}
if (opt.firstPartyOnly) {
pairs.push('First-Party-Only');
}
if (opt.sameSite) {
pairs.push(opt.sameSite === true ? 'SameSite' : `SameSite=${opt.sameSite}`);
}
return { cookieString: pairs.join('; '), sanitizedValue };
};
const isStringifiedRegEx = /JSON\.parse\((.*)\)/;
const isTypedRegEx = /false|true|null/;
const deserialize = (string) => {
if (typeof string !== 'string') {
return string;
}
if (isStringifiedRegEx.test(string)) {
let obj = string.match(isStringifiedRegEx)[1];
if (obj) {
try {
return JSON.parse(decode(obj));
} catch (e) {
console.error('[ostrio:cookies] [.get()] [deserialize()] Exception:', e, string, obj);
return string;
}
}
return string;
} else if (isTypedRegEx.test(string)) {
try {
return JSON.parse(string);
} catch (e) {
return string;
}
}
return string;
};
/**
* @locus Anywhere
* @class __cookies
* @param opts {Object} - Options (configuration) object
* @param opts._cookies {Object|String} - Current cookies as String or Object
* @param opts.TTL {Number|Boolean} - Default cookies expiration time (max-age) in milliseconds, by default - session (false)
* @param opts.runOnServer {Boolean} - Expose Cookies class to Server
* @param opts.response {http.ServerResponse|Object} - This object is created internally by a HTTP server
* @param opts.allowQueryStringCookies {Boolean} - Allow passing Cookies in a query string (in URL). Primary should be used only in Cordova environment
* @param opts.allowedCordovaOrigins {Regex|Boolean} - [Server] Allow setting Cookies from that specific origin which in Meteor/Cordova is localhost:12XXX (^http://localhost:12[0-9]{3}$)
* @summary Internal Class
*/
class __cookies {
constructor(opts) {
this.__pendingCookies = [];
this.TTL = opts.TTL || false;
this.response = opts.response || false;
this.runOnServer = opts.runOnServer || false;
this.allowQueryStringCookies = opts.allowQueryStringCookies || false;
this.allowedCordovaOrigins = opts.allowedCordovaOrigins || false;
if (this.allowedCordovaOrigins === true) {
this.allowedCordovaOrigins = /^http:\/\/localhost:12[0-9]{3}$/;
}
this.originRE = new RegExp(`^https?:\/\/(${rootUrl ? rootUrl : ''}${mobileRootUrl ? ('|' + mobileRootUrl) : ''})$`);
if (helpers.isObject(opts._cookies)) {
this.cookies = opts._cookies;
} else {
this.cookies = parse(opts._cookies);
}
}
/**
* @locus Anywhere
* @memberOf __cookies
* @name get
* @param {String} key - The name of the cookie to read
* @param {String} _tmp - Unparsed string instead of user's cookies
* @summary Read a cookie. If the cookie doesn't exist a null value will be returned.
* @returns {String|void}
*/
get(key, _tmp) {
const cookieString = _tmp ? parse(_tmp) : this.cookies;
if (!key || !cookieString) {
return void 0;
}
if (cookieString.hasOwnProperty(key)) {
return deserialize(cookieString[key]);
}
return void 0;
}
/**
* @locus Anywhere
* @memberOf __cookies
* @name set
* @param {String} key - The name of the cookie to create/overwrite
* @param {String} value - The value of the cookie
* @param {Object} opts - [Optional] Cookie options (see readme docs)
* @summary Create/overwrite a cookie.
* @returns {Boolean}
*/
set(key, value, opts = {}) {
if (key && !helpers.isUndefined(value)) {
if (helpers.isNumber(this.TTL) && opts.expires === undefined) {
opts.expires = new Date(+new Date() + this.TTL);
}
const { cookieString, sanitizedValue } = serialize(key, value, opts);
this.cookies[key] = sanitizedValue;
if (Meteor.isClient) {
document.cookie = cookieString;
} else if (this.response) {
this.__pendingCookies.push(cookieString);
this.response.setHeader('Set-Cookie', this.__pendingCookies);
}
return true;
}
return false;
}
/**
* @locus Anywhere
* @memberOf __cookies
* @name remove
* @param {String} key - The name of the cookie to create/overwrite
* @param {String} path - [Optional] The path from where the cookie will be
* readable. E.g., "/", "/mydir"; if not specified, defaults to the current
* path of the current document location (string or null). The path must be
* absolute (see RFC 2965). For more information on how to use relative paths
* in this argument, see: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie#Using_relative_URLs_in_the_path_parameter
* @param {String} domain - [Optional] The domain from where the cookie will
* be readable. E.g., "example.com", ".example.com" (includes all subdomains)
* or "subdomain.example.com"; if not specified, defaults to the host portion
* of the current document location (string or null).
* @summary Remove a cookie(s).
* @returns {Boolean}
*/
remove(key, path = '/', domain = '') {
if (key && this.cookies.hasOwnProperty(key)) {
const { cookieString } = serialize(key, '', {
domain,
path,
expires: new Date(0)
});
delete this.cookies[key];
if (Meteor.isClient) {
document.cookie = cookieString;
} else if (this.response) {
this.response.setHeader('Set-Cookie', cookieString);
}
return true;
} else if (!key && this.keys().length > 0 && this.keys()[0] !== '') {
const keys = Object.keys(this.cookies);
for (let i = 0; i < keys.length; i++) {
this.remove(keys[i]);
}
return true;
}
return false;
}
/**
* @locus Anywhere
* @memberOf __cookies
* @name has
* @param {String} key - The name of the cookie to create/overwrite
* @param {String} _tmp - Unparsed string instead of user's cookies
* @summary Check whether a cookie exists in the current position.
* @returns {Boolean}
*/
has(key, _tmp) {
const cookieString = _tmp ? parse(_tmp) : this.cookies;
if (!key || !cookieString) {
return false;
}
return cookieString.hasOwnProperty(key);
}
/**
* @locus Anywhere
* @memberOf __cookies
* @name keys
* @summary Returns an array of all readable cookies from this location.
* @returns {[String]}
*/
keys() {
if (this.cookies) {
return Object.keys(this.cookies);
}
return [];
}
/**
* @locus Client
* @memberOf __cookies
* @name send
* @param cb {Function} - Callback
* @summary Send all cookies over XHR to server.
* @returns {void}
*/
send(cb = NoOp) {
if (Meteor.isServer) {
cb(new Meteor.Error(400, 'Can\'t run `.send()` on server, it\'s Client only method!'));
}
if (this.runOnServer) {
let path = `${window.__meteor_runtime_config__.ROOT_URL_PATH_PREFIX || window.__meteor_runtime_config__.meteorEnv.ROOT_URL_PATH_PREFIX || ''}/___cookie___/set`;
let query = '';
if ((Meteor.isCordova || Meteor.isDesktop) && this.allowQueryStringCookies) {
const cookiesKeys = this.keys();
const cookiesArray = [];
for (let i = 0; i < cookiesKeys.length; i++) {
const { sanitizedValue } = serialize(cookiesKeys[i], this.get(cookiesKeys[i]));
const pair = `${cookiesKeys[i]}=${sanitizedValue}`;
if (!cookiesArray.includes(pair)) {
cookiesArray.push(pair);
}
}
if (cookiesArray.length) {
path = Meteor.absoluteUrl('___cookie___/set');
query = `?___cookies___=${encodeURIComponent(cookiesArray.join('; '))}`;
}
}
fetch(`${path}${query}`, {
credentials: 'include',
type: 'cors'
}).then((response) => {
cb(void 0, response);
}).catch(cb);
} else {
cb(new Meteor.Error(400, 'Can\'t send cookies on server when `runOnServer` is false.'));
}
return void 0;
}
}
/**
* @function
* @locus Server
* @summary Middleware handler
* @private
*/
const __middlewareHandler = (request, response, opts) => {
let _cookies = {};
if (opts.runOnServer) {
if (request.headers && request.headers.cookie) {
_cookies = parse(request.headers.cookie);
}
return new __cookies({
_cookies,
TTL: opts.TTL,
runOnServer: opts.runOnServer,
response,
allowQueryStringCookies: opts.allowQueryStringCookies
});
}
throw new Meteor.Error(400, 'Can\'t use middleware when `runOnServer` is false.');
};
/**
* @locus Anywhere
* @class Cookies
* @param opts {Object}
* @param opts.TTL {Number} - Default cookies expiration time (max-age) in milliseconds, by default - session (false)
* @param opts.auto {Boolean} - [Server] Auto-bind in middleware as `req.Cookies`, by default `true`
* @param opts.handler {Function} - [Server] Middleware handler
* @param opts.runOnServer {Boolean} - Expose Cookies class to Server
* @param opts.allowQueryStringCookies {Boolean} - Allow passing Cookies in a query string (in URL). Primary should be used only in Cordova environment
* @param opts.allowedCordovaOrigins {Regex|Boolean} - [Server] Allow setting Cookies from that specific origin which in Meteor/Cordova is localhost:12XXX (^http://localhost:12[0-9]{3}$)
* @summary Main Cookie class
*/
class Cookies extends __cookies {
constructor(opts = {}) {
opts.TTL = helpers.isNumber(opts.TTL) ? opts.TTL : false;
opts.runOnServer = (opts.runOnServer !== false) ? true : false;
opts.allowQueryStringCookies = (opts.allowQueryStringCookies !== true) ? false : true;
if (Meteor.isClient) {
opts._cookies = document.cookie;
super(opts);
} else {
opts._cookies = {};
super(opts);
opts.auto = (opts.auto !== false) ? true : false;
this.opts = opts;
this.handler = helpers.isFunction(opts.handler) ? opts.handler : false;
this.onCookies = helpers.isFunction(opts.onCookies) ? opts.onCookies : false;
if (opts.runOnServer && !Cookies.isLoadedOnServer) {
Cookies.isLoadedOnServer = true;
if (opts.auto) {
WebApp.connectHandlers.use((req, res, next) => {
if (urlRE.test(req._parsedUrl.path)) {
const matchedCordovaOrigin = !!req.headers.origin
&& this.allowedCordovaOrigins
&& this.allowedCordovaOrigins.test(req.headers.origin);
const matchedOrigin = matchedCordovaOrigin
|| (!!req.headers.origin && this.originRE.test(req.headers.origin));
if (matchedOrigin) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
const cookiesArray = [];
let cookiesObject = {};
if (matchedCordovaOrigin && opts.allowQueryStringCookies && req.query.___cookies___) {
cookiesObject = parse(decodeURIComponent(req.query.___cookies___));
} else if (req.headers.cookie) {
cookiesObject = parse(req.headers.cookie);
}
const cookiesKeys = Object.keys(cookiesObject);
if (cookiesKeys.length) {
for (let i = 0; i < cookiesKeys.length; i++) {
const { cookieString } = serialize(cookiesKeys[i], cookiesObject[cookiesKeys[i]]);
if (!cookiesArray.includes(cookieString)) {
cookiesArray.push(cookieString);
}
}
if (cookiesArray.length) {
res.setHeader('Set-Cookie', cookiesArray);
}
}
helpers.isFunction(this.onCookies) && this.onCookies(__middlewareHandler(req, res, opts));
res.writeHead(200);
res.end('');
} else {
req.Cookies = __middlewareHandler(req, res, opts);
helpers.isFunction(this.handler) && this.handler(req.Cookies);
next();
}
});
}
}
}
}
/**
* @locus Server
* @memberOf Cookies
* @name middleware
* @summary Get Cookies instance into callback
* @returns {void}
*/
middleware() {
if (!Meteor.isServer) {
throw new Meteor.Error(500, '[ostrio:cookies] Can\'t use `.middleware()` on Client, it\'s Server only!');
}
return (req, res, next) => {
helpers.isFunction(this.handler) && this.handler(__middlewareHandler(req, res, this.opts));
next();
};
}
}
if (Meteor.isServer) {
Cookies.isLoadedOnServer = false;
}
/* Export the Cookies class */
export { Cookies };