@evup/auth 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +793 -2
  4. package/dist/astro/index.d.ts +22 -0
  5. package/dist/astro/index.js +34 -0
  6. package/dist/astro/integration-middleware.d.ts +1 -0
  7. package/dist/astro/integration-middleware.js +3 -0
  8. package/dist/astro/middleware.d.ts +9 -0
  9. package/dist/astro/middleware.js +36 -0
  10. package/dist/astro/route.d.ts +3 -0
  11. package/dist/astro/route.js +6 -0
  12. package/dist/astro/runtime.d.ts +8 -0
  13. package/dist/astro/runtime.js +58 -0
  14. package/dist/client/index.d.ts +15 -0
  15. package/dist/client/index.js +34 -0
  16. package/dist/errors.d.ts +11 -0
  17. package/dist/errors.js +12 -0
  18. package/dist/hono/index.d.ts +26 -0
  19. package/dist/hono/index.js +53 -0
  20. package/dist/next/index.d.ts +25 -0
  21. package/dist/next/index.js +84 -0
  22. package/dist/next/read.d.ts +7 -0
  23. package/dist/next/read.js +11 -0
  24. package/dist/resource/index.d.ts +48 -0
  25. package/dist/resource/index.js +174 -0
  26. package/dist/server/auth.d.ts +4 -0
  27. package/dist/server/auth.js +386 -0
  28. package/dist/server/config.d.ts +42 -0
  29. package/dist/server/config.js +103 -0
  30. package/dist/server/cookie.d.ts +30 -0
  31. package/dist/server/cookie.js +105 -0
  32. package/dist/server/index.d.ts +5 -0
  33. package/dist/server/index.js +3 -0
  34. package/dist/server/oidc.d.ts +17 -0
  35. package/dist/server/oidc.js +44 -0
  36. package/dist/server/pages.d.ts +3 -0
  37. package/dist/server/pages.js +12 -0
  38. package/dist/server/redirect.d.ts +5 -0
  39. package/dist/server/redirect.js +28 -0
  40. package/dist/server/types.d.ts +109 -0
  41. package/dist/server/types.js +1 -0
  42. package/package.json +86 -4
