Skip to content
Myr

feat(middleware): Simple cookie signing functionality (#1279)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Torsten Engelbrecht · committed by GitHub · parent 47ae014 · Browse files · 6 files+417 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+417 added−44 removed

  • tests:+213 added−26 removed
  • other:+204 added−18 removed

6 files+417 added−44 removed

modified:deno_dist/middleware/cookie/index.ts+31 added-2 removed
modified:deno_dist/utils/cookie.ts+71 added-7 removed
modified:src/middleware/cookie/index.test.ts+103 added-1 removed
1import { Hono } from '../../hono'2import { getCookie, setCookie, deleteCookie } from '.'2import { getCookie, getSignedCookie, setCookie, setSignedCookie, deleteCookie } from '.'34describe('Cookie Middleware', () => {5 describe('Parse cookie', () => {6 const apps: Record<string, Hono> = {}
39 unmodified lines
46 expect(res.headers.get('Yummy-Cookie')).toBe('choco')47 expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48 })49 })5051 const app = new Hono()5253 app.get('/cookie-signed-get-all', async (c) => {54 const secret = 'secret lucky charm'55 const { fortune_cookie: fortuneCookie, fruit_cookie: fruitCookie } = await getSignedCookie(56 c,57 secret58 )59 const res = new Response('Signed fortune cookie')60 if (typeof fortuneCookie !== 'undefined' && typeof fruitCookie !== 'undefined') {61 // just examples for tests sake62 res.headers.set('Fortune-Cookie', fortuneCookie || 'INVALID')63 res.headers.set('Fruit-Cookie', fruitCookie || 'INVALID')64 }65 return res66 })6768 app.get('/cookie-signed-get-one', async (c) => {69 const secret = 'secret lucky charm'70 const fortuneCookie = await getSignedCookie(c, secret, 'fortune_cookie')71 const res = new Response('Signed fortune cookie')72 if (typeof fortuneCookie !== 'undefined') {73 // just an example for tests sake74 res.headers.set('Fortune-Cookie', fortuneCookie || 'INVALID')75 }76 return res77 })7879 it('Get signed cookies', async () => {80 const req = new Request('http://localhost/cookie-signed-get-all')81 const cookieString =82 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'83 req.headers.set('Cookie', cookieString)84 const res = await app.request(req)85 expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')86 expect(res.headers.get('Fruit-Cookie')).toBe('mango')87 })8889 it('Get signed cookies invalid signature', async () => {90 const req = new Request('http://localhost/cookie-signed-get-all')91 const cookieString =92 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.verytasty%3D'93 req.headers.set('Cookie', cookieString)94 const res = await app.request(req)95 expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')96 expect(res.headers.get('Fruit-Cookie')).toBe('INVALID')97 })9899 it('Get signed cookie', async () => {100 const req = new Request('http://localhost/cookie-signed-get-one')101 const cookieString =102 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'103 req.headers.set('Cookie', cookieString)104 const res = await app.request(req)105 expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')106 })107108 it('Get signed cookie witn invalid signature', async () => {109 const req = new Request('http://localhost/cookie-signed-get-one')110 const cookieString =111 'fortune_cookie=lots-of-money.nolucktoday%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'112 req.headers.set('Cookie', cookieString)113 const res = await app.request(req)114 expect(res.headers.get('Fortune-Cookie')).toBe('INVALID')115 })116 })117118 describe('Set cookie', () => {119 const app = new Hono()
9 unmodified lines
129 const header = res.headers.get('Set-Cookie')130 expect(header).toBe('delicious_cookie=macha')131 })132133 app.get('/set-signed-cookie', async (c) => {134 const secret = 'secret chocolate chips'135 await setSignedCookie(c, 'delicious_cookie', 'macha', secret)136 return c.text('Give signed cookie')137 })138139 it('Set signed cookie with setSignedCookie()', async () => {140 const res = await app.request('http://localhost/set-signed-cookie')141 expect(res.status).toBe(200)142 const header = res.headers.get('Set-Cookie')143 expect(header).toBe('delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D')144 })145146 app.get('/set-cookie-complex', (c) => {147 setCookie(c, 'great_cookie', 'banana', {148 path: '/',149 secure: true,
14 unmodified lines
164 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'165 )166 })167168 app.get('/set-signed-cookie-complex', async (c) => {169 const secret = 'secret chocolate chips'170 await setSignedCookie(c, 'great_cookie', 'banana', secret, {171 path: '/',172 secure: true,173 domain: 'example.com',174 httpOnly: true,175 maxAge: 1000,176 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),177 sameSite: 'Strict',178 })179 return c.text('Give signed cookie')180 })181182 it('Complex pattern (signed)', async () => {183 const res = await app.request('http://localhost/set-signed-cookie-complex')184 expect(res.status).toBe(200)185 const header = res.headers.get('Set-Cookie')186 expect(header).toBe(187 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'188 )189 })190191 app.get('/set-cookie-multiple', (c) => {192 setCookie(c, 'delicious_cookie', 'macha')193 setCookie(c, 'delicious_cookie', 'choco')194 return c.text('Give cookie')
55 unmodified lines
modified:src/middleware/cookie/index.ts+31 added-2 removed
modified:src/utils/cookie.test.ts+110 added-25 removed
1import type { Cookie } from './cookie'2import { parse, serialize } from './cookie'1import type { Cookie, SignedCookie } from './cookie'2import { parse, parseSigned, serialize, serializeSigned } from './cookie'34describe('Parse cookie', () => {5 it('Should parse cookie', () => {5 it('Should parse cookies', () => {6 const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '7 const cookie: Cookie = parse(cookieString)8 expect(cookie['yummy_cookie']).toBe('choco')9 expect(cookie['tasty_cookie']).toBe('strawberry')10 })1112 it('Should parse one cookie specified by name', () => {13 const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '14 const cookie: Cookie = parse(cookieString, 'yummy_cookie')15 expect(cookie['yummy_cookie']).toBe('choco')16 expect(cookie['tasty_cookie']).toBeUndefined()17 })1819 it('Should parse cookies but ignore signed cookies', () => {20 const cookieString =21 'yummy_cookie=choco; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'22 const cookie: Cookie = parse(cookieString)23 expect(cookie['yummy_cookie']).toBe('choco')24 expect(cookie['tasty_cookie']).toBeUndefined()25 })2627 it('Should parse signed cookies', async () => {28 const secret = 'secret ingredient'29 const cookieString =30 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'31 const cookie: SignedCookie = await parseSigned(cookieString, secret)32 expect(cookie['yummy_cookie']).toBe('choco')33 expect(cookie['tasty_cookie']).toBe('strawberry')34 })3536 it('Should parse signed cookies and return "false" for wrong signature', async () => {37 const secret = 'secret ingredient'38 const cookieString =39 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.invalidsignatur%3D'40 const cookie: SignedCookie = await parseSigned(cookieString, secret)41 expect(cookie['yummy_cookie']).toBe('choco')42 expect(cookie['tasty_cookie']).toBe(false)43 })4445 it('Should parse one signed cookie specified by name', async () => {46 const secret = 'secret ingredient'47 const cookieString =48 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'49 const cookie: SignedCookie = await parseSigned(cookieString, secret, 'tasty_cookie')50 expect(cookie['yummy_cookie']).toBeUndefined()51 expect(cookie['tasty_cookie']).toBe('strawberry')52 })5354 it('Should parse one signed cookie specified by name and return "false" for wrong signature', async () => {55 const secret = 'secret ingredient'56 const cookieString =57 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.invalidsignatur%3D'58 const cookie: SignedCookie = await parseSigned(cookieString, secret, 'tasty_cookie')59 expect(cookie['yummy_cookie']).toBeUndefined()60 expect(cookie['tasty_cookie']).toBe(false)61 })6263 it('Should parse signed cookies and ignore regular cookies', async () => {64 const secret = 'secret ingredient'65 const cookieString =66 'yummy_cookie=choco; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'67 const cookie: SignedCookie = await parseSigned(cookieString, secret)68 expect(cookie['yummy_cookie']).toBeUndefined()69 expect(cookie['tasty_cookie']).toBe('strawberry')70 })71})7273describe('Set cookie', () => {74 it('Should serialize cookie', () => {75 const serialized = serialize('delicious_cookie', 'macha')76 expect(serialized).toBe('delicious_cookie=macha')77 })15 expect(serialize('delicious_cookie', 'macha')).toBe('delicious_cookie=macha')16 expect(17 serialize('great_cookie', 'banana', {18 path: '/',19 secure: true,20 domain: 'example.com',21 httpOnly: true,22 maxAge: 1000,23 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),24 sameSite: 'Strict',25 })26 ).toBe(7879 it('Should serialize cookie with all options', () => {80 const serialized = serialize('great_cookie', 'banana', {81 path: '/',82 secure: true,83 domain: 'example.com',84 httpOnly: true,85 maxAge: 1000,86 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),87 sameSite: 'Strict',88 })89 expect(serialized).toBe(90 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'91 )92 })9394 it('Should serialize a signed cookie', async () => {95 const secret = 'secret chocolate chips'96 const serialized = await serializeSigned('delicious_cookie', 'macha', secret)97 expect(serialized).toBe(98 'delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D'99 )100 })101102 it('Should serialize singed cookie with all options', async () => {103 const secret = 'secret chocolate chips'104 const serialized = await serializeSigned('great_cookie', 'banana', secret, {105 path: '/',106 secure: true,107 domain: 'example.com',108 httpOnly: true,109 maxAge: 1000,110 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),111 sameSite: 'Strict',112 })113 expect(serialized).toBe(114 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'115 )116 })117118 it('Should serialize cookie with maxAge is 0', () => {32 expect(33 serialize('great_cookie', 'banana', {34 maxAge: 0,35 })36 ).toBe('great_cookie=banana; Max-Age=0')119 const serialized = serialize('great_cookie', 'banana', {120 maxAge: 0,121 })122 expect(serialized).toBe('great_cookie=banana; Max-Age=0')123 })124125 it('Should serialize cookie with maxAge is -1', () => {40 expect(41 serialize('great_cookie', 'banana', {42 maxAge: -1,43 })44 ).toBe('great_cookie=banana')126 const serialized = serialize('great_cookie', 'banana', {127 maxAge: -1,128 })129 expect(serialized).toBe('great_cookie=banana')130 })131})
modified:src/utils/cookie.ts+71 added-7 removed
1import { decodeURIComponent_ } from './url'23export type Cookie = Record<string, string>4export type SignedCookie = Record<string, string | false>5export type CookieOptions = {6 domain?: string7 expires?: Date8 httpOnly?: boolean9 maxAge?: number10 path?: string11 secure?: boolean11 signed?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14}1515export const parse = (cookie: string): Cookie => {16const makeSignature = async (value: string, secret: string): Promise<string> => {17 const algorithm = { name: 'HMAC', hash: 'SHA-256' }18 const encoder = new TextEncoder()19 const key = await crypto.subtle.importKey('raw', encoder.encode(secret), algorithm, false, [20 'sign',21 'verify',22 ])23 const signature = await crypto.subtle.sign(algorithm.name, key, encoder.encode(value))24 return btoa(String.fromCharCode(...new Uint8Array(signature)))25}2627const _parseCookiePairs = (cookie: string, name?: string): string[][] => {28 const pairs = cookie.split(/;\s*/g)29 const cookiePairs = pairs.map((pairStr: string) => pairStr.split(/\s*=\s*([^\s]+)/))30 if (!name) return cookiePairs31 return cookiePairs.filter((pair) => pair[0] === name)32}3334export const parse = (cookie: string, name?: string): Cookie => {35 const parsedCookie: Cookie = {}18 for (let i = 0, len = pairs.length; i < len; i++) {19 const pair = pairs[i].split(/\s*=\s*([^\s]+)/)20 parsedCookie[pair[0]] = decodeURIComponent_(pair[1])36 const unsingedCookies = _parseCookiePairs(cookie, name).filter((pair) => {37 // ignore signed cookies, assuming they always have that commonly accepted format38 if (pair[1].split('.').length === 2) return false39 return true40 })41 for (let [key, value] of unsingedCookies) {42 value = decodeURIComponent_(value)43 parsedCookie[key] = value44 }45 return parsedCookie46}4725export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {26 value = encodeURIComponent(value)48export const parseSigned = async (49 cookie: string,50 secret: string,51 name?: string52): Promise<SignedCookie> => {53 const parsedCookie: SignedCookie = {}54 const signedCookies = _parseCookiePairs(cookie, name).filter((pair) => {55 // ignore signed cookies, assuming they always have that commonly accepted format56 if (pair[1].split('.').length !== 2) return false57 return true58 })59 for (let [key, value] of signedCookies) {60 value = decodeURIComponent_(value)61 const signedPair = value.split('.')62 const signatureToCompare = await makeSignature(signedPair[0], secret)63 if (signedPair[1] !== signatureToCompare) {64 // cookie will be undefined when using getCookie65 parsedCookie[key] = false66 continue67 }68 parsedCookie[key] = signedPair[0]69 }70 return parsedCookie71}7273const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {74 let cookie = `${name}=${value}`7576 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {77 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`
24 unmodified lines
102 }103104 return cookie105}106107export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {108 value = encodeURIComponent(value)109 return _serialize(name, value, opt)110}111112export const serializeSigned = async (113 name: string,114 value: string,115 secret: string,116 opt: CookieOptions = {}117): Promise<string> => {118 const signature = await makeSignature(value, secret)119 value = `${value}.${signature}`120 value = encodeURIComponent(value)121 return _serialize(name, value, opt)122}