tokenNonceKeeper.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import NodeCache from 'node-cache'
  2. // Expiration period in seconds for the local nonce cache.
  3. const TokenExpirationPeriod = 30 // seconds
  4. // Max nonce number in local cache
  5. const MaxNonces = 100000
  6. // Local in-memory cache for nonces.
  7. const nonceCache = new NodeCache({
  8. stdTTL: TokenExpirationPeriod,
  9. deleteOnExpire: true,
  10. maxKeys: MaxNonces,
  11. })
  12. /**
  13. * Constructs and returns an expiration time for a token.
  14. */
  15. export function getTokenExpirationTime(): number {
  16. return Date.now() + 1000 * TokenExpirationPeriod
  17. }
  18. /**
  19. * Creates nonce string using the high precision process time and registers
  20. * it in the local in-memory cache with expiration time.
  21. *
  22. * @returns nonce string.
  23. */
  24. export function createNonce(): string {
  25. const nonce = process.hrtime.bigint().toString()
  26. nonceCache.set(nonce, null, TokenExpirationPeriod)
  27. return nonce
  28. }
  29. /**
  30. * Removes the nonce from the local cache.
  31. *
  32. * @param nonce - nonce string.
  33. * @returns true if nonce was present in local cache.
  34. */
  35. export function checkRemoveNonce(nonce: string): boolean {
  36. const deletedEntries = nonceCache.del(nonce)
  37. return deletedEntries > 0
  38. }