webhook-signatures.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /**
  2. * Proof that an inbound webhook came from the vendor it claims to.
  3. *
  4. * The secret in a webhook URL says which workshop a call is for; it does not
  5. * say who made the call, since anyone who has seen the URL can replay it.
  6. * Each vendor signs its deliveries in its own way, and these are those
  7. * schemes written once, with no I/O, so a route can check a delivery before
  8. * it reads anything out of it.
  9. */
  10. import {
  11. createHash,
  12. createHmac,
  13. createPublicKey,
  14. timingSafeEqual,
  15. verify as verifySignature,
  16. } from 'node:crypto'
  17. import { getAppBaseUrl } from './app-url'
  18. /**
  19. * Equality that takes the same time whether the strings differ in the first
  20. * byte or the last. Both sides are hashed first so lengths never leak either.
  21. */
  22. export function safeEqual(a: string, b: string): boolean {
  23. const left = createHash('sha256').update(a, 'utf8').digest()
  24. const right = createHash('sha256').update(b, 'utf8').digest()
  25. return timingSafeEqual(left, right)
  26. }
  27. /**
  28. * The URL a vendor was given for this request.
  29. *
  30. * Twilio signs the URL as registered in its console. Behind a proxy the host
  31. * that reaches Next is the container's, so the configured public address
  32. * stands in for the origin while path and query are taken from the request.
  33. */
  34. export function publicRequestUrl(requestUrl: string): string {
  35. const url = new URL(requestUrl)
  36. return `${getAppBaseUrl(url.origin)}${url.pathname}${url.search}`
  37. }
  38. export interface TwilioSignatureInput {
  39. authToken: string
  40. /** The full public URL, query string included. */
  41. url: string
  42. /** The POST form fields. Twilio signs the URL plus every field, sorted by name. */
  43. params: URLSearchParams | Record<string, string | string[]>
  44. /** The X-Twilio-Signature header, or null when it was not sent. */
  45. signature: string | null | undefined
  46. }
  47. function paramEntries(params: TwilioSignatureInput['params']): Array<[string, string[]]> {
  48. const grouped = new Map<string, string[]>()
  49. if (params instanceof URLSearchParams) {
  50. for (const [key, value] of params) {
  51. grouped.set(key, [...(grouped.get(key) ?? []), value])
  52. }
  53. } else {
  54. for (const [key, value] of Object.entries(params)) {
  55. grouped.set(key, Array.isArray(value) ? [...value] : [value])
  56. }
  57. }
  58. return [...grouped.entries()]
  59. .map(([key, values]) => [key, values.sort()] as [string, string[]])
  60. .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
  61. }
  62. /** The HMAC-SHA1 Twilio puts in X-Twilio-Signature, for tests and for checking. */
  63. export function twilioSignature(
  64. authToken: string,
  65. url: string,
  66. params: TwilioSignatureInput['params']
  67. ): string {
  68. let data = url
  69. for (const [key, values] of paramEntries(params)) {
  70. for (const value of values) data += key + value
  71. }
  72. return createHmac('sha1', authToken).update(data, 'utf8').digest('base64')
  73. }
  74. export function verifyTwilioSignature(input: TwilioSignatureInput): boolean {
  75. if (!input.signature || !input.authToken) return false
  76. return safeEqual(twilioSignature(input.authToken, input.url, input.params), input.signature)
  77. }
  78. export interface TelnyxSignatureInput {
  79. /** The account's public key as shown in the Telnyx portal: base64 of 32 raw bytes. */
  80. publicKeyBase64: string
  81. /** The telnyx-timestamp header: unix seconds. */
  82. timestamp: string | null | undefined
  83. rawBody: string
  84. /** The telnyx-signature-ed25519 header. */
  85. signatureBase64: string | null | undefined
  86. maxAgeSeconds?: number
  87. /** Milliseconds since the epoch, for tests. */
  88. now?: number
  89. }
  90. /** DER prefix that turns raw ed25519 public key bytes into SubjectPublicKeyInfo. */
  91. const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')
  92. export function verifyTelnyxSignature(input: TelnyxSignatureInput): boolean {
  93. const { timestamp, signatureBase64, maxAgeSeconds = 300, now = Date.now() } = input
  94. if (!timestamp || !signatureBase64 || !input.publicKeyBase64) return false
  95. const issued = Number(timestamp)
  96. if (!Number.isFinite(issued)) return false
  97. if (Math.abs(now / 1000 - issued) > maxAgeSeconds) return false
  98. try {
  99. const raw = Buffer.from(input.publicKeyBase64.trim(), 'base64')
  100. if (raw.length !== 32) return false
  101. const publicKey = createPublicKey({
  102. key: Buffer.concat([ED25519_SPKI_PREFIX, raw]),
  103. format: 'der',
  104. type: 'spki',
  105. })
  106. const signature = Buffer.from(signatureBase64, 'base64')
  107. if (signature.length !== 64) return false
  108. const message = Buffer.from(`${timestamp}|${input.rawBody}`, 'utf8')
  109. return verifySignature(null, message, publicKey, signature)
  110. } catch {
  111. return false
  112. }
  113. }
  114. export interface VonageJwtInput {
  115. /** The bearer token from the Authorization header. */
  116. token: string | null | undefined
  117. /** The account's signature secret. */
  118. secret: string
  119. rawBody: string
  120. /** Milliseconds since the epoch, for tests. */
  121. now?: number
  122. }
  123. function decodeJwtPart(part: string): unknown {
  124. return JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
  125. }
  126. /**
  127. * Vonage signs webhooks with an HS256 JWT over the account's signature
  128. * secret. The token binds the body through `payload_hash`, the SHA-256 of the
  129. * exact bytes delivered, so a valid token cannot be reused on another body.
  130. */
  131. export function verifyVonageJwt(input: VonageJwtInput): boolean {
  132. const { token, secret, rawBody, now = Date.now() } = input
  133. if (!token || !secret) return false
  134. const parts = token.trim().split('.')
  135. if (parts.length !== 3) return false
  136. const [encodedHeader, encodedPayload, encodedSignature] = parts
  137. try {
  138. const header = decodeJwtPart(encodedHeader) as { alg?: unknown }
  139. if (header?.alg !== 'HS256') return false
  140. const expected = createHmac('sha256', secret)
  141. .update(`${encodedHeader}.${encodedPayload}`, 'utf8')
  142. .digest('base64url')
  143. if (!safeEqual(expected, encodedSignature)) return false
  144. const payload = decodeJwtPart(encodedPayload) as {
  145. exp?: unknown
  146. payload_hash?: unknown
  147. }
  148. if (typeof payload.exp === 'number' && payload.exp * 1000 <= now) return false
  149. if (typeof payload.payload_hash === 'string') {
  150. const bodyHash = createHash('sha256').update(rawBody, 'utf8').digest('hex')
  151. if (!safeEqual(bodyHash, payload.payload_hash.toLowerCase())) return false
  152. }
  153. return true
  154. } catch {
  155. return false
  156. }
  157. }
  158. const warned = new Set<string>()
  159. /**
  160. * Logs a message once per key for the life of the process. For a connection
  161. * that lacks the credential its vendor signs with: worth saying, not worth
  162. * saying on every delivery.
  163. */
  164. export function warnOnce(key: string, message: string): void {
  165. if (warned.has(key)) return
  166. warned.add(key)
  167. console.warn(message)
  168. }