@oauth-spa-kit/server 2.3.1 → 2.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
@@ -83,6 +83,56 @@ for the lower-level protocol primitives these handlers are built from, and
83
83
  [`@oauth-spa-kit/react`](https://www.npmjs.com/package/@oauth-spa-kit/react)
84
84
  for a client-side `useAuth()` hook that talks to these routes.
85
85
 
86
+ ## Server-side session store (optional)
87
+
88
+ By default the session cookie is fully self-contained -- access/id/refresh tokens, the DPoP key
89
+ pair, and user claims are all sealed (AES-256-GCM) directly into the cookie value. That's zero
90
+ infrastructure to run, but it does mean the cookie grows with however much token/claims data
91
+ accumulates, and browsers/proxies cap cookie size (commonly ~4KB).
92
+
93
+ Pass a `store` to keep the cookie small regardless: the cookie then carries only a random opaque
94
+ id, and the actual session data lives wherever you point `store` -- Redis, Cloudflare KV,
95
+ [unstorage](https://unstorage.unjs.io/), anything. The interface is deliberately three methods,
96
+ no framework assumptions:
97
+
98
+ ```ts
99
+ import type { SessionStore } from "@oauth-spa-kit/server";
100
+
101
+ const store: SessionStore = {
102
+ async get(sessionId) {
103
+ return redis.get(`session:${sessionId}`);
104
+ },
105
+ async set(sessionId, sealedPayload, maxAgeSeconds) {
106
+ await redis.set(`session:${sessionId}`, sealedPayload, "EX", maxAgeSeconds);
107
+ },
108
+ async delete(sessionId) {
109
+ await redis.del(`session:${sessionId}`);
110
+ },
111
+ };
112
+
113
+ const config: OAuthHandlersConfig = {
114
+ oauth: { /* ... */ },
115
+ session: {
116
+ password: process.env.OAUTH_SESSION_PASSWORD!,
117
+ store, // omit entirely to keep the default fully-in-cookie behavior
118
+ },
119
+ };
120
+ ```
121
+
122
+ The value handed to `store.set` is still sealed the same way the cookie itself would be -- your
123
+ store never sees plaintext tokens even if it's logged or inspected. `createLogoutHandler` and
124
+ `createLivenessHandler`'s rejected-session path both call the new `deleteStoredSession` for you,
125
+ so a logout (or a session AuthZEN/the AS itself has revoked) invalidates the store entry
126
+ immediately rather than only once your store's own TTL catches up. If you're writing a custom
127
+ handler instead of using the provided ones, call it yourself alongside `clearSessionHeader`:
128
+
129
+ ```ts
130
+ import { clearSessionHeader, deleteStoredSession } from "@oauth-spa-kit/server";
131
+
132
+ await deleteStoredSession(request, config.session); // no-op if no store is configured
133
+ headers.append("Set-Cookie", clearSessionHeader(config.session));
134
+ ```
135
+
86
136
  ## AuthZEN (externalized authorization)
87
137
 
88
138
  Once a request is authenticated, [`evaluateAccess`](https://openid.net/specs/authorization-api-1_0-01.html)
package/dist/handlers.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { computeJwkThumbprint, createDpopProof, createPkceParams, discoverOidcConfiguration, exchangeAuthorizationCode, exchangeRefreshToken, exportDpopKeyPair, fetchJwks, generateDpopKeyPair, importDpopKeyPair, parseUserAgent, pushAuthorizationRequest, verifyJwt, OAuthError, TokenExchangeError, } from "@oauth-spa-kit/core";
2
2
  import { clearPkceStateHeader, readPkceState, writePkceStateHeader } from "./pkceState.js";
3
- import { clearSessionHeader, readSession, writeSessionHeader } from "./session.js";
3
+ import { clearSessionHeader, deleteStoredSession, readSession, writeSessionHeader } from "./session.js";
4
4
  async function resolveDiscovery(config) {
5
5
  return config.oauth.discoveryDocument
6
6
  ?? discoverOidcConfiguration(config.oauth.authority, config.fetchImpl);
@@ -169,6 +169,7 @@ export function createSessionHandler(config) {
169
169
  });
170
170
  }
171
171
  if (!session.tokens.refreshToken) {
172
+ await deleteStoredSession(request, config.session);
172
173
  return new Response(JSON.stringify({ user: null }), {
173
174
  status: 401,
174
175
  headers: { "content-type": "application/json", "Set-Cookie": clearSessionHeader(config.session) },
@@ -185,7 +186,7 @@ export function createSessionHandler(config) {
185
186
  dpopKeyPair,
186
187
  fetchImpl: config.fetchImpl,
187
188
  });
188
- const setCookie = await writeSessionHeader(session, config.session);
189
+ const setCookie = await writeSessionHeader(session, config.session, request);
189
190
  return new Response(JSON.stringify({ user: session.user, device: session.device }), {
190
191
  status: 200,
191
192
  headers: { "content-type": "application/json", "Set-Cookie": setCookie },
@@ -194,6 +195,7 @@ export function createSessionHandler(config) {
194
195
  catch {
195
196
  // Refresh token invalid, rotated-and-reused, or revoked -- force a
196
197
  // real re-login rather than silently keep serving a stale session.
198
+ await deleteStoredSession(request, config.session);
197
199
  return new Response(JSON.stringify({ user: null }), {
198
200
  status: 401,
199
201
  headers: { "content-type": "application/json", "Set-Cookie": clearSessionHeader(config.session) },
@@ -211,6 +213,7 @@ export function createLogoutHandler(config) {
211
213
  // it, expect the AS to fall back to an interactive "are you sure?" prompt and/or drop
212
214
  // post_logout_redirect_uri entirely instead of honoring it.
213
215
  const session = await readSession(request, config.session);
216
+ await deleteStoredSession(request, config.session);
214
217
  const headers = new Headers({ "content-type": "application/json" });
215
218
  headers.append("Set-Cookie", clearSessionHeader(config.session));
216
219
  const discovery = await resolveDiscovery(config).catch(() => null);
@@ -251,7 +254,7 @@ export async function getAuthorizationHeader(request, config) {
251
254
  dpopKeyPair,
252
255
  fetchImpl: config.fetchImpl,
253
256
  });
254
- const setCookie = await writeSessionHeader(session, config.session);
257
+ const setCookie = await writeSessionHeader(session, config.session, request);
255
258
  return { header: `${session.tokens.tokenType} ${session.tokens.accessToken}`, setCookie };
256
259
  }
257
260
  return { header: `${session.tokens.tokenType} ${session.tokens.accessToken}` };
@@ -323,6 +326,7 @@ export function createLivenessHandler(config) {
323
326
  // immediately redirects to a fresh login on `onSessionExpired`: a consumer that
324
327
  // instead just shows a "session expired" message would otherwise keep sending a
325
328
  // cookie doomed to fail every subsequent request.
329
+ await deleteStoredSession(request, config.session);
326
330
  const headers = new Headers({ "content-type": "application/json" });
327
331
  headers.append("Set-Cookie", clearSessionHeader(config.session));
328
332
  return new Response(JSON.stringify({ alive: false }), { status: 401, headers });
package/dist/session.d.ts CHANGED
@@ -7,6 +7,20 @@ export interface StoredSession {
7
7
  /** This device's friendly label ("Chrome on macOS"), parsed from the callback request's User-Agent at sign-in. */
8
8
  device?: string;
9
9
  }
10
+ /**
11
+ * A pluggable server-side backing store for session data (Redis, Cloudflare KV, unstorage,
12
+ * whatever the consumer already runs) -- entirely optional. Deliberately minimal (three methods,
13
+ * no framework/runtime assumptions) so it works unmodified on Node, Cloudflare Workers, Deno, or
14
+ * Vercel Edge, the same portability goal `sealJson`/`unsealJson` already have.
15
+ */
16
+ export interface SessionStore {
17
+ /** Fetch the sealed session payload previously stored under this id, or `null` if missing/expired/evicted. */
18
+ get(sessionId: string): Promise<string | null>;
19
+ /** Persist the sealed payload under this id. `maxAgeSeconds` is the same TTL the cookie itself uses -- pass it through to your store's own expiry (e.g. Redis `EX`). */
20
+ set(sessionId: string, sealedPayload: string, maxAgeSeconds: number): Promise<void>;
21
+ /** Remove the entry for this id (logout, or a rejected liveness check) -- must not throw for an id that's already gone. */
22
+ delete(sessionId: string): Promise<void>;
23
+ }
10
24
  export interface SessionConfig {
11
25
  /** >=32 char secret. Load from env (`OAUTH_SESSION_PASSWORD`); rotate by supporting two passwords during migration if you need zero-downtime rotation. */
12
26
  password: string;
@@ -18,7 +32,33 @@ export interface SessionConfig {
18
32
  * refresh token; it isn't itself a trust boundary extension.
19
33
  */
20
34
  maxAgeSeconds?: number;
35
+ /**
36
+ * Optional server-side session store. When provided, the cookie carries only a random opaque
37
+ * session id (itself still meaningless without store access) and the actual `StoredSession`
38
+ * (tokens, DPoP key pair, user claims, device label) lives in `store` instead, keyed by that
39
+ * id -- the cookie's size no longer grows with token/claims size. Omit to keep the original
40
+ * fully-self-contained sealed-cookie behavior (still the default: no store to wire up for a
41
+ * consumer that doesn't need one).
42
+ */
43
+ store?: SessionStore;
21
44
  }
22
45
  export declare function readSession(request: Request, config: SessionConfig): Promise<StoredSession | null>;
23
- export declare function writeSessionHeader(session: StoredSession, config: SessionConfig): Promise<string>;
46
+ /**
47
+ * @param previousRequest When re-writing a session that already exists (e.g. after a token
48
+ * refresh), pass the *incoming* request so a store-backed session can delete the just-rotated-out
49
+ * entry under its old id -- otherwise every refresh would mint a new store entry and orphan the
50
+ * old one to expire via TTL alone instead of being cleaned up immediately. Omit for a brand-new
51
+ * session (login callback) where there is no previous entry to clean up. Ignored when no store
52
+ * is configured (the cookie itself is simply overwritten either way).
53
+ */
54
+ export declare function writeSessionHeader(session: StoredSession, config: SessionConfig, previousRequest?: Request): Promise<string>;
24
55
  export declare function clearSessionHeader(config: SessionConfig): string;
56
+ /**
57
+ * Removes this request's session from `config.store`, if configured -- so a logout (or a
58
+ * rejected liveness check) invalidates the session immediately server-side, rather than only
59
+ * once the store's own TTL catches up. Safe to call unconditionally alongside
60
+ * `clearSessionHeader` regardless of whether a store is actually configured, whether the
61
+ * request has a session cookie at all, or whether the store has already evicted the entry --
62
+ * a no-op in every one of those cases, never an error.
63
+ */
64
+ export declare function deleteStoredSession(request: Request, config: SessionConfig): Promise<void>;
package/dist/session.js CHANGED
@@ -6,14 +6,53 @@ export async function readSession(request, config) {
6
6
  const raw = parseCookies(request)[cookieName];
7
7
  if (!raw)
8
8
  return null;
9
+ if (config.store) {
10
+ const sealed = await config.store.get(raw);
11
+ if (!sealed)
12
+ return null;
13
+ return unsealJson(sealed, config.password);
14
+ }
9
15
  return unsealJson(raw, config.password);
10
16
  }
11
- export async function writeSessionHeader(session, config) {
17
+ /**
18
+ * @param previousRequest When re-writing a session that already exists (e.g. after a token
19
+ * refresh), pass the *incoming* request so a store-backed session can delete the just-rotated-out
20
+ * entry under its old id -- otherwise every refresh would mint a new store entry and orphan the
21
+ * old one to expire via TTL alone instead of being cleaned up immediately. Omit for a brand-new
22
+ * session (login callback) where there is no previous entry to clean up. Ignored when no store
23
+ * is configured (the cookie itself is simply overwritten either way).
24
+ */
25
+ export async function writeSessionHeader(session, config, previousRequest) {
12
26
  const sealed = await sealJson(session, config.password);
13
- return serializeCookie(config.cookieName ?? DEFAULTS.cookieName, sealed, {
14
- maxAgeSeconds: config.maxAgeSeconds ?? DEFAULTS.maxAgeSeconds,
15
- });
27
+ const maxAgeSeconds = config.maxAgeSeconds ?? DEFAULTS.maxAgeSeconds;
28
+ const cookieName = config.cookieName ?? DEFAULTS.cookieName;
29
+ if (config.store) {
30
+ const sessionId = crypto.randomUUID();
31
+ await config.store.set(sessionId, sealed, maxAgeSeconds);
32
+ if (previousRequest) {
33
+ await deleteStoredSession(previousRequest, config);
34
+ }
35
+ return serializeCookie(cookieName, sessionId, { maxAgeSeconds });
36
+ }
37
+ return serializeCookie(cookieName, sealed, { maxAgeSeconds });
16
38
  }
17
39
  export function clearSessionHeader(config) {
18
40
  return expireCookie(config.cookieName ?? DEFAULTS.cookieName);
19
41
  }
42
+ /**
43
+ * Removes this request's session from `config.store`, if configured -- so a logout (or a
44
+ * rejected liveness check) invalidates the session immediately server-side, rather than only
45
+ * once the store's own TTL catches up. Safe to call unconditionally alongside
46
+ * `clearSessionHeader` regardless of whether a store is actually configured, whether the
47
+ * request has a session cookie at all, or whether the store has already evicted the entry --
48
+ * a no-op in every one of those cases, never an error.
49
+ */
50
+ export async function deleteStoredSession(request, config) {
51
+ if (!config.store)
52
+ return;
53
+ const cookieName = config.cookieName ?? DEFAULTS.cookieName;
54
+ const sessionId = parseCookies(request)[cookieName];
55
+ if (!sessionId)
56
+ return;
57
+ await config.store.delete(sessionId);
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oauth-spa-kit/server",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "description": "BFF-pattern OAuth handlers: sealed HttpOnly-cookie sessions + login/callback/refresh/logout route factories, built on Web-standard Request/Response so they drop into Nitro, Next.js route handlers, Cloudflare Workers, or plain Node (via a small adapter).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,7 +22,7 @@
22
22
  "node": ">=18"
23
23
  },
24
24
  "dependencies": {
25
- "@oauth-spa-kit/core": "2.3.1"
25
+ "@oauth-spa-kit/core": "2.4.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "typescript": "^5.6.0",