/
cookies.js
278 lines (243 loc) · 8.86 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
'use strict';
const assert = require('assert');
const utility = require('utility');
const _isSameSiteNoneCompatible = require('should-send-same-site-none').isSameSiteNoneCompatible;
const Keygrip = require('./keygrip');
const Cookie = require('./cookie');
const CookieError = require('./error');
const KEYS_ARRAY = Symbol('eggCookies:keysArray');
const KEYS = Symbol('eggCookies:keys');
const PARSED_UA = Symbol('eggCookies:parsedUA');
const keyCache = new Map();
/**
* cookies for egg
* extend pillarjs/cookies, add encrypt and decrypt
*/
class Cookies {
constructor(ctx, keys, defaultCookieOptions) {
this[KEYS_ARRAY] = keys;
this._keys = keys;
// default cookie options
this._defaultCookieOptions = defaultCookieOptions;
this._autoChips = defaultCookieOptions && defaultCookieOptions.autoChips;
this.ctx = ctx;
this.secure = this.ctx.secure;
this.app = ctx.app;
}
get keys() {
if (!this[KEYS]) {
const keysArray = this[KEYS_ARRAY];
assert(Array.isArray(keysArray), '.keys required for encrypt/sign cookies');
const cache = keyCache.get(keysArray);
if (cache) {
this[KEYS] = cache;
} else {
this[KEYS] = new Keygrip(this[KEYS_ARRAY]);
keyCache.set(keysArray, this[KEYS]);
}
}
return this[KEYS];
}
/**
* get cookie value by name
* @param {String} name - cookie's name
* @param {Object} opts - cookies' options
* - {Boolean} signed - default to true
* - {Boolean} encrypt - default to false
* @return {String} value - cookie's value
*/
get(name, opts) {
opts = opts || {};
let value = this._get(name, opts);
if (value === undefined && this._autoChips) {
// try to read _CHIPS-${name} prefix cookie
value = this._get(this._formatChipsCookieName(name), opts);
}
return value;
}
_get(name, opts) {
const signed = computeSigned(opts);
const header = this.ctx.get('cookie');
if (!header) return;
const match = header.match(getPattern(name));
if (!match) return;
let value = match[1];
if (!opts.encrypt && !signed) return value;
// signed
if (signed) {
const sigName = name + '.sig';
const sigValue = this.get(sigName, { signed: false });
if (!sigValue) return;
const raw = name + '=' + value;
const index = this.keys.verify(raw, sigValue);
if (index < 0) {
// can not match any key, remove ${name}.sig
this.set(sigName, null, { path: '/', signed: false, overwrite: true });
return;
}
if (index > 0) {
// not signed by the first key, update sigValue
this.set(sigName, this.keys.sign(raw), { signed: false, overwrite: true });
}
return value;
}
// encrypt
value = utility.base64decode(value, true, 'buffer');
const res = this.keys.decrypt(value);
return res ? res.value.toString() : undefined;
}
set(name, value, opts) {
opts = Object.assign({}, this._defaultCookieOptions, opts);
if (this._autoChips) {
opts.partitioned = false;
opts.removeUnpartitioned = false;
}
const signed = computeSigned(opts);
value = value || '';
if (!this.secure && opts.secure) {
throw new CookieError('Cannot send secure cookie over unencrypted connection');
}
let headers = this.ctx.response.get('set-cookie') || [];
if (!Array.isArray(headers)) headers = [ headers ];
// encrypt
if (opts.encrypt) {
value = value && utility.base64encode(this.keys.encrypt(value), true);
}
// http://browsercookielimits.squawky.net/
if (value.length > 4093) {
this.app.emit('cookieLimitExceed', { name, value, ctx: this.ctx });
}
// https://github.com/linsight/should-send-same-site-none
// fixed SameSite=None: Known Incompatible Clients
const userAgent = this.ctx.get('user-agent');
let isSameSiteNone = false;
let autoChips = this._autoChips;
if (opts.sameSite && typeof opts.sameSite === 'string' && opts.sameSite.toLowerCase() === 'none') {
isSameSiteNone = true;
if (opts.secure === false || !this.secure || (userAgent && !this.isSameSiteNoneCompatible(userAgent))) {
// Non-secure context or Incompatible clients, don't send SameSite=None property
opts.sameSite = false;
isSameSiteNone = false;
}
}
if (autoChips || opts.partitioned) {
// allow to set partitioned: secure=true and sameSite=none and chrome >= 118
if (!isSameSiteNone || opts.secure === false || !this.secure || (userAgent && !this.isPartitionedCompatible(userAgent))) {
// Non-secure context or Incompatible clients, don't send partitioned property
autoChips = false;
opts.partitioned = false;
}
}
// remove unpartitioned same name cookie first
if (opts.partitioned && opts.removeUnpartitioned) {
const overwrite = opts.overwrite;
if (overwrite) {
opts.overwrite = false;
headers = ignoreCookiesByName(headers, name);
}
const removeCookieOpts = Object.assign({}, opts, {
partitioned: false,
});
const removeUnpartitionedCookie = new Cookie(name, '', removeCookieOpts);
// if user not set secure, reset secure to ctx.secure
if (opts.secure === undefined) removeUnpartitionedCookie.attrs.secure = this.secure;
headers = pushCookie(headers, removeUnpartitionedCookie);
// signed
if (signed) {
removeUnpartitionedCookie.name += '.sig';
headers = ignoreCookiesByName(headers, removeUnpartitionedCookie.name);
headers = pushCookie(headers, removeUnpartitionedCookie);
}
} else if (autoChips) {
// add _CHIPS-${name} prefix cookie
const newCookieName = this._formatChipsCookieName(name);
const newCookieOpts = Object.assign({}, opts, {
partitioned: true,
});
const newPartitionedCookie = new Cookie(newCookieName, value, newCookieOpts);
// if user not set secure, reset secure to ctx.secure
if (opts.secure === undefined) newPartitionedCookie.attrs.secure = this.secure;
headers = pushCookie(headers, newPartitionedCookie);
// signed
if (signed) {
newPartitionedCookie.value = value && this.keys.sign(newPartitionedCookie.toString());
newPartitionedCookie.name += '.sig';
headers = ignoreCookiesByName(headers, newPartitionedCookie.name);
headers = pushCookie(headers, newPartitionedCookie);
}
}
const cookie = new Cookie(name, value, opts);
// if user not set secure, reset secure to ctx.secure
if (opts.secure === undefined) cookie.attrs.secure = this.secure;
headers = pushCookie(headers, cookie);
// signed
if (signed) {
cookie.value = value && this.keys.sign(cookie.toString());
cookie.name += '.sig';
headers = pushCookie(headers, cookie);
}
this.ctx.set('set-cookie', headers);
return this;
}
_formatChipsCookieName(name) {
return `_CHIPS-${name}`;
}
_parseChromiumAndMajorVersion(userAgent) {
if (!this[PARSED_UA]) {
this[PARSED_UA] = parseChromiumAndMajorVersion(userAgent);
}
return this[PARSED_UA];
}
isSameSiteNoneCompatible(userAgent) {
// Chrome >= 80.0.0.0
const result = this._parseChromiumAndMajorVersion(userAgent);
if (result.chromium) return result.majorVersion >= 80;
return _isSameSiteNoneCompatible(userAgent);
}
isPartitionedCompatible(userAgent) {
// support: Chrome >= 114.0.0.0
// default enable: Chrome >= 118.0.0.0
// https://developers.google.com/privacy-sandbox/3pcd/chips
const result = this._parseChromiumAndMajorVersion(userAgent);
if (result.chromium) return result.majorVersion >= 118;
return false;
}
}
// https://github.com/linsight/should-send-same-site-none/blob/master/index.js#L86
function parseChromiumAndMajorVersion(userAgent) {
const m = /Chrom[^ \/]{1,100}\/(\d{1,100}?)\./.exec(userAgent);
if (!m) return { chromium: false, version: null };
// Extract digits from first capturing group.
return { chromium: true, majorVersion: parseInt(m[1]) };
}
const partternCache = new Map();
function getPattern(name) {
const cache = partternCache.get(name);
if (cache) return cache;
const reg = new RegExp(
'(?:^|;) *' +
name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +
'=([^;]*)'
);
partternCache.set(name, reg);
return reg;
}
function computeSigned(opts) {
// encrypt default to false, signed default to true.
// disable singed when encrypt is true.
if (opts.encrypt) return false;
return opts.signed !== false;
}
function pushCookie(cookies, cookie) {
if (cookie.attrs.overwrite) {
cookies = ignoreCookiesByName(cookies, cookie.name);
}
cookies.push(cookie.toHeader());
return cookies;
}
function ignoreCookiesByName(cookies, name) {
const prefix = `${name}=`;
return cookies.filter(c => !c.startsWith(prefix));
}
Cookies.CookieError = CookieError;
module.exports = Cookies;