@oxyhq/services 8.1.2 → 8.3.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.
Files changed (33) hide show
  1. package/lib/commonjs/ui/components/OxyProvider.js +10 -3
  2. package/lib/commonjs/ui/components/OxyProvider.js.map +1 -1
  3. package/lib/commonjs/ui/context/OxyContext.js +499 -79
  4. package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
  5. package/lib/commonjs/ui/hooks/useSessionManagement.js +7 -3
  6. package/lib/commonjs/ui/hooks/useSessionManagement.js.map +1 -1
  7. package/lib/commonjs/ui/utils/ssoBounce.js +158 -0
  8. package/lib/commonjs/ui/utils/ssoBounce.js.map +1 -0
  9. package/lib/module/ui/components/OxyProvider.js +10 -3
  10. package/lib/module/ui/components/OxyProvider.js.map +1 -1
  11. package/lib/module/ui/context/OxyContext.js +499 -79
  12. package/lib/module/ui/context/OxyContext.js.map +1 -1
  13. package/lib/module/ui/context/hooks/useAuthOperations.js.map +1 -1
  14. package/lib/module/ui/hooks/useSessionManagement.js +7 -3
  15. package/lib/module/ui/hooks/useSessionManagement.js.map +1 -1
  16. package/lib/module/ui/utils/ssoBounce.js +148 -0
  17. package/lib/module/ui/utils/ssoBounce.js.map +1 -0
  18. package/lib/typescript/commonjs/ui/components/OxyProvider.d.ts.map +1 -1
  19. package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
  20. package/lib/typescript/commonjs/ui/hooks/useSessionManagement.d.ts.map +1 -1
  21. package/lib/typescript/commonjs/ui/utils/ssoBounce.d.ts +89 -0
  22. package/lib/typescript/commonjs/ui/utils/ssoBounce.d.ts.map +1 -0
  23. package/lib/typescript/module/ui/components/OxyProvider.d.ts.map +1 -1
  24. package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
  25. package/lib/typescript/module/ui/hooks/useSessionManagement.d.ts.map +1 -1
  26. package/lib/typescript/module/ui/utils/ssoBounce.d.ts +89 -0
  27. package/lib/typescript/module/ui/utils/ssoBounce.d.ts.map +1 -0
  28. package/package.json +2 -2
  29. package/src/ui/components/OxyProvider.tsx +4 -3
  30. package/src/ui/context/OxyContext.tsx +513 -87
  31. package/src/ui/context/hooks/useAuthOperations.ts +1 -1
  32. package/src/ui/hooks/useSessionManagement.ts +8 -4
  33. package/src/ui/utils/ssoBounce.ts +146 -0
@@ -3,7 +3,7 @@ import type { ApiError, User } from '@oxyhq/core';
3
3
  import type { AuthState } from '../../stores/authStore';
4
4
  import type { ClientSession, SessionLoginResponse } from '@oxyhq/core';
5
5
  import { DeviceManager } from '@oxyhq/core';
6
- import { fetchSessionsWithFallback, mapSessionsToClient } from '../../utils/sessionHelpers';
6
+ import { fetchSessionsWithFallback } from '../../utils/sessionHelpers';
7
7
  import { handleAuthError, isInvalidSessionError } from '../../utils/errorHandlers';
8
8
  import type { StorageInterface } from '../../utils/storageHelpers';
9
9
  import type { OxyServices } from '@oxyhq/core';
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
2
  import type { ApiError, User } from '@oxyhq/core';
3
3
  import type { ClientSession } from '@oxyhq/core';
4
4
  import { mergeSessions, normalizeAndSortSessions, sessionsArraysEqual } from '@oxyhq/core';
5
- import { fetchSessionsWithFallback, mapSessionsToClient, validateSessionBatch } from '../utils/sessionHelpers';
5
+ import { fetchSessionsWithFallback, validateSessionBatch } from '../utils/sessionHelpers';
6
6
  import { getStorageKeys, type StorageInterface } from '../utils/storageHelpers';
7
7
  import { handleAuthError, isInvalidSessionError } from '../utils/errorHandlers';
8
8
  import type { OxyServices } from '@oxyhq/core';
