@eggjs/cookies 3.0.1 → 4.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cookies.ts DELETED
@@ -1,333 +0,0 @@
1
- import assert from 'node:assert';
2
- import { base64decode, base64encode } from 'utility';
3
- import { isSameSiteNoneCompatible } from 'should-send-same-site-none';
4
- import { Keygrip } from './keygrip.js';
5
- import { Cookie, CookieSetOptions } from './cookie.js';
6
- import { CookieError } from './error.js';
7
-
8
- const keyCache = new Map<string[], Keygrip>();
9
-
10
- export interface DefaultCookieOptions extends CookieSetOptions {
11
- /**
12
- * Auto get and set `_CHIPS-` prefix cookie to adaptation CHIPS mode (The default value is false).
13
- */
14
- autoChips?: boolean;
15
- }
16
-
17
- export interface CookieGetOptions {
18
- /**
19
- * Whether to sign or not (The default value is true).
20
- */
21
- signed?: boolean;
22
- /**
23
- * Encrypt the cookie's value or not (The default value is false).
24
- */
25
- encrypt?: boolean;
26
- }
27
-
28
- /**
29
- * cookies for egg
30
- * extend pillarjs/cookies, add encrypt and decrypt
31
- */
32
- export class Cookies {
33
- readonly #keysArray: string[];
34
- #keys: Keygrip;
35
- readonly #defaultCookieOptions?: DefaultCookieOptions;
36
- readonly #autoChips?: boolean;
37
- readonly ctx: Record<string, any>;
38
- readonly app: Record<string, any>;
39
- readonly secure: boolean;
40
- #parseChromiumResult?: ParseChromiumResult;
41
-
42
- constructor(ctx: Record<string, any>, keys: string[], defaultCookieOptions?: DefaultCookieOptions) {
43
- this.#keysArray = keys;
44
- // default cookie options
45
- this.#defaultCookieOptions = defaultCookieOptions;
46
- this.#autoChips = defaultCookieOptions?.autoChips;
47
- this.ctx = ctx;
48
- this.secure = this.ctx.secure;
49
- this.app = ctx.app;
50
- }
51
-
52
- get keys() {
53
- if (!this.#keys) {
54
- assert(Array.isArray(this.#keysArray), '.keys required for encrypt/sign cookies');
55
- const cache = keyCache.get(this.#keysArray);
56
- if (cache) {
57
- this.#keys = cache;
58
- } else {
59
- this.#keys = new Keygrip(this.#keysArray);
60
- keyCache.set(this.#keysArray, this.#keys);
61
- }
62
- }
63
- return this.#keys;
64
- }
65
-
66
- /**
67
- * get cookie value by name
68
- * @param {String} name - cookie's name
69
- * @param {Object} opts - cookies' options
70
- * - {Boolean} signed - default to true
71
- * - {Boolean} encrypt - default to false
72
- * @return {String} value - cookie's value
73
- */
74
- get(name: string, opts: CookieGetOptions = {}): string | undefined {
75
- let value = this._get(name, opts);
76
- if (value === undefined && this.#autoChips) {
77
- // try to read _CHIPS-${name} prefix cookie
78
- value = this._get(this.#formatChipsCookieName(name), opts);
79
- }
80
- return value;
81
- }
82
-
83
- _get(name: string, opts: CookieGetOptions) {
84
- const signed = computeSigned(opts);
85
- const header: string = this.ctx.get('cookie');
86
- if (!header) return;
87
-
88
- const match = header.match(getPattern(name));
89
- if (!match) return;
90
-
91
- let value = match[1];
92
- if (!opts.encrypt && !signed) return value;
93
-
94
- // signed
95
- if (signed) {
96
- const sigName = name + '.sig';
97
- const sigValue = this.get(sigName, { signed: false });
98
- if (!sigValue) return;
99
-
100
- const raw = name + '=' + value;
101
- const index = this.keys.verify(raw, sigValue);
102
- if (index < 0) {
103
- // can not match any key, remove ${name}.sig
104
- this.set(sigName, null, { path: '/', signed: false, overwrite: true });
105
- return;
106
- }
107
- if (index > 0) {
108
- // not signed by the first key, update sigValue
109
- this.set(sigName, this.keys.sign(raw), { signed: false, overwrite: true });
110
- }
111
- return value;
112
- }
113
-
114
- // encrypt
115
- value = base64decode(value, true, 'buffer') as string;
116
- const res = this.keys.decrypt(value);
117
- return res ? res.value.toString() : undefined;
118
- }
119
-
120
- set(name: string, value: string | null, opts?: CookieSetOptions) {
121
- opts = {
122
- ...this.#defaultCookieOptions,
123
- ...opts,
124
- };
125
- const signed = computeSigned(opts);
126
- value = value || '';
127
- if (!this.secure && opts.secure) {
128
- throw new CookieError('Cannot send secure cookie over unencrypted connection');
129
- }
130
-
131
- let headers: string[] = this.ctx.response.get('set-cookie') || [];
132
- if (!Array.isArray(headers)) {
133
- headers = [ headers ];
134
- }
135
-
136
- // encrypt
137
- if (opts.encrypt) {
138
- value = value && base64encode(this.keys.encrypt(value), true);
139
- }
140
-
141
- // http://browsercookielimits.squawky.net/
142
- if (value.length > 4093) {
143
- this.app.emit('cookieLimitExceed', { name, value, ctx: this.ctx });
144
- }
145
-
146
- // https://github.com/linsight/should-send-same-site-none
147
- // fixed SameSite=None: Known Incompatible Clients
148
- const userAgent: string | undefined = this.ctx.get('user-agent');
149
- let isSameSiteNone = false;
150
- // disable autoChips if partitioned enable
151
- let autoChips = !opts.partitioned && this.#autoChips;
152
- if (opts.sameSite && typeof opts.sameSite === 'string' && opts.sameSite.toLowerCase() === 'none') {
153
- isSameSiteNone = true;
154
- if (opts.secure === false || !this.secure || (userAgent && !this.isSameSiteNoneCompatible(userAgent))) {
155
- // Non-secure context or Incompatible clients, don't send SameSite=None property
156
- opts.sameSite = false;
157
- isSameSiteNone = false;
158
- }
159
- }
160
- if (autoChips || opts.partitioned) {
161
- // allow to set partitioned: secure=true and sameSite=none and chrome >= 118
162
- if (!isSameSiteNone || opts.secure === false || !this.secure || (userAgent && !this.isPartitionedCompatible(userAgent))) {
163
- // Non-secure context or Incompatible clients, don't send partitioned property
164
- autoChips = false;
165
- opts.partitioned = false;
166
- }
167
- }
168
-
169
- // remove unpartitioned same name cookie first
170
- if (opts.partitioned && opts.removeUnpartitioned) {
171
- const overwrite = opts.overwrite;
172
- if (overwrite) {
173
- opts.overwrite = false;
174
- headers = ignoreCookiesByName(headers, name);
175
- }
176
- const removeCookieOpts = {
177
- ...opts,
178
- partitioned: false,
179
- };
180
- const removeUnpartitionedCookie = new Cookie(name, '', removeCookieOpts);
181
- // if user not set secure, reset secure to ctx.secure
182
- if (opts.secure === undefined) {
183
- removeUnpartitionedCookie.attrs.secure = this.secure;
184
- }
185
-
186
- headers = pushCookie(headers, removeUnpartitionedCookie);
187
- // signed
188
- if (signed) {
189
- removeUnpartitionedCookie.name += '.sig';
190
- headers = ignoreCookiesByNameAndPath(headers,
191
- removeUnpartitionedCookie.name, removeUnpartitionedCookie.attrs.path);
192
- headers = pushCookie(headers, removeUnpartitionedCookie);
193
- }
194
- } else if (autoChips) {
195
- // add _CHIPS-${name} prefix cookie
196
- const newCookieName = this.#formatChipsCookieName(name);
197
- const newCookieOpts = {
198
- ...opts,
199
- partitioned: true,
200
- };
201
- const newPartitionedCookie = new Cookie(newCookieName, value, newCookieOpts);
202
- // if user not set secure, reset secure to ctx.secure
203
- if (opts.secure === undefined) newPartitionedCookie.attrs.secure = this.secure;
204
-
205
- headers = pushCookie(headers, newPartitionedCookie);
206
- // signed
207
- if (signed) {
208
- newPartitionedCookie.value = value && this.keys.sign(newPartitionedCookie.toString());
209
- newPartitionedCookie.name += '.sig';
210
- headers = ignoreCookiesByNameAndPath(headers,
211
- newPartitionedCookie.name, newPartitionedCookie.attrs.path);
212
- headers = pushCookie(headers, newPartitionedCookie);
213
- }
214
- }
215
-
216
- const cookie = new Cookie(name, value, opts);
217
- // if user not set secure, reset secure to ctx.secure
218
- if (opts.secure === undefined) {
219
- cookie.attrs.secure = this.secure;
220
- }
221
- headers = pushCookie(headers, cookie);
222
-
223
- // signed
224
- if (signed) {
225
- cookie.value = value && this.keys.sign(cookie.toString());
226
- cookie.name += '.sig';
227
- headers = pushCookie(headers, cookie);
228
- }
229
-
230
- this.ctx.set('set-cookie', headers);
231
- return this;
232
- }
233
-
234
- #formatChipsCookieName(name: string) {
235
- return `_CHIPS-${name}`;
236
- }
237
-
238
- #parseChromiumAndMajorVersion(userAgent: string) {
239
- if (!this.#parseChromiumResult) {
240
- this.#parseChromiumResult = parseChromiumAndMajorVersion(userAgent);
241
- }
242
- return this.#parseChromiumResult;
243
- }
244
-
245
- isSameSiteNoneCompatible(userAgent: string) {
246
- // Chrome >= 80.0.0.0
247
- const result = this.#parseChromiumAndMajorVersion(userAgent);
248
- if (result.chromium) {
249
- return result.majorVersion >= 80;
250
- }
251
- return isSameSiteNoneCompatible(userAgent);
252
- }
253
-
254
- isPartitionedCompatible(userAgent: string) {
255
- // support: Chrome >= 114.0.0.0
256
- // default enable: Chrome >= 118.0.0.0
257
- // https://developers.google.com/privacy-sandbox/3pcd/chips
258
- const result = this.#parseChromiumAndMajorVersion(userAgent);
259
- if (result.chromium) {
260
- return result.majorVersion >= 118;
261
- }
262
- return false;
263
- }
264
- }
265
-
266
- interface ParseChromiumResult {
267
- chromium: boolean;
268
- majorVersion: number;
269
- }
270
-
271
- // https://github.com/linsight/should-send-same-site-none/blob/master/index.js#L86
272
- function parseChromiumAndMajorVersion(userAgent: string): ParseChromiumResult {
273
- const m = /Chrom[^ /]{1,100}\/(\d{1,100}?)\./.exec(userAgent);
274
- if (!m) {
275
- return { chromium: false, majorVersion: 0 };
276
- }
277
- // Extract digits from first capturing group.
278
- return { chromium: true, majorVersion: parseInt(m[1]) };
279
- }
280
-
281
- const _patternCache = new Map<string, RegExp>();
282
- function getPattern(name: string) {
283
- const cache = _patternCache.get(name);
284
- if (cache) {
285
- return cache;
286
- }
287
- const reg = new RegExp(
288
- '(?:^|;) *' +
289
- name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +
290
- '=([^;]*)',
291
- );
292
- _patternCache.set(name, reg);
293
- return reg;
294
- }
295
-
296
- function computeSigned(opts: { encrypt?: boolean; signed?: boolean | number }) {
297
- // encrypt default to false, signed default to true.
298
- // disable singed when encrypt is true.
299
- if (opts.encrypt) return false;
300
- return opts.signed !== false;
301
- }
302
-
303
- function pushCookie(cookies: string[], cookie: Cookie) {
304
- if (cookie.attrs.overwrite) {
305
- cookies = ignoreCookiesByName(cookies, cookie.name);
306
- }
307
- cookies.push(cookie.toHeader());
308
- return cookies;
309
- }
310
-
311
- function ignoreCookiesByName(cookies: string[], name: string) {
312
- const prefix = `${name}=`;
313
- return cookies.filter(c => !c.startsWith(prefix));
314
- }
315
-
316
- function ignoreCookiesByNameAndPath(cookies: string[], name: string, path: string | null | undefined) {
317
- if (!path) {
318
- return ignoreCookiesByName(cookies, name);
319
- }
320
- const prefix = `${name}=`;
321
- // foo=hello; path=/path1; samesite=none
322
- const includedPath = `; path=${path};`;
323
- // foo=hello; path=/path1
324
- const endsWithPath = `; path=${path}`;
325
- return cookies.filter(c => {
326
- if (c.startsWith(prefix)) {
327
- if (c.includes(includedPath) || c.endsWith(endsWithPath)) {
328
- return false;
329
- }
330
- }
331
- return true;
332
- });
333
- }
package/src/error.ts DELETED
@@ -1,6 +0,0 @@
1
- export class CookieError extends Error {
2
- constructor(message: string, options?: ErrorOptions) {
3
- super(message, options);
4
- this.name = this.constructor.name;
5
- }
6
- }
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from './cookies.js';
2
- export * from './cookie.js';
3
- export * from './error.js';
4
- export * from './keygrip.js';
package/src/keygrip.ts DELETED
@@ -1,129 +0,0 @@
1
- import { debuglog } from 'node:util';
2
- import crypto, { type Cipher } from 'node:crypto';
3
- import assert from 'node:assert';
4
-
5
- const debug = debuglog('@eggjs/cookies:keygrip');
6
-
7
- const KEY_LEN = 32;
8
- const IV_SIZE = 16;
9
- const passwordCache = new Map();
10
-
11
- const replacer: Record<string, string> = {
12
- '/': '_',
13
- '+': '-',
14
- '=': '',
15
- };
16
-
17
- function constantTimeCompare(a: Buffer, b: Buffer) {
18
- if (a.length !== b.length) {
19
- return false;
20
- }
21
- return crypto.timingSafeEqual(a, b);
22
- }
23
-
24
- // patch from https://github.com/crypto-utils/keygrip
25
-
26
- export class Keygrip {
27
- readonly #keys: string[];
28
- readonly #hash = 'sha256';
29
- readonly #cipher = 'aes-256-cbc';
30
-
31
- constructor(keys: string[]) {
32
- assert(Array.isArray(keys) && keys.length > 0, 'keys must be provided and should be an array');
33
- this.#keys = keys;
34
- }
35
-
36
- // encrypt a message
37
- encrypt(data: string, key?: string) {
38
- key = key || this.#keys[0];
39
- const password = keyToPassword(key);
40
- const cipher = crypto.createCipheriv(this.#cipher, password.key, password.iv);
41
- return crypt(cipher, data);
42
- }
43
-
44
- // decrypt a single message
45
- // returns false on bad decrypts
46
- decrypt(data: string | Buffer): { value: Buffer, index: number } | false {
47
- // decrypt every key
48
- const keys = this.#keys;
49
- for (let i = 0; i < keys.length; i++) {
50
- const value = this.#decryptByKey(data, keys[i]);
51
- if (value !== false) {
52
- return { value, index: i };
53
- }
54
- }
55
- return false;
56
- }
57
-
58
- #decryptByKey(data: string | Buffer, key: string) {
59
- try {
60
- const password = keyToPassword(key);
61
- const cipher = crypto.createDecipheriv(this.#cipher, password.key, password.iv);
62
- return crypt(cipher, data);
63
- } catch (err: any) {
64
- debug('crypt error: %s', err);
65
- return false;
66
- }
67
- }
68
-
69
- sign(data: string | Buffer, key?: string) {
70
- // default to the first key
71
- key = key || this.#keys[0];
72
-
73
- // url safe base64
74
- return crypto
75
- .createHmac(this.#hash, key)
76
- .update(data)
77
- .digest('base64')
78
- .replace(/\/|\+|=/g, x => {
79
- return replacer[x];
80
- });
81
- }
82
-
83
- verify(data: string, digest: string) {
84
- const keys = this.#keys;
85
- for (let i = 0; i < keys.length; i++) {
86
- const key = keys[i];
87
- if (constantTimeCompare(Buffer.from(digest), Buffer.from(this.sign(data, key)))) {
88
- debug('data %s match key %s, index: %d', data, key, i);
89
- return i;
90
- }
91
- }
92
- return -1;
93
- }
94
- }
95
-
96
- function crypt(cipher: Cipher, data: string | Buffer) {
97
- const text = Buffer.isBuffer(data) ? cipher.update(data) : cipher.update(data, 'utf-8');
98
- const pad = cipher.final();
99
- return Buffer.concat([ text, pad ]);
100
- }
101
-
102
- function keyToPassword(key: string) {
103
- if (passwordCache.has(key)) {
104
- return passwordCache.get(key);
105
- }
106
-
107
- // Simulate EVP_BytesToKey.
108
- // see https://github.com/nodejs/help/issues/1673#issuecomment-503222925
109
- const bytes = Buffer.alloc(KEY_LEN + IV_SIZE);
110
- let lastHash = null,
111
- nBytes = 0;
112
- while (nBytes < bytes.length) {
113
- const hash = crypto.createHash('md5');
114
- if (lastHash) hash.update(lastHash);
115
- hash.update(key);
116
- lastHash = hash.digest();
117
- lastHash.copy(bytes, nBytes);
118
- nBytes += lastHash.length;
119
- }
120
-
121
- // Use these for decryption.
122
- const password = {
123
- key: bytes.subarray(0, KEY_LEN),
124
- iv: bytes.subarray(KEY_LEN, bytes.length),
125
- };
126
-
127
- passwordCache.set(key, password);
128
- return password;
129
- }