@fastify/cookie 7.0.0 → 7.3.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,48 +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
- - 14
18
- - 16
19
- - 18
20
- os:
21
- - macos-latest
22
- - ubuntu-latest
23
- - windows-latest
24
- steps:
25
- - uses: actions/checkout@v3
26
- - name: Use Node.js
27
- uses: actions/setup-node@v3
28
- with:
29
- node-version: ${{ matrix.node-version }}
30
- - name: Install Dependencies
31
- run: |
32
- npm install --ignore-scripts
33
- - name: Lint
34
- run: |
35
- npm run lint:ci
36
- - name: Run Tests
37
- run: |
38
- npm test
39
- automerge:
40
- needs: test
41
- runs-on: ubuntu-latest
42
- permissions:
43
- pull-requests: write
44
- contents: write
45
- steps:
46
- - uses: fastify/github-action-merge-dependabot@v3
47
- with:
48
- github-token: ${{ secrets.GITHUB_TOKEN }}
15
+ uses: fastify/workflows/.github/workflows/plugins-ci.yml@v3
16
+ with:
17
+ lint: true
package/README.md CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  ![CI](https://github.com/fastify/fastify-cookie/workflows/CI/badge.svg)
4
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)
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
@@ -58,7 +57,7 @@ fastify.get('/', (req, reply) => {
58
57
  ## TypeScript Example
59
58
 
60
59
  ```ts
61
- import { FastifyCookieOptions } from '@fastify/cookie'
60
+ import type { FastifyCookieOptions } from '@fastify/cookie'
62
61
  import cookie from '@fastify/cookie'
63
62
  import fastify from 'fastify'
64
63
 
@@ -100,7 +99,8 @@ with a value of `'foo'` on the cookie path `/`.
100
99
  + `name`: a string name for the cookie to be set
101
100
  + `value`: a string value for the cookie
102
101
  + `options`: an options object as described in the [cookie serialize][cs] documentation
103
- with a extra param "signed" for signed cookie
102
+ + `options.signed`: the cookie should be signed
103
+ + `options.secure`: if set to `true` it will set the Secure-flag. If it is set to `"auto"` Secure-flag is set when the connection is using tls.
104
104
 
105
105
  #### Securing the cookie
106
106
 
@@ -202,7 +202,7 @@ the provided signer's (or the default signer if no custom implementation is prov
202
202
  fastify.register(require('@fastify/cookie'), { secret: 'my-secret' })
203
203
 
204
204
  fastify.get('/', (req, rep) => {
205
- if (fastify.unsign(req.cookie.foo).valid === false) {
205
+ if (fastify.unsignCookie(req.cookie.foo).valid === false) {
206
206
  rep.send('cookie is invalid')
207
207
  return
208
208
  }
@@ -211,6 +211,50 @@ fastify.get('/', (req, rep) => {
211
211
  })
212
212
  ```
213
213
 
214
+ ### Other cases of manual signing
215
+
216
+ Sometimes the service under test should only accept requests with signed cookies, but it does not generate them itself.
217
+
218
+ **Example:**
219
+
220
+ ```js
221
+
222
+ test('Request requires signed cookie', async () => {
223
+ const response = await app.inject({
224
+ method: 'GET',
225
+ url: '/',
226
+ headers: {
227
+ cookies : {
228
+ 'sid': app.signCookie(sidValue)
229
+ }
230
+ },
231
+ });
232
+
233
+ expect(response.statusCode).toBe(200);
234
+ });
235
+ ```
236
+
237
+ ### Manual signing/unsigning with low level utilities
238
+
239
+ with signerFactory
240
+
241
+ ```js
242
+ const { fastifyCookie } = require('@fastify/cookie');
243
+
244
+ const signer = fastifyCookie.signerFactory('secret');
245
+ const signedValue = signer.sign('test');
246
+ const {valid, renew, value } = signer.unsign(signedValue);
247
+ ```
248
+
249
+ with sign/unsign utilities
250
+
251
+ ```js
252
+ const { fastifyCookie } = require('@fastify/cookie');
253
+
254
+ const signedValue = fastifyCookie.sign('test', 'secret');
255
+ const unsignedvalue = fastifyCookie.unsign(signedValue, 'secret');
256
+ ```
257
+
214
258
 
215
259
  ## License
216
260
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/cookie",
3
- "version": "7.0.0",
3
+ "version": "7.3.0",
4
4
  "description": "Plugin for fastify to add support for cookies",
5
5
  "main": "plugin.js",
6
6
  "types": "plugin.d.ts",
@@ -39,19 +39,20 @@
39
39
  },
40
40
  "homepage": "https://github.com/fastify/fastify-cookie#readme",
41
41
  "devDependencies": {
42
- "@types/node": "^17.0.16",
42
+ "@types/node": "^18.0.0",
43
43
  "fastify": "^4.0.0-rc.2",
44
44
  "pre-commit": "^1.2.2",
45
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
- "fastify-plugin": "^3.0.1"
55
+ "fastify-plugin": "^4.0.0"
55
56
  },
56
57
  "tsd": {
57
58
  "directory": "test"
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,12 +97,13 @@ 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
- secure?: boolean;
102
+ secure?: boolean | 'auto';
96
103
  signed?: boolean;
97
104
  }
98
105
 
99
- interface Signer {
106
+ export interface Signer {
100
107
  sign: (input: string) => string;
101
108
  unsign: (input: string) => {
102
109
  valid: boolean;
@@ -110,7 +117,17 @@ export interface FastifyCookieOptions {
110
117
  parseOptions?: CookieSerializeOptions;
111
118
  }
112
119
 
113
- declare const fastifyCookie: FastifyPluginCallback<NonNullable<FastifyCookieOptions>>;
120
+ export type Sign = (value: string, secret: string) => string;
121
+ export type Unsign = (input: string, secret: string) => string | false;
122
+ export type SignerFactory = (secret: string) => Signer;
123
+
124
+ export interface FastifyCookie extends FastifyPluginCallback<NonNullable<FastifyCookieOptions>>{
125
+ signerFactory: SignerFactory;
126
+ sign: Sign;
127
+ unsign: Unsign;
128
+ }
129
+
130
+ declare const fastifyCookie: FastifyCookie;
114
131
 
115
132
  export default fastifyCookie;
116
133
  export { fastifyCookie };
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
 
@@ -15,6 +16,15 @@ function fastifyCookieSetCookie (reply, name, value, options, signer) {
15
16
  value = signer.sign(value)
16
17
  }
17
18
 
19
+ if (opts.secure === 'auto') {
20
+ if (isConnectionSecure(reply.request)) {
21
+ opts.secure = true
22
+ } else {
23
+ opts.sameSite = 'lax'
24
+ opts.secure = false
25
+ }
26
+ }
27
+
18
28
  const serialized = cookie.serialize(name, value, opts)
19
29
  let setCookie = reply.getHeader('Set-Cookie')
20
30
  if (!setCookie) {
@@ -58,6 +68,7 @@ function plugin (fastify, options, next) {
58
68
  const signer = typeof secret === 'string' || enableRotation ? signerFactory(secret) : secret
59
69
 
60
70
  fastify.decorate('parseCookie', parseCookie)
71
+ fastify.decorate('signCookie', signCookie)
61
72
  fastify.decorate('unsignCookie', unsignCookie)
62
73
 
63
74
  fastify.decorateRequest('cookies', null)
@@ -76,6 +87,10 @@ function plugin (fastify, options, next) {
76
87
  return cookie.parse(cookieHeader, options.parseOptions)
77
88
  }
78
89
 
90
+ function signCookie (value) {
91
+ return signer.sign(value)
92
+ }
93
+
79
94
  function unsignCookie (value) {
80
95
  return signer.unsign(value)
81
96
  }
@@ -90,6 +105,13 @@ function plugin (fastify, options, next) {
90
105
  }
91
106
  }
92
107
 
108
+ function isConnectionSecure (request) {
109
+ return (
110
+ request.raw.socket?.encrypted === true ||
111
+ request.headers['x-forwarded-proto'] === 'https'
112
+ )
113
+ }
114
+
93
115
  const fastifyCookie = fp(plugin, {
94
116
  fastify: '4.x',
95
117
  name: '@fastify/cookie'
@@ -108,3 +130,11 @@ const fastifyCookie = fp(plugin, {
108
130
  fastifyCookie.fastifyCookie = fastifyCookie
109
131
  fastifyCookie.default = fastifyCookie
110
132
  module.exports = fastifyCookie
133
+
134
+ fastifyCookie.fastifyCookie.signerFactory = signerFactory
135
+ fastifyCookie.fastifyCookie.sign = sign
136
+ fastifyCookie.fastifyCookie.unsign = unsign
137
+
138
+ module.exports.signerFactory = signerFactory
139
+ module.exports.sign = sign
140
+ 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,61 @@ 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
+ })
779
+
780
+ test('handle secure:auto of cookieOptions', async (t) => {
781
+ const fastify = Fastify()
782
+
783
+ await fastify.register(plugin)
784
+
785
+ fastify.get('/test1', (req, reply) => {
786
+ reply
787
+ .setCookie('foo', 'foo', { path: '/', secure: 'auto' })
788
+ .send()
789
+ })
790
+
791
+ const res = await fastify.inject({
792
+ method: 'GET',
793
+ url: '/test1',
794
+ headers: { 'x-forwarded-proto': 'https' }
795
+ })
796
+
797
+ const cookies = res.cookies
798
+ t.equal(cookies.length, 1)
799
+ t.equal(cookies[0].name, 'foo')
800
+ t.equal(cookies[0].value, 'foo')
801
+ t.equal(cookies[0].secure, true)
802
+ t.equal(cookies[0].path, '/')
803
+
804
+ const res2 = await fastify.inject({
805
+ method: 'GET',
806
+ url: '/test1'
807
+ })
808
+
809
+ const cookies2 = res2.cookies
810
+ t.equal(cookies2.length, 1)
811
+ t.equal(cookies2[0].name, 'foo')
812
+ t.equal(cookies2[0].value, 'foo')
813
+ t.equal(cookies2[0].sameSite, 'Lax')
814
+ t.same(cookies2[0].secure, null)
815
+ t.equal(cookies2[0].path, '/')
816
+ })
@@ -1,14 +1,10 @@
1
- import fastify, { FastifyInstance, FastifyPluginCallback, FastifyReply, setCookieWrapper } from 'fastify';
2
- import { Server } from 'http';
1
+ import cookie from '../plugin';
3
2
  import { expectType } from 'tsd';
4
3
  import * as fastifyCookieStar from '..';
5
- import fastifyCookieDefault, {
6
- CookieSerializeOptions,
7
- fastifyCookie as fastifyCookieNamed
8
- } from '..';
9
- import cookie, { FastifyCookieOptions } from '../plugin';
10
-
11
4
  import fastifyCookieCjsImport = require('..');
5
+ import fastifyCookieDefault, { fastifyCookie as fastifyCookieNamed } from '..';
6
+ import fastify, { FastifyInstance, FastifyReply, setCookieWrapper } from 'fastify';
7
+
12
8
  const fastifyCookieCjs = require('..');
13
9
 
14
10
  const app: FastifyInstance = fastify();
@@ -20,16 +16,24 @@ app.register(fastifyCookieCjsImport.fastifyCookie);
20
16
  app.register(fastifyCookieStar.default);
21
17
  app.register(fastifyCookieStar.fastifyCookie);
22
18
 
23
- expectType<FastifyPluginCallback<FastifyCookieOptions, Server>>(fastifyCookieNamed);
24
- expectType<FastifyPluginCallback<FastifyCookieOptions, Server>>(fastifyCookieDefault);
25
- expectType<FastifyPluginCallback<FastifyCookieOptions, Server>>(fastifyCookieCjsImport.default);
26
- expectType<FastifyPluginCallback<FastifyCookieOptions, Server>>(fastifyCookieCjsImport.fastifyCookie);
27
- expectType<FastifyPluginCallback<FastifyCookieOptions, Server>>(fastifyCookieStar.default);
28
- expectType<FastifyPluginCallback<FastifyCookieOptions, Server>>(
19
+ expectType<fastifyCookieStar.FastifyCookie>(fastifyCookieNamed);
20
+ expectType<fastifyCookieStar.FastifyCookie>(fastifyCookieDefault);
21
+ expectType<fastifyCookieStar.FastifyCookie>(fastifyCookieCjsImport.default);
22
+ expectType<fastifyCookieStar.FastifyCookie>(fastifyCookieCjsImport.fastifyCookie);
23
+ expectType<fastifyCookieStar.FastifyCookie>(fastifyCookieStar.default);
24
+ expectType<fastifyCookieStar.FastifyCookie>(
29
25
  fastifyCookieStar.fastifyCookie
30
26
  );
31
27
  expectType<any>(fastifyCookieCjs);
32
28
 
29
+ expectType<fastifyCookieStar.Sign>(fastifyCookieDefault.sign);
30
+ expectType<fastifyCookieStar.Unsign>(fastifyCookieDefault.unsign);
31
+ expectType<fastifyCookieStar.SignerFactory >(fastifyCookieDefault.signerFactory );
32
+
33
+ expectType<fastifyCookieStar.Sign>(fastifyCookieNamed.sign);
34
+ expectType<fastifyCookieStar.Unsign>(fastifyCookieNamed.unsign);
35
+ expectType<fastifyCookieStar.SignerFactory >(fastifyCookieNamed.signerFactory );
36
+
33
37
  const server = fastify();
34
38
 
35
39
  server.register(cookie);
@@ -42,13 +46,14 @@ server.after((_err) => {
42
46
 
43
47
  server.get('/', (request, reply) => {
44
48
  const test = request.cookies.test;
49
+ expectType<string | undefined>(test);
45
50
 
46
51
  expectType<setCookieWrapper>(reply.cookie);
47
52
  expectType<setCookieWrapper>(reply.setCookie);
48
53
 
49
54
  expectType<FastifyReply>(
50
55
  reply
51
- .setCookie('test', test, { domain: 'example.com', path: '/' })
56
+ .setCookie('test', test!, { domain: 'example.com', path: '/' })
52
57
  .clearCookie('foo')
53
58
  .send({ hello: 'world' })
54
59
  );
@@ -63,7 +68,7 @@ serverWithHttp2.after(() => {
63
68
  serverWithHttp2.get('/', (request, reply) => {
64
69
  const test = request.cookies.test;
65
70
  reply
66
- .setCookie('test', test, { domain: 'example.com', path: '/' })
71
+ .setCookie('test', test!, { domain: 'example.com', path: '/' })
67
72
  .clearCookie('foo')
68
73
  .send({ hello: 'world' });
69
74
  });
@@ -75,26 +80,26 @@ testSamesiteOptionsApp.register(cookie);
75
80
  testSamesiteOptionsApp.after(() => {
76
81
  server.get('/test-samesite-option-true', (request, reply) => {
77
82
  const test = request.cookies.test;
78
- reply.setCookie('test', test, { sameSite: true }).send({ hello: 'world' });
83
+ reply.setCookie('test', test!, { sameSite: true }).send({ hello: 'world' });
79
84
  });
80
85
  server.get('/test-samesite-option-false', (request, reply) => {
81
86
  const test = request.cookies.test;
82
- reply.setCookie('test', test, { sameSite: false }).send({ hello: 'world' });
87
+ reply.setCookie('test', test!, { sameSite: false }).send({ hello: 'world' });
83
88
  });
84
89
  server.get('/test-samesite-option-lax', (request, reply) => {
85
90
  const test = request.cookies.test;
86
- reply.setCookie('test', test, { sameSite: 'lax' }).send({ hello: 'world' });
91
+ reply.setCookie('test', test!, { sameSite: 'lax' }).send({ hello: 'world' });
87
92
  });
88
93
  server.get('/test-samesite-option-strict', (request, reply) => {
89
94
  const test = request.cookies.test;
90
95
  reply
91
- .setCookie('test', test, { sameSite: 'strict' })
96
+ .setCookie('test', test!, { sameSite: 'strict' })
92
97
  .send({ hello: 'world' });
93
98
  });
94
99
  server.get('/test-samesite-option-none', (request, reply) => {
95
100
  const test = request.cookies.test;
96
101
  reply
97
- .setCookie('test', test, { sameSite: 'none' })
102
+ .setCookie('test', test!, { sameSite: 'none' })
98
103
  .send({ hello: 'world' });
99
104
  });
100
105
  });
@@ -106,13 +111,13 @@ appWithImplicitHttpSigned.register(cookie, {
106
111
  });
107
112
  appWithImplicitHttpSigned.after(() => {
108
113
  server.get('/', (request, reply) => {
109
- appWithImplicitHttpSigned.unsignCookie(request.cookies.test);
114
+ appWithImplicitHttpSigned.unsignCookie(request.cookies.test!);
110
115
  appWithImplicitHttpSigned.unsignCookie('test');
111
116
 
112
- reply.unsignCookie(request.cookies.test);
117
+ reply.unsignCookie(request.cookies.test!);
113
118
  reply.unsignCookie('test');
114
119
 
115
- request.unsignCookie(request.cookies.anotherTest);
120
+ request.unsignCookie(request.cookies.anotherTest!);
116
121
  request.unsignCookie('anotherTest');
117
122
 
118
123
  reply.send({ hello: 'world' });
@@ -126,7 +131,7 @@ appWithRotationSecret.register(cookie, {
126
131
  });
127
132
  appWithRotationSecret.after(() => {
128
133
  server.get('/', (request, reply) => {
129
- reply.unsignCookie(request.cookies.test);
134
+ reply.unsignCookie(request.cookies.test!);
130
135
  const { valid, renew, value } = reply.unsignCookie('test');
131
136
 
132
137
  expectType<boolean>(valid);
@@ -158,7 +163,7 @@ appWithParseOptions.register(cookie, {
158
163
  });
159
164
  appWithParseOptions.after(() => {
160
165
  server.get('/', (request, reply) => {
161
- const { valid, renew, value } = reply.unsignCookie(request.cookies.test);
166
+ const { valid, renew, value } = reply.unsignCookie(request.cookies.test!);
162
167
 
163
168
  expectType<boolean>(valid);
164
169
  expectType<boolean>(renew);
@@ -179,7 +184,7 @@ appWithCustomSigner.register(cookie, {
179
184
  })
180
185
  appWithCustomSigner.after(() => {
181
186
  server.get('/', (request, reply) => {
182
- reply.unsignCookie(request.cookies.test)
187
+ reply.unsignCookie(request.cookies.test!)
183
188
  const { valid, renew, value } = reply.unsignCookie('test')
184
189
 
185
190
  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
- })