Make the cookie library set the SamSite cookie value to strict by default. If callers want to set it to something else, they can pass it through the opts object like they can 'exprires'.

Also added a test file for jar.js so I could test the set method. The 
other methods remain untested.
This commit is contained in:
picklesrus 2020-07-20 15:18:09 -04:00
parent c8aa7250fc
commit 10a4e92d21
2 changed files with 55 additions and 1 deletions

View file

@ -78,7 +78,8 @@ const Jar = {
set: (name, value, opts) => {
opts = opts || {};
defaults(opts, {
expires: new Date(new Date().setYear(new Date().getFullYear() + 1))
expires: new Date(new Date().setYear(new Date().getFullYear() + 1)),
SameSite: 'Strict'
});
opts.path = '/';
const obj = cookie.serialize(name, value, opts);

53
test/unit/lib/jar.test.js Normal file
View file

@ -0,0 +1,53 @@
const jar = require('../../../src/lib/jar');
const cookie = require('cookie');
jest.mock('cookie', () => ({serialize: jest.fn()}));
describe('unit test lib/jar.js', () => {
test('simple set test with no opts', () => {
jar.set('name', 'value');
expect(cookie.serialize).toHaveBeenCalled();
expect(cookie.serialize).toHaveBeenCalledWith('name', 'value',
expect.objectContaining({
path: '/',
SameSite: 'Strict',
expires: expect.anything() // not specifically matching the date because it is hard to mock
}));
});
test('test with opts', () => {
jar.set('a', 'b', {option: 'one'});
expect(cookie.serialize).toHaveBeenCalled();
expect(cookie.serialize).toHaveBeenCalledWith('a', 'b',
expect.objectContaining({
option: 'one',
path: '/',
SameSite: 'Strict',
expires: expect.anything() // not specifically matching the date because it is hard to mock
}));
});
test('expires opts overrides default', () => {
jar.set('a', 'b', {
option: 'one',
expires: 'someday'
});
expect(cookie.serialize).toHaveBeenCalled();
expect(cookie.serialize).toHaveBeenCalledWith('a', 'b',
expect.objectContaining({
option: 'one',
path: '/',
expires: 'someday'
}));
});
test('SameSite opts overrides default', () => {
jar.set('a', 'b', {
option: 'one',
SameSite: 'override'
});
expect(cookie.serialize).toHaveBeenCalled();
expect(cookie.serialize).toHaveBeenCalledWith('a', 'b',
expect.objectContaining({
option: 'one',
SameSite: 'override'
}));
});
});