‹›Ronin Code
acme/public-apimain · sandboxed working copyConnecting… claude-sonnet (sample)
Explorer
src › server › middleware.ts
+10−0
| 1 | import type { Request, Response, NextFunction } from "express"; | |
| + | 2 | import { rateLimit } from "../lib/rateLimit"; |
| 3 | ||
| 4 | export function withRequestId(req: Request, res: Response, next: NextFunction) { | |
| 5 | const id = req.header("x-request-id") ?? crypto.randomUUID(); | |
| 6 | res.setHeader("x-request-id", id); | |
| 7 | next(); | |
| 8 | } | |
| 9 | ||
| 10 | export function withSecurityHeaders(_req: Request, res: Response, next: NextFunction) { | |
| 11 | res.setHeader("x-content-type-options", "nosniff"); | |
| 12 | res.setHeader("referrer-policy", "no-referrer"); | |
| 13 | next(); | |
| 14 | } | |
| + | 15 | |
| + | 16 | // Emits X-RateLimit-* headers so clients can back off before they are throttled. |
| + | 17 | export function withRateLimitHeaders(req: Request, res: Response, next: NextFunction) { |
| + | 18 | const { limit, remaining, reset } = rateLimit.peek(req.ip); |
| + | 19 | res.setHeader("x-ratelimit-limit", String(limit)); |
| + | 20 | res.setHeader("x-ratelimit-remaining", String(remaining)); |
| + | 21 | res.setHeader("x-ratelimit-reset", String(reset)); |
| + | 22 | next(); |
| + | 23 | } |
Ask first
runs in an isolated sandbox
$ pnpm test -- rateLimit
ronin › sandbox › node 22 · isolated working copy
✓ tests/rateLimit.test.ts (4)
✓ emits x-ratelimit-limit header
✓ decrements remaining on each request
✓ resets after the window elapses
✓ never reports negative remaining
Test Files 1 passed (1) · Tests 4 passed (4) · 1.2s
Sample runNo command was executed in your environment.