From b122bb49030e506cda8edd47341f1fa90023995a Mon Sep 17 00:00:00 2001 From: Julien Rousseau Date: Tue, 28 Nov 2023 12:46:01 -0500 Subject: [PATCH] fixed caching issue on signature generation --- src/auth/cached.ts | 21 ++++++++++++++------- src/auth/ed25519.ts | 4 ++-- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/auth/cached.ts b/src/auth/cached.ts index 58c63f3..9590b29 100644 --- a/src/auth/cached.ts +++ b/src/auth/cached.ts @@ -1,19 +1,26 @@ import { sign, verify } from "./ed25519.js"; -// Keep in memory the latest generated signature. We do not regenerate it it is still valid. -let latestSignature: ReturnType = { signature: "", publicKey: "", expirationTime: 0 }; +// Keep in memory the latest generated signature for every secret key. +// We do not regenerate them if they are still valid. +const latestSignatures = new Map>(); export function cachedSign(...args: Parameters): ReturnType { - const [_, expirationTimeInSecs] = args; + const [secretKey, durationInSecs] = args; // Do not recalculate a signature it the latest one expires in less than 40% of the expiryTime - if (latestSignature.expirationTime - new Date().getTime() <= 0.4 * expirationTimeInSecs * 1000) { + let latestSignature = latestSignatures.get(secretKey); + if (!latestSignature || generatedSignatureIsExpired(latestSignature.expirationTime, durationInSecs)) { latestSignature = sign(...args); + latestSignatures.set(secretKey, latestSignature); } return latestSignature; } +function generatedSignatureIsExpired(expirationTime: number, signatureDurationInSecs: number) { + return expirationTime - new Date().getTime() <= 0.4 * signatureDurationInSecs * 1000; +} + // Keep in memory which signatures are currently valid, and at what time they become invalid. // This allows to skip the ed25519 validation process each time and only compare the expiration time. const validSignatures = new Map(); @@ -24,7 +31,7 @@ export function cachedVerify(...args: Parameters): ReturnType): ReturnType): ReturnType= expirationTime; } diff --git a/src/auth/ed25519.ts b/src/auth/ed25519.ts index 2d3b209..61a2929 100644 --- a/src/auth/ed25519.ts +++ b/src/auth/ed25519.ts @@ -1,8 +1,8 @@ import nacl from "tweetnacl"; -export function sign(secretKey: string, expirationTimeInSecs: number) { +export function sign(secretKey: string, durationInSecs: number) { const publicKey = secretKey.substring(nacl.sign.secretKeyLength); - const expirationTime = new Date().getTime() + expirationTimeInSecs * 1000; + const expirationTime = new Date().getTime() + durationInSecs * 1000; const payload = JSON.stringify({ exp: expirationTime, id: publicKey }); const signedBuffer = nacl.sign.detached(Buffer.from(payload), Buffer.from(secretKey, "hex"));