@oauth-spa-kit/server 2.1.0 → 2.2.1

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
@@ -25,6 +25,7 @@ import {
25
25
  createCallbackHandler,
26
26
  createSessionHandler,
27
27
  createLogoutHandler,
28
+ createLivenessHandler,
28
29
  getAuthorizationHeader,
29
30
  getUserInfo,
30
31
  type OAuthHandlersConfig,
@@ -48,11 +49,13 @@ const config: OAuthHandlersConfig = {
48
49
  };
49
50
 
50
51
  // Each returns a plain (Request) => Promise<Response> -- mount at
51
- // GET /auth/login, GET /auth/callback, GET /auth/session, POST /auth/logout.
52
+ // GET /auth/login, GET /auth/callback, GET /auth/session, POST /auth/logout,
53
+ // GET /auth/liveness (optional -- see below).
52
54
  export const login = createLoginHandler(config);
53
55
  export const callback = createCallbackHandler(config);
54
56
  export const session = createSessionHandler(config);
55
57
  export const logout = createLogoutHandler(config);
58
+ export const liveness = createLivenessHandler(config);
56
59
 
57
60
  // From any other API route that needs to call an upstream resource server:
58
61
  const authHeader = await getAuthorizationHeader(request, config);
@@ -64,8 +67,17 @@ if (info) console.log(info.claims); // raw claims, shape depends on your granted
64
67
  ```
65
68
 
66
69
  The SPA never sees an access or refresh token -- only `GET /auth/session`'s
67
- `{ user }` response, backed by a sealed cookie the browser can't read or
68
- exfiltrate via JS. See
70
+ `{ user, device }` response, backed by a sealed cookie the browser can't
71
+ read or exfiltrate via JS. `device` is a best-effort label ("Chrome on
72
+ macOS") parsed from the callback request's `User-Agent` at sign-in --
73
+ useful for "you're signed in on X" UI, not a fingerprinting mechanism.
74
+
75
+ `createLivenessHandler` mounts a lightweight `GET /auth/liveness` that
76
+ returns `{ alive: boolean }`, backed by `getUserInfo` -- meant to be polled
77
+ on an interval from `@oauth-spa-kit/core`'s `createSessionClient`
78
+ (`livenessCheckIntervalMs`) so a session revoked or an account deactivated
79
+ server-side ends the SPA's session promptly, not just on the next
80
+ navigation. See
69
81
  [`@oauth-spa-kit/core`](https://www.npmjs.com/package/@oauth-spa-kit/core)
70
82
  for the lower-level protocol primitives these handlers are built from, and
71
83
  [`@oauth-spa-kit/react`](https://www.npmjs.com/package/@oauth-spa-kit/react)
@@ -56,3 +56,13 @@ export interface UserInfoResult {
56
56
  * rather than just decoding the stored id_token.
57
57
  */
58
58
  export declare function getUserInfo(request: Request, config: OAuthHandlersConfig): Promise<UserInfoResult | null>;
59
+ /**
60
+ * For a background liveness-polling loop (e.g. `@oauth-spa-kit/core`'s
61
+ * `createSessionClient` with `livenessCheckIntervalMs` set): a lightweight
62
+ * `{ alive: boolean }` check that, unlike `/auth/session`, always makes a
63
+ * real round trip to the AS's userinfo_endpoint via `getUserInfo` rather than
64
+ * just inspecting the locally stored token expiry -- so it also catches a
65
+ * session that's been revoked or an account that's been deactivated
66
+ * server-side, mid-session, before the access token itself would expire.
67
+ */
68
+ export declare function createLivenessHandler(config: OAuthHandlersConfig): (request: Request) => Promise<Response>;
package/dist/handlers.js CHANGED
@@ -1,4 +1,4 @@
1
- import { computeJwkThumbprint, createDpopProof, createPkceParams, discoverOidcConfiguration, exchangeAuthorizationCode, exchangeRefreshToken, exportDpopKeyPair, fetchJwks, generateDpopKeyPair, importDpopKeyPair, pushAuthorizationRequest, verifyJwt, OAuthError, TokenExchangeError, } from "@oauth-spa-kit/core";
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
3
  import { clearSessionHeader, readSession, writeSessionHeader } from "./session.js";
4
4
  async function resolveDiscovery(config) {
@@ -129,8 +129,9 @@ export function createCallbackHandler(config) {
129
129
  fetchImpl: config.fetchImpl,
130
130
  });
131
131
  const user = await verifyIdToken(tokens.idToken, discovery, config, pkce.nonce);
132
+ const device = parseUserAgent(request.headers.get("user-agent"));
132
133
  const headers = new Headers({ Location: pkce.returnTo });
133
- headers.append("Set-Cookie", await writeSessionHeader({ tokens, user, dpopKeyPair: pkce.dpopKeyPair }, config.session));
134
+ headers.append("Set-Cookie", await writeSessionHeader({ tokens, user, dpopKeyPair: pkce.dpopKeyPair, device }, config.session));
134
135
  headers.append("Set-Cookie", clearPkceStateHeader());
135
136
  return new Response(null, { status: 302, headers });
136
137
  }
@@ -157,7 +158,7 @@ export function createSessionHandler(config) {
157
158
  const expiringSoon = session.tokens.expiresAt !== null
158
159
  && session.tokens.expiresAt - Date.now() < thresholdMs;
159
160
  if (!expiringSoon) {
160
- return new Response(JSON.stringify({ user: session.user }), {
161
+ return new Response(JSON.stringify({ user: session.user, device: session.device }), {
161
162
  status: 200,
162
163
  headers: { "content-type": "application/json" },
163
164
  });
@@ -180,7 +181,7 @@ export function createSessionHandler(config) {
180
181
  fetchImpl: config.fetchImpl,
181
182
  });
182
183
  const setCookie = await writeSessionHeader(session, config.session);
183
- return new Response(JSON.stringify({ user: session.user }), {
184
+ return new Response(JSON.stringify({ user: session.user, device: session.device }), {
184
185
  status: 200,
185
186
  headers: { "content-type": "application/json", "Set-Cookie": setCookie },
186
187
  });
@@ -293,3 +294,43 @@ export async function getUserInfo(request, config) {
293
294
  }
294
295
  return { claims: (await response.json()), setCookie: auth.setCookie };
295
296
  }
297
+ /**
298
+ * For a background liveness-polling loop (e.g. `@oauth-spa-kit/core`'s
299
+ * `createSessionClient` with `livenessCheckIntervalMs` set): a lightweight
300
+ * `{ alive: boolean }` check that, unlike `/auth/session`, always makes a
301
+ * real round trip to the AS's userinfo_endpoint via `getUserInfo` rather than
302
+ * just inspecting the locally stored token expiry -- so it also catches a
303
+ * session that's been revoked or an account that's been deactivated
304
+ * server-side, mid-session, before the access token itself would expire.
305
+ */
306
+ export function createLivenessHandler(config) {
307
+ return async function livenessHandler(request) {
308
+ let result;
309
+ try {
310
+ result = await getUserInfo(request, config);
311
+ }
312
+ catch {
313
+ // Any failure here -- a rejected refresh (TokenExchangeError) or the AS's
314
+ // userinfo_endpoint itself rejecting the access token (OAuthError, e.g. the session
315
+ // backing it was explicitly revoked server-side) -- means this session is dead. Clear
316
+ // the local cookie unconditionally rather than only for TokenExchangeError: leaving a
317
+ // known-dead cookie in place is only harmless because the default Nuxt/React wiring
318
+ // immediately redirects to a fresh login on `onSessionExpired`: a consumer that
319
+ // instead just shows a "session expired" message would otherwise keep sending a
320
+ // cookie doomed to fail every subsequent request.
321
+ const headers = new Headers({ "content-type": "application/json" });
322
+ headers.append("Set-Cookie", clearSessionHeader(config.session));
323
+ return new Response(JSON.stringify({ alive: false }), { status: 401, headers });
324
+ }
325
+ if (!result) {
326
+ return new Response(JSON.stringify({ alive: false }), {
327
+ status: 401,
328
+ headers: { "content-type": "application/json" },
329
+ });
330
+ }
331
+ const headers = new Headers({ "content-type": "application/json" });
332
+ if (result.setCookie)
333
+ headers.append("Set-Cookie", result.setCookie);
334
+ return new Response(JSON.stringify({ alive: true }), { status: 200, headers });
335
+ };
336
+ }
package/dist/session.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface StoredSession {
4
4
  user: AuthenticatedUser;
5
5
  /** The exact key pair the tokens are DPoP-bound to -- reused for every refresh. Absent only if `config.oauth.dpop === false`. */
6
6
  dpopKeyPair?: SerializedDpopKeyPair;
7
+ /** This device's friendly label ("Chrome on macOS"), parsed from the callback request's User-Agent at sign-in. */
8
+ device?: string;
7
9
  }
8
10
  export interface SessionConfig {
9
11
  /** >=32 char secret. Load from env (`OAUTH_SESSION_PASSWORD`); rotate by supporting two passwords during migration if you need zero-downtime rotation. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oauth-spa-kit/server",
3
- "version": "2.1.0",
3
+ "version": "2.2.1",
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.1.0"
25
+ "@oauth-spa-kit/core": "2.2.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "typescript": "^5.6.0",