From d2b6413ab3b2588a06f5b852e40254afe2e50d92 Mon Sep 17 00:00:00 2001 From: Oliver Eyton-Williams Date: Wed, 3 Jul 2024 16:24:13 +0200 Subject: [PATCH] fix: stricter types for unsigned cookies (#292) The success and failure cases are distinct and the types can reflect this. --- types/plugin.d.ts | 10 +++++++--- types/plugin.test-d.ts | 36 ++++++++++++++++++++++++------------ 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/types/plugin.d.ts b/types/plugin.d.ts index 2e0f959..ef4af4f 100644 --- a/types/plugin.d.ts +++ b/types/plugin.d.ts @@ -155,10 +155,14 @@ declare namespace fastifyCookie { export type Unsign = (input: string, secret: string | Buffer, algorithm?: string) => UnsignResult; export type SignerFactory = (secrets: string | string[] | Buffer | Buffer[], algorithm?: string) => SignerBase; - export interface UnsignResult { - valid: boolean; + export type UnsignResult = { + valid: true; renew: boolean; - value: string | null; + value: string; + } | { + valid: false; + renew: false; + value: null; } export const signerFactory: SignerFactory; diff --git a/types/plugin.test-d.ts b/types/plugin.test-d.ts index 05824bf..2174356 100644 --- a/types/plugin.test-d.ts +++ b/types/plugin.test-d.ts @@ -150,11 +150,15 @@ appWithRotationSecret.register(cookie, { appWithRotationSecret.after(() => { server.get('/', (request, reply) => { reply.unsignCookie(request.cookies.test!); - const { valid, renew, value } = reply.unsignCookie('test'); + const unsigned = reply.unsignCookie('test'); - expectType(valid); - expectType(renew); - expectType(value); + expectType(unsigned.valid); + if (unsigned.valid) { + expectType(unsigned.value); + } else { + expectType(unsigned.value); + } + expectType(unsigned.renew); reply.send({ hello: 'world' }); }); @@ -182,11 +186,15 @@ appWithParseOptions.register(cookie, { }); appWithParseOptions.after(() => { server.get('/', (request, reply) => { - const { valid, renew, value } = reply.unsignCookie(request.cookies.test!); + const unsigned = reply.unsignCookie(request.cookies.test!); - expectType(valid); - expectType(renew); - expectType(value); + expectType(unsigned.valid); + if (unsigned.valid) { + expectType(unsigned.value); + } else { + expectType(unsigned.value); + } + expectType(unsigned.renew); }); }); @@ -204,11 +212,15 @@ appWithCustomSigner.register(cookie, { appWithCustomSigner.after(() => { server.get('/', (request, reply) => { reply.unsignCookie(request.cookies.test!) - const { valid, renew, value } = reply.unsignCookie('test') + const unsigned = reply.unsignCookie('test') - expectType(valid) - expectType(renew) - expectType(value) + expectType(unsigned.valid); + if (unsigned.valid) { + expectType(unsigned.value); + } else { + expectType(unsigned.value); + } + expectType(unsigned.renew); reply.send({ hello: 'world' }) })