Skip to content

Instantly share code, notes, and snippets.

@rjz
Created August 8, 2023 22:41
Show Gist options
  • Save rjz/9f1339d1c0dfbbf09be95295b90dded4 to your computer and use it in GitHub Desktop.
Save rjz/9f1339d1c0dfbbf09be95295b90dded4 to your computer and use it in GitHub Desktop.
TypeScript wrapper for adding HMAC signatures to an existing codec / SerDe implementation
/** `x/crypto` if running in `deno` */
import { createHmac } from 'node:crypto'
/** A signing secret */
const HMAC_SECRET = '<YOUR SIGNING SECRET HERE>'
/** Length of a hexidecimal HMAC digest */
const HMAC_LENGTH = 64
function hmac(message: string): string {
return createHmac('sha256', HMAC_SECRET).update(message).digest('hex')
}
interface Codec<T> {
encode(payload: T): string
decode(payload: string): T | null
}
function create<T>(codec: Codec<T>): Codec<T> {
return {
encode(payload: T) {
const encoded = codec.encode(payload)
return hmac(encoded) + encoded
},
decode(x: string): T | null {
const signature = x.substring(0, HMAC_LENGTH)
const payload = x.substring(HMAC_LENGTH)
const computed = hmac(payload)
if (computed !== signature) {
return null
}
return codec.decode(payload)
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment