What the agent does
The agent first finds where the provider's token is kept and who uses it. In an app like nextauthjs/next-auth-example, the jwt callback in auth.ts has one line for it: when account?.provider === "keycloak" it returns { ...token, accessToken: account.access_token }. Since account is only present at sign-in, that is the last time the token is touched. The session callback copies it to session.accessToken, and app/[...proxy]/route.tsx forwards requests to THIRD_PARTY_API_EXAMPLE_BACKEND with Authorization: Bearer ${session?.accessToken}. Nothing records when the access token expires and the refresh token is dropped, so once the provider's token lapses the proxy keeps sending it while the Auth.js session cookie is still good. The user looks signed in and every backend call is refused.
The change follows the Auth.js guide for JWT sessions, in the names this file already uses. At sign-in the callback also stores expiresAt from account.expires_at, which is in seconds, and refreshToken. On later calls it returns the token untouched while Date.now() is below expiresAt * 1000, less a short margin. Past that it posts a refresh_token grant with the client id and secret to the provider's token endpoint, stores the new access token and a new expiresAt computed from expires_in, and keeps the old refresh token when the response carries none, since some providers issue one only once. A failed refresh does not throw; it sets token.error = "RefreshTokenError", which the session callback passes on. The refresh token itself is never copied to the session. The agent puts this in lib/refresh-token.ts as a function that takes the token and a fetch, reads token_endpoint from the issuer's /.well-known/openid-configuration so no provider URL is hard-coded, and uses the AUTH_KEYCLOAK_ID, AUTH_KEYCLOAK_SECRET and AUTH_KEYCLOAK_ISSUER variables already named in docker-compose.yml. The existing trigger === "update" line stays.
A rotated token only helps if it gets back into the cookie, and this is where the agent reads the library and not just the guide. In next-auth 5.0.0-beta.32, the version a fresh install resolved when this page was written, a bare await auth() returns the session and discards the Set-Cookie headers that came with it, while the wrapper form auth((req) => ...) and the middleware copy them onto the response. The proxy route calls the bare form, and its path is outside the middleware: the matcher in middleware.ts skips anything starting with api, and the client example calls /api/authenticated/greeting. Left alone, an expired token would be refreshed on every proxied request and saved on none, and a provider that allows each refresh token one use would refuse the second attempt. The agent rewrites the proxy handler in the wrapper form and reads req.auth, the pattern app/api/protected/route.ts already uses.
The types and the screens follow. The declare module blocks at the end of auth.ts gain expiresAt, refreshToken and error on JWT and error on Session. components/client-example.tsx calls signIn("keycloak") from an effect when session.error is "RefreshTokenError". The repository has no test runner, so the agent adds Vitest and tests the refresh function with a stubbed fetch: a token that is still valid makes no request, an expired one is replaced, a response without refresh_token keeps the old one, a 400 from the provider sets the error and leaves the rest of the token intact. It installs with pnpm, runs tsc --noEmit, the tests and pnpm build.
Start it with one API call
POST https://api.phoenix.so/o/{org}/sessions with this body:
{
"agent": "claude",
"input": "Add refresh token rotation to this Next.js app, which uses Auth.js (next-auth v5) with JWT sessions and stores a Keycloak access token in the JWT. Read auth.ts, middleware.ts, app/[...proxy]/route.tsx, app/api/protected/route.ts, components/client-example.tsx, docker-compose.yml and package.json first, then read how the installed next-auth version handles Set-Cookie in auth() for the bare and wrapper forms. In the jwt callback, at sign-in store accessToken, expiresAt (account.expires_at, seconds) and refreshToken; afterwards return the token while it is valid, and when it has expired exchange the refresh token at the provider's token endpoint, read from the issuer's OpenID configuration. Keep the old refresh token if the response has none. On failure set token.error = \"RefreshTokenError\" and do not throw. Put the exchange in lib/refresh-token.ts as a function that takes the token and a fetch. Expose only accessToken and error on the session, never the refresh token, and extend the module augmentation. Make sure every server path that can trigger a refresh also writes the updated session cookie; change app/[...proxy]/route.tsx to the auth((req) => ...) wrapper form if the bare form does not. In the client example, call signIn(\"keycloak\") when session.error is RefreshTokenError. Keep the existing update trigger. Add Vitest and test the refresh function with a stubbed fetch: still valid, expired, no new refresh token, provider error. Install with pnpm, run tsc --noEmit, the tests and pnpm build, and open a pull request.",
"resources": [
{
"url": "https://github.com/your-org/your-app"
}
]
}- Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
- Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
- Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.
What comes back
A pull request with the new lib/refresh-token.ts, the reworked jwt and session callbacks and type declarations in auth.ts, the proxy route in wrapper form, the effect in the client example, and the Vitest setup with its tests. The description walks through the life of a token: stored at sign-in, reused until expiresAt, exchanged once, written back in the cookie on that same response. It names the next-auth version the install resolved, and it says plainly that no real provider was called: the sandbox has no Keycloak realm or client secret for this app, so the exchange is covered by tests against a stub.
A reviewer checks three things. First, that no path reads the session in a way that refreshes without saving; the description lists every auth() call in the repository and which form it uses. Second, what the browser can see: session.accessToken was already exposed by this example and still is, the refresh token is not. Third, concurrency. Two requests arriving just after expiry can both try to refresh, and with single-use refresh tokens the slower one fails and sets the error. The Auth.js guide names this race and offers no built-in fix; the pull request states it as a known limit and what the user sees when it happens, which is a new sign-in.
Run it on every Linear issue labelled auth
Token problems show up as tickets: users report being signed in but getting errors after an hour. In the console, add an automation on the Project that holds the app with a linear trigger on linear.issue.labeled, the label auth, and a saved prompt that tells the agent to trace the provider token named in the issue from sign-in to the request that uses it and fix where it goes stale. The issue is added after the prompt when someone in your Rush org applies the label, and the run opens a pull request. The automation's runner needs a Linear connection, made in the console under Settings → Connections.
The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.
Why run it on Rush?
The bug this job prevents is invisible on a laptop. A developer signs in, the token is fresh, everything works, and the change ships; the failure waits for the access token's lifetime to pass. The agent's sandbox makes expiry a test input and not a waiting period, and its run keeps every command and the output. The cases a reviewer cares about, expired, refreshed, refused, are each a test with a recorded result.
The other half is reading the dependency. Whether a refreshed session is saved depends on how the installed next-auth handles cookies in each calling style. The agent reads the version that is in node_modules for the run and cites the file in the pull request, so the claim is tied to a version a reviewer can open.
Frequently asked questions
Does this work for Google or GitHub instead of Keycloak?
The exchange is the standard refresh_token grant, so any provider that issues refresh tokens works with a different token endpoint and client variables. Google only issues one when the sign-in asks for offline access, which the Auth.js guide does with access_type: "offline" and prompt: "consent".
Is it safe to keep a refresh token in a cookie?
Auth.js keeps it in an encrypted JWT inside an HttpOnly cookie, and its guide says that this is simpler but less secure than a database. The pull request keeps the refresh token out of the session object, so client code cannot read it. Moving it to a database means switching the session strategy, which is a larger change than this one.
What does the user see when a refresh fails?
The session carries error: "RefreshTokenError" and the client example starts a new sign-in with the same provider. Server-rendered pages can make the same check after auth() and redirect.