package/README.md CHANGED
@@ -1,3 +1,794 @@
1
- # Temporary Holding Version
1
+ # @evup/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An SDK that lets your app sign users in with **EvUp Account** (`auth.evup.cloud`) and lets your API / MCP server verify the access tokens issued by EvUp.
4
+
5
+ - **Sign-in (Relying Party):** OIDC Authorization Code + PKCE (S256), session stored in an encrypted cookie (JWE `dir` + `A256GCM`), automatic access token refresh, RP-initiated sign-out.
6
+ - **Resource server (MCP / API):** verifies JWT access tokens (`typ: at+jwt`, `iss`, `aud`) with EvUp's JWKS, publishes protected resource metadata (RFC 9728) and a standards-compliant `WWW-Authenticate` challenge.
7
+ - **Web standards only** (`fetch`, `Request`/`Response`, WebCrypto, `Headers`): runs on Cloudflare Workers, Bun, Deno, Node >= 20. No `node:` imports in runtime code.
8
+ - **Thin adapters** for Hono, Astro, Next.js (App Router); other frameworks use the core with about 10 lines (see [Recipes for other frameworks](#recipes-for-other-frameworks)).
9
+
10
+ > AI assistants: this guide is served as Markdown at `<origin>/llms-full.txt` (index at `<origin>/llms.txt`), with `<origin>` your EvUp Account origin.
11
+
12
+ > Published on npm as `@evup/auth` (MIT). In this monorepo it is the workspace `@evup/auth` at `packages/auth`. The EvUp auth server does **not** use this SDK.
13
+
14
+ ## Table of contents
15
+
16
+ 1. [Installation](#installation)
17
+ 2. [Registering your app on EvUp](#registering-your-app-on-evup)
18
+ 3. [Environment variables](#environment-variables)
19
+ 4. [Quick start](#quick-start)
20
+ 5. [By framework](#by-framework): [Hono](#hono) · [Astro](#astro) · [Next.js](#nextjs-app-router) · [Core: fetch / Workers / Bun / Deno](#core-fetch-workers-bun-deno) · [Browser (`/client`)](#react-or-any-browser-client) · [Recipes for other frameworks](#recipes-for-other-frameworks)
21
+ 6. [Protecting pages and APIs](#protecting-pages-and-apis)
22
+ 7. [Permissions (RBAC)](#permissions-rbac)
23
+ 8. [Access denied and waitlist](#access-denied-and-waitlist)
24
+ 9. [Signing out](#signing-out)
25
+ 10. [MCP / API resource server](#mcp--api-resource-server)
26
+ 11. [Configuration reference](#configuration-reference)
27
+ 12. [Errors](#errors)
28
+ 13. [Security notes](#security-notes)
29
+ 14. [Local development with a local IdP](#local-development-with-a-local-idp)
30
+ 15. [FAQ](#faq)
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ npm install @evup/auth
36
+ ```
37
+
38
+ The package depends on `oauth4webapi` and `jose`. `hono`, `astro` and `next` are **optional peer dependencies**: you only need the one you use.
39
+
40
+ Import paths:
41
+
42
+ | Import | Used for |
43
+ |---|---|
44
+ | `@evup/auth/server` | `createEvupAuth` (core, framework-independent) |
45
+ | `@evup/auth/client` | `createEvupClient` (browser, no secret) |
46
+ | `@evup/auth/hono` | `evupAuth`, `requireUser`, `evupResource` |
47
+ | `@evup/auth/astro` | the `evup` integration, `createEvupMiddleware` |
48
+ | `@evup/auth/next` | `handlers`, `getSession`, `getUser`, `withEvupAuth` |
49
+ | `@evup/auth/resource` | `createEvupResource` (MCP / API server) |
50
+
51
+ ## Registering your app on EvUp
52
+
53
+ An EvUp admin goes to **/admin/apps → Add app** (type *Web app (server)* if the app has a backend, or *SPA / Mobile* if it cannot keep a secret). After creating it, open the app's detail page and configure:
54
+
55
+ 1. **Post-sign-in redirect URLs (`redirect_uris`)**: add exactly the SDK's callback URL, for example `https://app.example.com/auth/callback`. It must match the `redirectUri` in your configuration **exactly**. With no URL, the app cannot sign anyone in.
56
+ 2. **Post-sign-out redirect URLs (`post_logout_redirect_uris`)**: add the URL you want users to return to after signing out, for example `https://app.example.com/`, and set the same value in `postLogoutRedirectUri`. This list is **separate** from the one above.
57
+ 3. The **Allow the app to sign users out** switch (`enable_end_session`) is **on by default** for new apps. Only an admin can change it. If it is off, sign-out ends on EvUp's `invalid_client` error page ("The client is not allowed to initiate logout") instead of returning to the app (see [Signing out](#signing-out)).
58
+ 4. **Client secret**: shown **once** when a web app is created. An app that cannot keep a secret (SPA, mobile) is a *public client*: omit `EVUP_CLIENT_SECRET` and the SDK automatically uses `token_endpoint_auth_method=none` with PKCE.
59
+ 5. If the app has its own MCP / API server: add its URL in the **API resources** card (see [MCP / API resource server](#mcp--api-resource-server)).
60
+ 6. Optional: *First-party* (skips the consent screen), the `open` / `restricted` access mode and roles / permissions (see [Permissions](#permissions-rbac)).
61
+
62
+ IdP parameters (the SDK reads all of them from discovery, nothing is hardcoded):
63
+
64
+ | | |
65
+ |---|---|
66
+ | Issuer | `https://auth.evup.cloud/api/auth` (**not** the bare origin) |
67
+ | Discovery | `https://auth.evup.cloud/api/auth/.well-known/openid-configuration` |
68
+ | PKCE | `S256` only; `response_type=code`; the callback carries the `iss` parameter (RFC 9207) |
69
+ | id_token | signed with `EdDSA`, lives 1 hour |
70
+ | Scopes for a regular app | `openid profile email offline_access` (+ `phone`) |
71
+
72
+ ## Environment variables
73
+
74
+ | Variable | Required | Meaning |
75
+ |---|---|---|
76
+ | `EVUP_CLIENT_ID` | yes | the app's client id (or pass `clientId`) |
77
+ | `EVUP_CLIENT_SECRET` | no | client secret; if missing the app is a public client |
78
+ | `EVUP_SESSION_SECRET` | yes | cookie encryption key, **>= 32 characters** (`openssl rand -base64 32`) |
79
+
80
+ The SDK reads in this order: a value passed directly in the configuration, then `config.env`, then `process.env` (if it exists). On Cloudflare Workers pass the request's `env` (`env: c.env`).
81
+
82
+ ## Quick start
83
+
84
+ Hono on Node / Bun, enough to sign in, protect a route and sign out:
85
+
86
+ ```ts
87
+ import { Hono } from "hono";
88
+ import { createEvupAuth } from "@evup/auth/server";
89
+ import { evupAuth, requireUser, type EvupVariables } from "@evup/auth/hono";
90
+
91
+ const auth = createEvupAuth({
92
+ redirectUri: "https://app.example.com/auth/callback",
93
+ postLogoutRedirectUri: "https://app.example.com/",
94
+ });
95
+
96
+ const app = new Hono<{ Variables: EvupVariables }>();
97
+ app.use(evupAuth(auth));
98
+
99
+ app.get("/", (c) => c.html(c.var.user ? `Hello ${c.var.user.name ?? c.var.user.email}` : `<a href="/auth/sign-in">Sign in</a>`));
100
+ app.get("/dashboard", requireUser(), (c) => c.json({ email: c.var.user!.email }));
101
+
102
+ export default app;
103
+ ```
104
+
105
+ Put `EVUP_CLIENT_ID`, `EVUP_CLIENT_SECRET` and `EVUP_SESSION_SECRET` in the environment. The SDK serves 4 routes under `basePath` (default `/auth`) on its own:
106
+
107
+ | Route | Method | What it does |
108
+ |---|---|---|
109
+ | `/auth/sign-in` | GET | redirects to EvUp. Query: `returnTo`, `prompt`, `locale`, `loginHint` |
110
+ | `/auth/callback` | GET | receives `code`, exchanges the tokens, sets the session cookie, redirects to `returnTo` |
111
+ | `/auth/sign-out` | POST | clears the cookie, revokes the refresh token, redirects to EvUp's end-session |
112
+ | `/auth/session` | GET | JSON `{ "user": {...} }` or `{ "user": null }` (no tokens), `Cache-Control: no-store` |
113
+
114
+ ## By framework
115
+
116
+ ### Hono
117
+
118
+ **Node / Bun / Deno:** see [Quick start](#quick-start).
119
+
120
+ **Cloudflare Workers:** `env` only exists during a request, so pass a factory that receives `c`. The factory runs **once per isolate** and is then cached.
121
+
122
+ ```ts
123
+ import { Hono } from "hono";
124
+ import { createEvupAuth } from "@evup/auth/server";
125
+ import { evupAuth, requireUser, type EvupVariables } from "@evup/auth/hono";
126
+
127
+ type Bindings = { EVUP_CLIENT_ID: string; EVUP_CLIENT_SECRET?: string; EVUP_SESSION_SECRET: string };
128
+
129
+ const app = new Hono<{ Bindings: Bindings; Variables: EvupVariables }>();
130
+
131
+ app.use(
132
+ evupAuth((c) =>
133
+ createEvupAuth({
134
+ env: c.env,
135
+ redirectUri: "https://app.example.com/auth/callback",
136
+ postLogoutRedirectUri: "https://app.example.com/",
137
+ }),
138
+ ),
139
+ );
140
+
141
+ app.get("/me", requireUser(), (c) => c.json(c.var.user));
142
+
143
+ export default app;
144
+ ```
145
+
146
+ The middleware sets `c.var.user` (`EvupUser | null`), `c.var.session` (`Session | null`) and `c.var.evupAuth`; when the session has just been refreshed or cleared it adds `Set-Cookie` to the response itself.
147
+
148
+ `requireUser()` (place it **after** `evupAuth`): browser navigation requests (`GET` with `Accept: text/html`) are redirected to `/auth/sign-in?returnTo=<current path>`; every other request gets a `401` JSON `{ "error": "unauthorized", ... }`.
149
+
150
+ To protect an API with a Bearer token (MCP / resource server): see [Hono](#hono-1).
151
+
152
+ ### Astro
153
+
154
+ Requires `output: "server"` (or hybrid pages with `prerender = false`).
155
+
156
+ **Option 1: integration** (easiest). The configuration only accepts JSON values (it is embedded into the server bundle) and does **not** accept `secret`, `clientSecret`, `onAccessDenied`, `env`, `fetch`; secrets are read from environment variables.
157
+
158
+ ```js
159
+ // astro.config.mjs
160
+ import { defineConfig } from "astro/config";
161
+ import evup from "@evup/auth/astro";
162
+
163
+ export default defineConfig({
164
+ output: "server",
165
+ integrations: [
166
+ evup({
167
+ redirectUri: process.env.EVUP_REDIRECT_URI ?? "https://app.example.com/auth/callback",
168
+ postLogoutRedirectUri: "https://app.example.com/",
169
+ }),
170
+ ],
171
+ });
172
+ ```
173
+
174
+ The integration adds the route `/auth/[...evup]` and a middleware that fills `Astro.locals.user` / `Astro.locals.session`. To get types for `Astro.locals`, add this to `src/env.d.ts`:
175
+
176
+ ```ts
177
+ /// <reference types="@evup/auth/astro" />
178
+ ```
179
+
180
+ ```astro
181
+ ---
182
+ // src/pages/dashboard.astro
183
+ const user = Astro.locals.user;
184
+ if (!user) return Astro.redirect(`/auth/sign-in?returnTo=${encodeURIComponent(Astro.url.pathname)}`);
185
+ ---
186
+ <h1>Hello {user.name ?? user.email}</h1>
187
+ <form method="post" action="/auth/sign-out"><button type="submit">Sign out</button></form>
188
+ ```
189
+
190
+ **Option 2: manual middleware** (needed when you want `onAccessDenied`, a custom `fetch` or runtime-dependent configuration). No integration needed; the middleware serves the `/auth/*` routes itself.
191
+
192
+ ```ts
193
+ // src/middleware.ts
194
+ import { createEvupAuth } from "@evup/auth/server";
195
+ import { createEvupMiddleware } from "@evup/auth/astro";
196
+
197
+ // Node: do not pass `env`, the SDK reads process.env (EVUP_CLIENT_ID, EVUP_CLIENT_SECRET, EVUP_SESSION_SECRET)
198
+ export const onRequest = createEvupMiddleware(
199
+ createEvupAuth({
200
+ redirectUri: "https://app.example.com/auth/callback",
201
+ postLogoutRedirectUri: "https://app.example.com/",
202
+ }),
203
+ );
204
+ ```
205
+
206
+ > **Do not use `env: import.meta.env`.** In a production build, Astro only inlines private variables that are written with their **exact name** (`import.meta.env.EVUP_SESSION_SECRET`), while accessing the whole `import.meta.env` object does not include them, so the secret would vanish in production even though it works in dev. With Node, put the variables in the process environment (`process.env`); during `astro dev`, Astro loads `.env` into `import.meta.env` rather than `process.env`, so run dev with `node --env-file=.env ./node_modules/astro/bin/astro.mjs dev` or export the variables in the shell. You can use `astro:env/server` (`getSecret`) and pass the values into `env` (this approach has not been verified). On Workers, use `env` from `cloudflare:workers` as shown below.
207
+
208
+ Or pass a factory (can be `async`) that receives the `APIContext`: `createEvupMiddleware((ctx) => createEvupAuth({ ... }))`, which runs once per isolate. Prerendered pages get `locals.user === null` and do not read cookies.
209
+
210
+ **Cloudflare Workers (`@astrojs/cloudflare`):** since Astro 6, `Astro.locals.runtime.env` has been removed (accessing it throws); use option 2 with `env` from `cloudflare:workers`:
211
+
212
+ ```ts
213
+ // src/middleware.ts
214
+ import { env } from "cloudflare:workers";
215
+ import { createEvupAuth } from "@evup/auth/server";
216
+ import { createEvupMiddleware } from "@evup/auth/astro";
217
+
218
+ export const onRequest = createEvupMiddleware(
219
+ createEvupAuth({
220
+ env,
221
+ redirectUri: "https://app.example.com/auth/callback",
222
+ postLogoutRedirectUri: "https://app.example.com/",
223
+ }),
224
+ );
225
+ ```
226
+
227
+ If `EVUP_CLIENT_ID` / `EVUP_SESSION_SECRET` are not yet available when the module loads, `createEvupAuth` does not fail immediately but reports a `config` error on the first request; a value that is present but wrong (a secret shorter than 32 characters) fails right at creation.
228
+
229
+ The integration (option 1) merges variables in increasing priority: `import.meta.env` (only effective in dev), `process.env`, then the Workers binding (`locals.runtime.env`, then `cloudflare:workers`). Production should rely on `process.env` or the Workers binding, not on `import.meta.env`. On Workers prefer option 2, because it is the explicit path.
230
+
231
+ ### Next.js (App Router)
232
+
233
+ This example is for Next.js 15/16. Shared file:
234
+
235
+ ```ts
236
+ // lib/evup.ts
237
+ import { createEvupAuth } from "@evup/auth/server";
238
+
239
+ export const auth = createEvupAuth({
240
+ redirectUri: process.env.EVUP_REDIRECT_URI ?? "https://app.example.com/auth/callback",
241
+ postLogoutRedirectUri: "https://app.example.com/",
242
+ });
243
+ ```
244
+
245
+ **Route handler** `app/auth/[...evup]/route.ts`:
246
+
247
+ ```ts
248
+ import { handlers } from "@evup/auth/next";
249
+ import { auth } from "@/lib/evup";
250
+
251
+ export const { GET, POST } = handlers(auth);
252
+ ```
253
+
254
+ **Server Component / Server Action:**
255
+
256
+ ```tsx
257
+ // app/dashboard/page.tsx
258
+ import { redirect } from "next/navigation";
259
+ import { getUser } from "@evup/auth/next";
260
+ import { auth } from "@/lib/evup";
261
+
262
+ export default async function Dashboard() {
263
+ const user = await getUser(auth);
264
+ if (!user) redirect("/auth/sign-in?returnTo=/dashboard");
265
+ return <h1>Hello {user.name ?? user.email}</h1>;
266
+ }
267
+ ```
268
+
269
+ `getSession(auth)` and `getUser(auth)` from `@evup/auth/next` **only read the cookie and never refresh**. A Server Component cannot set cookies; if it refreshed, the browser would not receive the new refresh token, the next request would reuse the old refresh token and EvUp would revoke the whole token family (the user gets signed out). Refreshing is done in `withEvupAuth` (middleware/proxy) and in route handlers, where cookies can be set. `withEvupAuth` refreshes earlier (when less than **120 seconds** remain, instead of the default 60) so a Server Component always receives a non-expired access token while rendering. Consequence: **attach `withEvupAuth`** to every path that uses `session.accessToken`; otherwise `session.expiresAt` may already be in the past (`user` is always readable).
270
+
271
+ **Middleware / proxy** (Next.js 16 renames `middleware.ts` to `proxy.ts`, with the export named `proxy`; Next.js <= 15 uses `middleware.ts` with the export `middleware`):
272
+
273
+ ```ts
274
+ // proxy.ts (Next.js 16)
275
+ import { withEvupAuth } from "@evup/auth/next";
276
+ import { auth } from "@/lib/evup";
277
+
278
+ export const proxy = withEvupAuth(auth, { protect: ["/dashboard", "/settings"] });
279
+
280
+ export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
281
+ ```
282
+
283
+ ```ts
284
+ // middleware.ts (Next.js <= 15)
285
+ import { withEvupAuth } from "@evup/auth/next";
286
+ import { auth } from "@/lib/evup";
287
+
288
+ export const middleware = withEvupAuth(auth, { protect: ["/dashboard", "/settings"] });
289
+ ```
290
+
291
+ `protect` is a list of path prefixes (`"/dashboard"` covers `/dashboard/x` but not `/dashboards`). A signed-out visitor on a protected path: page navigations (`GET`/`HEAD` with `Accept: text/html`, or Next's client-side navigations carrying the `RSC` header) are redirected to `/auth/sign-in?returnTo=...`; every other request (API, `POST`...) gets a `401` JSON `{ "error": "unauthorized" }`, like Hono's `requireUser()`. A freshly refreshed cookie is sent to the browser **and** to the page being rendered.
292
+
293
+ **Client Component:**
294
+
295
+ ```tsx
296
+ "use client";
297
+ import { useEffect, useState } from "react";
298
+ import { createEvupClient, type EvupUser } from "@evup/auth/client";
299
+
300
+ const evup = createEvupClient();
301
+
302
+ export function UserMenu() {
303
+ const [user, setUser] = useState<EvupUser | null>(null);
304
+ useEffect(() => {
305
+ evup.getUser().then(setUser);
306
+ }, []);
307
+ if (!user) return <button onClick={() => evup.signIn({ returnTo: "/dashboard" })}>Sign in</button>;
308
+ return <button onClick={() => evup.signOut()}>Sign out {user.email}</button>;
309
+ }
310
+ ```
311
+
312
+ ### Core: fetch / Workers / Bun / Deno
313
+
314
+ `createEvupAuth` only needs a `Request` and returns a `Response`, so it works with any runtime. Pattern: run `auth.handler(req)` first (it returns `null` if the request is not an SDK route), then `getSession`.
315
+
316
+ **Cloudflare Workers** (no framework):
317
+
318
+ ```ts
319
+ import { createEvupAuth, type EvupAuth } from "@evup/auth/server";
320
+
321
+ let auth: EvupAuth | undefined;
322
+
323
+ export default {
324
+ async fetch(req: Request, env: Env): Promise<Response> {
325
+ auth ??= createEvupAuth({
326
+ env,
327
+ redirectUri: "https://app.example.com/auth/callback",
328
+ postLogoutRedirectUri: "https://app.example.com/",
329
+ });
330
+ const served = await auth.handler(req);
331
+ if (served) return served;
332
+
333
+ const { session, headers } = await auth.getSession(req);
334
+ const res = session
335
+ ? Response.json({ email: session.user.email })
336
+ : Response.redirect(new URL("/auth/sign-in", req.url).href, 302);
337
+ // headers carries Set-Cookie when the session has just been refreshed or cleared: it must be sent
338
+ const out = new Response(res.body, res);
339
+ for (const cookie of headers.getSetCookie()) out.headers.append("set-cookie", cookie);
340
+ return out;
341
+ },
342
+ };
343
+ ```
344
+
345
+ **Bun:**
346
+
347
+ ```ts
348
+ import { createEvupAuth } from "@evup/auth/server";
349
+
350
+ const auth = createEvupAuth({ redirectUri: "http://localhost:3000/auth/callback" });
351
+
352
+ Bun.serve({
353
+ port: 3000,
354
+ async fetch(req) {
355
+ const served = await auth.handler(req);
356
+ if (served) return served;
357
+ // getSession may refresh the session: Set-Cookie must be sent, otherwise the new refresh token is lost
358
+ const { session, headers } = await auth.getSession(req);
359
+ const res = new Response(session ? `Hello ${session.user.email}` : "Not signed in");
360
+ for (const cookie of headers.getSetCookie()) res.headers.append("set-cookie", cookie);
361
+ return res;
362
+ },
363
+ });
364
+ ```
365
+
366
+ **Deno:**
367
+
368
+ ```ts
369
+ import { createEvupAuth } from "npm:@evup/auth/server";
370
+
371
+ const auth = createEvupAuth({ redirectUri: "http://localhost:8000/auth/callback" });
372
+
373
+ Deno.serve(async (req) => (await auth.handler(req)) ?? new Response("Not found", { status: 404 }));
374
+ ```
375
+
376
+ > `getUser(req)` only reads the cookie and **never refreshes** (it does not call EvUp and produces no `Set-Cookie`); the session behind it may already have an expired access token. When you need a non-expired session (fresh permissions, `accessToken`), use `getSession(req)` and **always send `headers.getSetCookie()`**: the refresh token rotates, and if the new cookie is dropped the next refresh reuses the old token and EvUp revokes the whole token family.
377
+
378
+ ### React or any browser (`/client`)
379
+
380
+ `@evup/auth/client` has no secret and never sees tokens: it calls the SDK's routes on the same origin.
381
+
382
+ ```ts
383
+ import { createEvupClient } from "@evup/auth/client";
384
+
385
+ const evup = createEvupClient({ basePath: "/auth" }); // default "/auth"
386
+
387
+ const user = await evup.getUser(); // EvupUser | null (GET /auth/session)
388
+ evup.signIn({ returnTo: "/dashboard" }); // full-page navigation to /auth/sign-in
389
+ await evup.signOut(); // POST /auth/sign-out (Accept: application/json), then navigates to redirectTo
390
+ ```
391
+
392
+ `signIn` takes `{ returnTo?, prompt?, locale?, loginHint? }`; `signOut` takes `{ returnTo? }`.
393
+
394
+ ### Recipes for other frameworks
395
+
396
+ They all follow the same mold: `auth.handler(request)` serves the SDK's routes; `auth.getSession(request)` gives the user; attach `headers.getSetCookie()` to the response.
397
+
398
+ **SvelteKit** (`src/hooks.server.ts`):
399
+
400
+ ```ts
401
+ import type { Handle } from "@sveltejs/kit";
402
+ import { env } from "$env/dynamic/private";
403
+ import { createEvupAuth } from "@evup/auth/server";
404
+
405
+ const auth = createEvupAuth({ env, redirectUri: "https://app.example.com/auth/callback" });
406
+
407
+ export const handle: Handle = async ({ event, resolve }) => {
408
+ const served = await auth.handler(event.request);
409
+ if (served) return served;
410
+ const { session, headers } = await auth.getSession(event.request);
411
+ event.locals.user = session?.user ?? null; // declare `user` in App.Locals
412
+ const response = await resolve(event);
413
+ const out = new Response(response.body, response); // the original response's headers may be immutable
414
+ for (const cookie of headers.getSetCookie()) out.headers.append("set-cookie", cookie);
415
+ return out;
416
+ };
417
+ ```
418
+
419
+ **Nuxt / H3 v1** (`server/middleware/evup.ts`; with H3 v2 `event.req` is already a `Request`, return the `Response` directly):
420
+
421
+ ```ts
422
+ import { appendResponseHeader, defineEventHandler, sendWebResponse, toWebRequest } from "h3";
423
+ import { createEvupAuth } from "@evup/auth/server";
424
+
425
+ const auth = createEvupAuth({ env: process.env, redirectUri: "https://app.example.com/auth/callback" });
426
+
427
+ export default defineEventHandler(async (event) => {
428
+ const request = toWebRequest(event);
429
+ const served = await auth.handler(request);
430
+ if (served) return sendWebResponse(event, served);
431
+ const { session, headers } = await auth.getSession(request);
432
+ event.context.user = session?.user ?? null;
433
+ for (const cookie of headers.getSetCookie()) appendResponseHeader(event, "set-cookie", cookie);
434
+ });
435
+ ```
436
+
437
+ **React Router v7 / Remix** (route splat `route("auth/*", "routes/auth.tsx")`):
438
+
439
+ ```ts
440
+ // app/evup.server.ts
441
+ import { createEvupAuth } from "@evup/auth/server";
442
+ export const auth = createEvupAuth({ env: process.env, redirectUri: "https://app.example.com/auth/callback" });
443
+
444
+ // app/routes/auth.tsx : serves /auth/*
445
+ import type { LoaderFunctionArgs, ActionFunctionArgs } from "react-router";
446
+ import { auth } from "~/evup.server";
447
+ const serve = async ({ request }: LoaderFunctionArgs | ActionFunctionArgs) => (await auth.handler(request)) ?? new Response("Not found", { status: 404 });
448
+ export const loader = serve;
449
+ export const action = serve;
450
+
451
+ // in the loader of a route that needs the user
452
+ import { data } from "react-router";
453
+ export async function loader({ request }: LoaderFunctionArgs) {
454
+ const { session, headers } = await auth.getSession(request);
455
+ return data({ user: session?.user ?? null }, { headers }); // headers carries Set-Cookie on refresh
456
+ }
457
+ ```
458
+
459
+ **Express** (convert Node's `req` into a `Request`; set `app.set("trust proxy", true)` behind a reverse proxy):
460
+
461
+ ```ts
462
+ import express from "express";
463
+ import { createEvupAuth } from "@evup/auth/server";
464
+
465
+ const auth = createEvupAuth({ redirectUri: "http://localhost:3000/auth/callback" });
466
+ const app = express();
467
+
468
+ const toRequest = (req: express.Request): Request => {
469
+ const headers = new Headers();
470
+ for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
471
+ return new Request(`${req.protocol}://${req.get("host")}${req.originalUrl}`, { method: req.method, headers });
472
+ };
473
+
474
+ const send = async (res: express.Response, response: Response) => {
475
+ res.status(response.status);
476
+ response.headers.forEach((value, name) => name !== "set-cookie" && res.setHeader(name, value));
477
+ res.setHeader("set-cookie", response.headers.getSetCookie());
478
+ res.send(Buffer.from(await response.arrayBuffer()));
479
+ };
480
+
481
+ app.use(async (req, res, next) => {
482
+ const request = toRequest(req);
483
+ const served = await auth.handler(request);
484
+ if (served) return send(res, served);
485
+ const { session, headers } = await auth.getSession(request);
486
+ res.locals.user = session?.user ?? null;
487
+ for (const cookie of headers.getSetCookie()) res.append("set-cookie", cookie);
488
+ next();
489
+ });
490
+ ```
491
+
492
+ The `Request` above carries no body, so for `POST /auth/sign-out` pass `returnTo` through the query (`/auth/sign-out?returnTo=/bye`).
493
+
494
+ ## Protecting pages and APIs
495
+
496
+ - **Pages (HTML):** check `user`; if `null`, redirect to `${basePath}/sign-in?returnTo=<path>`. `returnTo` only accepts same-origin relative paths (starting with `/`, not `//`); any other value becomes `/`.
497
+ - **The app's own API (cookie):** return a `401` JSON when there is no session. Hono's `requireUser()` and Next's `withEvupAuth` do this.
498
+ - **API for external clients (Bearer token):** use [`@evup/auth/resource`](#mcp--api-resource-server), not cookies.
499
+ - **Calling other APIs on behalf of the user:** `session.accessToken`. It is opaque unless you configure `resource` (in which case it is a JWT for that API, see [Configuration reference](#configuration-reference)). Never expose the token to the browser.
500
+
501
+ ## Permissions (RBAC)
502
+
503
+ EvUp puts the `permissions` claim (an array of strings) into the app's id_token, access token and userinfo, based on the roles assigned in **/admin/apps → app**. The SDK exposes it as `user.permissions`; role names are not included.
504
+
505
+ ```ts
506
+ // getSession refreshes permissions when the access token is about to expire; send headers (Set-Cookie) along with the response
507
+ const { session, headers } = await auth.getSession(request);
508
+ if (!session?.user.permissions.includes("post:write")) return new Response("Forbidden", { status: 403 });
509
+ ```
510
+
511
+ `auth.getUser(request)` also has `permissions`, but it is only the value stored at the last sign-in or refresh (no refresh), so use it for display, not for sensitive access decisions.
512
+
513
+ Permissions are recomputed on every access token refresh (at most once an hour), so a role change takes effect within that time. A user whose access to the app has been revoked gets a 4xx error (`invalid_grant`) on the next refresh and the session is cleared.
514
+
515
+ On a resource server, `token.permissions` has the same meaning (see below).
516
+
517
+ ## Access denied and waitlist
518
+
519
+ An app in `restricted` mode only lets members or emails in the *allowed domains* in. A denied user sees an EvUp page (where they can request access and join the waitlist) with a button back to the app with `error=access_denied` plus `state` and `iss`.
520
+
521
+ The SDK handles that callback:
522
+
523
+ - By default it returns **403** with a small "Access denied" HTML page that has a **Sign in with another account** link to `/auth/sign-in?prompt=select_account`.
524
+ - To show your own page (for example one that explains how to request access), pass `onAccessDenied`:
525
+
526
+ ```ts
527
+ createEvupAuth({
528
+ redirectUri: "https://app.example.com/auth/callback",
529
+ onAccessDenied: (req, err) =>
530
+ new Response(`This account has not been granted access. ${err.description ?? ""}`, { status: 403, headers: { "content-type": "text/plain; charset=utf-8" } }),
531
+ });
532
+ ```
533
+
534
+ When a refresh happens after the user has had access revoked or has been banned, EvUp returns `invalid_grant`: the SDK clears the session cookie and `getSession` returns `session: null`.
535
+
536
+ ## Signing out
537
+
538
+ `POST /auth/sign-out` (POST only, so links or images on other sites cannot sign the user out; a different origin is rejected with 403):
539
+
540
+ ```html
541
+ <form method="post" action="/auth/sign-out">
542
+ <button type="submit">Sign out</button>
543
+ </form>
544
+ ```
545
+
546
+ Or `createEvupClient().signOut()` / `auth.signOut(request, { returnTo })`. The SDK:
547
+
548
+ 1. clears the session cookie;
549
+ 2. revokes the refresh token (`/oauth2/revoke`, best effort). **A public client (no `clientSecret`) cannot revoke it**: this EvUp endpoint requires client authentication, so the SDK skips this step; the refresh token only becomes invalid when the EvUp session ends in step 3;
550
+ 3. redirects to EvUp's `end_session_endpoint`: `/oauth2/end-session?id_token_hint=<id_token>&client_id=<id>&post_logout_redirect_uri=<postLogoutRedirectUri>`.
551
+
552
+ `returnTo` (a relative path) is only used when the EvUp sign-out page **cannot** be used (the IdP does not publish `end_session_endpoint`, or it cannot be reached); in that case the user goes to `returnTo` (default `/`). To send users back to a page after sign-out, register that URL as a *post-logout redirect URI* and set `postLogoutRedirectUri`.
553
+
554
+ ### What EvUp's `/oauth2/end-session` accepts (read from `@better-auth/oauth-provider`)
555
+
556
+ - **Parameters** (GET or POST form): `id_token_hint`, `client_id`, `post_logout_redirect_uri`, `state`.
557
+ - **`id_token_hint`**: an id_token signed by EvUp itself (signature checked through JWKS; `exp` is **not** checked, so an expired id_token still works), correct `iss`, `aud` containing the client, with `sid` and `sub` claims. If it is valid and matches the current browser session, EvUp **ends the session immediately** without asking anything.
558
+ - **No valid `id_token_hint`** (for example the SDK dropped the id_token because the cookie was too large, see [Security notes](#security-notes)) or a hint from a session other than the browser's: EvUp shows a **"Confirm logout"** page and only signs out once the user confirms. A valid `client_id` is enough for EvUp to know where to return after confirmation.
559
+ - **`client_id`**: optional when there is a hint (by default derived from the hint's `aud`/`azp`); it must be an existing, non-disabled client with **`enable_end_session` turned on**, otherwise EvUp returns an `invalid_client` error ("The client is not allowed to initiate logout").
560
+ - **`post_logout_redirect_uri`**: must match, **character for character**, an entry in the app's *post-sign-out redirect URLs* (the sign-in redirect list is not used). EvUp only redirects on a match; if it does not match, the user is still signed out but stops at EvUp's "Logged out. The requested post-logout redirect was not registered." page. Only `client_id` needs to accompany it; `http://` is only allowed for localhost.
561
+ - **`state`**: if sent, EvUp appends it to `post_logout_redirect_uri` when redirecting. The SDK does not use this `state`.
562
+ - **Back-channel logout** (`backchannel_logout_uri`): SDK v0.1 has no receiver yet. The session in the app ends on the next refresh (when EvUp returns `invalid_grant`), that is, after about 1 hour at most.
563
+
564
+ ## MCP / API resource server
565
+
566
+ Use this when your app has its own MCP server or API that clients (Claude Code, Cursor, your own app...) call with an access token issued by EvUp.
567
+
568
+ **1. Register:** in the app's detail page, card **API resources → Add resource**, enter the URL that the server publishes as its `resource` (for example `https://api.example.com/mcp`; add a separate entry for dev, for example `http://localhost:8787/mcp`). Users can only obtain a token for the resource if they pass the app's access rules (in `restricted` mode, only members).
569
+
570
+ **2. The token** EvUp issues for the resource: a JWT signed with the key at `jwks_uri`, header `typ: "at+jwt"`, `iss` = issuer, `aud` containing the resource URL (may be an array), `azp` = client id, `scope` separated by spaces, `sub` = user id, `permissions` = RBAC permissions, lives 600 seconds. The scopes that a token for an app's resource can carry are `openid profile email offline_access`; for fine-grained authorization use `permissions`.
571
+
572
+ **3. The SDK** (`createEvupResource`) verifies exactly as EvUp's own resource server does: `typ at+jwt`, `iss` must match exactly, `aud` containing the resource, `sub`, `exp`, `azp`, `scope` are required; tokens bound with DPoP (`cnf`) are rejected; the JWKS comes from discovery, is cached per isolate, and is reloaded automatically when an unknown `kid` appears (keys rotate every 90 days).
573
+
574
+ ```ts
575
+ import { createEvupResource } from "@evup/auth/resource";
576
+
577
+ const resource = createEvupResource({
578
+ resource: "https://api.example.com/mcp", // must equal the registered URL
579
+ scopes: ["openid"], // optional: published and required
580
+ resourceName: "Example API",
581
+ });
582
+
583
+ resource.metadataPath; // "/.well-known/oauth-protected-resource/mcp"
584
+ resource.metadata(); // the RFC 9728 document
585
+ await resource.verify(req); // { ok: true, token } | { ok: false, status: 401 | 403, response }
586
+ await resource.handle(req, async (req, token) => Response.json({ sub: token.sub }));
587
+ ```
588
+
589
+ The metadata document (matches how EvUp publishes its own `/mcp`):
590
+
591
+ ```json
592
+ {
593
+ "resource": "https://api.example.com/mcp",
594
+ "authorization_servers": ["https://auth.evup.cloud/api/auth"],
595
+ "scopes_supported": ["openid"],
596
+ "bearer_methods_supported": ["header"],
597
+ "resource_name": "Example API"
598
+ }
599
+ ```
600
+
601
+ Error responses (JSON `{ "error", "error_description" }`, with CORS `Access-Control-Allow-Origin: *` and `Access-Control-Expose-Headers: WWW-Authenticate`):
602
+
603
+ | Situation | Status | `WWW-Authenticate` |
604
+ |---|---|---|
605
+ | No Bearer token | 401 | `Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"` |
606
+ | Token invalid / expired / wrong `aud`, `iss`, `typ` | 401 | `Bearer error="invalid_token", error_description="...", resource_metadata="..."` |
607
+ | Missing required scope | 403 | `Bearer error="insufficient_scope", error_description="...", scope="<required scope>", resource_metadata="..."` |
608
+
609
+ `handle()` and `evupResource()` (Hono) answer a CORS `OPTIONS` preflight with `204` without needing a token, with `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Headers: Authorization, Content-Type, Mcp-Protocol-Version` and `Access-Control-Allow-Methods` (MCP clients running in a browser need this). `resource.preflightResponse()` gives you the same response if you do your own routing.
610
+
611
+ If you configure `scopes`, the 401 challenge for the no-token case also carries `scope="..."` (like EvUp's own resource server) so the client knows which scope to request.
612
+
613
+ If EvUp's discovery/JWKS cannot be loaded, `verify` **throws** `EvupAuthError` (`discovery_failed`) instead of returning 401, so the client is not pushed into a re-authorization loop because of an infrastructure error.
614
+
615
+ ### Hono
616
+
617
+ ```ts
618
+ import { Hono } from "hono";
619
+ import { createEvupResource } from "@evup/auth/resource";
620
+ import { evupResource, type EvupVariables } from "@evup/auth/hono";
621
+
622
+ const resource = createEvupResource({ resource: "https://api.example.com/mcp", resourceName: "Example API" });
623
+
624
+ const app = new Hono<{ Variables: EvupVariables }>();
625
+
626
+ app.get(resource.metadataPath, evupResource(resource)); // serves the metadata (no token needed)
627
+ app.use("/mcp", evupResource(resource)); // every request to /mcp needs a valid Bearer token
628
+ app.post("/mcp", (c) => c.json({ user: c.var.evupToken.sub, permissions: c.var.evupToken.permissions }));
629
+
630
+ export default app;
631
+ ```
632
+
633
+ ### Plain fetch / Workers
634
+
635
+ ```ts
636
+ import { createEvupResource } from "@evup/auth/resource";
637
+
638
+ const resource = createEvupResource({ resource: "https://api.example.com/mcp" });
639
+
640
+ export default {
641
+ fetch: (req: Request) =>
642
+ resource.handle(req, async (_req, token) => {
643
+ if (!token.permissions.includes("reports:read")) return new Response("Forbidden", { status: 403 });
644
+ return Response.json({ sub: token.sub, clientId: token.clientId });
645
+ }),
646
+ };
647
+ ```
648
+
649
+ ### Next.js route
650
+
651
+ ```ts
652
+ // app/mcp/route.ts
653
+ import { createEvupResource } from "@evup/auth/resource";
654
+
655
+ const resource = createEvupResource({ resource: "https://api.example.com/mcp" });
656
+
657
+ export const POST = (req: Request) => resource.handle(req, async (_req, token) => Response.json({ sub: token.sub }));
658
+ ```
659
+
660
+ ```ts
661
+ // app/.well-known/oauth-protected-resource/mcp/route.ts
662
+ import { createEvupResource } from "@evup/auth/resource";
663
+
664
+ const resource = createEvupResource({ resource: "https://api.example.com/mcp" });
665
+
666
+ export const GET = () => resource.metadataResponse();
667
+ ```
668
+
669
+ ### What an MCP client does
670
+
671
+ An MCP client calls `POST /mcp` without a token, gets a `401` with `WWW-Authenticate: Bearer resource_metadata="..."`, fetches the metadata to learn the `authorization_servers`, registers (DCR) or uses an existing client, goes through EvUp's sign-in and consent with `resource=<your URL>` (RFC 8707), then calls again with `Authorization: Bearer <JWT>`. That is why the `resource` URL you register must **exactly** match the URL the client uses to call.
672
+
673
+ ## Configuration reference
674
+
675
+ `createEvupAuth(config)` (`@evup/auth/server`):
676
+
677
+ | Option | Default | Meaning |
678
+ |---|---|---|
679
+ | `redirectUri` | required | absolute callback URL, registered in the app. `https`, or `http` for localhost |
680
+ | `clientId` | `EVUP_CLIENT_ID` | |
681
+ | `clientSecret` | `EVUP_CLIENT_SECRET` | if missing, a public client (`none`); if present, `client_secret_basic` |
682
+ | `secret` | `EVUP_SESSION_SECRET` | cookie encryption key, >= 32 characters |
683
+ | `issuer` | `https://auth.evup.cloud/api/auth` | |
684
+ | `scopes` | `["openid","profile","email","offline_access"]` | must include `openid` |
685
+ | `resource` | none | `string` or `string[]` (RFC 8707); the access token becomes a JWT for that API |
686
+ | `postLogoutRedirectUri` | none | URI registered as a post-logout redirect |
687
+ | `cookie.name` | `"evup_session"` | |
688
+ | `cookie.maxAge` | 30 days (seconds) | |
689
+ | `cookie.sameSite` | `"lax"` | `"lax"` or `"none"` (requires `secure`). `"strict"` is rejected: the browser does not send the cookie on the redirect after the IdP callback, so the user would land signed out |
690
+ | `cookie.secure` | `true` when `redirectUri` is https (or `sameSite: "none"`), `false` for http localhost | |
691
+ | `cookie.domain` | none | |
692
+ | `cookie.path` | `"/"` | |
693
+ | `basePath` | `"/auth"` | the routes live under this path |
694
+ | `onAccessDenied` | default 403 page | `(req, err) => Response` |
695
+ | `onError` | `console.error` | `(req, err) => void`: called for every other callback error (`invalid_state`, `callback_failed`, `discovery_failed`; not called for `access_denied`). By default it logs `[evup-auth] <code>: <message> (<cause.message>)`, never tokens. Errors thrown from the hook are ignored |
696
+ | `env` | `process.env` | where `EVUP_*` is read from; Workers pass `env` (only string values are read) |
697
+ | `fetch` | global `fetch` | used for every request to EvUp |
698
+
699
+ Return value (`EvupAuth`):
700
+
701
+ ```ts
702
+ interface EvupAuth {
703
+ readonly basePath: string;
704
+ handler(req: Request): Promise<Response | null>; // SDK routes; null for other requests
705
+ signIn(req: Request, opts?: { returnTo?: string; prompt?: string; locale?: string; loginHint?: string }): Promise<Response>;
706
+ callback(req: Request): Promise<Response>;
707
+ signOut(req: Request, opts?: { returnTo?: string }): Promise<Response>;
708
+ getSession(req: Request, opts?: { refresh?: boolean; refreshWindow?: number }): Promise<{ session: Session | null; headers: Headers }>;
709
+ getUser(req: Request): Promise<EvupUser | null>; // only reads the cookie, no refresh
710
+ }
711
+
712
+ type EvupUser = {
713
+ id: string; email: string; emailVerified: boolean; name?: string; picture?: string;
714
+ permissions: string[]; claims: Record<string, unknown>; // claims: id_token merged with userinfo
715
+ };
716
+ type Session = { user: EvupUser; accessToken: string; expiresAt: number /* ms epoch */; scope: string };
717
+ ```
718
+
719
+ `createEvupResource(config)` (`@evup/auth/resource`): `{ resource, issuer?, scopes?, resourceName?, clockTolerance? = 30, fetch? }` → `{ metadataPath, metadata(), metadataResponse(), preflightResponse(), verify(req | string), handle(req, next) }`. A valid token: `{ sub, clientId, scopes, permissions, exp, claims }` (`exp` in seconds).
720
+
721
+ Session behavior:
722
+
723
+ - **`getSession(req, opts?)`** refreshes when the access token has less than 60 seconds left (`opts.refreshWindow`, in seconds, changes this threshold; `opts.refresh: false` only reads the cookie). **`getUser(req)` never refreshes**: it reads the user from the cookie, does not call EvUp, produces no `Set-Cookie`, and the session behind it may already be past `expiresAt` (an expired access token that has not been renewed). Why it matters: EvUp rotates refresh tokens and treats reuse of a rotated token as theft, revoking the whole token family. Any refresh whose new cookie does not reach the browser leads to that on the next request.
724
+ - **Sharing a single refresh:** concurrent requests in one isolate with the same cookie share **one** refresh. Across isolates/instances, the EvUp auth server accepts reuse of a just-rotated refresh token within **90 seconds** (`refreshTokenReuseInterval`) and returns the same result, so two instances refreshing at almost the same time do not break the token family. Reuse after 90 seconds still revokes the whole family (for example a tab holding the old cookie after another tab has refreshed): the session is cleared and the user signs in again.
725
+ - **Errors on refresh:** every OAuth 4xx error response (except 408/429) such as `invalid_grant`, `invalid_request`, `invalid_client`, `unauthorized_client`, `invalid_scope`, `invalid_target` clears the session (`session: null` with a `Set-Cookie` that clears the cookie). Network errors, timeouts, 5xx, 408 and 429 leave the cookie in place: the session stays usable until the access token actually expires, then `session: null` without clearing the cookie, and the next request tries again.
726
+ - No refresh token (`offline_access` not requested): the session expires with the access token (1 hour).
727
+ - The `session` route returns JSON without tokens.
728
+
729
+ ## Errors
730
+
731
+ `EvupAuthError` (`@evup/auth/server`, also exported from `@evup/auth/resource`) has `code`, `message`, `description?` (the OAuth `error_description` if present) and `cause`.
732
+
733
+ | `code` | When |
734
+ |---|---|
735
+ | `config` | wrong or missing configuration (relative `redirectUri`, short secret, missing `clientId`/`secret`); **thrown**, not swallowed |
736
+ | `access_denied` | EvUp denied the user (callback `error=access_denied`) |
737
+ | `invalid_state` | transaction cookie missing/expired, `state` or `iss` mismatch |
738
+ | `callback_failed` | code exchange failed, id_token invalid (`nonce`, `aud`...), session too large for the cookie |
739
+ | `discovery_failed` | the issuer's discovery or JWKS could not be loaded (the callback returns 502; `verify` throws) |
740
+
741
+ Errors in the callback never leak details to the user: they see a "Sign-in failed" page (400/502) or "Access denied" (403); `onAccessDenied` replaces the 403 page and `onError` receives every other error (see the configuration table). Refresh errors are not `EvupAuthError`: they are handled as described in [Session behavior](#configuration-reference).
742
+
743
+ ## Security notes
744
+
745
+ - **Session cookie** `evup_session`: JWE (`dir` + `A256GCM`) via `jose`; key = HKDF-SHA256(`secret`, info `"evup-auth session"`). Contents: the user's claims (stored once, `user` is rebuilt on read), access token, refresh token, expiry, scope, id_token. `HttpOnly` is always on, `SameSite=Lax`, `Secure` on https. At most 3800 bytes: beyond that the **id_token is dropped** first (sign-out then goes through EvUp's confirmation page), then `claims` is trimmed down to `sub`, `email`, `email_verified`, `name`, `picture`, `permissions`; if it is still too large the error is `callback_failed`.
746
+ - **Transaction cookie** `evup_tx` (10 minutes, a different HKDF key): `state`, `nonce`, `code_verifier`, `returnTo`. Cleared after the callback (even on error). If you open two sign-in tabs at once, the earlier one becomes invalid.
747
+ - **PKCE S256** is mandatory; `state` and `nonce` are random; the callback checks `state` and `iss` (RFC 9207), and the id_token is checked for `iss`, `aud`, `exp`, `nonce` (oauth4webapi). The id_token is received directly from the token endpoint over TLS, so its signature does not need to be re-verified on the client.
748
+ - **Open redirect:** `returnTo` only accepts same-origin paths; `//host`, `/\host`, control characters, `/..//host` and absolute URLs all become `/`.
749
+ - **CSRF-safe sign-out:** `POST` only, rejects an `Origin` different from the request's origin / `redirectUri` and `Sec-Fetch-Site: cross-site`.
750
+ - **Rotating `secret`:** changing `EVUP_SESSION_SECRET` **invalidates every existing session** (users only have to sign in again; signing in through EvUp usually requires entering nothing if they still have a session there). Multiple simultaneous secrets are not supported yet. Change it during off-peak hours or accept one round of re-sign-in.
751
+ - **No secret in the bundle:** the Astro integration rejects `secret` and `clientSecret`.
752
+ - **Tokens stay server-side:** access and refresh tokens never reach the browser (encrypted `HttpOnly` cookie; the `session` route returns no tokens).
753
+ - **Resource server:** rejects DPoP-bound tokens because it does not check proof-of-possession; `typ` must be `at+jwt` (an id_token cannot be used as an access token).
754
+
755
+ ## Local development with a local IdP
756
+
757
+ Run EvUp locally (`npm run dev` in the auth repo, default `http://localhost:4400`) and point the SDK at it:
758
+
759
+ ```ts
760
+ createEvupAuth({
761
+ issuer: "http://localhost:4400/api/auth",
762
+ redirectUri: "http://localhost:3000/auth/callback",
763
+ postLogoutRedirectUri: "http://localhost:3000/",
764
+ });
765
+ ```
766
+
767
+ - `http` is only accepted for `localhost`, `127.0.0.1`, `[::1]` and `*.localhost` (issuer, `redirectUri`, `postLogoutRedirectUri`, `resource`); every other host must be `https`.
768
+ - With an `http` `redirectUri`, the cookie is not set `Secure` (Safari does not accept `Secure` cookies over http).
769
+ - Register in the app: redirect URI `http://localhost:3000/auth/callback`, post-logout `http://localhost:3000/`. Use a separate dev app instead of the production app.
770
+ - Dev resource: add `http://localhost:8787/mcp` as a separate entry in **API resources**.
771
+
772
+ Run the package's tests: `npm test -w @evup/auth` (completely offline). The test that reads the real discovery of `auth.evup.cloud` (a single public `GET`) only runs when `EVUP_LIVE_TEST=1` is set.
773
+
774
+ ## Releasing
775
+
776
+ The package has its own version and is released from the repo root with `npm run release:sdk` (preview: `-- --dry-run`). The tag `auth-vX.Y.Z` triggers `.github/workflows/release-sdk.yml`: build, test, `npm publish`, then a GitHub Release from the package's `CHANGELOG.md`. Publishing uses npm Trusted Publishing (OIDC): on npmjs.com the package `@evup/auth` trusts this repository and the `release-sdk.yml` workflow, so no `NPM_TOKEN` is stored (fallback: an `NPM_TOKEN` secret via `NODE_AUTH_TOKEN`). The workflow skips `npm publish` when the version is already on npm (for example the first version, published by hand) and still creates the GitHub Release. `--provenance` is off while the repository is private.
777
+
778
+ ## FAQ
779
+
780
+ **Why are users signed out after about 1 hour?** A session without a refresh token (you removed `offline_access` from `scopes`) expires with the access token. Keep `offline_access` (the default).
781
+
782
+ **How long until a user's role change takes effect?** At the next access token refresh (at most 1 hour). To make it immediate: call `auth.signOut` or require the user to sign in again.
783
+
784
+ **`getUser` or `getSession`?** `getUser` only reads the cookie and never refreshes, so it is safe everywhere but may return the user of a session whose access token has expired. `getSession` may refresh; use it in middleware/handlers and **always send `headers.getSetCookie()`**, because the refresh token rotates: if the new cookie is dropped, the next refresh is treated by EvUp as token reuse and the whole token family is revoked.
785
+
786
+ **How do I call EvUp's API or my own API on behalf of the user?** Use `session.accessToken` on the server side. To make the token a JWT for your API, set `resource: "https://api.example.com/mcp"` (the URL must be registered in **API resources**) and then verify it in the API with `createEvupResource`.
787
+
788
+ **Cookie too large / no id_token anymore?** This is normal when there are many claims. The only consequence: sign-out goes through EvUp's confirmation page. Reduce `scopes` or the number of permissions if you want to avoid it.
789
+
790
+ **Can I run multiple instances (multiple isolates / servers)?** Yes. The encrypted cookie is the entire state; all that is needed is for every instance to use the same `EVUP_SESSION_SECRET`. Refresh deduplication only works within one instance; across instances, EvUp allows reuse of a just-rotated refresh token for 90 seconds, so two instances refreshing almost simultaneously are still safe. Only when reuse happens after 90 seconds (for example a tab holding the old cookie) does EvUp revoke the whole token family and the user has to sign in again.
791
+
792
+ **A `secret` shorter than 32 characters?** `createEvupAuth` throws `EvupAuthError` (`config`) right at creation if the secret is passed directly or is already present in `env`; if the variable is not yet available at creation (Workers), the error comes on the first request.
793
+
794
+ **Is `client_credentials` / machine-to-machine supported?** No: EvUp does not have this grant. Use the user's refresh token or an API key.