@fastify/cookie 6.0.0 → 7.2.0

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.
@@ -1,49 +1,17 @@
1
1
  name: CI
2
- 'on':
2
+
3
+ on:
3
4
  push:
4
5
  paths-ignore:
5
- - docs/**
6
+ - 'docs/**'
6
7
  - '*.md'
7
8
  pull_request:
8
9
  paths-ignore:
9
- - docs/**
10
+ - 'docs/**'
10
11
  - '*.md'
12
+
11
13
  jobs:
12
14
  test:
13
- runs-on: ${{ matrix.os }}
14
- strategy:
15
- matrix:
16
- node-version:
17
- - 10
18
- - 12
19
- - 14
20
- - 16
21
- os:
22
- - macos-latest
23
- - ubuntu-latest
24
- - windows-latest
25
- steps:
26
- - uses: actions/checkout@v3
27
- - name: Use Node.js
28
- uses: actions/setup-node@v3
29
- with:
30
- node-version: ${{ matrix.node-version }}
31
- - name: Install Dependencies
32
- run: |
33
- npm install --ignore-scripts
34
- - name: Lint
35
- run: |
36
- npm run lint:ci
37
- - name: Run Tests
38
- run: |
39
- npm test
40
- automerge:
41
- needs: test
42
- runs-on: ubuntu-latest
43
- permissions:
44
- pull-requests: write
45
- contents: write
46
- steps:
47
- - uses: fastify/github-action-merge-dependabot@v3
48
- with:
49
- github-token: ${{ secrets.GITHUB_TOKEN }}
15
+ uses: fastify/workflows/.github/workflows/plugins-ci.yml@v3
16
+ with:
17
+ lint: true
package/README.md CHANGED
@@ -1,8 +1,7 @@
1
- # fastify-cookie
1
+ # @fastify/cookie
2
2
 
3
3
  ![CI](https://github.com/fastify/fastify-cookie/workflows/CI/badge.svg)
4
- [![NPM version](https://img.shields.io/npm/v/fastify-cookie.svg?style=flat)](https://www.npmjs.com/package/fastify-cookie)
5
- [![Known Vulnerabilities](https://snyk.io/test/github/fastify/fastify-cookie/badge.svg)](https://snyk.io/test/github/fastify/fastify-cookie)
4
+ [![NPM version](https://img.shields.io/npm/v/@fastify/cookie.svg?style=flat)](https://www.npmjs.com/package/@fastify/cookie)
6
5
  [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
7
6
 
8
7
  A plugin for [Fastify](http://fastify.io/) that adds support for reading and
@@ -12,16 +11,27 @@ This plugin's cookie parsing works via Fastify's `onRequest` hook. Therefore,
12
11
  you should register it prior to any other `onRequest` hooks that will depend
13
12
  upon this plugin's actions.
14
13
 
15
- `fastify-cookie` [v2.x](https://github.com/fastify/fastify-cookie/tree/v2.x)
14
+ `@fastify/cookie` [v2.x](https://github.com/fastify/fastify-cookie/tree/v2.x)
16
15
  supports both Fastify@1 and Fastify@2.
17
- `fastify-cookie` v3 only supports Fastify@2.
16
+ `@fastify/cookie` v3 only supports Fastify@2.
17
+
18
+ ## Installation
19
+ ```sh
20
+ npm i @fastify/cookie
21
+ ```
22
+
23
+ or
24
+
25
+ ```sh
26
+ yarn add @fastify/cookie
27
+ ```
18
28
 
19
29
  ## Example
20
30
 
21
31
  ```js
22
32
  const fastify = require('fastify')()
23
33
 
24
- fastify.register(require('fastify-cookie'), {
34
+ fastify.register(require('@fastify/cookie'), {
25
35
  secret: "my-secret", // for cookies signature
26
36
  parseOptions: {} // options for parsing cookies
27
37
  })
@@ -47,8 +57,8 @@ fastify.get('/', (req, reply) => {
47
57
  ## TypeScript Example
48
58
 
49
59
  ```ts
50
- import { FastifyCookieOptions } from 'fastify-cookie'
51
- import cookie from 'fastify-cookie'
60
+ import type { FastifyCookieOptions } from '@fastify/cookie'
61
+ import cookie from '@fastify/cookie'
52
62
  import fastify from 'fastify'
53
63
 
54
64
  const app = fastify()
@@ -126,7 +136,7 @@ Key rotation is when an encryption key is retired and replaced by generating a n
126
136
 
127
137
  **Example:**
128
138
  ```js
129
- fastify.register(require('fastify-cookie'), {
139
+ fastify.register(require('@fastify/cookie'), {
130
140
  secret: [key1, key2]
131
141
  })
132
142
  ```
@@ -161,7 +171,7 @@ The `secret` option optionally accepts an object with `sign` and `unsign` functi
161
171
 
162
172
  **Example:**
163
173
  ```js
164
- fastify.register(require('fastify-cookie'), {
174
+ fastify.register(require('@fastify/cookie'), {
165
175
  secret: {
166
176
  sign: (value) => {
167
177
  // sign using custom logic
@@ -188,10 +198,10 @@ the provided signer's (or the default signer if no custom implementation is prov
188
198
  **Example:**
189
199
 
190
200
  ```js
191
- fastify.register(require('fastify-cookie'), { secret: 'my-secret' })
201
+ fastify.register(require('@fastify/cookie'), { secret: 'my-secret' })
192
202
 
193
203
  fastify.get('/', (req, rep) => {
194
- if (fastify.unsign(req.cookie.foo).valid === false) {
204
+ if (fastify.unsignCookie(req.cookie.foo).valid === false) {
195
205
  rep.send('cookie is invalid')
196
206
  return
197
207
  }
@@ -200,6 +210,50 @@ fastify.get('/', (req, rep) => {
200
210
  })
201
211
  ```
202
212
 
213
+ ### Other cases of manual signing
214
+
215
+ Sometimes the service under test should only accept requests with signed cookies, but it does not generate them itself.
216
+
217
+ **Example:**
218
+
219
+ ```js
220
+
221
+ test('Request requires signed cookie', async () => {
222
+ const response = await app.inject({
223
+ method: 'GET',
224
+ url: '/',
225
+ headers: {
226
+ cookies : {
227
+ 'sid': app.signCookie(sidValue)
228
+ }
229
+ },
230
+ });
231
+
232
+ expect(response.statusCode).toBe(200);
233
+ });
234
+ ```
235
+
236
+ ### Manual signing/unsigning with low level utilities
237
+
238
+ with signerFactory
239
+
240
+ ```js
241
+ const { signerFactory } = require('@fastify/cookie');
242
+
243
+ const signer = signerFactory('secret');
244
+ const signedValue = signer.sign('test');
245
+ const {valid, renew, value } = signer.unsign(signedValue);
246
+ ```
247
+
248
+ with sign/unsign utilities
249
+
250
+ ```js
251
+ const { sign, unsign } = require('@fastify/cookie');
252
+
253
+ const signedValue = sign('test', 'secret');
254
+ const unsignedvalue = unsign(signedValue, 'secret');
255
+ ```
256
+
203
257
 
204
258
  ## License
205
259
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/cookie",
3
- "version": "6.0.0",
3
+ "version": "7.2.0",
4
4
  "description": "Plugin for fastify to add support for cookies",
5
5
  "main": "plugin.js",
6
6
  "types": "plugin.d.ts",
@@ -39,17 +39,18 @@
39
39
  },
40
40
  "homepage": "https://github.com/fastify/fastify-cookie#readme",
41
41
  "devDependencies": {
42
- "@types/node": "^17.0.16",
43
- "fastify": "^3.27.1",
42
+ "@types/node": "^18.0.0",
43
+ "fastify": "^4.0.0-rc.2",
44
44
  "pre-commit": "^1.2.2",
45
- "sinon": "^13.0.1",
45
+ "sinon": "^14.0.0",
46
46
  "snazzy": "^9.0.0",
47
47
  "standard": "^17.0.0",
48
48
  "tap": "^16.0.0",
49
- "tsd": "^0.20.0",
49
+ "tsd": "^0.22.0",
50
50
  "typescript": "^4.5.5"
51
51
  },
52
52
  "dependencies": {
53
+ "cookie": "^0.5.0",
53
54
  "cookie-signature": "^1.1.0",
54
55
  "fastify-plugin": "^3.0.1"
55
56
  },
package/plugin.d.ts CHANGED
@@ -21,13 +21,19 @@ declare module 'fastify' {
21
21
  parseCookie(cookieHeader: string): {
22
22
  [key: string]: string;
23
23
  };
24
+ /**
25
+ * Manual cookie signing method
26
+ * @docs https://github.com/fastify/fastify-cookie#manual-cookie-parsing
27
+ * @param value cookie value
28
+ */
29
+ signCookie(value: string): string;
24
30
  }
