Skip to main content

Class: RouteUtils

Defined in: service-core/src/routes/RouteUtils.ts:33

Provides a set of utilities for converting Route classes to HTTP middleware.

Constructors​

Constructor​

new RouteUtils(): RouteUtils

Returns​

RouteUtils

Properties​

corsConfig​

protected corsConfig: any = {}

Defined in: service-core/src/routes/RouteUtils.ts:59


csrfConfig​

protected csrfConfig: any

Defined in: service-core/src/routes/RouteUtils.ts:56


rateLimiter?​

protected optional rateLimiter?: RateLimiter

Defined in: service-core/src/routes/RouteUtils.ts:47


trustedProxies​

protected trustedProxies: string[] = []

Defined in: service-core/src/routes/RouteUtils.ts:53


trustedRoles​

protected trustedRoles: string[]

Defined in: service-core/src/routes/RouteUtils.ts:50

Methods​

checkCsrf()​

checkCsrf(): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:98

Creates a middleware function that enforces CSRF protection for a state-changing request whose only credential came from the jwt cookie (req.auth?.source === "cookie". See JWTAuthResult/JWTStrategy). A request authenticated via an Authorization header, API key, or query-string token never had that cookie automatically attached by the browser, so it was never exposed to this class of forgery and is left untouched here.

Returns​

RequestHandler


checkElevation()​

checkElevation(lastStart?): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:65

Creates a middleware function that checks if the user has elevated privileges and if not throws the AUTH_REQUIRES_ELEVATION error.

Parameters​

lastStart?​

number = -1

Returns​

RequestHandler


checkRateLimiter()​

checkRateLimiter(options): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:247

Creates a middleware function that performs rate limiting on the request.

The identifier is options.id when set. Otherwise it is the request method plus the matched route pattern with its decoded params, or the normalized request path (see getRateLimitPath()). With options.perUser, an authenticated caller gets a bucket keyed on their uid and an anonymous caller gets a bucket keyed on their client IP address, so one anonymous client can't exhaust the limit for every other anonymous caller.

Parameters​

options​

RateLimitOptions

Returns​

RequestHandler


checkRequiredPerms()​

checkRequiredPerms(aclUid): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:274

Creates a middleware function that verifies the incoming request is from a valid user with at least one of the specified roles.

Parameters​

aclUid​

string

Returns​

RequestHandler


checkRequiredRoles()​

checkRequiredRoles(requiredRoles): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:301

Creates a middleware function that verifies the incoming request is from a valid user with at least one of the specified roles.

Parameters​

requiredRoles​

string[]

The list of roles that the authenticated user must have.

Returns​

RequestHandler


checkRequiredScopes()​

checkRequiredScopes(requiredScopes): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:346

Creates a middleware function that verifies the incoming request's token carries at least one of the specified scopes. This is a coarse, token-level pre-check that runs before the per-resource ACL check — see RequiresScope.

Parameters​

requiredScopes​

string[]

The list of scopes of which the authenticated user's token must carry at least one.

Returns​

RequestHandler


checkTrusedRoles()​

checkTrusedRoles(): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:322

Creates a middleware function that verifies the incoming request is from a valid user with at least one of the trusted roles.

Returns​

RequestHandler


getFuncArray()​

getFuncArray(route, funcs, send?): RequestHandler[]

Defined in: service-core/src/routes/RouteUtils.ts:402

Converts the given array of string or Function objects to functions bound to the given route object.

Parameters​

route​

any

The route object that the list of functions is bound to.

funcs​

(string | Function)[]

The array of functions (or function names) to return.

send?​

boolean = false

Set to true to have the last wrapped function send its payload to the client.

Returns​

RequestHandler[]

An array of Function objects mapping to the route object.


getRouteMethods()​

getRouteMethods(route): Map<string, any>

Defined in: service-core/src/routes/RouteUtils.ts:425

Searches an route object for any functions that implement a @Method decorator.

Parameters​

route​

any

The route object to search.

Returns​

Map<string, any>

The list of @Method decorated functions that were found.


registerRoute()​

