Use with tRPC
This guide
- You build
A tRPC router on the core: guarded procedures, CSRF on every mutation, cookies written only by procedures marked to write them, and errors that say no more than the public code.
- You need first
A Node server with Redis and Prisma, whose
auth.tsandconfig.tsare used as they are, and@trpc/server11 withzod4.- It works when
router.test.tspasses: every procedure has an access rule, no query carries a secret, and a mutation without the CSRF token is refused with403.
@noctcore/auth-trpc puts the core behind tRPC procedures. The core stays the same: the flows return AuthResult values and never throw, and the adapter only decides who gets through, writes the cookies and turns a refusal into a tRPC error that says no more than the public code.
This guide builds on A Node server with Redis and Prisma: auth.ts and config.ts there are used as they are.
How the pieces fit
Section titled “How the pieces fit”protectedProcedure the session
check, ahead of everything the chain adds.
In the browser, createClient in client.ts sends each mutation on httpLink, one per request, and batches queries on httpBatchStreamLink. On the server, authContext.node(opts), or .fetch(opts) on the fetch adapter, builds ctx.auth once per HTTP request: the session, the client IP, the CSRF checks and, on a query, the cookies the page needs. Each procedure then runs the checks of its chain. login is built on publicProcedure, which checks CSRF on a mutation and refuses with forbidden, and uses writesCookies, which refuses with internal on a streamed batch; its handler calls setSession, which writes the cookies. exportData is built on protectedProcedure, which checks CSRF (forbidden) and the session (session_expired), then uses freshAuth('5m') (fresh_auth_required) and rateLimited (rate_limited) before its handler runs.
Text version
Build it
Section titled “Build it”-
Install
Section titled “Install”Terminal window bun add @noctcore/auth-trpc @noctcore/auth @trpc/server zodTwo of them are peer dependencies, and CI runs the adapter at both floors:
Peer Range @trpc/server11.22.1 or later (within 11) zod4.3 or later (within 4) -
The router
Section titled “The router”src/router.ts import type { AppAuth } from '../node-server/auth.ts';import {acceptedOutput,authErrorFormatter,createAuthMiddlewares,csrfTokenOutput,loginInput,loginOutput,reauthenticateInput,registerInput,requestPasswordResetInput,revokedOutput,revokeSessionInput,sessionListOutput,toTRPCError,userOutput,verifyEmailLinkInput,type AuthContextOf,} from '@noctcore/auth-trpc';import { initTRPC } from '@trpc/server';import { z } from 'zod';// ctx.auth from createAuthContext, typed by your createAuth result.export type Context = AuthContextOf<AppAuth>;// The formatter keeps stacks, submitted values and internal messages out of// the errors tRPC and the adapter raise. Messages you throw yourself go out// as you wrote them.const t = initTRPC.context<Context>().create({ errorFormatter: authErrorFormatter });// Build every procedure on these two: assertProceduresGuarded fails on one// that uses neither.const { publicProcedure, protectedProcedure, freshAuth, rateLimited, writesCookies } =createAuthMiddlewares(t);export function createAppRouter(auth: AppAuth) {return t.router({// A query: hands the page its pre-session and CSRF cookies on first load.session: publicProcedure.query(async ({ ctx }) => ({ signedIn: (await ctx.auth.user()) !== null })),register: publicProcedure.input(registerInput).output(acceptedOutput).mutation(async ({ ctx, input }) => {const result = await auth.register({ ...input, meta: ctx.auth.meta });if (!result.ok) throw toTRPCError(result);// The same answer for a new address and a taken one.return { status: 'accepted' as const };}),// writesCookies hands the procedure ctx.auth.setSession and signOut;// without it they are not there. On a streamed batch it refuses first.login: publicProcedure.use(writesCookies).input(loginInput).output(loginOutput).mutation(async ({ ctx, input }) => {const result = await auth.login({...input,deviceToken: ctx.auth.deviceToken,meta: ctx.auth.meta,});if (!result.ok) throw toTRPCError(result);if (result.value.kind === 'challenge') return result.value;return { kind: 'session' as const, ...ctx.auth.setSession(result.value.session) };}),requestPasswordReset: publicProcedure.input(requestPasswordResetInput).output(acceptedOutput).mutation(async ({ ctx, input }) => {const result = await auth.requestPasswordReset({ ...input, meta: ctx.auth.meta });if (!result.ok) throw toTRPCError(result);return { status: 'accepted' as const };}),// A mutation (a POST), called when the user clicks Confirm on the page the// mail links to, with the token from its URL fragment; never on page load,// so a mail scanner that fetches the link verifies nothing. ctx.auth.session// is resolved on public procedures too: a link for another account is refused.verifyEmailLink: publicProcedure.use(writesCookies).input(verifyEmailLinkInput).mutation(async ({ ctx, input }) => {const result = await auth.verifyEmailLink({token: input.token,session: ctx.auth.session,meta: ctx.auth.meta,});if (!result.ok) throw toTRPCError(result);// Signed in as this account: the session was re-issued. Otherwise// nobody is signed in (with linkWithoutSession) and the page says so.const issued = result.value.session;return issued ? { verified: true, ...ctx.auth.setSession(issued) } : { verified: true };}),logout: publicProcedure.use(writesCookies).output(csrfTokenOutput).mutation(({ ctx }) => ctx.auth.signOut()),// The output schema strips everything but id, email and emailVerified.me: protectedProcedure.output(userOutput).query(({ ctx }) => ctx.user),// Each session is named by its public handle, never its store key.sessions: protectedProcedure.output(sessionListOutput).query(({ ctx }) => auth.sessions.list(ctx.session)),// Signs out one device by the handle the list showed. Another device needs// a fresh password proof by default; a handle that names none of the caller's// sessions answers { revoked: false }. Revoking the current one? Use logout.revokeSession: protectedProcedure.input(revokeSessionInput).output(revokedOutput).mutation(async ({ ctx, input }) => {const result = await auth.sessions.revoke({session: ctx.session,handle: input.handle,meta: ctx.auth.meta,});if (!result.ok) throw toTRPCError(result);// result.value.sessionId is the store key: keep it on the server.return { revoked: result.value.revoked };}),// Re-entering the password rotates the session: setSession writes the new// cookie and a CSRF token bound to it.reauthenticate: protectedProcedure.use(writesCookies).input(reauthenticateInput).output(csrfTokenOutput).mutation(async ({ ctx, input }) => {const result = await auth.reauthenticate({session: ctx.session,password: input.password,meta: ctx.auth.meta,});if (!result.ok) throw toTRPCError(result);return ctx.auth.setSession(result.value);}),// Your own sensitive action: a password proof from the last 5 minutes.exportData: protectedProcedure.use(freshAuth('5m')).use(rateLimited('export', { limit: 3, window: '1h' })).output(z.object({ queued: z.boolean() })).mutation(() => ({ queued: true })),});}export type AppRouter = ReturnType<typeof createAppRouter>;createAuthMiddlewares(t)returns two base procedures and the middlewares behind them. Each refusal carries only its public code:Middleware Lets a call through when Refuses with publicProcedurea mutation passes CSRF; no session needed forbiddenprotectedProcedureit also has a valid session session_expired, ortwo_factor_enrollment_requiredfreshAuth(maxAge?)the password proof is newer than freshAuthAgefresh_auth_requiredrole(...roles)the user holds one of the roles forbiddenrateLimited(name, rule?)the budget for nameis not used uprate_limited, orinternalwhen the counter store does not answerwritesCookiesit is the only cookie writer of an unstreamed mutation internalpublicProcedurechecks CSRF on every mutation and needs no session: sign-up, sign-in, the reset request, sign-out.protectedProcedurealso refuses a caller without a valid session (UNAUTHORIZED,session_expired) and addsctx.user, loaded from your user store on this request (so a deleted user is signed out at once), andctx.session. Under the two-factor plugin’senforcement, a session past the grace window isenrollment-only: it is refused (FORBIDDEN,two_factor_enrollment_required) on every procedure whose meta does not saytwoFactorEnrollment: true, and so arefreshAuth,roleand the nestjs-trpcAuthGuardMiddleware, which run the same check. Type the meta withinitTRPC.meta<AuthProcedureMeta>()to have the key checked. See Enforcement with a grace period.freshAuth(maxAge?)asks for a password proof newer thanfreshAuthAge;maxAgecan only make it shorter.role(...roles)reads the roles through therolesoption ofcreateAuthContexton every call, so a role taken away stops working on the next request. Both run the session check themselves.rateLimited(name, rule?)counts calls per client IP in a fixed window (10 a minute by default; see tiers and per-user keys), under a key of its own so it never shares a budget with the core’s doors. When the counter store does not answer, the call is refused. It does not check CSRF itself: it counts every call that reaches it, in the order of the chain. OnpublicProcedureandprotectedProcedurethe CSRF and session checks run before it, so a forged mutation is refused without using up the victim’s budget; on a baret.procedure, or ahead of those checks, it counts forged calls too.writesCookiesis the only way to the cookie writers. After it,ctx.authhassetSession,signOutandclearSession; without it they are not on the type, so an unmarked procedure that calls one does not compile, and from untyped code they throw anAuthConfigErrorbefore writing anything. Only a mutation may carry it: a query skips the CSRF check and runs on a GET, which a link on another site can send with theSameSite=Laxsession cookie, sowritesCookieson a query refuses every call before the procedure runs, as a configuration error (the client seesinternal). It also refuses a subscription and a streamed batch; see the client.
authed,freshAuth,role,publicProcedureandwritesCookieseach run the CSRF check on a mutation themselves, so leaving thecsrfstep out of a chain does not skip it, and a cookie writer is never reachable from a forged request. The verdict is computed once, when the context is built, so a chain that checks it twice pays only a lookup. -
The context
Section titled “The context”src/server.ts import { createAuthContext } from '@noctcore/auth-trpc';import { createHTTPServer } from '@trpc/server/adapters/standalone';import { buildAuth } from '../node-server/auth.ts';import { config } from '../node-server/config.ts';import { createAppRouter } from './router.ts';const auth = buildAuth({async send(event) {process.stdout.write(`[mail] ${event.type} to ${event.to}\n`);},});// Checked once, here: a short CSRF secret, an empty origin list or a bad hop// count stops the server before it listens.const authContext = createAuthContext({auth,trustedHops: config.trustedHops,csrf: {// Not the auth secret. Add the previous one after it during a rollover.secrets: [config.csrfSecret],allowedOrigins: [config.origin],},// How long an open subscription may go on before its session is checked// again (the default; a number means seconds, 0 checks every event).revalidateSubscriptions: '30s',});createHTTPServer({router: createAppRouter(auth),basePath: '/trpc/',createContext: (opts) => authContext.node(opts),}).listen(3000);createAuthContextchecks the options once, and itsnode(opts)(the standalone, Express and nestjs-trpc adapters) orfetch(opts)buildsctx.authonce per HTTP request, so every procedure of a batch shares it:- the session cookie is read and validated through the core (
validateRequest); a token the core refused for good is cleared (clearsSessionCookie), one another request may still be adopting from your own store is kept; - the client IP comes from the core’s
clientIp, countingtrustedHopsfrom the right ofX-Forwarded-For(at most 16), or skipping the proxies atrustedHopslist names by address (CIDR ranges and the presetsloopback,linklocalanduniquelocal); withclientIpHeaderset (such ascf-connecting-ip, off by default), a single-address header from your edge wins, but only withtrustedHopsas a proxy list (a hop count is refused at boot), only when the socket address is inside it, and only when it holds exactly one IP. The list must name the edge, or hops that accept traffic only from it (see Trust proxy and client IPs); - the three CSRF checks are computed from the headers: the
Originis on the allowlist,Sec-Fetch-Sitesayssame-originwhen the browser sends it (orcross-sitefrom an origin oncsrf.crossSiteOrigins, for a desktop shell; see Cookies and desktop shells), and the double-submit token matches its cookie and is bound to this session or pre-session; - on a query, the page gets what it needs for its next mutation: a pre-session id when it has none, and a CSRF cookie bound to the current session or pre-session. Both take the
SameSitethatsession.cookie.sameSitegives the request’sOrigin, like the session cookie.
The CSRF cookie is readable by the page, which echoes it in the
x-csrf-tokenheader on every mutation; see the client.A failure while building the context (a store down) answers
internal, and only the error’s name is logged: a store error can carry the session key.The WebSocket adapter (
applyWSSHandler) is not supported yet. It builds the context once per connection and passes the socket asres, so the cookies a first visit needs could not be set, and a session would be validated once and kept after a sign-out, a password change or a revocation until the socket closed.node(opts)refuses aresthat cannot set headers with anAuthConfigErrorbefore it reads anything: the client seesinternaland the connection is closed.The Fastify adapter is not supported yet either. A Fastify reply has
getHeaderbut nosetHeader(that is onreply.raw), sonode(opts)refuses it the same way, on every request.On the fetch adapter
Section titled “On the fetch adapter”src/fetch.ts import type { AppAuth } from '../node-server/auth.ts';import { createAuthContext } from '@noctcore/auth-trpc';import { fetchRequestHandler } from '@trpc/server/adapters/fetch';import { createAppRouter } from './router.ts';// On the fetch adapter (Bun, Deno, edge runtimes) a Request carries no peer// address, so hand it over from your server. Without it, and with no trusted// hops, every client shares one rate-limit bucket.export function createFetchHandler(auth: AppAuth, settings: { csrfSecret: string; origin: string }) {const authContext = createAuthContext({auth,trustedHops: 0,csrf: { secrets: [settings.csrfSecret], allowedOrigins: [settings.origin] },});const router = createAppRouter(auth);return (req: Request, remoteAddress: string | undefined) =>fetchRequestHandler({endpoint: '/trpc',req,router,createContext: (opts) =>authContext.fetch(opts, remoteAddress === undefined ? {} : { remoteAddress }),});}A fetch
Requestcarries no peer address, so pass it from your server (on Bun,server.requestIP(req)?.address). Behind proxies, count them intrustedHopsas on Node (without a peer address the count picks the sameX-Forwarded-Forentry it would with one), or list them by address: with a list and no peer address, nothing is trusted.Background polls
Section titled “Background polls”Every request that carries a session counts as activity and refreshes its last-active time, at most once per
touchInterval. For procedures the page calls on its own, such as a poll on a timer, mark them passive so an idle session still expires while only they are called (see Background polls): settouch: falsein the procedure’s meta, or passcreateAuthContextatouchpredicate over procedure paths, such astouch: (path) => path !== 'notifications.count'. Both are read from the calls tRPC parsed before it built the context, and a batch touches when any of its procedures is active. A passive call is still answered with its session, and the CSRF verdict and the guarded procedures do not change.touch: falseoncreateAuthContexttouches on no request; the default touches on every one.Three cases where the option or the meta has no effect:
- nestjs-trpc with
AuthModulemounted. The session is validated twice, and each validation decides on its own whether to touch: first the NestCsrfMiddleware(on every route), withAuthModule’stouchoption, then the tRPC context, withcreateAuthContext’stouchand the procedure meta. The last-active time is written when either says touch, so a poll stays passive only when it is marked in both: inAuthModule’s predicate (the path it sees is the HTTP path, such as/trpc/notifications.count, where a batch joins its procedures in one path with commas) and bymeta({ touch: false })or thecreateAuthContextpredicate. If/trpcis incsrf.exempt, the middleware returns before it validates, and the tRPC side is the only switch (see Use with NestJS). - The WebSocket adapter. It is not supported yet, and
node(opts)refuses its connections (see The context). On@trpc/server11.28.0, the version checked, it builds the context once per connection and names no call, so the option and the meta could not apply to a subscription on it. - A predicate that returns a promise. The result is compared with
falseonly, so an async predicate always touches.
The meta flag is read from tRPC’s
call.procedure, which tRPC marks@internal; the meta test inpackages/auth-trpc/tests/background-polls.test.tsfails if a tRPC upgrade drops the field.Subscriptions
Section titled “Subscriptions”tRPC builds the context once per HTTP request, and a subscription served over SSE (
httpSubscriptionLink, on by default in@trpc/server11) is one request that stays open until the client leaves orsse.maxDurationMsends it, which has no default. The session is validated when the stream opens, so on its own a stream opened before a sign-out, a password change or a revocation would go on sending events to that browser. A reconnect is a new request, validated like any other.So every session check (
authed,freshAuth,role,protectedProcedure, and the nestjs-trpcAuthGuardMiddleware,AuthedMiddleware,FreshAuthMiddlewareandRoleMiddleware) keeps a subscription’s events behind it. Before an event leaves, when the last check started longer ago than therevalidateSubscriptionsoption ofcreateAuthContext(default'30s'; a number means seconds), the session is validated again and its user loaded. When either is gone, or the session became enrollment-only, the stream ends withsession_expired(ortwo_factor_enrollment_required) in place of the event: tRPC sends it as the stream’s error event andhttpSubscriptionLinkcloses the subscription without retrying. The procedure’s own iterator is returned, so itsfinallyruns as it does when the client leaves.The server example above sets
revalidateSubscriptions: '30s', the default.- The bound. An event is not sent once the last check that saw the session live started longer ago than
revalidateSubscriptions. A check counts from when it started, so a revocation that lands while a check is reading the store is caught by the next one. The bound is read on the core’s clock (the wall clock by default), which is not monotonic: a clock stepped backwards delays the next check by the step.0checks before every event;falseturns the check off and the stream keeps the session it opened with. - The cost. One session validation and one user read per open stream per bound, and only while events flow: a stream that sends nothing reads nothing, and its connection stays open until its next event, the client leaving, or
sse.maxDurationMs. Setsse.maxDurationMsininitTRPC.create({ sse: { maxDurationMs } })too if idle streams should not stay open for long. - No touch. The check does not count as activity, so an open stream never keeps an idle session alive, whatever
touchsays. A page that only reads a stream sends no activity, so onceidleTimeoutpasses the stream ends withsession_expiredand the user is signed out, as on any idle page. - A store failure. It ends the stream with
internal, logging only the error’s name.internalis a codehttpSubscriptionLinkretries, so the client reconnects, and the new request is validated like any other;session_expiredandtwo_factor_enrollment_requiredclose the subscription without a retry. - What is checked again. The session, its user and the enrollment-only standing. A role and a fresh proof are checked when the stream opens, and not again until the client reconnects. A public subscription has no session check, so one that reads
ctx.auth.sessionkeeps the session it opened with: build it onprotectedProcedure. - Observables. A procedure that returns an observable is read as an async iterable, as tRPC’s SSE handler reads it.
- the session cookie is read and validated through the core (
-
The client
Section titled “The client”src/client.ts import type { AppRouter } from './router.ts';import { createTRPCClient, httpBatchStreamLink, httpLink, splitLink } from '@trpc/client';// The page reads the CSRF cookie and echoes it on every request; mutations// are refused without it.export function createClient(url: string, readCsrfCookie: () => string) {const headers = () => ({ 'x-csrf-token': readCsrfCookie() });return createTRPCClient<AppRouter>({links: [splitLink({// A streamed batch sends its headers before any procedure runs, so a// procedure that sets a cookie cannot go through it. Mutations go one// per request: two sign-ins in one batch would both run.condition: (op) => op.type === 'mutation',true: httpLink({ url, headers }),false: httpBatchStreamLink({ url, headers }),}),],});}httpBatchStreamLink(the create-t3-app default) sends the response headers before any procedure of the batch runs, so a cookie set by a procedure cannot reach the browser: on the fetch adapter it would be dropped, on Node the write would fail after the flow had already run. The adapter does not let either happen silently:writesCookiesrefuses the call on a streamed batch before the procedure runs, so no sign-in, rotation or sign-out happens without its cookie. The client seesinternal, and the server gets anAuthConfigErrornaming the fix. It decides what is streamed exactly as tRPC does: thetrpc-acceptheader when present, otherwise anAcceptheader that listsapplication/jsonl.- A subscription’s response is a stream too, so
writesCookieson a subscription refuses every call, as a configuration error. Write cookies from a mutation (a query is refused too; see the router). - A procedure without
writesCookieshas no writers at all (see the router), so it cannot reach this case.
So route mutations to
httpLinkorhttpBatchLink, withsplitLinkas above. Queries can keep streaming: the pre-session and CSRF cookies are written when the context is built, before the stream starts.
Cookies on sign-in and rotation
Section titled “Cookies on sign-in and rotation”Every flow that issues a session hands it to ctx.auth.setSession(issued), in a procedure marked writesCookies, which writes the session cookie, the trusted-device cookie and a CSRF cookie bound to the new session, and returns the token for the response. That covers sign-in and every rotation: reauthenticate, changePassword, sessions.revokeOthers and the email verification flows. A token from before the rotation stops verifying the moment the new cookie lands. ctx.auth.signOut() signs out through the core and starts a fresh pre-session; after sessions.revokeAll, pass its blank cookie to ctx.auth.clearSession(cookie).
So the first procedure of a batch to reach writesCookies claims the request, and any other marked procedure in the same batch is refused before it runs: the client sees internal, and the server gets an AuthConfigError. Which one wins depends on timing, not on its place in the batch. As a backstop, a second setSession, signOut or clearSession call in one request throws before writing. Procedures without the marker share a batch freely.
Rate limit tiers, per-user keys and exemptions
Section titled “Rate limit tiers, per-user keys and exemptions”createAuthMiddlewares(t, { rateLimits }) takes named rules, checked when the middlewares are made (a bad name, a limit that is not a whole number of at least 1, a window that is not a duration longer than zero, or a bad keyBy throws an AuthConfigError at boot, and so does the same in a rule passed to rateLimited):
const t = initTRPC.context<Context>().meta<RateLimitMeta>().create({ errorFormatter: authErrorFormatter });
const { publicProcedure, protectedProcedure, rateLimited, writesCookies } = createAuthMiddlewares(t, { rateLimits: { default: { limit: 20, window: '1m' }, sensitive: { limit: 5, window: '1h', keyBy: 'user' }, },});
exportData: protectedProcedure.use(rateLimited('export', 'sensitive')).mutation(/* ... */),logout: publicProcedure.use(writesCookies).meta({ rateLimit: 'exempt' }).mutation(/* ... */),- Which rule.
rateLimited(name, rule)counts withrulewhen given: a tier name (typed from the keys ofrateLimits, and an unknown one throws at boot) or a rule of its own. Without one it takes the tier namedname, else the tier nameddefault, else 10 a minute. The budget belongs toname: two procedures that pass the same name share one budget, two names never do, whatever tier they use. - Who is counted. By default, the client IP. A rule with
keyBy: 'user'counts a signed-in caller by user, so a user keeps one budget across IPs and users behind one shared IP (an office, a carrier NAT) stop spending each other’s. The user comes only from the session the core accepted, never from anything the client sent: a call with no session, or with a cookie the core refused, counts by its client IP, so a made-up cookie is no fresh budget. The counter key holds the core’s keyed hash of the user id (an HMAC under a key derived from the server secret, like session handles), so a reader of the counter store cannot link a key to a guessable user id. - Exemptions. A procedure whose meta says
rateLimit: 'exempt'is never counted, including by arateLimitedon the base procedure it was built from, so a sign-out cannot be rate limited out. AddRateLimitMetato your meta type (initTRPC.meta<RateLimitMeta>(), or extend it);AuthProcedureMetaalready includes it. Meta is set in your code, never by the client.
Verification links
Section titled “Verification links”verifyEmailLink in the router is a mutation on publicProcedure, so it is a POST and checks CSRF. The context resolves the session on public procedures too: pass ctx.auth.session as it is (null when nobody is signed in). A link for one account opened while signed in as another is then refused (session_expired) and stays usable for its owner. By default a link opened with no session is refused the same way; with emailVerification.linkWithoutSession on it verifies the address and signs nobody in.
Errors
Section titled “Errors”Throw toTRPCError(result) when a flow refuses. The message is the public code, there is no cause, and the tRPC code follows a fixed table (AUTH_ERROR_TRPC_CODES): invalid_credentials is UNAUTHORIZED, rate_limited is TOO_MANY_REQUESTS, fresh_auth_required and forbidden are FORBIDDEN, and so on. A code the table does not know becomes INTERNAL_SERVER_ERROR with the message internal, never the raw value.
authErrorFormatter adds data.auth (the public code and, on rate_limited, retryAfterSeconds) and covers what tRPC builds itself:
- no error carries a stack, in development or production (tRPC adds one whenever
NODE_ENVis notproduction, with absolute paths); - an input that fails validation is answered with the message
invalid_inputanddata.input, a list of paths and issue codes, never the submitted value; - any other
BAD_REQUEST, such as a body that is not JSON (the parser’s message quotes the body), and the request errorsPARSE_ERROR,METHOD_NOT_SUPPORTED,UNSUPPORTED_MEDIA_TYPE,PAYLOAD_TOO_LARGEandNOT_FOUND(tRPC’s quotes the requested path) are answered with a fixed message, the code in lower case, whoever raised them; - any internal error is answered with
internal, without its message.
Sign-in answers an unknown email and a wrong password with the same error, and sign-up and the reset request answer a taken and a new address with the same { status: 'accepted' }, as long as your procedure returns the same thing in both cases, as the router above does.
Schemas
Section titled “Schemas”The package exports a Zod input and output for every auth flow. The outputs are plain objects that strip every key they do not name: userOutput sends id, email and emailVerified, whatever your user record grows. Declare output: on every procedure that returns a record.
inspectPasswordResetInput ({ token }) and resetInspectionOutput ({ userId, email, expiresAt, secondFactorRequired }) are for a reset page that checks its link on load with auth.inspectPasswordReset. The token is a secret: put the procedure on a mutation.
sessionListOutput names each session by its public handle, never its store key, and strips a store key a procedure returns by mistake. revokeSessionInput takes that handle ({ handle }); see Session handles for what revoke answers.
The inputs check shape and size only; whether an email is valid or a password long enough is the flow’s answer, with its public code. Every input that carries a secret belongs to a mutation, since tRPC sends a query’s input in the URL, where access logs, proxies and browser history keep it.
nestjs-trpc
Section titled “nestjs-trpc”The same middleware bodies come as classes for nestjs-trpc. Register AuthGuardMiddleware in globalMiddlewares: it checks CSRF on every mutation and requires a session on every procedure unless its meta says auth: 'public' (@Mutation({ meta: { auth: 'public' } })), so a procedure nobody marked is closed. WritesCookiesMiddleware (with @UseMiddlewares) is the only way to the cookie writers, as on plain tRPC: without it, setSession, signOut and clearSession throw an AuthConfigError before writing anything. nestjs-trpc types @Ctx() by hand, so type it as { auth: AuthWriter } only on marked procedures; the compiler cannot check the marker there. signOut refuses before the core signs out, but in an unmarked procedure setSession refuses only after your flow ran (a rotation then leaves the browser without its new session), so mark every procedure that issues a session. RoleMiddleware(...roles), FreshAuthMiddleware(maxAge?) and RateLimitMiddleware(name, rule?) make the classes (a rule may say keyBy: 'user'; a tier is a rule constant passed to each class that uses it, and @Mutation({ meta: { rateLimit: 'exempt' } }) skips the count) for @UseMiddlewares(...), once, at module level; list every class in a module’s providers. A role or fresh-proof class on a procedure marked public refuses every call, as a configuration error, and so does WritesCookiesMiddleware on a @Query or a @Subscription: put it on a @Mutation.
The context class returns authContext.node(opts), and the error formatter goes in trpc: { errorFormatter: authErrorFormatter }.
Check it works
Section titled “Check it works”The test runs the same flows over in-memory stores, so it needs no Redis or Postgres. The site runs this file with node --test.
| Test | Passes when |
|---|---|
| every procedure has an access rule, and no query carries a secret | assertProceduresGuarded and assertNoSecretQueries find nothing in the router |
| a mutation without the CSRF token is refused, and passes with it | register answers 403 with the cookies alone, and 200 once the csrf cookie is echoed in x-csrf-token |
import assert from 'node:assert/strict';import { test } from 'node:test';import { createAuth } from '@noctcore/auth';import { memoryStores, plainHasher, recordingMailer } from '@noctcore/auth/testing';import { assertNoSecretQueries, assertProceduresGuarded } from '@noctcore/auth-trpc';import type { AppAuth } from '../node-server/auth.ts';import { createFetchHandler } from './fetch.ts';import { createAppRouter } from './router.ts';
const ORIGIN = 'http://localhost:3000';
// The same flows over in-memory stores, so the test needs no Redis or Postgres.const auth = createAuth({ stores: memoryStores(), password: { hasher: plainHasher(), breachCheck: false }, session: { cookie: { secure: false } }, secret: 'test-auth-secret-that-is-32-bytes-or-more', urls: { resetPassword: (token) => `${ORIGIN}/reset-password#${token}` }, mailer: recordingMailer(),}) as unknown as AppAuth;
test('every procedure has an access rule, and no query carries a secret', () => { const router = createAppRouter(auth);
assertProceduresGuarded(router); assertNoSecretQueries(router);});
test('a mutation without the CSRF token is refused, and passes with it', async () => { const handle = createFetchHandler(auth, { csrfSecret: 'test-csrf-secret-that-is-32-bytes-or-more', origin: ORIGIN, });
// The first query hands out the pre-session and CSRF cookies. const first = await handle(new Request(`${ORIGIN}/trpc/session`), '127.0.0.1'); const cookies = first.headers.getSetCookie().map((line) => line.split(';')[0] ?? ''); const csrf = cookies.find((c) => c.startsWith('csrf='))?.slice('csrf='.length) ?? '';
const register = (headers: Record<string, string>) => handle( new Request(`${ORIGIN}/trpc/register`, { method: 'POST', headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, body: JSON.stringify({ email: 'ada@example.com', password: 'correct horse battery' }), }), '127.0.0.1', );
assert.equal((await register({ cookie: cookies.join('; ') })).status, 403); assert.equal((await register({ cookie: cookies.join('; '), 'x-csrf-token': csrf })).status, 200);});assertProceduresGuarded(router)fails on a procedure built ont.procedurewith neitherpublicProcedurenor a session check, on one built onpublicProcedurethat also asks for a session, a role or a fresh proof (the two say opposite things), and on a query or subscription markedwritesCookies, which the middleware would refuse on every call. It checks which markers a procedure carries, not their order: arateLimitedplaced ahead of the session check passes it.assertNoSecretQueries(router)fails on a query or subscription whose input has a key naming a secret (password,pwd,token,code,secret,otp,hotp,pin). It splits a key into words (camelCase, snake_case, kebab-case) in one linear pass, socurrentPasswordandreset_tokenmatch, and it matches plurals (recoveryCodes,apiTokens) and run-together lower-case names ending in a secret word (resettoken,accesstokens,otpcode,verificationcode,pincode,newpin,2facode).credential,jwt,bearerandauthorizationmatch as the last word only (credentials,accessJwt), socredentialId,jwtIssuerandauthorizationUrlpass. Key pairs match written as two words or one:apiKey,privateKey,accessKey,signingKeyandencryptionKey, whilepublicKeyand a barekeypass. Names that only look like a secret word (postcode,barcode,pinned,spinner,keyboard) pass, andsessionId,passandsignaturestay out on purpose: each is as often a plain identifier, a flag or a value meant for a URL. A postalpincodefield is flagged likepinCodealways was; allow its path once checked. It walks every part of a Zod 4 schema: object shapes and catch-alls, array elements, tuple items and rest, record, map and set keys and values (a record keyed by an enum or literal is checked by its values), unions, intersections, both sides of a pipe, and wrapped and lazy schemas. It fails closed on what it cannot read:z.preprocess()(its function sees the raw input before any schema), a validator that is not Zod 4,z.unknown()andz.any()(a loose object’s catch-all among them),z.custom()andz.instanceof(), and any Zod type it does not know. It also fails on a lazy router. List a path inallowonce you have checked it by hand. A record keyed byz.string()accepts any key name, which no static check can see.
Both walk a plain tRPC router. They cannot see into nestjs-trpc, which builds its router at boot. Neither can see what a procedure’s handler calls, so they cannot report a cookie writer without writesCookies; the type of ctx.auth does that at compile time instead, and the writers refuse at run time.