25
31
 
26
32
  interface FastifyRequest {
27
33
  /**
28
34
  * Request cookies
29
35
  */
30
- cookies: { [cookieName: string]: string };
36
+ cookies: { [cookieName: string]: string | undefined };
31
37
 
32
38
  /**
33
39
  * Unsigns the specified cookie using the secret provided.
@@ -91,6 +97,7 @@ export interface CookieSerializeOptions {
91
97
  httpOnly?: boolean;
92
98
  maxAge?: number;
93
99
  path?: string;
100
+ priority?: 'low' | 'medium' | 'high';
94
101
  sameSite?: boolean | 'lax' | 'strict' | 'none';
95
102
  secure?: boolean;
96
103
  signed?: boolean;
@@ -105,6 +112,10 @@ interface Signer {
105
112
  };
106
113
  }
107
114
 
115
+ declare const signerFactory: Signer;
116
+ declare const sign: (value: string, secret: string) => string;
117
+ declare const unsign: (input: string, secret: string) => string | false;
118
+
108
119
  export interface FastifyCookieOptions {
109
120
  secret?: string | string[] | Signer;
110
121
  parseOptions?: CookieSerializeOptions;
@@ -113,4 +124,4 @@ export interface FastifyCookieOptions {
113
124
  declare const fastifyCookie: FastifyPluginCallback<NonNullable<FastifyCookieOptions>>;
114
125
 
115
126
  export default fastifyCookie;
116
- export { fastifyCookie };
127
+ export { fastifyCookie, signerFactory, sign, unsign };
package/plugin.js CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict'
2
2
 
3
+ const { sign, unsign } = require('cookie-signature')
3
4
  const fp = require('fastify-plugin')
4
- const cookie = require('./cookie')
5
+ const cookie = require('cookie')
5
6
 
6
7
  const signerFactory = require('./signer')
7
8
 
@@ -58,6 +59,7 @@ function plugin (fastify, options, next) {
58
59
  const signer = typeof secret === 'string' || enableRotation ? signerFactory(secret) : secret
59
60
 
60
61
  fastify.decorate('parseCookie', parseCookie)
62
+ fastify.decorate('signCookie', signCookie)
61
63
  fastify.decorate('unsignCookie', unsignCookie)
62
64
 
63
65
  fastify.decorateRequest('cookies', null)
@@ -76,6 +78,10 @@ function plugin (fastify, options, next) {
76
78
  return cookie.parse(cookieHeader, options.parseOptions)
77
79
  }
78
80
 
81
+ function signCookie (value) {
82
+ return signer.sign(value)
83
+ }
84
+
79
85
  function unsignCookie (value) {
80
86
  return signer.unsign(value)
81
87
  }
@@ -91,8 +97,8 @@ function plugin (fastify, options, next) {
91
97
  }
92
98
 
93
99
  const fastifyCookie = fp(plugin, {
94
- fastify: '>=3',
95
- name: 'fastify-cookie'
100
+ fastify: '4.x',
101
+ name: '@fastify/cookie'
96
102
  })
97
103
 
98
104
  /**
@@ -108,3 +114,11 @@ const fastifyCookie = fp(plugin, {
108
114
  fastifyCookie.fastifyCookie = fastifyCookie
109
115
  fastifyCookie.default = fastifyCookie
110
116
  module.exports = fastifyCookie
117
+
118
+ fastifyCookie.fastifyCookie.signerFactory = signerFactory
119
+ fastifyCookie.fastifyCookie.sign = sign
120
+ fastifyCookie.fastifyCookie.unsign = unsign
121
+
122
+ module.exports.signerFactory = signerFactory
123
+ module.exports.sign = sign
124
+ module.exports.unsign = unsign
@@ -243,6 +243,61 @@ test('parses incoming cookies', (t) => {
243
243
  })
244
244
  })
245
245
 
246
+ test('defined and undefined cookies', (t) => {
247
+ t.plan(23)
248
+ const fastify = Fastify()
249
+ fastify.register(plugin)
250
+
251
+ // check that it parses the cookies in the onRequest hook
252
+ for (const hook of ['preValidation', 'preHandler']) {
253
+ fastify.addHook(hook, (req, reply, done) => {
254
+ t.ok(req.cookies)
255
+
256
+ t.ok(req.cookies.bar)
257
+ t.notOk(req.cookies.baz)
258
+
259
+ t.equal(req.cookies.bar, 'bar')
260
+ t.equal(req.cookies.baz, undefined)
261
+ done()
262
+ })
263
+ }
264
+
265
+ fastify.addHook('preParsing', (req, reply, payload, done) => {
266
+ t.ok(req.cookies)
267
+
268
+ t.ok(req.cookies.bar)
269
+ t.notOk(req.cookies.baz)
270
+
271
+ t.equal(req.cookies.bar, 'bar')
272
+ t.equal(req.cookies.baz, undefined)
273
+ done()
274
+ })
275
+
276
+ fastify.get('/test2', (req, reply) => {
277
+ t.ok(req.cookies)
278
+
279
+ t.ok(req.cookies.bar)
280
+ t.notOk(req.cookies.baz)
281
+
282
+ t.equal(req.cookies.bar, 'bar')
283
+ t.equal(req.cookies.baz, undefined)
284
+
285
+ reply.send({ hello: 'world' })
286
+ })
287
+
288
+ fastify.inject({
289
+ method: 'GET',
290
+ url: '/test2',
291
+ headers: {
292
+ cookie: 'bar=bar'
293
+ }
294
+ }, (err, res) => {
295
+ t.error(err)
296
+ t.equal(res.statusCode, 200)
297
+ t.same(JSON.parse(res.body), { hello: 'world' })
298
+ })
299
+ })
300
+
246
301
  test('does not modify supplied cookie options object', (t) => {
247
302
  t.plan(3)
248
303
  const expireDate = Date.now() + 1000
@@ -701,3 +756,23 @@ test('cookies set with plugin options parseOptions field', (t) => {
701
756
  }
702
757
  )
703
758
  })
759
+
760
+ test('create signed cookie manually using signCookie decorator', async (t) => {
761
+ const fastify = Fastify()
762
+
763
+ await fastify.register(plugin, { secret: 'secret' })
764
+
765
+ fastify.get('/test1', (req, reply) => {
766
+ reply.send({
767
+ unsigned: req.unsignCookie(req.cookies.foo)
768
+ })
769
+ })
770
+
771
+ const res = await fastify.inject({
772
+ method: 'GET',
773
+ url: '/test1',
774
+ headers: { cookie: `foo=${fastify.signCookie('bar')}` }
775
+ })
776
+ t.equal(res.statusCode, 200)
777
+ t.same(JSON.parse(res.body), { unsigned: { value: 'bar', renew: false, valid: true } })
778
+ })
@@ -3,7 +3,6 @@ import { Server } from 'http';
3
3
  import { expectType } from 'tsd';
4
4
  import * as fastifyCookieStar from '..';
5
5
  import fastifyCookieDefault, {
6
- CookieSerializeOptions,
7
6
  fastifyCookie as fastifyCookieNamed
8
7
  } from '..';
9
8
  import cookie, { FastifyCookieOptions } from '../plugin';
@@ -42,13 +41,14 @@ server.after((_err) => {
42
41
 
43
42
  server.get('/', (request, reply) => {
44
43
  const test = request.cookies.test;
44
+ expectType<string | undefined>(test);
45
45
 
46
46
  expectType<setCookieWrapper>(reply.cookie);
47
47
  expectType<setCookieWrapper>(reply.setCookie);
48
48
 
49
49
  expectType<FastifyReply>(
50
50
  reply
51
- .setCookie('test', test, { domain: 'example.com', path: '/' })
51
+ .setCookie('test', test!, { domain: 'example.com', path: '/' })
52
52
  .clearCookie('foo')
53
53
  .send({ hello: 'world' })
54
54
  );
@@ -63,7 +63,7 @@ serverWithHttp2.after(() => {
63
63
  serverWithHttp2.get('/', (request, reply) => {
64
64
  const test = request.cookies.test;
65
65
  reply
66
- .setCookie('test', test, { domain: 'example.com', path: '/' })
66
+ .setCookie('test', test!, { domain: 'example.com', path: '/' })
67
67
  .clearCookie('foo')
68
68
  .send({ hello: 'world' });
69
69
  });
@@ -75,26 +75,26 @@ testSamesiteOptionsApp.register(cookie);
75
75
  testSamesiteOptionsApp.after(() => {
76
76
  server.get('/test-samesite-option-true', (request, reply) => {
77
77
  const test = request.cookies.test;
78
- reply.setCookie('test', test, { sameSite: true }).send({ hello: 'world' });
78
+ reply.setCookie('test', test!, { sameSite: true }).send({ hello: 'world' });
79
79
  });
80
80
  server.get('/test-samesite-option-false', (request, reply) => {
81
81
  const test = request.cookies.test;
82
- reply.setCookie('test', test, { sameSite: false }).send({ hello: 'world' });
82
+ reply.setCookie('test', test!, { sameSite: false }).send({ hello: 'world' });
83
83
  });
84
84
  server.get('/test-samesite-option-lax', (request, reply) => {
85
85
  const test = request.cookies.test;
86
- reply.setCookie('test', test, { sameSite: 'lax' }).send({ hello: 'world' });
86
+ reply.setCookie('test', test!, { sameSite: 'lax' }).send({ hello: 'world' });
87
87
  });
88
88
  server.get('/test-samesite-option-strict', (request, reply) => {
89
89
  const test = request.cookies.test;
90
90
  reply
91
- .setCookie('test', test, { sameSite: 'strict' })
91
+ .setCookie('test', test!, { sameSite: 'strict' })
92
92
  .send({ hello: 'world' });
93
93
  });
94
94
  server.get('/test-samesite-option-none', (request, reply) => {
95
95
  const test = request.cookies.test;
96
96
  reply
97
- .setCookie('test', test, { sameSite: 'none' })
97
+ .setCookie('test', test!, { sameSite: 'none' })
98
98
  .send({ hello: 'world' });
99
99
  });
100
100
  });
@@ -106,13 +106,13 @@ appWithImplicitHttpSigned.register(cookie, {
106
106
  });
107
107
  appWithImplicitHttpSigned.after(() => {
108
108
  server.get('/', (request, reply) => {
109
- appWithImplicitHttpSigned.unsignCookie(request.cookies.test);
109
+ appWithImplicitHttpSigned.unsignCookie(request.cookies.test!);
110
110
  appWithImplicitHttpSigned.unsignCookie('test');
111
111
 
112
- reply.unsignCookie(request.cookies.test);
112
+ reply.unsignCookie(request.cookies.test!);
113
113
  reply.unsignCookie('test');
114
114
 
115
- request.unsignCookie(request.cookies.anotherTest);
115
+ request.unsignCookie(request.cookies.anotherTest!);
116
116
  request.unsignCookie('anotherTest');
117
117
 
118
118
  reply.send({ hello: 'world' });
@@ -126,7 +126,7 @@ appWithRotationSecret.register(cookie, {
126
126
  });
127
127
  appWithRotationSecret.after(() => {
128
128
  server.get('/', (request, reply) => {
129
- reply.unsignCookie(request.cookies.test);
129
+ reply.unsignCookie(request.cookies.test!);
130
130
  const { valid, renew, value } = reply.unsignCookie('test');
131
131
 
132
132
  expectType<boolean>(valid);
@@ -158,7 +158,7 @@ appWithParseOptions.register(cookie, {
158
158
  });
159
159
  appWithParseOptions.after(() => {
160
160
  server.get('/', (request, reply) => {
161
- const { valid, renew, value } = reply.unsignCookie(request.cookies.test);
161
+ const { valid, renew, value } = reply.unsignCookie(request.cookies.test!);
162
162
 
163
163
  expectType<boolean>(valid);
164
164
  expectType<boolean>(renew);
@@ -179,7 +179,7 @@ appWithCustomSigner.register(cookie, {
179
179
  })
180
180
  appWithCustomSigner.after(() => {
181
181
  server.get('/', (request, reply) => {
182
- reply.unsignCookie(request.cookies.test)
182
+ reply.unsignCookie(request.cookies.test!)
183
183
  const { valid, renew, value } = reply.unsignCookie('test')
184
184
 
185
185
  expectType<boolean>(valid)
package/cookie.js DELETED
@@ -1,225 +0,0 @@
1
- /*!
2
- * Adapted from https://github.com/jshttp/cookie
3
- *
4
- * (The MIT License)
5
- *
6
- * Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com>
7
- * Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
8
- *
9
- * Permission is hereby granted, free of charge, to any person obtaining
10
- * a copy of this software and associated documentation files (the
11
- * 'Software'), to deal in the Software without restriction, including
12
- * without limitation the rights to use, copy, modify, merge, publish,
13
- * distribute, sublicense, and/or sell copies of the Software, and to
14
- * permit persons to whom the Software is furnished to do so, subject to
15
- * the following conditions:
16
- *
17
- * The above copyright notice and this permission notice shall be
18
- * included in all copies or substantial portions of the Software.
19
- *
20
- * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
21
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24
- * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
25
- * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26
- * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27
- */
28
-
29
- 'use strict'
30
-
31
- /**
32
- * Module exports.
33
- * @public
34
- */
35
-
36
- exports.parse = parse
37
- exports.serialize = serialize
38
-
39
- /**
40
- * Module variables.
41
- * @private
42
- */
43
-
44
- const decode = decodeURIComponent
45
- const encode = encodeURIComponent
46
-
47
- /**
48
- * RegExp to match field-content in RFC 7230 sec 3.2
49
- *
50
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
51
- * field-vchar = VCHAR / obs-text
52
- * obs-text = %x80-FF
53
- */
54
-
55
- const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line
56
-
57
- /**
58
- * Parse a cookie header.
59
- *
60
- * Parse the given cookie header string into an object
61
- * The object has the various cookies as keys(names) => values
62
- *
63
- * @param {string} str
64
- * @param {object} [options]
65
- * @return {object}
66
- * @public
67
- */
68
-
69
- function parse (str, options) {
70
- if (typeof str !== 'string') {
71
- throw new TypeError('argument str must be a string')
72
- }
73
-
74
- const result = {}
75
- const dec = (options && options.decode) || decode
76
-
77
- let pos = 0
78
- let terminatorPos = 0
79
- let eqIdx = 0
80
-
81
- while (true) {
82
- if (terminatorPos === str.length) {
83
- break
84
- }
85
- terminatorPos = str.indexOf(';', pos)
86
- terminatorPos = (terminatorPos === -1) ? str.length : terminatorPos
87
- eqIdx = str.indexOf('=', pos)
88
-
89
- // skip things that don't look like key=value
90
- if (eqIdx === -1 || eqIdx > terminatorPos) {
91
- pos = terminatorPos + 1
92
- continue
93
- }
94
-
95
- const key = str.substring(pos, eqIdx++).trim()
96
-
97
- // only assign once
98
- if (undefined === result[key]) {
99
- const val = (str.charCodeAt(eqIdx) === 0x22)
100
- ? str.substring(eqIdx + 1, terminatorPos - 1).trim()
101
- : str.substring(eqIdx, terminatorPos).trim()
102
-
103
- result[key] = (dec !== decode || val.indexOf('%') !== -1)
104
- ? tryDecode(val, dec)
105
- : val
106
- }
107
- pos = terminatorPos + 1
108
- }
109
- return result
110
- }
111
-
112
- /**
113
- * Serialize data into a cookie header.
114
- *
115
- * Serialize the a name value pair into a cookie string suitable for
116
- * http headers. An optional options object specified cookie parameters.
117
- *
118
- * serialize('foo', 'bar', { httpOnly: true })
119
- * => "foo=bar; httpOnly"
120
- *
121
- * @param {string} name
122
- * @param {string} val
123
- * @param {object} [options]
124
- * @return {string}
125
- * @public
126
- */
127
-
128
- function serialize (name, val, options) {
129
- const opt = options || {}
130
- const enc = opt.encode || encode
131
- if (typeof enc !== 'function') {
132
- throw new TypeError('option encode is invalid')
133
- }
134
-
135
- if (!fieldContentRegExp.test(name)) {
136
- throw new TypeError('argument name is invalid')
137
- }
138
-
139
- const value = enc(val)
140
- if (value && !fieldContentRegExp.test(value)) {
141
- throw new TypeError('argument val is invalid')
142
- }
143
-
144
- let str = name + '=' + value
145
- if (opt.maxAge != null) {
146
- const maxAge = opt.maxAge - 0
147
- if (isNaN(maxAge) || !isFinite(maxAge)) {
148
- throw new TypeError('option maxAge is invalid')
149
- }
150
-
151
- str += '; Max-Age=' + Math.floor(maxAge)
152
- }
153
-
154
- if (opt.domain) {
155
- if (!fieldContentRegExp.test(opt.domain)) {
156
- throw new TypeError('option domain is invalid')
157
- }
158
-
159
- str += '; Domain=' + opt.domain
160
- }
161
-
162
- if (opt.path) {
163
- if (!fieldContentRegExp.test(opt.path)) {
164
- throw new TypeError('option path is invalid')
165
- }
166
-
167
- str += '; Path=' + opt.path
168
- }
169
-
170
- if (opt.expires) {
171
- if (typeof opt.expires.toUTCString !== 'function') {
172
- throw new TypeError('option expires is invalid')
173
- }
174
-
175
- str += '; Expires=' + opt.expires.toUTCString()
176
- }
177
-
178
- if (opt.httpOnly) {
179
- str += '; HttpOnly'
180
- }
181
-
182
- if (opt.secure) {
183
- str += '; Secure'
184
- }
185
-
186
- if (opt.sameSite) {
187
- const sameSite = typeof opt.sameSite === 'string'
188
- ? opt.sameSite.toLowerCase()
189
- : opt.sameSite
190
- switch (sameSite) {
191
- case true:
192
- str += '; SameSite=Strict'
193
- break
194
- case 'lax':
195
- str += '; SameSite=Lax'
196
- break
197
- case 'strict':
198
- str += '; SameSite=Strict'
199
- break
200
- case 'none':
201
- str += '; SameSite=None'
202
- break
203
- default:
204
- throw new TypeError('option sameSite is invalid')
205
- }
206
- }
207
-
208
- return str
209
- }
210
-
211
- /**
212
- * Try decoding a string using a decoding function.
213
- *
214
- * @param {string} str
215
- * @param {function} decode
216
- * @private
217
- */
218
-
219
- function tryDecode (str, decode) {
220
- try {
221
- return decode(str)
222
- } catch (e) {
223
- return str
224
- }
225
- }
@@ -1,205 +0,0 @@
1
- 'use strict'
2
-
3
- const tap = require('tap')
4
- const test = tap.test
5
-
6
- const cookie = require('../cookie')
7
-
8
- test('parse: argument validation', (t) => {
9
- t.plan(2)
10
- t.throws(cookie.parse.bind(), /argument str must be a string/)
11
- t.throws(cookie.parse.bind(null, 42), /argument str must be a string/)
12
- t.end()
13
- })
14
-
15
- test('parse: basic', (t) => {
16
- t.plan(2)
17
- t.same(cookie.parse('foo=bar'), { foo: 'bar' })
18
- t.same(cookie.parse('foo=123'), { foo: '123' })
19
- t.end()
20
- })
21
-
22
- test('parse: ignore spaces', (t) => {
23
- t.plan(1)
24
- t.same(cookie.parse('FOO = bar; baz = raz'), { FOO: 'bar', baz: 'raz' })
25
- t.end()
26
- })
27
-
28
- test('parse: escaping', (t) => {
29
- t.plan(2)
30
- t.same(cookie.parse('foo="bar=123456789&name=Magic+Mouse"'), { foo: 'bar=123456789&name=Magic+Mouse' })
31
- t.same(cookie.parse('email=%20%22%2c%3b%2f'), { email: ' ",;/' })
32
- t.end()
33
- })
34
-
35
- test('parse: ignore escaping error and return original value', (t) => {
36
- t.plan(1)
37
- t.same(cookie.parse('foo=%1;bar=bar'), { foo: '%1', bar: 'bar' })
38
- t.end()
39
- })
40
-
41
- test('parse: ignore non values', (t) => {
42
- t.plan(1)
43
- t.same(cookie.parse('foo=%1;bar=bar;HttpOnly;Secure'),
44
- { foo: '%1', bar: 'bar' })
45
- t.end()
46
- })
47
-
48
- test('parse: unencoded', (t) => {
49
- t.plan(2)
50
- t.same(cookie.parse('foo="bar=123456789&name=Magic+Mouse"', {
51
- decode: function (v) { return v }
52
- }), { foo: 'bar=123456789&name=Magic+Mouse' })
53
-
54
- t.same(cookie.parse('email=%20%22%2c%3b%2f', {
55
- decode: function (v) { return v }
56
- }), { email: '%20%22%2c%3b%2f' })
57
- t.end()
58
- })
59
-
60
- test('parse: dates', (t) => {
61
- t.plan(1)
62
- t.same(cookie.parse('priority=true; expires=Wed, 29 Jan 2014 17:43:25 GMT; Path=/', {
63
- decode: function (v) { return v }
64
- }), { priority: 'true', Path: '/', expires: 'Wed, 29 Jan 2014 17:43:25 GMT' })
65
- t.end()
66
- })
67
-
68
- test('parse: missing value', (t) => {
69
- t.plan(1)
70
- t.same(cookie.parse('foo; bar=1; fizz= ; buzz=2', {
71
- decode: function (v) { return v }
72
- }), { bar: '1', fizz: '', buzz: '2' })
73
- t.end()
74
- })
75
-
76
- test('parse: assign only once', (t) => {
77
- t.plan(3)
78
- t.same(cookie.parse('foo=%1;bar=bar;foo=boo'), { foo: '%1', bar: 'bar' })
79
- t.same(cookie.parse('foo=false;bar=bar;foo=true'), { foo: 'false', bar: 'bar' })
80
- t.same(cookie.parse('foo=;bar=bar;foo=boo'), { foo: '', bar: 'bar' })
81
- t.end()
82
- })
83
-
84
- test('serializer: basic', (t) => {
85
- t.plan(6)
86
- t.same(cookie.serialize('foo', 'bar'), 'foo=bar')
87
- t.same(cookie.serialize('foo', 'bar baz'), 'foo=bar%20baz')
88
- t.same(cookie.serialize('foo', ''), 'foo=')
89
- t.throws(cookie.serialize.bind(cookie, 'foo\n', 'bar'), /argument name is invalid/)
90
- t.throws(cookie.serialize.bind(cookie, 'foo\u280a', 'bar'), /argument name is invalid/)
91
- t.throws(cookie.serialize.bind(cookie, 'foo', 'bar', { encode: 42 }), /option encode is invalid/)
92
- t.end()
93
- })
94
-
95
- test('serializer: path', (t) => {
96
- t.plan(2)
97
- t.same(cookie.serialize('foo', 'bar', { path: '/' }), 'foo=bar; Path=/')
98
- t.throws(cookie.serialize.bind(cookie, 'foo', 'bar', {
99
- path: '/\n'
100
- }), /option path is invalid/)
101
- t.end()
102
- })
103
-
104
- test('serializer: secure', (t) => {
105
- t.plan(2)
106
- t.same(cookie.serialize('foo', 'bar', { secure: true }), 'foo=bar; Secure')
107
- t.same(cookie.serialize('foo', 'bar', { secure: false }), 'foo=bar')
108
- t.end()
109
- })
110
-
111
- test('serializer: domain', (t) => {
112
- t.plan(2)
113
- t.same(cookie.serialize('foo', 'bar', { domain: 'example.com' }), 'foo=bar; Domain=example.com')
114
- t.throws(cookie.serialize.bind(cookie, 'foo', 'bar', {
115
- domain: 'example.com\n'
116
- }), /option domain is invalid/)
117
- t.end()
118
- })
119
-
120
- test('serializer: httpOnly', (t) => {
121
- t.plan(1)
122
- t.same(cookie.serialize('foo', 'bar', { httpOnly: true }), 'foo=bar; HttpOnly')
123
- t.end()
124
- })
125
-
126
- test('serializer: maxAge', (t) => {
127
- t.plan(9)
128
- t.throws(function () {
129
- cookie.serialize('foo', 'bar', {
130
- maxAge: 'buzz'
131
- })
132
- }, /option maxAge is invalid/)
133
-
134
- t.throws(function () {
135
- cookie.serialize('foo', 'bar', {
136
- maxAge: Infinity
137
- })
138
- }, /option maxAge is invalid/)
139
-
140
- t.same(cookie.serialize('foo', 'bar', { maxAge: 1000 }), 'foo=bar; Max-Age=1000')
141
- t.same(cookie.serialize('foo', 'bar', { maxAge: '1000' }), 'foo=bar; Max-Age=1000')
142
- t.same(cookie.serialize('foo', 'bar', { maxAge: 0 }), 'foo=bar; Max-Age=0')
143
- t.same(cookie.serialize('foo', 'bar', { maxAge: '0' }), 'foo=bar; Max-Age=0')
144
- t.same(cookie.serialize('foo', 'bar', { maxAge: null }), 'foo=bar')
145
- t.same(cookie.serialize('foo', 'bar', { maxAge: undefined }), 'foo=bar')
146
- t.same(cookie.serialize('foo', 'bar', { maxAge: 3.14 }), 'foo=bar; Max-Age=3')
147
- t.end()
148
- })
149
-
150
- test('serializer: expires', (t) => {
151
- t.plan(2)
152
- t.same(cookie.serialize('foo', 'bar', {
153
- expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900))
154
- }), 'foo=bar; Expires=Sun, 24 Dec 2000 10:30:59 GMT')
155
-
156
- t.throws(cookie.serialize.bind(cookie, 'foo', 'bar', {
157
- expires: Date.now()
158
- }), /option expires is invalid/)
159
- t.end()
160
- })
161
-
162
- test('sameSite', (t) => {
163
- t.plan(9)
164
- t.same(cookie.serialize('foo', 'bar', { sameSite: true }), 'foo=bar; SameSite=Strict')
165
- t.same(cookie.serialize('foo', 'bar', { sameSite: 'Strict' }), 'foo=bar; SameSite=Strict')
166
- t.same(cookie.serialize('foo', 'bar', { sameSite: 'strict' }), 'foo=bar; SameSite=Strict')
167
- t.same(cookie.serialize('foo', 'bar', { sameSite: 'Lax' }), 'foo=bar; SameSite=Lax')
168
- t.same(cookie.serialize('foo', 'bar', { sameSite: 'lax' }), 'foo=bar; SameSite=Lax')
169
- t.same(cookie.serialize('foo', 'bar', { sameSite: 'None' }), 'foo=bar; SameSite=None')
170
- t.same(cookie.serialize('foo', 'bar', { sameSite: 'none' }), 'foo=bar; SameSite=None')
171
- t.same(cookie.serialize('foo', 'bar', { sameSite: false }), 'foo=bar')
172
-
173
- t.throws(cookie.serialize.bind(cookie, 'foo', 'bar', {
174
- sameSite: 'foo'
175
- }), /option sameSite is invalid/)
176
- t.end()
177
- })
178
-
179
- test('escaping', (t) => {
180
- t.plan(1)
181
- t.same(cookie.serialize('cat', '+ '), 'cat=%2B%20')
182
- t.end()
183
- })
184
-
185
- test('parse->serialize', (t) => {
186
- t.plan(2)
187
- t.same(cookie.parse(cookie.serialize('cat', 'foo=123&name=baz five')),
188
- { cat: 'foo=123&name=baz five' })
189
-
190
- t.same(cookie.parse(cookie.serialize('cat', ' ";/')),
191
- { cat: ' ";/' })
192
- t.end()
193
- })
194
-
195
- test('unencoded', (t) => {
196
- t.plan(2)
197
- t.same(cookie.serialize('cat', '+ ', {
198
- encode: function (value) { return value }
199
- }), 'cat=+ ')
200
-
201
- t.throws(cookie.serialize.bind(cookie, 'cat', '+ \n', {
202
- encode: function (value) { return value }
203
- }), /argument val is invalid/)
204
- t.end()
205
- })