@oauth-spa-kit/server 2.0.6 → 2.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.
package/README.md CHANGED
@@ -25,7 +25,9 @@ import {
25
25
  createCallbackHandler,
26
26
  createSessionHandler,
27
27
  createLogoutHandler,
28
+ createLivenessHandler,
28
29
  getAuthorizationHeader,
30
+ getUserInfo,
29
31
  type OAuthHandlersConfig,
30
32
  } from "@oauth-spa-kit/server";
31
33
 
@@ -47,19 +49,35 @@ const config: OAuthHandlersConfig = {
47
49
  };
48
50
 
49
51
  // Each returns a plain (Request) => Promise<Response> -- mount at
50
- // 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).
51
54
  export const login = createLoginHandler(config);
52
55
  export const callback = createCallbackHandler(config);
53
56
  export const session = createSessionHandler(config);
54
57
  export const logout = createLogoutHandler(config);
58
+ export const liveness = createLivenessHandler(config);
55
59
 
56
60
  // From any other API route that needs to call an upstream resource server:
57
61
  const authHeader = await getAuthorizationHeader(request, config);
62
+
63
+ // Or, for the AS's own userinfo_endpoint specifically (DPoP proof, nonce
64
+ // retry, and token refresh all handled for you):
65
+ const info = await getUserInfo(request, config);
66
+ if (info) console.log(info.claims); // raw claims, shape depends on your granted scopes
58
67
  ```
59
68
 
60
69
  The SPA never sees an access or refresh token -- only `GET /auth/session`'s
61
- `{ user }` response, backed by a sealed cookie the browser can't read or
62
- 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
63
81
  [`@oauth-spa-kit/core`](https://www.npmjs.com/package/@oauth-spa-kit/core)
64
82
  for the lower-level protocol primitives these handlers are built from, and
65
83
  [`@oauth-spa-kit/react`](https://www.npmjs.com/package/@oauth-spa-kit/react)
@@ -42,3 +42,27 @@ export interface AuthorizationHeaderResult {
42
42
  * the token never crosses back into the browser.
43
43
  */
44
44
  export declare function getAuthorizationHeader(request: Request, config: OAuthHandlersConfig): Promise<AuthorizationHeaderResult | null>;
45
+ export interface UserInfoResult {
46
+ /** Whatever the AS's userinfo_endpoint returned -- raw, unmapped claims (shape varies per AS/scope grant). */
47
+ claims: Record<string, unknown>;
48
+ /** Set only when the access token was refreshed -- forward this Set-Cookie on your outgoing response. */
49
+ setCookie?: string;
50
+ }
51
+ /**
52
+ * Calls the AS's userinfo_endpoint with the session's (DPoP-bound, if
53
+ * enabled) access token, refreshing it first if it's expiring soon -- the
54
+ * id_token is meant to be a thin proof of authentication at login time, not
55
+ * a source of the current profile, which is why this hits userinfo_endpoint
56
+ * rather than just decoding the stored id_token.
57
+ */
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, 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
  });
@@ -250,3 +251,80 @@ export async function getAuthorizationHeader(request, config) {
250
251
  }
251
252
  return { header: `${session.tokens.tokenType} ${session.tokens.accessToken}` };
252
253
  }
254
+ /**
255
+ * Calls the AS's userinfo_endpoint with the session's (DPoP-bound, if
256
+ * enabled) access token, refreshing it first if it's expiring soon -- the
257
+ * id_token is meant to be a thin proof of authentication at login time, not
258
+ * a source of the current profile, which is why this hits userinfo_endpoint
259
+ * rather than just decoding the stored id_token.
260
+ */
261
+ export async function getUserInfo(request, config) {
262
+ const session = await readSession(request, config.session);
263
+ if (!session)
264
+ return null;
265
+ const auth = await getAuthorizationHeader(request, config);
266
+ if (!auth)
267
+ return null;
268
+ const discovery = await resolveDiscovery(config);
269
+ if (!discovery.userinfo_endpoint) {
270
+ throw new OAuthError("Discovery document has no userinfo_endpoint");
271
+ }
272
+ const userinfoEndpoint = discovery.userinfo_endpoint;
273
+ const dpopKeyPair = session.dpopKeyPair ? await importDpopKeyPair(session.dpopKeyPair) : undefined;
274
+ const accessToken = auth.header.slice(auth.header.indexOf(" ") + 1);
275
+ const fetchImpl = config.fetchImpl ?? fetch;
276
+ async function callUserInfo(nonce) {
277
+ const headers = { Authorization: auth.header };
278
+ if (dpopKeyPair) {
279
+ headers.DPoP = await createDpopProof({ keyPair: dpopKeyPair, htm: "GET", htu: userinfoEndpoint, accessToken, nonce });
280
+ }
281
+ return fetchImpl(userinfoEndpoint, { headers });
282
+ }
283
+ // DPoP resource endpoints can nonce-challenge the same way the token endpoint does (RFC 9449
284
+ // section 8), just via WWW-Authenticate/DPoP-Nonce response headers instead of a JSON body --
285
+ // so this retries once, mirroring the token-endpoint retry in @oauth-spa-kit/core.
286
+ let response = await callUserInfo();
287
+ if (response.status === 401 && dpopKeyPair) {
288
+ const nonce = response.headers.get("DPoP-Nonce");
289
+ if (nonce)
290
+ response = await callUserInfo(nonce);
291
+ }
292
+ if (!response.ok) {
293
+ throw new OAuthError(`userinfo_endpoint returned ${response.status}`);
294
+ }
295
+ return { claims: (await response.json()), setCookie: auth.setCookie };
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 (cause) {
313
+ const headers = new Headers({ "content-type": "application/json" });
314
+ if (cause instanceof TokenExchangeError) {
315
+ headers.append("Set-Cookie", clearSessionHeader(config.session));
316
+ }
317
+ return new Response(JSON.stringify({ alive: false }), { status: 401, headers });
318
+ }
319
+ if (!result) {
320
+ return new Response(JSON.stringify({ alive: false }), {
321
+ status: 401,
322
+ headers: { "content-type": "application/json" },
323
+ });
324
+ }
325
+ const headers = new Headers({ "content-type": "application/json" });
326
+ if (result.setCookie)
327
+ headers.append("Set-Cookie", result.setCookie);
328
+ return new Response(JSON.stringify({ alive: true }), { status: 200, headers });
329
+ };
330
+ }
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.0.6",
3
+ "version": "2.2.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.0.6"
25
+ "@oauth-spa-kit/core": "2.2.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "typescript": "^5.6.0",