@@ -364,7 +364,11 @@ export const useSessionManagement = ({
364
364
 
365
365
  const refreshSessions = useCallback(
366
366
  async (activeUserId?: string): Promise<void> => {
367
- if (!activeSessionIdRef.current) return;
367
+ // Capture the active session id once so the async closure below uses a
368
+ // narrowed, non-null local instead of re-reading the ref (which the
369
+ // compiler cannot prove stays non-null across awaits).
370
+ const activeSessionId = activeSessionIdRef.current;
371
+ if (!activeSessionId) return;
368
372
 
369
373
  if (refreshInFlightRef.current) {
370
374
  await refreshInFlightRef.current;
@@ -379,7 +383,7 @@ export const useSessionManagement = ({
379
383
 
380
384
  const refreshPromise = (async () => {
381
385
  try {
382
- const deviceSessions = await fetchSessionsWithFallback(oxyServices, activeSessionIdRef.current!, {
386
+ const deviceSessions = await fetchSessionsWithFallback(oxyServices, activeSessionId, {
383
387
  fallbackUserId: activeUserId,
384
388
  logger,
385
389
  });
@@ -389,7 +393,7 @@ export const useSessionManagement = ({
389
393
  const otherSessions = sessionsRef.current
390
394
  .filter(
391
395
  (session) =>
392
- session.sessionId !== activeSessionIdRef.current &&
396
+ session.sessionId !== activeSessionId &&
393
397
  !removedSessionsRef.current.has(session.sessionId),
394
398
  )
395
399
  .map((session) => session.sessionId);
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Central cross-domain SSO bounce — per-origin sessionStorage keys and small
3
+ * pure predicates shared by the cold-boot `sso-return` / `sso-bounce` steps and
4
+ * the bfcache `pageshow` re-evaluation.
5
+ *
6
+ * TRUE central SSO (Google/Meta/Clerk style) works like this for a Relying
7
+ * Party (mention.earth, homiio.com, alia.onl, …) with no local session:
8
+ *
9
+ * 1. `sso-bounce` (terminal, once): top-level navigate to
10
+ * `auth.oxy.so/sso?prompt=none&client_id=<origin>&return_to=<origin>/__oxy/sso-callback&state=<s>`.
11
+ * Before navigating it records, in this origin's `sessionStorage`, the CSRF
12
+ * `state`, a guard timestamp (loop breaker), and the real destination URL
13
+ * to restore after the callback.
14
+ * 2. The central IdP worker reads its first-party `fedcm_session`, mints a
15
+ * session, stores it under an opaque single-use `code`, and 303-redirects
16
+ * back to `<origin>/__oxy/sso-callback#oxy_sso=ok&code=<code>&state=<s>`
17
+ * (or `#oxy_sso=none` / `#oxy_sso=error`).
18
+ * 3. `sso-return` parses the fragment (`parseSsoReturnFragment` from core),
19
+ * validates `state`, exchanges the `code` via `oxyServices.exchangeSsoCode`,
20
+ * and commits the session — then restores the original destination.
21
+ *
22
+ * Loop proof (logged-out): first load all steps skip → `sso-bounce` sets
23
+ * guard/state/dest and navigates; the IdP (no central session) returns
24
+ * `#oxy_sso=none`; the callback load's `sso-return` sees `none`, sets the
25
+ * no-session flag, and `sso-bounce` is then disabled. Exactly ONE bounce, no
26
+ * loop. An interrupted bounce (user hit back mid-redirect) self-heals once the
27
+ * 30s guard TTL lapses.
28
+ *
29
+ * All state lives in `sessionStorage` (per tab, cleared on tab close) and is
30
+ * keyed per-origin so two RPs hosted in the same browser never collide. This
31
+ * module is pure with respect to navigation: it only reads/writes
32
+ * `sessionStorage` and parses URLs; it performs no redirects itself.
33
+ */
34
+
35
+ import { CENTRAL_AUTH_URL } from '@oxyhq/core';
36
+
37
+ /**
38
+ * The RP callback path the central IdP redirects back to. The SSO result is
39
+ * delivered in the fragment of this URL; `sso-return` consumes it and then
40
+ * restores the user's real destination.
41
+ */
42
+ export const SSO_CALLBACK_PATH = '/__oxy/sso-callback';
43
+
44
+ /**
45
+ * Self-healing TTL (ms) for the bounce guard. If a bounce is interrupted before
46
+ * the callback lands (e.g. the user navigates back mid-redirect), the guard
47
+ * would otherwise pin the RP signed-out forever. After this window the guard is
48
+ * treated as stale and a fresh single bounce is permitted.
49
+ */
50
+ export const SSO_GUARD_TTL_MS = 30_000;
51
+
52
+ const STATE_KEY_PREFIX = 'oxy_sso_state:';
53
+ const GUARD_KEY_PREFIX = 'oxy_sso_guard:';
54
+ const DEST_KEY_PREFIX = 'oxy_sso_dest:';
55
+ const NO_SESSION_KEY_PREFIX = 'oxy_sso_no_session:';
56
+
57
+ /**
58
+ * Perform the terminal top-level SSO bounce navigation.
59
+ *
60
+ * A thin wrapper over `window.location.assign(url)` so the single navigation
61
+ * seam lives in one place (and stays mockable in tests, where jsdom's
62
+ * `Location.assign` is a non-configurable native method). In production this is
63
+ * exactly `window.location.assign` — the document is torn down and replaced by
64
+ * the central IdP page. Off-browser it is a no-op (native never bounces).
65
+ */
66
+ export function ssoNavigate(url: string): void {
67
+ if (typeof window === 'undefined' || typeof window.location === 'undefined') {
68
+ return;
69
+ }
70
+ window.location.assign(url);
71
+ }
72
+
73
+ /** Per-origin CSRF state key (matched on return to defeat fragment forgery). */
74
+ export function ssoStateKey(origin: string): string {
75
+ return `${STATE_KEY_PREFIX}${origin}`;
76
+ }
77
+
78
+ /** Per-origin bounce guard key (a timestamp; loop breaker + self-heal TTL). */
79
+ export function ssoGuardKey(origin: string): string {
80
+ return `${GUARD_KEY_PREFIX}${origin}`;
81
+ }
82
+
83
+ /** Per-origin destination key (the real URL to restore after the callback). */
84
+ export function ssoDestKey(origin: string): string {
85
+ return `${DEST_KEY_PREFIX}${origin}`;
86
+ }
87
+
88
+ /**
89
+ * Per-origin "the central IdP has no session for me" key. Set after a
90
+ * `none`/`error` return (or a failed/forged exchange) so `sso-bounce` does not
91
+ * fire again this tab — the definitive loop breaker.
92
+ */
93
+ export function ssoNoSessionKey(origin: string): string {
94
+ return `${NO_SESSION_KEY_PREFIX}${origin}`;
95
+ }
96
+
97
+ /**
98
+ * Whether `origin` IS the central IdP origin. We must never bounce while on
99
+ * `auth.oxy.so` itself (it would bounce to itself). Compared by URL origin so a
100
+ * trailing-slash / path difference never defeats the guard.
101
+ */
102
+ export function isCentralIdPOrigin(origin: string): boolean {
103
+ let centralOrigin: string;
104
+ try {
105
+ centralOrigin = new URL(CENTRAL_AUTH_URL).origin;
106
+ } catch {
107
+ return false;
108
+ }
109
+ let candidateOrigin: string;
110
+ try {
111
+ candidateOrigin = new URL(origin).origin;
112
+ } catch {
113
+ return false;
114
+ }
115
+ return candidateOrigin === centralOrigin;
116
+ }
117
+
118
+ /**
119
+ * Read the bounce guard and decide whether it is still ACTIVE.
120
+ *
121
+ * Active means: a guard value is present AND it parses to a finite timestamp AND
122
+ * less than {@link SSO_GUARD_TTL_MS} has elapsed since it was set. An active
123
+ * guard disables `sso-bounce` (a bounce is already in flight this tab). A
124
+ * missing, malformed, or expired guard is NOT active, so a fresh bounce may
125
+ * proceed (this is the 30s self-heal for an interrupted bounce).
126
+ *
127
+ * @param storage - The session storage to read (injected for testability).
128
+ * @param origin - The page origin whose guard to evaluate.
129
+ * @param now - Current epoch ms (injected for deterministic tests).
130
+ */
131
+ export function guardActive(storage: Storage, origin: string, now: number): boolean {
132
+ let raw: string | null;
133
+ try {
134
+ raw = storage.getItem(ssoGuardKey(origin));
135
+ } catch {
136
+ return false;
137
+ }
138
+ if (raw === null || raw.length === 0) {
139
+ return false;
140
+ }
141
+ const stamp = Number(raw);
142
+ if (!Number.isFinite(stamp)) {
143
+ return false;
144
+ }
145
+ return now - stamp < SSO_GUARD_TTL_MS;
146
+ }