@oauth-spa-kit/core 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
@@ -29,10 +29,17 @@ for framework bindings, which both build on this package's
29
29
  ```ts
30
30
  import { createSessionClient } from "@oauth-spa-kit/core";
31
31
 
32
- const client = createSessionClient({ baseUrl: "/auth" });
32
+ const client = createSessionClient({
33
+ baseUrl: "/auth",
34
+ // Optional: poll GET /auth/liveness in the background so a session
35
+ // revoked or an account deactivated server-side ends this tab's session
36
+ // promptly, not just on the next navigation. Off by default.
37
+ livenessCheckIntervalMs: 60_000,
38
+ onSessionExpired: () => client.login(),
39
+ });
33
40
 
34
41
  client.subscribe((state) => {
35
- // state.ready, state.loggedIn, state.user
42
+ // state.ready, state.loggedIn, state.user, state.device
36
43
  });
37
44
 
38
45
  await client.refresh(); // GET /auth/session
@@ -40,6 +47,10 @@ client.login("/dashboard"); // full-page redirect, no silent/iframe path
40
47
  await client.logout();
41
48
  ```
42
49
 
50
+ `state.device` is a best-effort label ("Chrome on macOS") the server
51
+ package parses from the `User-Agent` at sign-in via `parseUserAgent()`,
52
+ also exported from this package -- useful for "you're signed in on X" UI.
53
+
43
54
  The lower-level protocol primitives (`createPkceParams`,
44
55
  `discoverOidcConfiguration`, `pushAuthorizationRequest`,
45
56
  `exchangeAuthorizationCode`, `exchangeRefreshToken`, `generateDpopKeyPair`,
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Best-effort, dependency-free "Chrome on macOS"-style label from a raw
3
+ * User-Agent string -- for "you're signed in on X" UI, not a fingerprinting
4
+ * tool. Order matters: several browsers' UAs share substrings (Edge and
5
+ * Opera both contain "Chrome/", real Safari and Chrome/Edge/Opera all
6
+ * contain "Safari/"), so the more specific token has to be checked first.
7
+ */
8
+ export declare function parseUserAgent(userAgent: string | null | undefined): string | undefined;
package/dist/device.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Best-effort, dependency-free "Chrome on macOS"-style label from a raw
3
+ * User-Agent string -- for "you're signed in on X" UI, not a fingerprinting
4
+ * tool. Order matters: several browsers' UAs share substrings (Edge and
5
+ * Opera both contain "Chrome/", real Safari and Chrome/Edge/Opera all
6
+ * contain "Safari/"), so the more specific token has to be checked first.
7
+ */
8
+ export function parseUserAgent(userAgent) {
9
+ if (!userAgent)
10
+ return undefined;
11
+ let browser = "Unknown browser";
12
+ if (/Edg\//.test(userAgent))
13
+ browser = "Edge";
14
+ else if (/OPR\/|Opera/.test(userAgent))
15
+ browser = "Opera";
16
+ else if (/Firefox\//.test(userAgent) || /FxiOS\//.test(userAgent))
17
+ browser = "Firefox";
18
+ else if (/CriOS\//.test(userAgent) || /Chrome\//.test(userAgent))
19
+ browser = "Chrome";
20
+ else if (/Version\/.*Safari\//.test(userAgent) || /Safari\//.test(userAgent))
21
+ browser = "Safari";
22
+ let os = "Unknown OS";
23
+ if (/iPhone/.test(userAgent))
24
+ os = "iPhone";
25
+ else if (/iPad/.test(userAgent))
26
+ os = "iPad";
27
+ else if (/Android/.test(userAgent))
28
+ os = "Android";
29
+ else if (/CrOS/.test(userAgent))
30
+ os = "ChromeOS";
31
+ else if (/Mac OS X|Macintosh/.test(userAgent))
32
+ os = "macOS";
33
+ else if (/Windows/.test(userAgent))
34
+ os = "Windows";
35
+ else if (/Linux/.test(userAgent))
36
+ os = "Linux";
37
+ return `${browser} on ${os}`;
38
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./types.js";
2
+ export * from "./device.js";
2
3
  export * from "./errors.js";
3
4
  export * from "./base64url.js";
4
5
  export * from "./pkce.js";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./types.js";
2
+ export * from "./device.js";
2
3
  export * from "./errors.js";
3
4
  export * from "./base64url.js";
4
5
  export * from "./pkce.js";
@@ -17,6 +17,25 @@ export interface SessionClientOptions {
17
17
  baseUrl?: string;
18
18
  fetchImpl?: typeof fetch;
19
19
  channelName?: string;
20
+ /**
21
+ * Interval (ms) for a background liveness check against `livenessPath`, on top of the
22
+ * normal navigation-triggered `refresh()` calls. Off by default -- opt in only if you need
23
+ * to react to a session dying (revoked access, deactivated account) *before* the user's next
24
+ * navigation. Unlike `/auth/session` (which only inspects the local cookie/token expiry),
25
+ * the liveness check makes a real round trip to the AS, so it also catches "token still
26
+ * technically unexpired but the account was just deactivated or the session was revoked
27
+ * elsewhere" -- not just token expiry, which is already handled reactively.
28
+ */
29
+ livenessCheckIntervalMs?: number;
30
+ /** Same-origin path for the liveness check. Defaults to `/auth/liveness`. */
31
+ livenessPath?: string;
32
+ /**
33
+ * Called once a liveness check confirms the session is actually dead (after two consecutive
34
+ * failures, to ride out a single transient network blip rather than force-logging someone
35
+ * out over it). `state.loggedIn` is already flipped to `false` before this fires -- use it
36
+ * for anything beyond reactive state, e.g. redirecting straight to `login()`.
37
+ */
38
+ onSessionExpired?: () => void;
20
39
  }
21
40
  export interface SessionClient {
22
41
  getState(): SessionState;
@@ -1,7 +1,10 @@
1
1
  const initialState = { ready: false, loggedIn: false, user: null };
2
+ /** Consecutive liveness-check failures required before treating a session as actually dead. */
3
+ const LIVENESS_FAILURE_THRESHOLD = 2;
2
4
  export function createSessionClient(options = {}) {
3
5
  const baseUrl = options.baseUrl ?? "";
4
6
  const fetchImpl = options.fetchImpl ?? fetch;
7
+ const livenessPath = options.livenessPath ?? "/auth/liveness";
5
8
  const channel = typeof BroadcastChannel !== "undefined"
6
9
  ? new BroadcastChannel(options.channelName ?? "oauth-spa-kit")
7
10
  : null;
@@ -25,7 +28,7 @@ export function createSessionClient(options = {}) {
25
28
  if (!response.ok)
26
29
  throw new Error(`/auth/session returned ${response.status}`);
27
30
  const body = await response.json();
28
- setState({ ready: true, loggedIn: Boolean(body.user), user: body.user ?? null });
31
+ setState({ ready: true, loggedIn: Boolean(body.user), user: body.user ?? null, device: body.device });
29
32
  }
30
33
  catch {
31
34
  setState({ ready: true, loggedIn: false, user: null });
@@ -35,6 +38,39 @@ export function createSessionClient(options = {}) {
35
38
  if (event.data === "session-changed")
36
39
  void refresh();
37
40
  });
41
+ if (typeof window !== "undefined" && options.livenessCheckIntervalMs) {
42
+ let consecutiveFailures = 0;
43
+ setInterval(() => {
44
+ void (async () => {
45
+ // Nothing to check liveness of yet -- the navigation-triggered refresh() is what
46
+ // notices a fresh sign-in and flips this back on.
47
+ if (!state.loggedIn)
48
+ return;
49
+ let alive;
50
+ try {
51
+ const response = await fetchImpl(`${baseUrl}${livenessPath}`, {
52
+ headers: { accept: "application/json" },
53
+ credentials: "same-origin",
54
+ });
55
+ alive = response.ok;
56
+ }
57
+ catch {
58
+ alive = false;
59
+ }
60
+ if (alive) {
61
+ consecutiveFailures = 0;
62
+ return;
63
+ }
64
+ consecutiveFailures += 1;
65
+ if (consecutiveFailures < LIVENESS_FAILURE_THRESHOLD)
66
+ return;
67
+ consecutiveFailures = 0;
68
+ setState({ ready: true, loggedIn: false, user: null });
69
+ channel?.postMessage("session-changed");
70
+ options.onSessionExpired?.();
71
+ })();
72
+ }, options.livenessCheckIntervalMs);
73
+ }
38
74
  return {
39
75
  getState: () => state,
40
76
  subscribe(callback) {
package/dist/types.d.ts CHANGED
@@ -85,4 +85,6 @@ export interface SessionState {
85
85
  ready: boolean;
86
86
  loggedIn: boolean;
87
87
  user: AuthenticatedUser | null;
88
+ /** This device's friendly label ("Chrome on macOS"), captured at sign-in. Undefined if not logged in or not captured. */
89
+ device?: string;
88
90
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oauth-spa-kit/core",
3
- "version": "2.0.6",
3
+ "version": "2.2.0",
4
4
  "description": "Framework- and runtime-agnostic OAuth 2.1 / OIDC primitives (PKCE, discovery, token exchange, DPoP) plus a fetch-based session client. Runs in the browser, Node, and edge runtimes -- no DOM or Node-only APIs.",
5
5
  "license": "MIT",
6
6
  "repository": {