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
Provenance
- Commit
35246d0- Tree
b3cc712- Author
Torsten Engelbrecht <torsten.engelbrecht@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
47ae014
6 files changed+417 added−44 removed
modified:deno_dist/middleware/cookie/index.ts+31 added-2 removed
123234567891011121314151617185 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859import type { Context } from '../../context.ts'import { parse, serialize } from '../../utils/cookie.ts'import type { CookieOptions, Cookie } from '../../utils/cookie.ts'import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie.ts'import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie.ts'
interface GetCookie { (c: Context, key: string): string | undefined (c: Context): Cookie}
interface GetSignedCookie { (c: Context, sercet: string, key: string): Promise<string | undefined | false> (c: Context, secret: string): Promise<SignedCookie>}
export const getCookie: GetCookie = (c, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined5 unmodified lines // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = await parseSigned(cookie, secret, key) return obj[key] } if (!cookie) return {} const obj = await parseSigned(cookie, secret) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => { const cookie = serialize(name, value, opt) c.header('set-cookie', cookie, { append: true })}
export const setSignedCookie = async ( c: Context, name: string, value: string, secret: string, opt?: CookieOptions): Promise<void> => { const cookie = await serializeSigned(name, value, secret, opt) c.header('set-cookie', cookie, { append: true })}
export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => { setCookie(c, name, '', { ...opt, maxAge: 0 })}modified:deno_dist/utils/cookie.ts+71 added-7 removed
12345678910111112131415151617181920212223242526272829303132333435181920363738394041424344454647252648495051525354555657585960616263646566676869707172737475767724 unmodified lines102103104105106107108109110111112113114115116117118119120121122import { decodeURIComponent_ } from './url.ts'
export type Cookie = Record<string, string>export type SignedCookie = Record<string, string | false>export type CookieOptions = { domain?: string expires?: Date httpOnly?: boolean maxAge?: number path?: string secure?: boolean signed?: boolean signingSecret?: string sameSite?: 'Strict' | 'Lax' | 'None'}
export const parse = (cookie: string): Cookie => {const makeSignature = async (value: string, secret: string): Promise<string> => { const algorithm = { name: 'HMAC', hash: 'SHA-256' } const encoder = new TextEncoder() const key = await crypto.subtle.importKey('raw', encoder.encode(secret), algorithm, false, [ 'sign', 'verify', ]) const signature = await crypto.subtle.sign(algorithm.name, key, encoder.encode(value)) return btoa(String.fromCharCode(...new Uint8Array(signature)))}
const _parseCookiePairs = (cookie: string, name?: string): string[][] => { const pairs = cookie.split(/;\s*/g) const cookiePairs = pairs.map((pairStr: string) => pairStr.split(/\s*=\s*([^\s]+)/)) if (!name) return cookiePairs return cookiePairs.filter((pair) => pair[0] === name)}
export const parse = (cookie: string, name?: string): Cookie => { const parsedCookie: Cookie = {} for (let i = 0, len = pairs.length; i < len; i++) { const pair = pairs[i].split(/\s*=\s*([^\s]+)/) parsedCookie[pair[0]] = decodeURIComponent_(pair[1]) const unsingedCookies = _parseCookiePairs(cookie, name).filter((pair) => { // ignore signed cookies, assuming they always have that commonly accepted format if (pair[1].split('.').length === 2) return false return true }) for (let [key, value] of unsingedCookies) { value = decodeURIComponent_(value) parsedCookie[key] = value } return parsedCookie}
export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => { value = encodeURIComponent(value)export const parseSigned = async ( cookie: string, secret: string, name?: string): Promise<SignedCookie> => { const parsedCookie: SignedCookie = {} const signedCookies = _parseCookiePairs(cookie, name).filter((pair) => { // ignore signed cookies, assuming they always have that commonly accepted format if (pair[1].split('.').length !== 2) return false return true }) for (let [key, value] of signedCookies) { value = decodeURIComponent_(value) const signedPair = value.split('.') const signatureToCompare = await makeSignature(signedPair[0], secret) if (signedPair[1] !== signatureToCompare) { // cookie will be undefined when using getCookie parsedCookie[key] = false continue } parsedCookie[key] = signedPair[0] } return parsedCookie}
const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => { let cookie = `${name}=${value}`
if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) { cookie += `; Max-Age=${Math.floor(opt.maxAge)}`24 unmodified lines }
return cookie}
export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => { value = encodeURIComponent(value) return _serialize(name, value, opt)}
export const serializeSigned = async ( name: string, value: string, secret: string, opt: CookieOptions = {}): Promise<string> => { const signature = await makeSignature(value, secret) value = `${value}.${signature}` value = encodeURIComponent(value) return _serialize(name, value, opt)}modified:src/middleware/cookie/index.test.ts+103 added-1 removed
1 import { Hono } from '../../hono'2-import { getCookie, setCookie, deleteCookie } from '.'2+import { getCookie, getSignedCookie, setCookie, setSignedCookie, deleteCookie } from '.'3 4 describe('Cookie Middleware', () => {5 describe('Parse cookie', () => {6 const apps: Record<string, Hono> = {}39 unmodified lines46 expect(res.headers.get('Yummy-Cookie')).toBe('choco')47 expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48 })49 })50+51+ const app = new Hono()52+53+ 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+ })67+68+ 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+ })78+79+ 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+ })88+89+ 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+ })98+99+ 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+ })107+108+ 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 })117 118 describe('Set cookie', () => {119 const app = new Hono()9 unmodified lines129 const header = res.headers.get('Set-Cookie')130 expect(header).toBe('delicious_cookie=macha')131 })132 133+ 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+ })138+139+ 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+ })145+146 app.get('/set-cookie-complex', (c) => {147 setCookie(c, 'great_cookie', 'banana', {148 path: '/',149 secure: true,14 unmodified lines164 '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 })167 168+ 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+ })181+182+ 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+ })190+191 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 linesmodified:src/middleware/cookie/index.ts+31 added-2 removed
123234567891011121314151617185 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859import type { Context } from '../../context'import { parse, serialize } from '../../utils/cookie'import type { CookieOptions, Cookie } from '../../utils/cookie'import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'
interface GetCookie { (c: Context, key: string): string | undefined (c: Context): Cookie}
interface GetSignedCookie { (c: Context, sercet: string, key: string): Promise<string | undefined | false> (c: Context, secret: string): Promise<SignedCookie>}
export const getCookie: GetCookie = (c, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined5 unmodified lines // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = await parseSigned(cookie, secret, key) return obj[key] } if (!cookie) return {} const obj = await parseSigned(cookie, secret) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => { const cookie = serialize(name, value, opt) c.header('set-cookie', cookie, { append: true })}
export const setSignedCookie = async ( c: Context, name: string, value: string, secret: string, opt?: CookieOptions): Promise<void> => { const cookie = await serializeSigned(name, value, secret, opt) c.header('set-cookie', cookie, { append: true })}
export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => { setCookie(c, name, '', { ...opt, maxAge: 0 })}modified:src/utils/cookie.test.ts+110 added-25 removed
1-import type { Cookie } from './cookie'2-import { parse, serialize } from './cookie'1+import type { Cookie, SignedCookie } from './cookie'2+import { parse, parseSigned, serialize, serializeSigned } from './cookie'3 4 describe('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 })11+12+ 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+ })18+19+ 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+ })26+27+ 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+ })35+36+ 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+ })44+45+ 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+ })53+54+ 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+ })62+63+ 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 })72 73 describe('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(78+79+ 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 })93 94+ 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+ })101+102+ 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+ })117+118 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 })124 125 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
1 import { decodeURIComponent_ } from './url'2 3 export type Cookie = Record<string, string>4+export type SignedCookie = Record<string, string | false>5 export type CookieOptions = {6 domain?: string7 expires?: Date8 httpOnly?: boolean9 maxAge?: number10 path?: string11 secure?: boolean11- signed?: boolean12+ signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 }15 15-export const parse = (cookie: string): Cookie => {16+const 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+}26+27+const _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+}33+34+export 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 }47 25-export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {26- value = encodeURIComponent(value)48+export 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+}72+73+const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {74 let cookie = `${name}=${value}`75 76 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {77 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`24 unmodified lines102 }103 104 return cookie105 }106+107+export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {108+ value = encodeURIComponent(value)109+ return _serialize(name, value, opt)110+}111+112+export 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+}