@evup/auth 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -24,7 +24,8 @@ An SDK that lets your app sign users in with **EvUp Account** (`auth.evup.cloud`
24
24
  13. [Errors](#errors)
25
25
  14. [Security notes](#security-notes)
26
26
  15. [Local development with a local IdP](#local-development-with-a-local-idp)
27
- 16. [FAQ](#faq)
27
+ 16. [Testing your app (e2e)](#testing-your-app-e2e)
28
+ 17. [FAQ](#faq)
28
29
 
29
30
  ## Installation
30
31
 
@@ -36,44 +37,44 @@ The package depends on `oauth4webapi` and `jose`. `hono`, `astro` and `next` are
36
37
 
37
38
  Import paths:
38
39
 
39
- | Import | Used for |
40
- |---|---|
41
- | `@evup/auth/server` | `createEvupAuth` (core, framework-independent) |
42
- | `@evup/auth/client` | `createEvupClient` (browser, no secret) |
43
- | `@evup/auth/hono` | `evupAuth`, `requireUser`, `evupResource` |
44
- | `@evup/auth/astro` | the `evup` integration, `createEvupMiddleware` |
45
- | `@evup/auth/next` | `handlers`, `getSession`, `getUser`, `withEvupAuth` |
46
- | `@evup/auth/resource` | `createEvupResource` (MCP / API server) |
47
- | `@evup/auth/m2m` | `createEvupClientCredentials` (server-to-server tokens, no user) |
40
+ | Import | Used for |
41
+ | --------------------- | ---------------------------------------------------------------- |
42
+ | `@evup/auth/server` | `createEvupAuth` (core, framework-independent) |
43
+ | `@evup/auth/client` | `createEvupClient` (browser, no secret) |
44
+ | `@evup/auth/hono` | `evupAuth`, `requireUser`, `evupResource` |
45
+ | `@evup/auth/astro` | the `evup` integration, `createEvupMiddleware` |
46
+ | `@evup/auth/next` | `handlers`, `getSession`, `getUser`, `withEvupAuth` |
47
+ | `@evup/auth/resource` | `createEvupResource` (MCP / API server) |
48
+ | `@evup/auth/m2m` | `createEvupClientCredentials` (server-to-server tokens, no user) |
48
49
 
49
50
  ## Registering your app on EvUp
50
51
 
51
- 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:
52
+ 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:
52
53
 
53
54
  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.
54
55
  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.
55
56
  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)).
56
- 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.
57
+ 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.
57
58
  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)).
58
- 6. Optional: *First-party* (skips the consent screen), the `open` / `restricted` access mode and roles / permissions (see [Permissions](#permissions-rbac)).
59
+ 6. Optional: _First-party_ (skips the consent screen), the `open` / `restricted` access mode and roles / permissions (see [Permissions](#permissions-rbac)).
59
60
 
60
61
  IdP parameters (the SDK reads all of them from discovery, nothing is hardcoded):
61
62
 
62
- | | |
63
- |---|---|
64
- | Issuer | `https://auth.evup.cloud/api/auth` (**not** the bare origin) |
65
- | Discovery | `https://auth.evup.cloud/api/auth/.well-known/openid-configuration` |
66
- | PKCE | `S256` only; `response_type=code`; the callback carries the `iss` parameter (RFC 9207) |
67
- | id_token | signed with `EdDSA`, lives 1 hour |
68
- | Scopes for a regular app | `openid profile email offline_access` (+ `phone`) |
63
+ | | |
64
+ | ------------------------ | -------------------------------------------------------------------------------------- |
65
+ | Issuer | `https://auth.evup.cloud/api/auth` (**not** the bare origin) |
66
+ | Discovery | `https://auth.evup.cloud/api/auth/.well-known/openid-configuration` |
67
+ | PKCE | `S256` only; `response_type=code`; the callback carries the `iss` parameter (RFC 9207) |
68
+ | id_token | signed with `EdDSA`, lives 1 hour |
69
+ | Scopes for a regular app | `openid profile email offline_access` (+ `phone`) |
69
70
 
70
71
  ## Environment variables
71
72
 
72
- | Variable | Required | Meaning |
73
- |---|---|---|
74
- | `EVUP_CLIENT_ID` | yes | the app's client id (or pass `clientId`) |
75
- | `EVUP_CLIENT_SECRET` | no | client secret; if missing the app is a public client |
76
- | `EVUP_SESSION_SECRET` | yes | cookie encryption key, **>= 32 characters** (`openssl rand -base64 32`) |
73
+ | Variable | Required | Meaning |
74
+ | --------------------- | -------- | ----------------------------------------------------------------------- |
75
+ | `EVUP_CLIENT_ID` | yes | the app's client id (or pass `clientId`) |
76
+ | `EVUP_CLIENT_SECRET` | no | client secret; if missing the app is a public client |
77
+ | `EVUP_SESSION_SECRET` | yes | cookie encryption key, **>= 32 characters** (`openssl rand -base64 32`) |
77
78
 
78
79
  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`).
79
80
 
@@ -87,8 +88,8 @@ import { createEvupAuth } from "@evup/auth/server";
87
88
  import { evupAuth, requireUser, type EvupVariables } from "@evup/auth/hono";
88
89
 
89
90
  const auth = createEvupAuth({
90
- redirectUri: "https://app.example.com/auth/callback",
91
- postLogoutRedirectUri: "https://app.example.com/",
91
+ redirectUri: "https://app.example.com/auth/callback",
92
+ postLogoutRedirectUri: "https://app.example.com/",
92
93
  });
93
94
 
94
95
  const app = new Hono<{ Variables: EvupVariables }>();
@@ -102,12 +103,12 @@ export default app;
102
103
 
103
104
  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:
104
105
 
105
- | Route | Method | What it does |
106
- |---|---|---|
107
- | `/auth/sign-in` | GET | redirects to EvUp. Query: `returnTo`, `prompt`, `locale`, `loginHint` |
108
- | `/auth/callback` | GET | receives `code`, exchanges the tokens, sets the session cookie, redirects to `returnTo` |
109
- | `/auth/sign-out` | POST | clears the cookie, revokes the refresh token, redirects to EvUp's end-session |
110
- | `/auth/session` | GET | JSON `{ "user": {...} }` or `{ "user": null }` (no tokens), `Cache-Control: no-store` |
106
+ | Route | Method | What it does |
107
+ | ---------------- | ------ | --------------------------------------------------------------------------------------- |
108
+ | `/auth/sign-in` | GET | redirects to EvUp. Query: `returnTo`, `prompt`, `locale`, `loginHint` |
109
+ | `/auth/callback` | GET | receives `code`, exchanges the tokens, sets the session cookie, redirects to `returnTo` |
110
+ | `/auth/sign-out` | POST | clears the cookie, revokes the refresh token, redirects to EvUp's end-session |
111
+ | `/auth/session` | GET | JSON `{ "user": {...} }` or `{ "user": null }` (no tokens), `Cache-Control: no-store` |
111
112
 
112
113
  ## By framework
113
114
 
@@ -127,13 +128,13 @@ type Bindings = { EVUP_CLIENT_ID: string; EVUP_CLIENT_SECRET?: string; EVUP_SESS
127
128
  const app = new Hono<{ Bindings: Bindings; Variables: EvupVariables }>();
128
129
 
129
130
  app.use(
130
- evupAuth((c) =>
131
- createEvupAuth({
132
- env: c.env,
133
- redirectUri: "https://app.example.com/auth/callback",
134
- postLogoutRedirectUri: "https://app.example.com/",
135
- }),
136
- ),
131
+ evupAuth((c) =>
132
+ createEvupAuth({
133
+ env: c.env,
134
+ redirectUri: "https://app.example.com/auth/callback",
135
+ postLogoutRedirectUri: "https://app.example.com/",
136
+ }),
137
+ ),
137
138
  );
138
139
 
139
140
  app.get("/me", requireUser(), (c) => c.json(c.var.user));
@@ -159,13 +160,13 @@ import { defineConfig } from "astro/config";
159
160
  import evup from "@evup/auth/astro";
160
161
 
161
162
  export default defineConfig({
162
- output: "server",
163
- integrations: [
164
- evup({
165
- redirectUri: process.env.EVUP_REDIRECT_URI ?? "https://app.example.com/auth/callback",
166
- postLogoutRedirectUri: "https://app.example.com/",
167
- }),
168
- ],
163
+ output: "server",
164
+ integrations: [
165
+ evup({
166
+ redirectUri: process.env.EVUP_REDIRECT_URI ?? "https://app.example.com/auth/callback",
167
+ postLogoutRedirectUri: "https://app.example.com/",
168
+ }),
169
+ ],
169
170
  });
170
171
  ```
171
172
 
@@ -181,6 +182,7 @@ The integration adds the route `/auth/[...evup]` and a middleware that fills `As
181
182
  const user = Astro.locals.user;
182
183
  if (!user) return Astro.redirect(`/auth/sign-in?returnTo=${encodeURIComponent(Astro.url.pathname)}`);
183
184
  ---
185
+
184
186
  <h1>Hello {user.name ?? user.email}</h1>
185
187
  <form method="post" action="/auth/sign-out"><button type="submit">Sign out</button></form>
186
188
  ```
@@ -194,10 +196,10 @@ import { createEvupMiddleware } from "@evup/auth/astro";
194
196
 
195
197
  // Node: do not pass `env`, the SDK reads process.env (EVUP_CLIENT_ID, EVUP_CLIENT_SECRET, EVUP_SESSION_SECRET)
196
198
  export const onRequest = createEvupMiddleware(
197
- createEvupAuth({
198
- redirectUri: "https://app.example.com/auth/callback",
199
- postLogoutRedirectUri: "https://app.example.com/",
200
- }),
199
+ createEvupAuth({
200
+ redirectUri: "https://app.example.com/auth/callback",
201
+ postLogoutRedirectUri: "https://app.example.com/",
202
+ }),
201
203
  );
202
204
  ```
203
205
 
@@ -214,11 +216,11 @@ import { createEvupAuth } from "@evup/auth/server";
214
216
  import { createEvupMiddleware } from "@evup/auth/astro";
215
217
 
216
218
  export const onRequest = createEvupMiddleware(
217
- createEvupAuth({
218
- env,
219
- redirectUri: "https://app.example.com/auth/callback",
220
- postLogoutRedirectUri: "https://app.example.com/",
221
- }),
219
+ createEvupAuth({
220
+ env,
221
+ redirectUri: "https://app.example.com/auth/callback",
222
+ postLogoutRedirectUri: "https://app.example.com/",
223
+ }),
222
224
  );
223
225
  ```
224
226
 
@@ -235,8 +237,8 @@ This example is for Next.js 15/16. Shared file:
235
237
  import { createEvupAuth } from "@evup/auth/server";
236
238
 
237
239
  export const auth = createEvupAuth({
238
- redirectUri: process.env.EVUP_REDIRECT_URI ?? "https://app.example.com/auth/callback",
239
- postLogoutRedirectUri: "https://app.example.com/",
240
+ redirectUri: process.env.EVUP_REDIRECT_URI ?? "https://app.example.com/auth/callback",
241
+ postLogoutRedirectUri: "https://app.example.com/",
240
242
  });
241
243
  ```
242
244
 
@@ -258,9 +260,9 @@ import { getUser } from "@evup/auth/next";
258
260
  import { auth } from "@/lib/evup";
259
261
 
260
262
  export default async function Dashboard() {
261
- const user = await getUser(auth);
262
- if (!user) redirect("/auth/sign-in?returnTo=/dashboard");
263
- return <h1>Hello {user.name ?? user.email}</h1>;
263
+ const user = await getUser(auth);
264
+ if (!user) redirect("/auth/sign-in?returnTo=/dashboard");
265
+ return <h1>Hello {user.name ?? user.email}</h1>;
264
266
  }
265
267
  ```
266
268
 
@@ -298,12 +300,12 @@ import { createEvupClient, type EvupUser } from "@evup/auth/client";
298
300
  const evup = createEvupClient();
299
301
 
300
302
  export function UserMenu() {
301
- const [user, setUser] = useState<EvupUser | null>(null);
302
- useEffect(() => {
303
- evup.getUser().then(setUser);
304
- }, []);
305
- if (!user) return <button onClick={() => evup.signIn({ returnTo: "/dashboard" })}>Sign in</button>;
306
- return <button onClick={() => evup.signOut()}>Sign out {user.email}</button>;
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>;
307
309
  }
308
310
  ```
309
311
 
@@ -319,24 +321,22 @@ import { createEvupAuth, type EvupAuth } from "@evup/auth/server";
319
321
  let auth: EvupAuth | undefined;
320
322
 
321
323
  export default {
322
- async fetch(req: Request, env: Env): Promise<Response> {
323
- auth ??= createEvupAuth({
324
- env,
325
- redirectUri: "https://app.example.com/auth/callback",
326
- postLogoutRedirectUri: "https://app.example.com/",
327
- });
328
- const served = await auth.handler(req);
329
- if (served) return served;
330
-
331
- const { session, headers } = await auth.getSession(req);
332
- const res = session
333
- ? Response.json({ email: session.user.email })
334
- : Response.redirect(new URL("/auth/sign-in", req.url).href, 302);
335
- // headers carries Set-Cookie when the session has just been refreshed or cleared: it must be sent
336
- const out = new Response(res.body, res);
337
- for (const cookie of headers.getSetCookie()) out.headers.append("set-cookie", cookie);
338
- return out;
339
- },
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 ? Response.json({ email: session.user.email }) : Response.redirect(new URL("/auth/sign-in", req.url).href, 302);
335
+ // headers carries Set-Cookie when the session has just been refreshed or cleared: it must be sent
336
+ const out = new Response(res.body, res);
337
+ for (const cookie of headers.getSetCookie()) out.headers.append("set-cookie", cookie);
338
+ return out;
339
+ },
340
340
  };
341
341
  ```
342
342
 
@@ -348,16 +348,16 @@ import { createEvupAuth } from "@evup/auth/server";
348
348
  const auth = createEvupAuth({ redirectUri: "http://localhost:3000/auth/callback" });
349
349
 
350
350
  Bun.serve({
351
- port: 3000,
352
- async fetch(req) {
353
- const served = await auth.handler(req);
354
- if (served) return served;
355
- // getSession may refresh the session: Set-Cookie must be sent, otherwise the new refresh token is lost
356
- const { session, headers } = await auth.getSession(req);
357
- const res = new Response(session ? `Hello ${session.user.email}` : "Not signed in");
358
- for (const cookie of headers.getSetCookie()) res.headers.append("set-cookie", cookie);
359
- return res;
360
- },
351
+ port: 3000,
352
+ async fetch(req) {
353
+ const served = await auth.handler(req);
354
+ if (served) return served;
355
+ // getSession may refresh the session: Set-Cookie must be sent, otherwise the new refresh token is lost
356
+ const { session, headers } = await auth.getSession(req);
357
+ const res = new Response(session ? `Hello ${session.user.email}` : "Not signed in");
358
+ for (const cookie of headers.getSetCookie()) res.headers.append("set-cookie", cookie);
359
+ return res;
360
+ },
361
361
  });
362
362
  ```
363
363
 
@@ -382,9 +382,9 @@ import { createEvupClient } from "@evup/auth/client";
382
382
 
383
383
  const evup = createEvupClient({ basePath: "/auth" }); // default "/auth"
384
384
 
385
- const user = await evup.getUser(); // EvupUser | null (GET /auth/session)
386
- evup.signIn({ returnTo: "/dashboard" }); // full-page navigation to /auth/sign-in
387
- await evup.signOut(); // POST /auth/sign-out (Accept: application/json), then navigates to redirectTo
385
+ const user = await evup.getUser(); // EvupUser | null (GET /auth/session)
386
+ evup.signIn({ returnTo: "/dashboard" }); // full-page navigation to /auth/sign-in
387
+ await evup.signOut(); // POST /auth/sign-out (Accept: application/json), then navigates to redirectTo
388
388
  ```
389
389
 
390
390
  `signIn` takes `{ returnTo?, prompt?, locale?, loginHint? }`; `signOut` takes `{ returnTo? }`.
@@ -403,14 +403,14 @@ import { createEvupAuth } from "@evup/auth/server";
403
403
  const auth = createEvupAuth({ env, redirectUri: "https://app.example.com/auth/callback" });
404
404
 
405
405
  export const handle: Handle = async ({ event, resolve }) => {
406
- const served = await auth.handler(event.request);
407
- if (served) return served;
408
- const { session, headers } = await auth.getSession(event.request);
409
- event.locals.user = session?.user ?? null; // declare `user` in App.Locals
410
- const response = await resolve(event);
411
- const out = new Response(response.body, response); // the original response's headers may be immutable
412
- for (const cookie of headers.getSetCookie()) out.headers.append("set-cookie", cookie);
413
- return out;
406
+ const served = await auth.handler(event.request);
407
+ if (served) return served;
408
+ const { session, headers } = await auth.getSession(event.request);
409
+ event.locals.user = session?.user ?? null; // declare `user` in App.Locals
410
+ const response = await resolve(event);
411
+ const out = new Response(response.body, response); // the original response's headers may be immutable
412
+ for (const cookie of headers.getSetCookie()) out.headers.append("set-cookie", cookie);
413
+ return out;
414
414
  };
415
415
  ```
416
416
 
@@ -423,12 +423,12 @@ import { createEvupAuth } from "@evup/auth/server";
423
423
  const auth = createEvupAuth({ env: process.env, redirectUri: "https://app.example.com/auth/callback" });
424
424
 
425
425
  export default defineEventHandler(async (event) => {
426
- const request = toWebRequest(event);
427
- const served = await auth.handler(request);
428
- if (served) return sendWebResponse(event, served);
429
- const { session, headers } = await auth.getSession(request);
430
- event.context.user = session?.user ?? null;
431
- for (const cookie of headers.getSetCookie()) appendResponseHeader(event, "set-cookie", cookie);
426
+ const request = toWebRequest(event);
427
+ const served = await auth.handler(request);
428
+ if (served) return sendWebResponse(event, served);
429
+ const { session, headers } = await auth.getSession(request);
430
+ event.context.user = session?.user ?? null;
431
+ for (const cookie of headers.getSetCookie()) appendResponseHeader(event, "set-cookie", cookie);
432
432
  });
433
433
  ```
434
434
 
@@ -449,8 +449,8 @@ export const action = serve;
449
449
  // in the loader of a route that needs the user
450
450
  import { data } from "react-router";
451
451
  export async function loader({ request }: LoaderFunctionArgs) {
452
- const { session, headers } = await auth.getSession(request);
453
- return data({ user: session?.user ?? null }, { headers }); // headers carries Set-Cookie on refresh
452
+ const { session, headers } = await auth.getSession(request);
453
+ return data({ user: session?.user ?? null }, { headers }); // headers carries Set-Cookie on refresh
454
454
  }
455
455
  ```
456
456
 
@@ -464,26 +464,26 @@ const auth = createEvupAuth({ redirectUri: "http://localhost:3000/auth/callback"
464
464
  const app = express();
465
465
 
466
466
  const toRequest = (req: express.Request): Request => {
467
- const headers = new Headers();
468
- for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
469
- return new Request(`${req.protocol}://${req.get("host")}${req.originalUrl}`, { method: req.method, headers });
467
+ const headers = new Headers();
468
+ for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
469
+ return new Request(`${req.protocol}://${req.get("host")}${req.originalUrl}`, { method: req.method, headers });
470
470
  };
471
471
 
472
472
  const send = async (res: express.Response, response: Response) => {
473
- res.status(response.status);
474
- response.headers.forEach((value, name) => name !== "set-cookie" && res.setHeader(name, value));
475
- res.setHeader("set-cookie", response.headers.getSetCookie());
476
- res.send(Buffer.from(await response.arrayBuffer()));
473
+ res.status(response.status);
474
+ response.headers.forEach((value, name) => name !== "set-cookie" && res.setHeader(name, value));
475
+ res.setHeader("set-cookie", response.headers.getSetCookie());
476
+ res.send(Buffer.from(await response.arrayBuffer()));
477
477
  };
478
478
 
479
479
  app.use(async (req, res, next) => {
480
- const request = toRequest(req);
481
- const served = await auth.handler(request);
482
- if (served) return send(res, served);
483
- const { session, headers } = await auth.getSession(request);
484
- res.locals.user = session?.user ?? null;
485
- for (const cookie of headers.getSetCookie()) res.append("set-cookie", cookie);
486
- next();
480
+ const request = toRequest(req);
481
+ const served = await auth.handler(request);
482
+ if (served) return send(res, served);
483
+ const { session, headers } = await auth.getSession(request);
484
+ res.locals.user = session?.user ?? null;
485
+ for (const cookie of headers.getSetCookie()) res.append("set-cookie", cookie);
486
+ next();
487
487
  });
488
488
  ```
489
489
 
@@ -514,7 +514,7 @@ On a resource server, `token.permissions` has the same meaning (see below).
514
514
 
515
515
  ## Access denied and waitlist
516
516
 
517
- 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`.
517
+ 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`.
518
518
 
519
519
  The SDK handles that callback:
520
520
 
@@ -523,9 +523,12 @@ The SDK handles that callback:
523
523
 
524
524
  ```ts
525
525
  createEvupAuth({
526
- redirectUri: "https://app.example.com/auth/callback",
527
- onAccessDenied: (req, err) =>
528
- new Response(`This account has not been granted access. ${err.description ?? ""}`, { status: 403, headers: { "content-type": "text/plain; charset=utf-8" } }),
526
+ redirectUri: "https://app.example.com/auth/callback",
527
+ onAccessDenied: (req, err) =>
528
+ new Response(`This account has not been granted access. ${err.description ?? ""}`, {
529
+ status: 403,
530
+ headers: { "content-type": "text/plain; charset=utf-8" },
531
+ }),
529
532
  });
530
533
  ```
531
534
 
@@ -537,7 +540,7 @@ When a refresh happens after the user has had access revoked or has been banned,
537
540
 
538
541
  ```html
539
542
  <form method="post" action="/auth/sign-out">
540
- <button type="submit">Sign out</button>
543
+ <button type="submit">Sign out</button>
541
544
  </form>
542
545
  ```
543
546
 
@@ -547,7 +550,7 @@ Or `createEvupClient().signOut()` / `auth.signOut(request, { returnTo })`. The S
547
550
  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;
548
551
  3. redirects to EvUp's `end_session_endpoint`: `/oauth2/end-session?id_token_hint=<id_token>&client_id=<id>&post_logout_redirect_uri=<postLogoutRedirectUri>`.
549
552
 
550
- `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
+ `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`.
551
554
 
552
555
  ### What EvUp's `/oauth2/end-session` accepts
553
556
 
@@ -555,7 +558,7 @@ Or `createEvupClient().signOut()` / `auth.signOut(request, { returnTo })`. The S
555
558
  - **`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.
556
559
  - **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.
557
560
  - **`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").
558
- - **`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
+ - **`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.
559
562
  - **`state`**: if sent, EvUp appends it to `post_logout_redirect_uri` when redirecting. The SDK does not use this `state`.
560
563
  - **Back-channel logout** (`backchannel_logout_uri`): the SDK 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.
561
564
 
@@ -573,14 +576,14 @@ Use this when your app has its own MCP server or API that clients (Claude Code,
573
576
  import { createEvupResource } from "@evup/auth/resource";
574
577
 
575
578
  const resource = createEvupResource({
576
- resource: "https://api.example.com/mcp", // must equal the registered URL
577
- scopes: ["openid"], // optional: published and required
578
- resourceName: "Example API",
579
+ resource: "https://api.example.com/mcp", // must equal the registered URL
580
+ scopes: ["openid"], // optional: published and required
581
+ resourceName: "Example API",
579
582
  });
580
583
 
581
- resource.metadataPath; // "/.well-known/oauth-protected-resource/mcp"
582
- resource.metadata(); // the RFC 9728 document
583
- await resource.verify(req); // { ok: true, token } | { ok: false, status: 401 | 403, response }
584
+ resource.metadataPath; // "/.well-known/oauth-protected-resource/mcp"
585
+ resource.metadata(); // the RFC 9728 document
586
+ await resource.verify(req); // { ok: true, token } | { ok: false, status: 401 | 403, response }
584
587
  await resource.handle(req, async (req, token) => Response.json({ sub: token.sub }));
585
588
  ```
586
589
 
@@ -588,21 +591,21 @@ The metadata document (matches how EvUp publishes its own `/mcp`):
588
591
 
589
592
  ```json
590
593
  {
591
- "resource": "https://api.example.com/mcp",
592
- "authorization_servers": ["https://auth.evup.cloud/api/auth"],
593
- "scopes_supported": ["openid"],
594
- "bearer_methods_supported": ["header"],
595
- "resource_name": "Example API"
594
+ "resource": "https://api.example.com/mcp",
595
+ "authorization_servers": ["https://auth.evup.cloud/api/auth"],
596
+ "scopes_supported": ["openid"],
597
+ "bearer_methods_supported": ["header"],
598
+ "resource_name": "Example API"
596
599
  }
597
600
  ```
598
601
 
599
602
  Error responses (JSON `{ "error", "error_description" }`, with CORS `Access-Control-Allow-Origin: *` and `Access-Control-Expose-Headers: WWW-Authenticate`):
600
603
 
601
- | Situation | Status | `WWW-Authenticate` |
602
- |---|---|---|
603
- | No Bearer token | 401 | `Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"` |
604
- | Token invalid / expired / wrong `aud`, `iss`, `typ` | 401 | `Bearer error="invalid_token", error_description="...", resource_metadata="..."` |
605
- | Missing required scope | 403 | `Bearer error="insufficient_scope", error_description="...", scope="<required scope>", resource_metadata="..."` |
604
+ | Situation | Status | `WWW-Authenticate` |
605
+ | --------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------- |
606
+ | No Bearer token | 401 | `Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"` |
607
+ | Token invalid / expired / wrong `aud`, `iss`, `typ` | 401 | `Bearer error="invalid_token", error_description="...", resource_metadata="..."` |
608
+ | Missing required scope | 403 | `Bearer error="insufficient_scope", error_description="...", scope="<required scope>", resource_metadata="..."` |
606
609
 
607
610
  `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.
608
611
 
@@ -622,7 +625,7 @@ const resource = createEvupResource({ resource: "https://api.example.com/mcp", r
622
625
  const app = new Hono<{ Variables: EvupVariables }>();
623
626
 
624
627
  app.get(resource.metadataPath, evupResource(resource)); // serves the metadata (no token needed)
625
- app.use("/mcp", evupResource(resource)); // every request to /mcp needs a valid Bearer token
628
+ app.use("/mcp", evupResource(resource)); // every request to /mcp needs a valid Bearer token
626
629
  app.post("/mcp", (c) => c.json({ user: c.var.evupToken.sub, permissions: c.var.evupToken.permissions }));
627
630
 
628
631
  export default app;
@@ -636,11 +639,11 @@ import { createEvupResource } from "@evup/auth/resource";
636
639
  const resource = createEvupResource({ resource: "https://api.example.com/mcp" });
637
640
 
638
641
  export default {
639
- fetch: (req: Request) =>
640
- resource.handle(req, async (_req, token) => {
641
- if (!token.permissions.includes("reports:read")) return new Response("Forbidden", { status: 403 });
642
- return Response.json({ sub: token.sub, clientId: token.clientId });
643
- }),
642
+ fetch: (req: Request) =>
643
+ resource.handle(req, async (_req, token) => {
644
+ if (!token.permissions.includes("reports:read")) return new Response("Forbidden", { status: 403 });
645
+ return Response.json({ sub: token.sub, clientId: token.clientId });
646
+ }),
644
647
  };
645
648
  ```
646
649
 
@@ -672,7 +675,7 @@ An MCP client calls `POST /mcp` without a token, gets a `401` with `WWW-Authenti
672
675
 
673
676
  Use this when a **server** has to call an API with no signed-in user: a cron job, a queue consumer, a backend calling another app's API. The server exchanges its own `client_id` and `client_secret` for a short-lived access token (OAuth `client_credentials`, RFC 6749 section 4.4). For work on behalf of a user, use the user's session token instead (see the FAQ).
674
677
 
675
- **1. Admin setup.** An EvUp admin opens the *calling* app's detail page (it must be a *Web app (server)*, a client with a secret), turns on **Machine-to-machine → Allow client credentials**, then **Add API**: pick an API resource of any app and the scopes the app may use there (`api:read`, `api:write`; their meaning is up to each API, and the token's `aud` pins which API). The API itself must be registered first in the **API resources** card of the app that serves it. Switching it off keeps the list, so switching on again restores it.
678
+ **1. Admin setup.** An EvUp admin opens the _calling_ app's detail page (it must be a _Web app (server)_, a client with a secret), turns on **Machine-to-machine → Allow client credentials**, then **Add API**: pick an API resource of any app and the scopes the app may use there. Scopes are declared by each API, in the **API resources** card of the app that serves it (_Machine-to-machine scopes_, for example `payments:read`, `payments:write`, `payments:refund`); an API that declares nothing uses `api:read` / `api:write` by default. Their meaning is up to each API, and the token's `aud` pins which API. Asking for a scope the API does not declare, or one not granted to your app there, returns `invalid_scope`. The API itself must be registered first in the **API resources** card of the app that serves it. Switching it off keeps the list, so switching on again restores it.
676
679
 
677
680
  **2. The calling side** (`createEvupClientCredentials`):
678
681
 
@@ -681,19 +684,23 @@ import { createEvupClientCredentials } from "@evup/auth/m2m";
681
684
 
682
685
  // EVUP_CLIENT_ID and EVUP_CLIENT_SECRET are read from the environment
683
686
  const payments = createEvupClientCredentials({
684
- resource: "https://payments.evup.cloud/api", // the API resource, exactly as registered
685
- scopes: ["api:write"], // optional: omit to get every scope granted for the resource
687
+ resource: "https://payments.evup.cloud/api", // the API resource, exactly as registered
688
+ scopes: ["api:write"], // optional: omit to get every scope granted for the resource
686
689
  });
687
690
 
688
- const token = await payments.getToken(); // a string; cached, renewed 60 s before it expires
691
+ const token = await payments.getToken(); // a string; cached, renewed 60 s before it expires
689
692
  ```
690
693
 
691
694
  Hono:
692
695
 
693
696
  ```ts
694
697
  app.post("/checkout", async (c) => {
695
- const res = await payments.fetch("https://payments.evup.cloud/api/charges", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ amount: 1000 }) });
696
- return c.json(await res.json(), res.status);
698
+ const res = await payments.fetch("https://payments.evup.cloud/api/charges", {
699
+ method: "POST",
700
+ headers: { "content-type": "application/json" },
701
+ body: JSON.stringify({ amount: 1000 }),
702
+ });
703
+ return c.json(await res.json(), res.status);
697
704
  });
698
705
  ```
699
706
 
@@ -715,8 +722,8 @@ const api = createEvupResource({ resource: "https://payments.evup.cloud/api", ac
715
722
 
716
723
  app.use("/api/*", evupResource(api));
717
724
  app.get("/api/charges", (c) => {
718
- const token = c.var.evupToken; // { kind: "client", sub: <client id>, clientId, scopes, permissions: [] ... }
719
- return c.json({ caller: token.clientId });
725
+ const token = c.var.evupToken; // { kind: "client", sub: <client id>, clientId, scopes, permissions: [] ... }
726
+ return c.json({ caller: token.clientId });
720
727
  });
721
728
  ```
722
729
 
@@ -732,44 +739,49 @@ app.get("/api/charges", (c) => {
732
739
 
733
740
  `createEvupAuth(config)` (`@evup/auth/server`):
734
741
 
735
- | Option | Default | Meaning |
736
- |---|---|---|
737
- | `redirectUri` | required | absolute callback URL, registered in the app. `https`, or `http` for localhost |
738
- | `clientId` | `EVUP_CLIENT_ID` | |
739
- | `clientSecret` | `EVUP_CLIENT_SECRET` | if missing, a public client (`none`); if present, `client_secret_basic` |
740
- | `secret` | `EVUP_SESSION_SECRET` | cookie encryption key, >= 32 characters |
741
- | `issuer` | `https://auth.evup.cloud/api/auth` | |
742
- | `scopes` | `["openid","profile","email","offline_access"]` | must include `openid` |
743
- | `resource` | none | `string` or `string[]` (RFC 8707); the access token becomes a JWT for that API |
744
- | `postLogoutRedirectUri` | none | URI registered as a post-logout redirect |
745
- | `cookie.name` | `"evup_session"` | |
746
- | `cookie.maxAge` | 30 days (seconds) | |
747
- | `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 |
748
- | `cookie.secure` | `true` when `redirectUri` is https (or `sameSite: "none"`), `false` for http localhost | |
749
- | `cookie.domain` | none | |
750
- | `cookie.path` | `"/"` | |
751
- | `basePath` | `"/auth"` | the routes live under this path |
752
- | `onAccessDenied` | default 403 page | `(req, err) => Response` |
753
- | `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 |
754
- | `env` | `process.env` | where `EVUP_*` is read from; Workers pass `env` (only string values are read) |
755
- | `fetch` | global `fetch` | used for every request to EvUp |
742
+ | Option | Default | Meaning |
743
+ | ----------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
744
+ | `redirectUri` | required | absolute callback URL, registered in the app. `https`, or `http` for localhost |
745
+ | `clientId` | `EVUP_CLIENT_ID` | |
746
+ | `clientSecret` | `EVUP_CLIENT_SECRET` | if missing, a public client (`none`); if present, `client_secret_basic` |
747
+ | `secret` | `EVUP_SESSION_SECRET` | cookie encryption key, >= 32 characters |
748
+ | `issuer` | `https://auth.evup.cloud/api/auth` | |
749
+ | `scopes` | `["openid","profile","email","offline_access"]` | must include `openid` |
750
+ | `resource` | none | `string` or `string[]` (RFC 8707); the access token becomes a JWT for that API |
751
+ | `postLogoutRedirectUri` | none | URI registered as a post-logout redirect |
752
+ | `cookie.name` | `"evup_session"` | |
753
+ | `cookie.maxAge` | 30 days (seconds) | |
754
+ | `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 |
755
+ | `cookie.secure` | `true` when `redirectUri` is https (or `sameSite: "none"`), `false` for http localhost | |
756
+ | `cookie.domain` | none | |
757
+ | `cookie.path` | `"/"` | |
758
+ | `basePath` | `"/auth"` | the routes live under this path |
759
+ | `onAccessDenied` | default 403 page | `(req, err) => Response` |
760
+ | `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 |
761
+ | `env` | `process.env` | where `EVUP_*` is read from; Workers pass `env` (only string values are read) |
762
+ | `fetch` | global `fetch` | used for every request to EvUp |
756
763
 
757
764
  Return value (`EvupAuth`):
758
765
 
759
766
  ```ts
760
767
  interface EvupAuth {
761
- readonly basePath: string;
762
- handler(req: Request): Promise<Response | null>; // SDK routes; null for other requests
763
- signIn(req: Request, opts?: { returnTo?: string; prompt?: string; locale?: string; loginHint?: string }): Promise<Response>;
764
- callback(req: Request): Promise<Response>;
765
- signOut(req: Request, opts?: { returnTo?: string }): Promise<Response>;
766
- getSession(req: Request, opts?: { refresh?: boolean; refreshWindow?: number }): Promise<{ session: Session | null; headers: Headers }>;
767
- getUser(req: Request): Promise<EvupUser | null>; // only reads the cookie, no refresh
768
+ readonly basePath: string;
769
+ handler(req: Request): Promise<Response | null>; // SDK routes; null for other requests
770
+ signIn(req: Request, opts?: { returnTo?: string; prompt?: string; locale?: string; loginHint?: string }): Promise<Response>;
771
+ callback(req: Request): Promise<Response>;
772
+ signOut(req: Request, opts?: { returnTo?: string }): Promise<Response>;
773
+ getSession(req: Request, opts?: { refresh?: boolean; refreshWindow?: number }): Promise<{ session: Session | null; headers: Headers }>;
774
+ getUser(req: Request): Promise<EvupUser | null>; // only reads the cookie, no refresh
768
775
  }
769
776
 
770
777
  type EvupUser = {
771
- id: string; email: string; emailVerified: boolean; name?: string; picture?: string;
772
- permissions: string[]; claims: Record<string, unknown>; // claims: id_token merged with userinfo
778
+ id: string;
779
+ email: string;
780
+ emailVerified: boolean;
781
+ name?: string;
782
+ picture?: string;
783
+ permissions: string[];
784
+ claims: Record<string, unknown>; // claims: id_token merged with userinfo
773
785
  };
774
786
  type Session = { user: EvupUser; accessToken: string; expiresAt: number /* ms epoch */; scope: string };
775
787
  ```
@@ -778,17 +790,17 @@ type Session = { user: EvupUser; accessToken: string; expiresAt: number /* ms ep
778
790
 
779
791
  `createEvupClientCredentials(config)` (`@evup/auth/m2m`):
780
792
 
781
- | Option | Default | Meaning |
782
- |---|---|---|
783
- | `resource` | required | the API resource URL, exactly as registered. `https`, or `http` for localhost |
784
- | `scopes` | none | omit to get every scope the admin granted for the resource; if given, must not be empty |
785
- | `clientId` | `EVUP_CLIENT_ID` | |
786
- | `clientSecret` | `EVUP_CLIENT_SECRET` | required |
787
- | `issuer` | `https://auth.evup.cloud/api/auth` | |
788
- | `refreshSkew` | `60` | seconds before `exp` a cached token is replaced |
789
- | `env` | `process.env` | where `EVUP_*` is read from (only string values are read) |
790
- | `fetch` | global `fetch` | used for discovery, the token request and `payments.fetch()` |
791
- | `now` | `Date.now` | clock in ms, for tests |
793
+ | Option | Default | Meaning |
794
+ | -------------- | ---------------------------------- | --------------------------------------------------------------------------------------- |
795
+ | `resource` | required | the API resource URL, exactly as registered. `https`, or `http` for localhost |
796
+ | `scopes` | none | omit to get every scope the admin granted for the resource; if given, must not be empty |
797
+ | `clientId` | `EVUP_CLIENT_ID` | |
798
+ | `clientSecret` | `EVUP_CLIENT_SECRET` | required |
799
+ | `issuer` | `https://auth.evup.cloud/api/auth` | |
800
+ | `refreshSkew` | `60` | seconds before `exp` a cached token is replaced |
801
+ | `env` | `process.env` | where `EVUP_*` is read from (only string values are read) |
802
+ | `fetch` | global `fetch` | used for discovery, the token request and `payments.fetch()` |
803
+ | `now` | `Date.now` | clock in ms, for tests |
792
804
 
793
805
  → `{ getToken({ forceRefresh? }), getTokenInfo({ forceRefresh? }) /* { accessToken, expiresAt (seconds), scopes } */, fetch(input, init), clear() }`.
794
806
 
@@ -804,13 +816,13 @@ Session behavior:
804
816
 
805
817
  `EvupAuthError` (`@evup/auth/server`, also exported from `@evup/auth/resource` and `@evup/auth/m2m`) has `code`, `message`, `description?` (the OAuth `error_description` if present), `oauthError?` (the OAuth `error` of a refused token request) and `cause`.
806
818
 
807
- | `code` | When |
808
- |---|---|
809
- | `config` | wrong or missing configuration (relative `redirectUri`, short secret, missing `clientId`/`secret`); **thrown**, not swallowed |
810
- | `access_denied` | EvUp denied the user (callback `error=access_denied`) |
811
- | `invalid_state` | transaction cookie missing/expired, `state` or `iss` mismatch |
812
- | `callback_failed` | code exchange failed, id_token invalid (`nonce`, `aud`...), session too large for the cookie |
813
- | `discovery_failed` | the issuer's discovery or JWKS could not be loaded (the callback returns 502; `verify` throws; a token request rejects) |
819
+ | `code` | When |
820
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
821
+ | `config` | wrong or missing configuration (relative `redirectUri`, short secret, missing `clientId`/`secret`); **thrown**, not swallowed |
822
+ | `access_denied` | EvUp denied the user (callback `error=access_denied`) |
823
+ | `invalid_state` | transaction cookie missing/expired, `state` or `iss` mismatch |
824
+ | `callback_failed` | code exchange failed, id_token invalid (`nonce`, `aud`...), session too large for the cookie |
825
+ | `discovery_failed` | the issuer's discovery or JWKS could not be loaded (the callback returns 502; `verify` throws; a token request rejects) |
814
826
  | `token_request_failed` | the `client_credentials` token request was refused or failed (`@evup/auth/m2m`); `oauthError` has the OAuth `error`, `description` the `error_description` |
815
827
 
816
828
  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).
@@ -833,9 +845,9 @@ If you run an EvUp Account instance locally (for example on `http://localhost:44
833
845
 
834
846
  ```ts
835
847
  createEvupAuth({
836
- issuer: "http://localhost:4400/api/auth",
837
- redirectUri: "http://localhost:3000/auth/callback",
838
- postLogoutRedirectUri: "http://localhost:3000/",
848
+ issuer: "http://localhost:4400/api/auth",
849
+ redirectUri: "http://localhost:3000/auth/callback",
850
+ postLogoutRedirectUri: "http://localhost:3000/",
839
851
  });
840
852
  ```
841
853
 
@@ -844,6 +856,35 @@ createEvupAuth({
844
856
  - 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.
845
857
  - Dev resource: add `http://localhost:8787/mcp` as a separate entry in **API resources**.
846
858
 
859
+ ## Testing your app (e2e)
860
+
861
+ `@evup/auth/testing` mints the same encrypted session cookie the SDK sets after a real sign-in, sealed with your **test** `EVUP_SESSION_SECRET`. A browser test (Playwright, ...) adds the cookie and starts signed in: the app needs no sign-in bypass, and the helper **never talks to the IdP**.
862
+
863
+ ```ts
864
+ // e2e/fixtures.ts
865
+ import { test as base } from "@playwright/test";
866
+ import { createTestSessionCookie } from "@evup/auth/testing";
867
+
868
+ export const test = base.extend({
869
+ context: async ({ context }, use) => {
870
+ const cookie = await createTestSessionCookie({
871
+ secret: process.env.EVUP_SESSION_SECRET!, // the test server's secret, at least 32 characters
872
+ user: { id: "e2e-user", email: "e2e@example.com", name: "E2E User" },
873
+ permissions: ["post:read", "post:write"],
874
+ });
875
+ await context.addCookies([cookie.playwright("http://localhost:4500")]);
876
+ await use(context);
877
+ },
878
+ });
879
+ ```
880
+
881
+ - Options: `secret` (same 32-character rule as `createEvupAuth`), `user` (`id`, `email`, `emailVerified` default `true`, `name`, `picture`, `permissions`, extra `claims`), `permissions` (merged into `user.permissions`), `expiresIn` (seconds the session lasts, default 3600), `scope` (default the SDK's default scopes), `cookie` (the same options as `createEvupAuth({ cookie })`: pass the same `name`, `path`, `domain`, `sameSite`, `secure` as the app) and `url` (the app's URL, e.g. its `redirectUri`: when `cookie.secure` is unset, `attributes` / `header` are `Secure` for an `https` URL, like `createEvupAuth` derives it from `redirectUri`; without `url` the header is not `Secure`).
882
+ - The result has `name`, `value`, `attributes`, `header` (a `Set-Cookie` value, e.g. `evup_session=…; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax`) and `playwright(url)`: the cookie for `context.addCookies()`, host-only on the URL's host (or `.domain`, the domain and its subdomains, when `cookie.domain` is set), `secure` only for an `https` URL (unless `cookie.secure` is set). For `http://localhost:4500`: `{ name: "evup_session", domain: "localhost", path: "/", httpOnly: true, secure: false, sameSite: "Lax", expires: now + 3600 }`.
883
+ - The app reads it like any session: `getSession()` / `getUser()` return the user and permissions without a network call (no discovery either; the app still needs its `clientId` and `secret` configured as usual).
884
+ - The session holds a fake access token (`"evup-test-access-token"`) and **no refresh token**. Do not call your own APIs with that token: anything that verifies it with the IdP rejects it. When `expiresIn` runs out, the SDK cannot refresh the session, so `getSession()` clears the cookie and the user is signed out (fails closed, no IdP call).
885
+
886
+ > **Warning:** only use this in tests, with a secret that exists only in the test environment. Anyone who holds an app's session secret can mint sessions for any user of that app: never ship the testing secret, never use the production `EVUP_SESSION_SECRET` in tests, and never import `@evup/auth/testing` from app code.
887
+
847
888
  ## FAQ
848
889
 
849
890
  **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).