Cookies and desktop shells
In short
- The threat
The session cookie is the credential, and browsers let sibling subdomains overwrite it, scripts read it and other sites send it; a desktop shell is cross-site by definition.
- The rule
__Host-,Secure,HttpOnlyandSameSite=Laxby default; a shell getsSameSite=Noneper origin, and only its exact origin gets past the CSRF check.- In the package
http/cookie.ts, configured undersession.cookieand the adapters’csrf.
What goes wrong
Section titled “What goes wrong”The session cookie is the credential, and browsers hand cookies around more freely than people expect:
- Cookie tossing. A sibling subdomain, such as a marketing site or a host for user content, can set a cookie for the parent domain that the browser then sends to your app, shadowing or overwriting the real one.
- Script. Script injected into a page can read a cookie and send it away.
- The network. A cookie sent over plain HTTP can be read on the network.
- Other sites. Another site can make the browser send requests with your cookie attached (see CSRF).
Desktop shells add a twist. An Electron app that serves its pages from its own scheme (app://) talks to your API from an origin that is not yours, so its requests are cross-site, and the defaults that protect the web app also keep the cookie away from the shell.
SameSite=None and its exact origin is listed,
so it signs in like the web page, while a request another site starts loses its cookie and is
refused.
Three requests reach the same API. Your web page at https://app.example gets its session cookie with SameSite=Lax from the sameSite function, sends it on a same-origin request and is handled. The desktop shell at app://desktop is cross-site; the function gives its cookie SameSite=None with Secure, so the cookie travels, and its requests pass the CSRF check because app://desktop is listed exactly in csrf.crossSiteOrigins. A request another site starts in a browser loses the Lax cookie there, and the CSRF check refuses it because its origin is not listed. The signed double-submit token is still required of every request.
Text version
The rule
Section titled “The rule”Every attribute the browser enforces is on by default, and the shell gets exactly one exception, per origin.
__Host- whenever the cookie is Secure
Section titled “__Host- whenever the cookie is Secure”The session cookie is named __Host-session by default. A browser accepts a __Host- cookie only if it is Secure, has Path=/ and has no Domain, so no subdomain can set or overwrite it.
The trusted-device cookies follow the same rule (__Host-device, and __Host-two-factor-device with the two-factor plugin), and so do the NestJS and tRPC adapters’ CSRF cookies (__Host-csrf and __Host-presession).
Secure by default, HttpOnly always
Section titled “Secure by default, HttpOnly always”session.cookie.secure is on by default. Turn it off only for plain-HTTP local development; that also drops the prefix.
The session cookie is always HttpOnly, so page script cannot read it. That keeps the token out of an injected script’s hands; it does not stop that script from sending requests as the user while the page is open.
SameSite=Lax by default
Section titled “SameSite=Lax by default”Cross-site subrequests and form posts carry no session cookie, while a link into the site still does. With the defaults, the session cookie is written as:
Set-Cookie: __Host-session=<token>; Path=/; HttpOnly; Secure; SameSite=Lax| Session | Cookie lifetime |
|---|---|
| Without “remember me” | No Max-Age, so the browser drops it when it closes, and the server ends it after 24 hours by default however active it is. |
| With “remember me” | Max-Age is the session’s remaining life, 30 days by default. |
Desktop shells: SameSite per origin, and None only with Secure
Section titled “Desktop shells: SameSite per origin, and None only with Secure”session.cookie.sameSite also takes a function of the request’s Origin, so the web app keeps Lax while a shell on its own scheme gets None (see In code).
Every cookie that travels with the session cookie follows it. The trusted-device cookies get the same answer, and so do the NestJS and tRPC adapters’ CSRF and pre-session cookies and the blank cookie they write to clear a refused session: every cookie that has to travel with the session cookie takes its SameSite from the same function, through the core’s resolveSameSite.
None without Secure is refused. None on a cookie that is not Secure is refused with a configuration error when createAuth starts, for a fixed sameSite value. A sameSite function cannot be checked without a request, so its None without Secure is refused when a cookie is built (usually at the first sign-in).
The origin is only a hint. It comes from the request’s Origin header, which a client that is not a browser can set to anything; that only changes the attributes of its own cookie.
None needs the rest of the CSRF defence
Section titled “None needs the rest of the CSRF defence”A cookie with SameSite=None is sent on requests other sites start too, so the origin it is meant for has to be checked. A shell’s requests arrive as cross-site, which verifyFetchSite refuses by default.
List the shell’s exact origin in the adapter’s csrf.crossSiteOrigins (or pass origin and crossSiteOrigins to verifyFetchSite yourself): that origin then passes the Origin check, and its cross-site requests pass the Sec-Fetch-Site check, while every other cross-site request is still refused. The signed double-submit token is still required. CSRF covers the trade-off.
AuthModule.forRoot takes the same csrf.crossSiteOrigins. Entries are matched exactly, scheme, host and port; a wildcard, null or anything that is not an origin stops the app at boot. The list is empty by default, so nothing changes until you name an origin.
How a shell gets its CSRF token
Section titled “How a shell gets its CSRF token”The page usually reads the double-submit token from the csrf cookie. A shell cannot: its document.cookie holds only its own origin’s cookies, never __Host-csrf, a host-only cookie of the API host. The same holds for a web app on another origin than the API. Its engine still stores the API’s cookies and sends them back; only its script cannot read them.
So both adapters return the token from a safe request:
- NestJS:
SessionCookies.csrfToken(req, res)in a@Public()GET route, such asGET /csrf-tokenanswering{ csrfToken }. - tRPC:
ctx.auth.csrfToken()in a public query, sent with GET throughhttpLinkorhttpBatchLink.
Either returns exactly the token the same response sets or keeps as the cookie, minting the pre-session and the cookie when missing, as any safe request does, and marks the response Cache-Control: no-store. The shell keeps the token in memory and echoes it in x-csrf-token:
- At start, before its first sign-in, it reads a token bound to its pre-session.
- After a sign-in or any rotation, it uses the token the flow returns (
SessionCookies.set,ctx.auth.setSession), since the old one stops verifying when the new session cookie lands. - After a restart with a persistent session, its memory and the browser-session cookies are gone but the session cookie is not, so it reads the route again and gets a token bound to that session.
Reading the token from a response grants nothing a cross-site page could use. The token is bound to the session or pre-session it was read for, and the cookie is still required next to it. And whatever your CORS setup lets a page on another origin read (this library configures none, and even a permissive cors({ origin: true, credentials: true }) changes nothing here), that page’s unsafe requests are refused on the Origin allowlist and the Sec-Fetch-Site check, whatever token they carry. An exempt path mints nothing, so the call refuses there, and it refuses on an unsafe method too. On tRPC it also refuses in a subscription and on a streamed batch, whose headers go out before any procedure runs.
Keep the token out of every cache
Section titled “Keep the token out of every cache”no-store only helps if nothing replaces it or answers before it is set. A cached token is still bound to its first caller, so the next caller cannot use it, but it has leaked all the same.
-
tRPC: tRPC applies your
responseMetaafter the procedures ran, and its headers replace or join theno-storethe call set (aHeadersobject is appended on the fetch adapter). That is where tRPC’s caching recipe putss-maxageon public queries, which is just what the token query looks like, and a CDN or proxy may read its own header from there instead ofCache-Control. Wrap your function inauthResponseMeta, or passauthResponseMeta()when you have none: on a response that handed out a token, on the Node and fetch adapters and batched queries included, it drops these headers yours returns, in either form and any case:Cache-Control,Surrogate-Control,CDN-Cache-Control, every*-CDN-Cache-Control(such asCloudflare-CDN-Cache-Control),X-Accel-ExpiresandEdge-Control. A proxy-specific cache header outside this list is not touched; keep such rules off the token route. Pass it to every tRPC handler you create that serves the token query.import { authResponseMeta } from '@noctcore/auth-trpc';createHTTPHandler({router,createContext: (opts) => authContext.node(opts),responseMeta: authResponseMeta(appResponseMeta),}); -
nestjs-trpc 2.14.0 and later:
TRPCModule.forRoot({ trpc: { ... } })passes the native adapter options,responseMetaincluded, on to tRPC, so wrap yours there:trpc: { responseMeta: authResponseMeta(appResponseMeta) }. Itstrpc.middlewarehook runs on the same requests and can set a cache header too: keep it from doing so on the token query. -
Earlier nestjs-trpc releases: there is no
responseMeta, so nothing inside tRPC can replace theno-store. Keep any Express or Fastify middleware of yours that sets a cache header off the tRPC base path, or serve the token from the Nest side instead, withSessionCookies.csrfTokenin a@Public()GET route, which the bullet below covers. -
NestJS: Nest’s
CacheInterceptorcaches GET responses by URL inside the app, and on a hit the handler never runs, sono-storenever reaches it: every caller gets the first caller’s token. Keep the token route out of it (no@CacheKeyor@CacheTTLon it, and skip it intrackBywhen the interceptor is global throughAPP_INTERCEPTOR) and out of any other response cache, and any interceptor or middleware that setsCache-Controlafter the handler, which would replace theno-store.
Limits for shells and other clients
Section titled “Limits for shells and other clients”__Host-, Secure, HttpOnly and SameSite are instructions to a browser. A client that is not a browser, such as a native HTTP library or a command-line tool, keeps cookies wherever its library does and enforces none of them. It must also send an Origin the allowlist names, because verifyRequestOrigin refuses an unsafe request without one.
In code
Section titled “In code”The per-origin SameSite and the allowlist that has to come with it, through the tRPC adapter.
import type { AuthConfig, AuthUser } from '@noctcore/auth';import { createAuthContext } from '@noctcore/auth-trpc';import { buildAuth } from '../build/node-server/auth';import { config } from '../build/node-server/config';
const SHELL = 'app://desktop';
// The web app keeps Lax; the shell on its own scheme gets None (with Secure).export const session = { cookie: { sameSite: (origin) => (origin === SHELL ? 'none' : 'lax'), },} satisfies AuthConfig<AuthUser, unknown, []>['session'];
const auth = buildAuth({ send: async () => {} });
// None needs the rest of the CSRF defence: name the shell's exact origin.export const authContext = createAuthContext({ auth, trustedHops: config.trustedHops, csrf: { secrets: [config.csrfSecret], allowedOrigins: [config.origin], crossSiteOrigins: [SHELL], },});Where the package and the guide differ
Section titled “Where the package and the guide differ”The guide asks for HttpOnly and Secure, and says SameSite mitigates many cross-site attacks but is not a complete solution on its own.
- The package sets all three by default and adds the
__Host-prefix, which the guide does not mention. - It pairs
SameSitewith the CSRF checks for the same reason the guide gives. - The guide does not cover desktop shells; the per-origin
SameSiteand theOriginallowlist exist for them.
Attack tests
Section titled “Attack tests”| Test | Attack | Stopped by |
|---|---|---|
| A018 | Cookie tossing and reading the session cookie from script | http/cookie.ts |
| A008 | Cross-site request forgery | http/csrf.ts, http/cookie.ts |
| A026 | Cross-site request forgery against a Nest app | auth-nestjs/csrf.middleware.ts |
| A033 | Cross-site request forgery against a tRPC mutation | auth-trpc/middlewares.ts |
| A079 | Riding the cross-site origin allowlist, through the Nest adapter | auth-nestjs/csrf.middleware.ts, auth-nestjs/session-cookies.ts |
| A080 | Riding the cross-site origin allowlist, through the tRPC adapter | auth-trpc/context.ts, auth/http/csrf-adapter.ts |
| A100 | Using a token read from the Nest token route for another session or pre-session | auth-nestjs/session-cookies.ts, auth-nestjs/csrf.middleware.ts |
| A101 | Using a token read from ctx.auth.csrfToken() for another session or pre-session |
auth-trpc/context.ts |
Further reading
Section titled “Further reading”- Browser client-side storage in Pilcrow’s auth guide.
- Set-Cookie on MDN, including the cookie prefixes.