import type { AnyProcedure, Context } from '@orpc/server' import type { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptor, } from '@orpc/server/standard' import { toArray } from '@orpc/shared' import type { StandardHeaders } from '@standard-server/core' import type { RateLimitResult } from './types' export const RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL: unique symbol = /* @__PURE__ */ Symbol.for( 'ORPC_RATELIMIT_HANDLER_PLUGIN_CONTEXT', ) export interface RateLimitHandlerPluginContext { [RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL]?: { /** * The result of the ratelimiter after applying limits */ checks: { procedure: AnyProcedure; path: readonly string[]; result: RateLimitResult }[] } } /** * Automatically adds HTTP rate limiting headers (`RateLimit-*` and `Retry-After`) * to responses when used with the `ratelimit` middleware. * * `RateLimit-Reset` and `Retry-After` are in seconds until the limit resets. * * @see {@link https://orpc.dev/docs/helpers/ratelimit#handler-plugin | Rate Limit Helpers - Handler Plugin} */ export class RateLimitHandlerPlugin implements StandardHandlerPlugin { readonly name = '~ratelimit' init(options: StandardHandlerOptions): StandardHandlerOptions { // oxlint-disable-next-line unicorn/consistent-function-scoping const routingInterceptor: StandardHandlerRoutingInterceptor = async (interceptorOptions) => { const pluginContext: Exclude< RateLimitHandlerPluginContext[typeof RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL], undefined > = { checks: [] } const result = await interceptorOptions.next({ ...interceptorOptions, context: { ...interceptorOptions.context, [RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL]: pluginContext, } satisfies RateLimitHandlerPluginContext, }) if (result.matched && pluginContext.checks.length) { const exceededChecks = pluginContext.checks.filter((r) => !r.result.success) // Pick the most constrained result: prefer exceeded limits, fall back to all results. // Treat undefined remaining as 0 — unknown capacity is assumed fully exhausted. const mostConstrained = ( exceededChecks.length ? exceededChecks : pluginContext.checks ).reduce((a, b) => (a.result.remaining ?? Infinity) <= (b.result.remaining ?? Infinity) ? a : b, ) const { reset } = mostConstrained.result const secondsUntilReset = reset === undefined ? undefined : Math.max(0, Math.ceil((reset - Date.now()) / 1000)).toString() const headers: StandardHeaders = { ...result.response.headers, 'ratelimit-limit': mostConstrained.result.limit?.toString(), 'ratelimit-remaining': mostConstrained.result.remaining?.toString(), 'ratelimit-reset': secondsUntilReset, } if ( result.response.status >= 400 && !mostConstrained.result.success && secondsUntilReset !== undefined ) { headers['retry-after'] = secondsUntilReset } return { ...result, response: { ...result.response, headers, }, } } return result } return { ...options, routingInterceptors: [...toArray(options.routingInterceptors), routingInterceptor], } } }