@eggjs/cookies 3.1.0 → 4.0.0-beta.14

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,336 +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
- const shouldIgnoreSecureError = opts && opts.ignoreSecureError;
127
- value = value || '';
128
- if (!shouldIgnoreSecureError) {
129
- if (!this.secure && opts.secure) {
130
- throw new CookieError('Cannot send secure cookie over unencrypted connection');
131
- }
132
- }
133
-
134
- let headers: string[] = this.ctx.response.get('set-cookie') || [];
135
- if (!Array.isArray(headers)) {
136
- headers = [ headers ];
137
- }
138
-
139
- // encrypt
140
- if (opts.encrypt) {
141
- value = value && base64encode(this.keys.encrypt(value), true);
142
- }
143
-
144
- // http://browsercookielimits.squawky.net/
145
- if (value.length > 4093) {
146
- this.app.emit('cookieLimitExceed', { name, value, ctx: this.ctx });
147
- }
148
-
149
- // https://github.com/linsight/should-send-same-site-none
150
- // fixed SameSite=None: Known Incompatible Clients
151
- const userAgent: string | undefined = this.ctx.get('user-agent');
152
- let isSameSiteNone = false;
153
- // disable autoChips if partitioned enable
154
- let autoChips = !opts.partitioned && this.#autoChips;
155
- if (opts.sameSite && typeof opts.sameSite === 'string' && opts.sameSite.toLowerCase() === 'none') {
156
- isSameSiteNone = true;
157
- if (opts.secure === false || !this.secure || (userAgent && !this.isSameSiteNoneCompatible(userAgent))) {
158
- // Non-secure context or Incompatible clients, don't send SameSite=None property
159
- opts.sameSite = false;
160
- isSameSiteNone = false;
161
- }
162
- }
163
- if (autoChips || opts.partitioned) {
164
- // allow to set partitioned: secure=true and sameSite=none and chrome >= 118
165
- if (!isSameSiteNone || opts.secure === false || !this.secure || (userAgent && !this.isPartitionedCompatible(userAgent))) {
166
- // Non-secure context or Incompatible clients, don't send partitioned property
167
- autoChips = false;
168
- opts.partitioned = false;
169
- }
170
- }
171
-
172
- // remove unpartitioned same name cookie first
173
- if (opts.partitioned && opts.removeUnpartitioned) {
174
- const overwrite = opts.overwrite;
175
- if (overwrite) {
176
- opts.overwrite = false;
177
- headers = ignoreCookiesByName(headers, name);
178
- }
179
- const removeCookieOpts = {
180
- ...opts,
181
- partitioned: false,
182
- };
183
- const removeUnpartitionedCookie = new Cookie(name, '', removeCookieOpts);
184
- // if user not set secure, reset secure to ctx.secure
185
- if (opts.secure === undefined) {
186
- removeUnpartitionedCookie.attrs.secure = this.secure;
187
- }
188
-
189
- headers = pushCookie(headers, removeUnpartitionedCookie);
190
- // signed
191
- if (signed) {
192
- removeUnpartitionedCookie.name += '.sig';
193
- headers = ignoreCookiesByNameAndPath(headers,
194
- removeUnpartitionedCookie.name, removeUnpartitionedCookie.attrs.path);
195
- headers = pushCookie(headers, removeUnpartitionedCookie);
196
- }
197
- } else if (autoChips) {
198
- // add _CHIPS-${name} prefix cookie
199
- const newCookieName = this.#formatChipsCookieName(name);
200
- const newCookieOpts = {
201
- ...opts,
202
- partitioned: true,
203
- };
204
- const newPartitionedCookie = new Cookie(newCookieName, value, newCookieOpts);
205
- // if user not set secure, reset secure to ctx.secure
206
- if (opts.secure === undefined) newPartitionedCookie.attrs.secure = this.secure;
207
-
208
- headers = pushCookie(headers, newPartitionedCookie);
209
- // signed
210
- if (signed) {
211
- newPartitionedCookie.value = value && this.keys.sign(newPartitionedCookie.toString());
212
- newPartitionedCookie.name += '.sig';
213
- headers = ignoreCookiesByNameAndPath(headers,
214
- newPartitionedCookie.name, newPartitionedCookie.attrs.path);
215
- headers = pushCookie(headers, newPartitionedCookie);
216
- }
217
- }
218
-
219
- const cookie = new Cookie(name, value, opts);
220
- // if user not set secure, reset secure to ctx.secure
221
- if (opts.secure === undefined) {
222
- cookie.attrs.secure = this.secure;
223
- }
224
- headers = pushCookie(headers, cookie);
225
-
226
- // signed
227
- if (signed) {
228
- cookie.value = value && this.keys.sign(cookie.toString());
229
- cookie.name += '.sig';
230
- headers = pushCookie(headers, cookie);
231
- }
232
-
233
- this.ctx.set('set-cookie', headers);
234
- return this;
235
- }
236
-
237
- #formatChipsCookieName(name: string) {
238
- return `_CHIPS-${name}`;
239
- }
240
-
241
- #parseChromiumAndMajorVersion(userAgent: string) {
242
- if (!this.#parseChromiumResult) {
243
- this.#parseChromiumResult = parseChromiumAndMajorVersion(userAgent);
244
- }
245
- return this.#parseChromiumResult;
246
- }
247
-
248
- isSameSiteNoneCompatible(userAgent: string) {
249
- // Chrome >= 80.0.0.0
250
- const result = this.#parseChromiumAndMajorVersion(userAgent);
251
- if (result.chromium) {
252
- return result.majorVersion >= 80;
253
- }
254
- return isSameSiteNoneCompatible(userAgent);
255
- }
256
-
257
- isPartitionedCompatible(userAgent: string) {
258
- // support: Chrome >= 114.0.0.0
259
- // default enable: Chrome >= 118.0.0.0
260
- // https://developers.google.com/privacy-sandbox/3pcd/chips
261
- const result = this.#parseChromiumAndMajorVersion(userAgent);
262
- if (result.chromium) {
263
- return result.majorVersion >= 118;
264
- }
265
- return false;
266
- }
267
- }
268
-
269
- interface ParseChromiumResult {
270
- chromium: boolean;
271
- majorVersion: number;
272
- }
273
-
274
- // https://github.com/linsight/should-send-same-site-none/blob/master/index.js#L86
275
- function parseChromiumAndMajorVersion(userAgent: string): ParseChromiumResult {
276
- const m = /Chrom[^ /]{1,100}\/(\d{1,100}?)\./.exec(userAgent);
277
- if (!m) {
278
- return { chromium: false, majorVersion: 0 };
279
- }
280
- // Extract digits from first capturing group.
281
- return { chromium: true, majorVersion: parseInt(m[1]) };
282
- }
283
-
284
- const _patternCache = new Map<string, RegExp>();
285
- function getPattern(name: string) {
286
- const cache = _patternCache.get(name);
287
- if (cache) {
288
- return cache;
289
- }
290
- const reg = new RegExp(
291
- '(?:^|;) *' +
292
- name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +
293
- '=([^;]*)',
294
- );
295
- _patternCache.set(name, reg);
296
- return reg;
297
- }
298
-
299
- function computeSigned(opts: { encrypt?: boolean; signed?: boolean | number }) {
300
- // encrypt default to false, signed default to true.
301
- // disable singed when encrypt is true.
302
- if (opts.encrypt) return false;
303
- return opts.signed !== false;
304
- }
305
-
306
- function pushCookie(cookies: string[], cookie: Cookie) {
307
- if (cookie.attrs.overwrite) {
308
- cookies = ignoreCookiesByName(cookies, cookie.name);
309
- }
310
- cookies.push(cookie.toHeader());
311
- return cookies;
312
- }
313
-
314
- function ignoreCookiesByName(cookies: string[], name: string) {
315
- const prefix = `${name}=`;
316
- return cookies.filter(c => !c.startsWith(prefix));
317
- }
318
-
319
- function ignoreCookiesByNameAndPath(cookies: string[], name: string, path: string | null | undefined) {
320
- if (!path) {
321
- return ignoreCookiesByName(cookies, name);
322
- }
323
- const prefix = `${name}=`;
324
- // foo=hello; path=/path1; samesite=none
325
- const includedPath = `; path=${path};`;
326
- // foo=hello; path=/path1
327
- const endsWithPath = `; path=${path}`;
328
- return cookies.filter(c => {
329
- if (c.startsWith(prefix)) {
330
- if (c.includes(includedPath) || c.endsWith(endsWithPath)) {
331
- return false;
332
- }
333
- }
334
- return true;
335
- });
336
- }
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
- }