@noctcore/auth-trpc
v0.12.0
Published
tRPC middlewares for @noctcore/auth: a session context, closed procedures, CSRF on mutations, safe error mapping and Zod schemas for the auth procedures.
Maintainers
Readme
Warning: early 0.x releases are not meant for production apps yet. The API may have breaking changes between minor versions until 1.0.
@noctcore/auth-trpc
tRPC middlewares for @noctcore/auth: a context that validates the session cookie through the core, guarded base procedures, CSRF on every mutation, error mapping that never reveals account state, and Zod schemas for the auth procedures. Plain tRPC on the fetch, Node and WebSocket adapters, and nestjs-trpc. On the WebSocket adapter, createAuthContext(...).ws(opts) refuses an upgrade whose Origin fails the CSRF allowlist, sets no cookies and validates the session on every call. The Fastify adapter is not supported yet, and is refused when the context is built.
import { initTRPC } from '@trpc/server';
import { authErrorFormatter, createAuthContext, createAuthMiddlewares } from '@noctcore/auth-trpc';
export const authContext = createAuthContext({
auth, // the createAuth(...) result
trustedHops: 1, // reverse proxies in front of the server, 0 when none, or their addresses
csrf: { secrets: [process.env.CSRF_SECRET], allowedOrigins: ['https://app.example'] },
roles: (user) => [user.role],
});
type Context = Awaited<ReturnType<typeof authContext.node>>;
const t = initTRPC.context<Context>().create({ errorFormatter: authErrorFormatter });
export const { publicProcedure, protectedProcedure, freshAuth, role, rateLimited, writesCookies } =
createAuthMiddlewares(t);- The context.
authContext.fetch(opts, { remoteAddress })orauthContext.node(opts)validates the session cookie with the core once per request.ctx.authholds the session, the request meta (client IP through the trusted hops, or an opt-inclientIpHeadersuch ascf-connecting-ip, which needstrustedHopsas a proxy list naming the edge) and the cookie writers:setSession(issued)on sign-in and every rotation,signOut(),clearSession(cookie), only in a procedure markedwritesCookies(elsewhere they are not on the type and refuse at run time; on a streamed batch the marker refuses before the flow runs, and in a batch only one marked procedure runs: a second is refused before its flow). Each writes a CSRF cookie bound to the new session or pre-session. A streamed batch (httpBatchStreamLink) sends its headers before any procedure runs, and send mutations throughhttpLinkwithsplitLink. - WebSockets.
createContext: (opts) => authContext.ws(opts)onapplyWSSHandler. The upgrade must pass the CSRFOriginallowlist andSec-Fetch-Sitechecks, or the connection is refused before any call (a WebSocket has no CORS, so this guards reads too); a missingOriginonly withwebSocket: { allowMissingOrigin: true }. No cookie is set:ctx.auth.csrfToken()andwritesCookiesrefuse. Every adapter middleware validates the session again on each call, so a sign-out or a revocation refuses the next call on an open socket.ctx.auth.metacomes from the upgrade request. - Guarded procedures.
publicProcedurechecks CSRF on mutations;protectedProcedurealso refuses a caller without a valid session and addsctx.user(loaded from your store on the request) andctx.session.freshAuth(maxAge?),role(...roles)andauthedrun the session and CSRF checks themselves;rateLimited(name, rule?)counts per client IP (or, withkeyBy: 'user', per signed-in user) with the core's throttle and refuses when the counter store is down;createAuthMiddlewares(t, { rateLimits })names tiers, and metarateLimit: 'exempt'skips the count. - CSRF on mutations. The
Originmust be allowed,Sec-Fetch-Sitemust saysame-originwhen sent, and the double-submit token must be bound to this session or pre-session. A refusal isFORBIDDENwith the messageforbiddenand nothing else. - Errors.
toTRPCError(failure)maps everyAuthErrorCodeto a tRPC code from the public code only; an unknown code becomesinternal.authErrorFormatternever sends a stack, answers an input error with paths and issue codes (never the value), a body that does not parse and the codesPARSE_ERROR,METHOD_NOT_SUPPORTED,UNSUPPORTED_MEDIA_TYPE,PAYLOAD_TOO_LARGEandNOT_FOUNDwith a fixed message, and any internal error withinternal. Messages your own procedures throw with any other code go out as written. - Schemas. Zod inputs and outputs for every auth flow. Outputs strip every key they do not name, so a password hash added to your user record never reaches the client.
- Checks for a test.
assertProceduresGuarded(router)fails on a procedure built with neither guarded builder, and on one marked public that asks for a session.assertNoSecretQueries(router)fails on a query whose input names a password, token, code or other secret anywhere in its Zod schema, since query inputs travel in the URL, and on an input it cannot read (z.unknown(),z.custom(),z.preprocess(), a validator that is not Zod 4). - nestjs-trpc.
AuthGuardMiddlewareinglobalMiddlewarescloses every procedure whose meta does not sayauth: 'public';WritesCookiesMiddleware,RoleMiddleware(...),FreshAuthMiddleware(...)andRateLimitMiddleware(...)run the same bodies as plain tRPC.
Needs @trpc/server 11.22.1 or later (within 11) and zod 4.3 or later (within 4).
The guide, with the context on each adapter, sign-in and rotation, and the checks to run in a test: Use with tRPC.
