Kai Nakamura
Apr 2026
2 tabs
timestamp = request.headers.fetch('X-Signature-Timestamp')
signature = request.headers.fetch('X-Signature')
payload = request.raw_post
data = "#{timestamp}.#{payload}"
expected = OpenSSL::HMAC.hexdigest('SHA256', ENV.fetch('WEBHOOK_SECRET'), data)
unless ActiveSupport::SecurityUtils.secure_compare(signature, expected)
head :unauthorized
end
import hashlib
import hmac
import time
timestamp = str(int(time.time()))
body = b'{"event":"member.approved","id":42}'
signing_string = f'{timestamp}.'.encode('utf-8') + body
signature = hmac.new(SECRET.encode('utf-8'), signing_string, hashlib.sha256).hexdigest()
2 files · ruby, python
Explain with highlit
When I need lightweight message integrity without standing up a full asymmetric trust model, HMAC signing is a solid tool. The important details are canonicalization, timestamp freshness, and constant-time comparison. Most failed implementations get the signing process almost right and that is not good enough.
Related snips
ruby
event_id = request.headers.fetch('X-Event-Id')
timestamp = request.headers.fetch('X-Signature-Timestamp').to_i
raise ActionController::BadRequest, 'stale request' if Time.now.to_i - timestamp > 300
raise ActionController::BadRequest, 'replay detected' if WebhookEvent.exists?(external_id: event_id)
Secure webhook endpoint design with replay protection
webhooks
replay-protection
hmac
by Kai Nakamura
1 tab
ruby
class CreateProcessedEvents < ActiveRecord::Migration[7.1]
def change
create_table :processed_events do |t|
t.string :event_key, null: false
t.string :job_class, null: false
t.jsonb :metadata, null: false, default: {}
Idempotent Job with Advisory Lock
rails
postgres
reliability
by codesnips
3 tabs
typescript
import crypto from 'crypto';
interface VerifyOptions {
rawBody: Buffer;
signatureHeader: string | undefined;
secret: string;
Webhook signature verification (timing-safe compare)
security
webhooks
hmac
by codesnips
3 tabs
ruby
class AddUniqueIndexToInventorySnapshots < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
add_index :inventory_snapshots,
[:warehouse_id, :sku],
Bulk Upsert with insert_all + Unique Index
rails
activerecord
postgres
by codesnips
3 tabs
typescript
import { Injectable } from '@nestjs/common';
export interface RateLimitResult {
allowed: boolean;
remaining: number;
limit: number;
Sliding-Window Webhook Rate Limiting with a NestJS Interceptor and In-Memory Counter
typescript
nestjs
rate-limiting
by codesnips
3 tabs
php
<?php
namespace App\Http\Controllers;
use App\Jobs\ProcessWebhook;
use App\Support\WebhookSignature;
Debounce Duplicate Webhooks in Laravel by Dispatching a Delayed Queued Job
laravel
webhooks
queues
by codesnips
3 tabs
Share this code
Here's the card — post it anywhere.