Skip to Content
Server

Middleware

Request id, security headers, CORS, CSRF, rate limiting and maintenance mode.

Usage

import { Hono } from "hono"
import { requestId } from "@dapplelight/signet-server/middleware/request-id"
import { secureHeaders } from "@dapplelight/signet-server/middleware/secure-headers"
import { corsMiddleware } from "@dapplelight/signet-server/middleware/cors"
import { csrfMiddleware } from "@dapplelight/signet-server/middleware/csrf"
import { rateLimit } from "@dapplelight/signet-server/middleware/rate-limit"
import { durableObjectStore } from "@dapplelight/signet-server/middleware/rate-limit-do"

const app = new Hono<{ Bindings: { RATE_LIMIT: DurableObjectNamespace } }>()

app.use("*", requestId())
app.use("*", secureHeaders({ relaxedPaths: ["/docs", "/openapi.json"] }))
app.use("*", corsMiddleware({ originEnvKeys: ["WEB_URL", "ADMIN_URL"] }))
app.use("/api/*", csrfMiddleware({ originEnvKeys: ["WEB_URL", "ADMIN_URL"] }))
app.use("/api/*", rateLimit({ max: 100, windowSeconds: 60, trust: "cloudflare" }))

// A login limit is a security control: exact count, and refuse if the store is down.
app.use("/api/auth/login", rateLimit({
  scope: "login",
  max: 5,
  windowSeconds: 60,
  trust: "cloudflare",
  store: (c) => durableObjectStore(c.env.RATE_LIMIT), // built per request: bindings live on c.env
  failOpen: false,
}))

API

middleware/cors

ExportWhat it does
corsMiddleware(options)CORS that only allows origins you list; never reflects an unknown origin.
allowedOrigins(options)The origins options allows right now (read per request).
CorsOptionsOptions type.

middleware/csrf

ExportWhat it does
csrfMiddleware(options)Blocks form-style unsafe requests from untrusted origins (403 FORBIDDEN envelope).
CsrfOptionsoriginEnvKeys, extraOrigins, devOrigins from CorsOptions.

middleware/maintenance

ExportWhat it does
maintenanceMode(options)503 MAINTENANCE with Retry-After for everyone off the allowlist.
MaintenanceState, MaintenanceOptionsTypes.

middleware/rate-limit

ExportWhat it does
rateLimit(options)Rate limiting with a pluggable store; 429 RATE_LIMITED.
memoryStore()Default store. Per-isolate fixed window.
clientIp(c, trust)The client IP under your trust setting. IPv6 is keyed by its /64.
RateLimitStore, RateLimitResult, RateLimitOptions, ClientIpTrustTypes.

middleware/rate-limit-do

ExportWhat it does
RateLimitCounterDurable Object class, one object per scope:key. Export it from the worker entry.
durableObjectStore(namespace)Exact RateLimitStore on that Durable Object.
RateLimitCounterState, RateLimitNamespaceStructural types.

middleware/request-id

ExportWhat it does
requestId(options)Sets c.get("reqId") and echoes the header.
RequestIdOptionsOptions type.

middleware/secure-headers

ExportWhat it does
secureHeaders(options)nosniff, frame deny, referrer, permissions, COOP, CORP, HSTS and a CSP.
STRICT_CSPDefault CSP: default-src 'none'; frame-ancestors 'none'; base-uri 'none'.
DOCS_CSPDefault relaxed CSP for relaxedPaths.
SecureHeadersOptionsOptions type.

rateLimit(options)

OptionTypeDefault
trustClientIpTrustrequired unless keyForThrows at construction otherwise.
keyFor(c) => stringclient IPUse a user id for per-account limits.
storeRateLimitStore | (c) => RateLimitStorememoryStore()A function builds one per request.
scopestring"api"Keeps "login" and "api" counters apart.
maxnumber100Requests per window.
windowSecondsnumber60
onNoIp"allow" | "reject" | "bucket""bucket"A request with no usable client IP: share one no-ip bucket (once full, every IP-less caller gets 429), let it through, or answer 400 BAD_REQUEST. Ignored with keyFor.
failOpenbooleantruefalse: a store error is 503 RATE_LIMIT_UNAVAILABLE.
onStoreError(err, c) => voidnoneHears every store failure.
getRequestId(c) => string | undefinedc.get("reqId")For the error envelope.

ClientIpTrust is "cloudflare" (read cf-connecting-ip, on Cloudflare Workers only; on Node, Bun or Deno it is ignored and onNoIp applies), { cloudflare: { originLocked: true } } (read it on any runtime, when the origin accepts only Cloudflare's IP ranges), { forwardedHops: n } (the n-th x-forwarded-for entry from the right) or "none" (one shared bucket).

corsMiddleware(options)

OptionTypeDefault
originEnvKeysstring[]noneEnv var names holding allowed origins.
extraOriginsstring[]noneLiteral origins.
devOriginsstring[]localhost:5173, localhost:5174Allowed only when APP_ENV (or NODE_ENV) is local, development or test. [] disables.
credentialsbooleantrueSend cookies.

maintenanceMode(options)

OptionTypeDefault
state(c) => { on, message?, until? }requiredMay be async. Read at most once per cacheMs.
pathsstring[]["/health", "/healthz"]Prefixes that always pass.
allow(c) => booleannoneLet a request through, e.g. an admin session.
cacheMsnumber50000 reads every request.
retryAfterSecondsnumber300Used when the state has no until.
messagestringnoneEnvelope message when the state has none.

secureHeaders(options)

OptionTypeDefault
cspstringSTRICT_CSP
relaxedPathsstring[][]Paths (and sub-paths) served relaxedCsp.
relaxedCspstringDOCS_CSP
hstsMaxAgenumberone year0 omits HSTS.

requestId(options)

OptionTypeDefault
childLogger(reqId) => unknownnonePer-request logger bound to the id.
headerstring"x-request-id"Header honoured from upstream and echoed.
accept(id) => boolean1-128 of [A-Za-z0-9_-]Anything else is replaced with a UUID.

Examples

Maintenance switch with an admin bypass

import { maintenanceMode } from "@dapplelight/signet-server/middleware/maintenance"
import { app } from "./app"
import { status } from "./status"

app.use("*", maintenanceMode({
  state: () => status.maintenance(),
  paths: ["/health", "/api/status", "/api/admin"],
  allow: (c) => c.get("session")?.role === "admin",
}))

Cookies across origins

import { csrfMiddleware } from "@dapplelight/signet-server/middleware/csrf"
import { app } from "./app"

// A SameSite=None session cookie loses Lax's protection: add CSRF before routes that read it.
app.use("/api/*", csrfMiddleware({ originEnvKeys: ["WEB_URL"] }))

Worker entry for the exact limiter

// Export from the worker entry so the binding finds it.
export { RateLimitCounter } from "@dapplelight/signet-server/middleware/rate-limit-do"
// wrangler.jsonc
"durable_objects": { "bindings": [{ "name": "RATE_LIMIT", "class_name": "RateLimitCounter" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["RateLimitCounter"] }]