registerRoute(app, route): Promise<void>

Defined in: service-core/src/routes/RouteUtils.ts:482

Registers the provided route object containing a set of decorated endpoints to the server.

Parameters​

app​

any

The HTTP application/router to register the route to.

route​

any

The route object to register.

Returns​

Promise<void>


sanitizeWsError()​

sanitizeWsError(): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:384

Creates a WebSocket-specific error-sanitizing middleware, appended as the last item in every @WebSocket() route's handler chain (see registerRoute()'s WS branch below). Mirrors what Server.ts's handleError()/serializeError() already do for ordinary HTTP routes: an ApiError's own status/code/message pass through unchanged (it's meant to reach the client), but anything else — a raw DB driver error, an unexpected throw from RateLimiter, ACLUtils.findACL(), or any other non-ApiError thrown by a middleware in the chain — is replaced with a generic internal error before runChain()'s own end-of-chain fallback can turn it into a response.

This matters specifically for WebSocket routes because runChain()'s fallback response, for a WS route, ends up as the literal WebSocket close reason (ws.close(1002, message) — see Router.ts/BunRouter.ts's ws() open handlers), visible to any client via the browser close event's event.reason. An ordinary HTTP route gets the same sanitization for free because Server.ts registers handleError as global middleware, which registerRoute() concatenates onto every HTTP route's own handler chain — but app.ws() is never given globalMiddleware (only the WS-specific chain built here), so WS routes need their own copy of the same safety net.

Returns​

RequestHandler


wrapMiddleware()​

wrapMiddleware(obj, func, send?): RequestHandler

Defined in: service-core/src/routes/RouteUtils.ts:719

Wraps the provided function with HTTP handling based on the function's defined decorators.

Parameters​

obj​

any

The bound object whose middleware function will be wrapped.

func​

Function

The decorated function to wrap.

send?​

boolean = false

Set to true to have func's result sent to the client.

Returns​

RequestHandler


getRateLimitPath()​

static getRateLimitPath(req): string

Defined in: service-core/src/routes/RouteUtils.ts:223

Returns the path part of a rate limit identifier for req. When the router has set req.routePattern, the pattern is used with each :param segment replaced by its decoded value from req.params, re-encoded. A pattern with a * wildcard can't be rebuilt from params, so it and a request without a pattern fall back to normalizeRateLimitPath(req.path).

Parameters​

req​

HttpRequest

The request to build the identifier path for.

Returns​

string


normalizeRateLimitPath()​

static normalizeRateLimitPath(path): string

Defined in: service-core/src/routes/RouteUtils.ts:198

Returns a canonical form of a request path for use in rate limit identifiers. The router percent-decodes :param values, so /clients/%61bc and /clients/abc reach the same handler. Keying on the raw path would give an attacker a separate bucket for every encoding variant. Each segment is decoded and then re-encoded (a malformed segment is kept as is), and empty segments from repeated or trailing slashes are dropped.

Parameters​

path​

string

The request path to normalize.

Returns​

string


resolveWebSocketOptions()​

static resolveWebSocketOptions(options, routeName): WebSocketRouteOptions | undefined

Defined in: service-core/src/routes/RouteUtils.ts:148

Validates the options of a @WebSocket() route and returns the object to pass to app.ws() as its wsOptions, or undefined when the route has no options (so it gets the router's defaults, exactly as a route that never had this feature). A field that is undefined is left out and keeps its default.

Every value must be a finite integer: maxPayloadLength from 1 to 16 MiB, maxBackpressure from 1 to 64 MiB, and idleTimeout 0 (disabled) or from 8 to 960 seconds (uWebSockets.js refuses 1 to 7 and anything over 960 by aborting while the route is being registered, so those are rejected here with a readable error instead). An option name that is not one of the three is rejected too, since it would otherwise be silently ignored.

Parameters​

options​

WebSocketRouteOptions | undefined

The options declared on the route, if any.

routeName​

string

A description of the route (e.g. WS /relay/:id), used in the error message.

Returns​

WebSocketRouteOptions | undefined

Throws​

Error naming the route when an option is invalid.