- 用事务 Outbox 和签名 Webhook 替换直接状态回调 - 增加 Outbox 投递 worker、重试与低频对账兜底 - 缓存客户领取页绑定状态并补充签名与迁移测试
46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
|
|
const SIGNATURE_PREFIX = 'sha256='
|
|
const DEFAULT_TOLERANCE_SECONDS = 300
|
|
|
|
export function buildWebhookSignature(secret: string, timestamp: string, rawBody: string) {
|
|
return (
|
|
SIGNATURE_PREFIX + createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')
|
|
)
|
|
}
|
|
|
|
export function verifyWebhookSignature(input: {
|
|
secret: string
|
|
timestamp: string
|
|
rawBody: string
|
|
signature: string
|
|
toleranceSeconds?: number
|
|
nowSeconds?: number
|
|
}) {
|
|
const secret = String(input.secret || '').trim()
|
|
const timestamp = String(input.timestamp || '').trim()
|
|
const signature = String(input.signature || '').trim()
|
|
if (!secret || !timestamp || !signature) return false
|
|
|
|
const timestampSeconds = Number(timestamp)
|
|
if (!Number.isInteger(timestampSeconds) || timestampSeconds <= 0) return false
|
|
|
|
const tolerance = Math.max(
|
|
1,
|
|
Math.trunc(Number(input.toleranceSeconds) || DEFAULT_TOLERANCE_SECONDS),
|
|
)
|
|
const nowSeconds = Math.trunc(Number(input.nowSeconds) || Date.now() / 1000)
|
|
if (Math.abs(nowSeconds - timestampSeconds) > tolerance) return false
|
|
|
|
const expected = buildWebhookSignature(secret, timestamp, String(input.rawBody || ''))
|
|
const expectedBuffer = Buffer.from(expected)
|
|
const providedBuffer = Buffer.from(signature)
|
|
if (expectedBuffer.length !== providedBuffer.length) return false
|
|
return timingSafeEqual(expectedBuffer, providedBuffer)
|
|
}
|
|
|
|
export function webhookToleranceSeconds() {
|
|
const value = Number(process.env.PLATFORM_FULFILLMENT_WEBHOOK_TOLERANCE_SECONDS || 300)
|
|
return Number.isFinite(value) && value > 0 ? Math.trunc(value) : DEFAULT_TOLERANCE_SECONDS
|
|
}
|