@oxyhq/core 5.4.3 → 6.0.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 (186) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +6 -3
  3. package/dist/cjs/OxyServices.base.js +7 -102
  4. package/dist/cjs/boot/coldBootV2.js +350 -0
  5. package/dist/cjs/boot/deviceBootReturn.js +152 -0
  6. package/dist/cjs/crypto/keyManager.js +95 -0
  7. package/dist/cjs/i18n/locales/en-US.json +13 -1
  8. package/dist/cjs/i18n/locales/es-ES.json +13 -1
  9. package/dist/cjs/i18n/locales/locales/en-US.json +13 -1
  10. package/dist/cjs/i18n/locales/locales/es-ES.json +13 -1
  11. package/dist/cjs/index.js +47 -43
  12. package/dist/cjs/mixins/OxyServices.accounts.js +6 -13
  13. package/dist/cjs/mixins/OxyServices.auth.js +66 -201
  14. package/dist/cjs/mixins/OxyServices.authorizedApps.js +38 -0
  15. package/dist/cjs/mixins/OxyServices.deviceBoot.js +119 -0
  16. package/dist/cjs/mixins/index.js +13 -17
  17. package/dist/cjs/session/SessionClient.js +44 -2
  18. package/dist/cjs/session/authStateStore.js +284 -0
  19. package/dist/cjs/session/createSessionClient.js +8 -2
  20. package/dist/cjs/session/refresh.js +264 -0
  21. package/dist/cjs/utils/accountUtils.js +1 -55
  22. package/dist/cjs/utils/authWebUrl.js +6 -15
  23. package/dist/cjs/utils/fapiAutoDetect.js +16 -64
  24. package/dist/cjs/utils/platform.js +19 -0
  25. package/dist/cjs/utils/ssoBounce.js +15 -340
  26. package/dist/cjs/utils/validationUtils.js +57 -0
  27. package/dist/esm/.tsbuildinfo +1 -1
  28. package/dist/esm/HttpService.js +6 -3
  29. package/dist/esm/OxyServices.base.js +7 -102
  30. package/dist/esm/boot/coldBootV2.js +344 -0
  31. package/dist/esm/boot/deviceBootReturn.js +146 -0
  32. package/dist/esm/crypto/keyManager.js +95 -0
  33. package/dist/esm/i18n/locales/en-US.json +13 -1
  34. package/dist/esm/i18n/locales/es-ES.json +13 -1
  35. package/dist/esm/i18n/locales/locales/en-US.json +13 -1
  36. package/dist/esm/i18n/locales/locales/es-ES.json +13 -1
  37. package/dist/esm/index.js +28 -18
  38. package/dist/esm/mixins/OxyServices.accounts.js +6 -13
  39. package/dist/esm/mixins/OxyServices.auth.js +66 -201
  40. package/dist/esm/mixins/OxyServices.authorizedApps.js +35 -0
  41. package/dist/esm/mixins/OxyServices.deviceBoot.js +116 -0
  42. package/dist/esm/mixins/index.js +13 -17
  43. package/dist/esm/session/SessionClient.js +44 -2
  44. package/dist/esm/session/authStateStore.js +278 -0
  45. package/dist/esm/session/createSessionClient.js +8 -2
  46. package/dist/esm/session/refresh.js +257 -0
  47. package/dist/esm/utils/accountUtils.js +0 -53
  48. package/dist/esm/utils/authWebUrl.js +6 -14
  49. package/dist/esm/utils/fapiAutoDetect.js +16 -63
  50. package/dist/esm/utils/platform.js +18 -0
  51. package/dist/esm/utils/ssoBounce.js +14 -324
  52. package/dist/esm/utils/validationUtils.js +56 -0
  53. package/dist/types/.tsbuildinfo +1 -1
  54. package/dist/types/HttpService.d.ts +13 -0
  55. package/dist/types/OxyServices.base.d.ts +0 -52
  56. package/dist/types/OxyServices.d.ts +0 -25
  57. package/dist/types/boot/coldBootV2.d.ts +76 -0
  58. package/dist/types/boot/deviceBootReturn.d.ts +83 -0
  59. package/dist/types/crypto/keyManager.d.ts +21 -0
  60. package/dist/types/index.d.ts +16 -21
  61. package/dist/types/mixins/OxyServices.accounts.d.ts +0 -2
  62. package/dist/types/mixins/OxyServices.analytics.d.ts +0 -2
  63. package/dist/types/mixins/OxyServices.appData.d.ts +0 -2
  64. package/dist/types/mixins/OxyServices.assets.d.ts +0 -2
  65. package/dist/types/mixins/OxyServices.auth.d.ts +35 -77
  66. package/dist/types/mixins/{OxyServices.redirect.d.ts → OxyServices.authorizedApps.d.ts} +35 -33
  67. package/dist/types/mixins/OxyServices.civic.d.ts +0 -2
  68. package/dist/types/mixins/OxyServices.connectedApps.d.ts +0 -2
  69. package/dist/types/mixins/OxyServices.contacts.d.ts +0 -2
  70. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +110 -0
  71. package/dist/types/mixins/OxyServices.devices.d.ts +0 -2
  72. package/dist/types/mixins/OxyServices.features.d.ts +0 -2
  73. package/dist/types/mixins/OxyServices.identity.d.ts +0 -2
  74. package/dist/types/mixins/OxyServices.language.d.ts +0 -2
  75. package/dist/types/mixins/OxyServices.links.d.ts +0 -2
  76. package/dist/types/mixins/OxyServices.location.d.ts +0 -2
  77. package/dist/types/mixins/OxyServices.nodes.d.ts +0 -2
  78. package/dist/types/mixins/OxyServices.payment.d.ts +0 -2
  79. package/dist/types/mixins/OxyServices.privacy.d.ts +0 -2
  80. package/dist/types/mixins/OxyServices.reputation.d.ts +0 -2
  81. package/dist/types/mixins/OxyServices.security.d.ts +0 -2
  82. package/dist/types/mixins/OxyServices.topics.d.ts +0 -2
  83. package/dist/types/mixins/OxyServices.user.d.ts +0 -2
  84. package/dist/types/mixins/OxyServices.utility.d.ts +0 -2
  85. package/dist/types/mixins/index.d.ts +6 -9
  86. package/dist/types/models/interfaces.d.ts +0 -67
  87. package/dist/types/session/SessionClient.d.ts +38 -1
  88. package/dist/types/session/authStateStore.d.ts +119 -0
  89. package/dist/types/session/createSessionClient.d.ts +8 -1
  90. package/dist/types/session/refresh.d.ts +93 -0
  91. package/dist/types/utils/accountUtils.d.ts +0 -14
  92. package/dist/types/utils/authWebUrl.d.ts +6 -12
  93. package/dist/types/utils/fapiAutoDetect.d.ts +15 -38
  94. package/dist/types/utils/platform.d.ts +14 -0
  95. package/dist/types/utils/ssoBounce.d.ts +14 -262
  96. package/dist/types/utils/validationUtils.d.ts +15 -0
  97. package/package.json +2 -2
  98. package/src/HttpService.ts +19 -3
  99. package/src/OxyServices.base.ts +7 -112
  100. package/src/OxyServices.ts +0 -38
  101. package/src/boot/__tests__/coldBootV2.test.ts +317 -0
  102. package/src/boot/__tests__/deviceBootReturn.test.ts +158 -0
  103. package/src/boot/coldBootV2.ts +426 -0
  104. package/src/boot/deviceBootReturn.ts +195 -0
  105. package/src/crypto/__tests__/sharedDeviceToken.test.ts +24 -0
  106. package/src/crypto/keyManager.ts +101 -0
  107. package/src/i18n/locales/en-US.json +13 -1
  108. package/src/i18n/locales/es-ES.json +13 -1
  109. package/src/index.ts +78 -64
  110. package/src/mixins/OxyServices.accounts.ts +6 -13
  111. package/src/mixins/OxyServices.auth.ts +78 -253
  112. package/src/mixins/OxyServices.authorizedApps.ts +75 -0
  113. package/src/mixins/OxyServices.deviceBoot.ts +146 -0
  114. package/src/mixins/__tests__/OxyServices.deviceBoot.test.ts +107 -0
  115. package/src/mixins/__tests__/accounts.test.ts +17 -44
  116. package/src/mixins/__tests__/authorizedApps.test.ts +63 -0
  117. package/src/mixins/__tests__/passwordSignIn.test.ts +91 -0
  118. package/src/mixins/index.ts +16 -22
  119. package/src/models/interfaces.ts +0 -79
  120. package/src/session/SessionClient.ts +69 -3
  121. package/src/session/__tests__/SessionClient.additive.test.ts +92 -0
  122. package/src/session/__tests__/SessionClient.rest.test.ts +25 -0
  123. package/src/session/__tests__/SessionClient.socketFactory.test.ts +79 -0
  124. package/src/session/__tests__/SessionClient.state.test.ts +18 -5
  125. package/src/session/__tests__/authStateStore.test.ts +209 -0
  126. package/src/session/__tests__/refresh.test.ts +256 -0
  127. package/src/session/authStateStore.ts +335 -0
  128. package/src/session/createSessionClient.ts +9 -1
  129. package/src/session/refresh.ts +334 -0
  130. package/src/utils/__tests__/authWebUrl.test.ts +5 -29
  131. package/src/utils/__tests__/fapiAutoDetect.test.ts +5 -126
  132. package/src/utils/__tests__/validationUtils.test.ts +30 -0
  133. package/src/utils/accountUtils.ts +0 -62
  134. package/src/utils/authWebUrl.ts +6 -15
  135. package/src/utils/fapiAutoDetect.ts +16 -60
  136. package/src/utils/platform.ts +21 -0
  137. package/src/utils/ssoBounce.ts +14 -371
  138. package/src/utils/validationUtils.ts +62 -0
  139. package/dist/cjs/AuthManager.js +0 -1110
  140. package/dist/cjs/AuthManagerTypes.js +0 -13
  141. package/dist/cjs/CrossDomainAuth.js +0 -206
  142. package/dist/cjs/mixins/OxyServices.fedcm.js +0 -823
  143. package/dist/cjs/mixins/OxyServices.redirect.js +0 -95
  144. package/dist/cjs/mixins/OxyServices.silent.js +0 -204
  145. package/dist/cjs/mixins/OxyServices.sso.js +0 -208
  146. package/dist/cjs/utils/ssoEstablish.js +0 -110
  147. package/dist/cjs/utils/ssoReturn.js +0 -267
  148. package/dist/esm/AuthManager.js +0 -1105
  149. package/dist/esm/AuthManagerTypes.js +0 -12
  150. package/dist/esm/CrossDomainAuth.js +0 -201
  151. package/dist/esm/mixins/OxyServices.fedcm.js +0 -821
  152. package/dist/esm/mixins/OxyServices.redirect.js +0 -92
  153. package/dist/esm/mixins/OxyServices.silent.js +0 -202
  154. package/dist/esm/mixins/OxyServices.sso.js +0 -204
  155. package/dist/esm/utils/ssoEstablish.js +0 -107
  156. package/dist/esm/utils/ssoReturn.js +0 -263
  157. package/dist/types/AuthManager.d.ts +0 -380
  158. package/dist/types/AuthManagerTypes.d.ts +0 -81
  159. package/dist/types/CrossDomainAuth.d.ts +0 -164
  160. package/dist/types/mixins/OxyServices.fedcm.d.ts +0 -331
  161. package/dist/types/mixins/OxyServices.silent.d.ts +0 -132
  162. package/dist/types/mixins/OxyServices.sso.d.ts +0 -138
  163. package/dist/types/utils/ssoEstablish.d.ts +0 -85
  164. package/dist/types/utils/ssoReturn.d.ts +0 -146
  165. package/src/AuthManager.ts +0 -1269
  166. package/src/AuthManagerTypes.ts +0 -86
  167. package/src/CrossDomainAuth.ts +0 -243
  168. package/src/__tests__/authManager.cookiePath.test.ts +0 -390
  169. package/src/__tests__/authManager.security.test.ts +0 -377
  170. package/src/__tests__/crossDomainAuth.test.ts +0 -116
  171. package/src/__tests__/establishDeviceRefreshSlot.test.ts +0 -221
  172. package/src/mixins/OxyServices.fedcm.ts +0 -1026
  173. package/src/mixins/OxyServices.redirect.ts +0 -122
  174. package/src/mixins/OxyServices.silent.ts +0 -272
  175. package/src/mixins/OxyServices.sso.ts +0 -261
  176. package/src/mixins/__tests__/constructorAuthWebUrl.test.ts +0 -85
  177. package/src/mixins/__tests__/fedcm.test.ts +0 -667
  178. package/src/mixins/__tests__/sessionBaseUrl.test.ts +0 -61
  179. package/src/mixins/__tests__/silent.test.ts +0 -102
  180. package/src/mixins/__tests__/sso.test.ts +0 -228
  181. package/src/utils/__tests__/consumeSsoReturn.test.ts +0 -816
  182. package/src/utils/__tests__/ssoBounce.test.ts +0 -219
  183. package/src/utils/__tests__/ssoEstablish.test.ts +0 -204
  184. package/src/utils/__tests__/ssoReturn.test.ts +0 -251
  185. package/src/utils/ssoEstablish.ts +0 -174
  186. package/src/utils/ssoReturn.ts +0 -372
@@ -1,174 +0,0 @@
1
- /**
2
- * Post-claim durable-session establish hop (web device-flow / "Sign in with
3
- * Oxy" QR).
4
- *
5
- * A WEB device-flow claim (`claimSessionByToken`) plants only IN-MEMORY tokens:
6
- * unlike a redirect/FedCM/silent sign-in, it never causes the IdP to plant a
7
- * `fedcm_session` cookie. So a reload has nothing to restore from — the
8
- * silent-iframe and `/sso` paths find no IdP session and the session is lost.
9
- *
10
- * This primitive closes that gap. AFTER the claim has committed and the session
11
- * has been durably persisted, it performs ONE top-level establish hop through
12
- * the RP's own per-apex IdP host (`auth.<rp-apex>`), reusing the EXISTING
13
- * `/sso/establish` endpoint: the server mints a short-lived, host+audience-bound
14
- * establish-token and returns a fully-formed establish URL; navigating to it
15
- * plants the durable first-party `fedcm_session` cookie and bounces back to the
16
- * RP callback with an opaque code the standard `sso-return` cold-boot step
17
- * exchanges.
18
- *
19
- * It reuses the SAME per-origin `sessionStorage` bounce contract
20
- * (`ssoStateKey` / `ssoGuardKey` / `ssoDestKey`) that {@link buildSsoBounceUrl}
21
- * primes for the terminal `/sso` bounce, so the post-bounce `sso-return` step
22
- * (`consumeSsoReturn`) validates the CSRF `state`, exchanges the code, and
23
- * restores the user's real destination with no extra wiring.
24
- *
25
- * Contract:
26
- * - WEB only — off-web / native it is a no-op returning `false`.
27
- * - NEVER fires while sitting on the central IdP origin (that would loop the
28
- * IdP against itself).
29
- * - Bounce state is persisted ONLY after the establish-URL request succeeds, so
30
- * a failed request leaves no stale state behind.
31
- * - SINGLE attempt: the caller invokes this exactly once per successful claim.
32
- * On ANY failure it does NOT navigate and returns `false`, leaving the
33
- * committed in-memory session exactly as-is (the user is no worse off than
34
- * before this hop existed).
35
- * - Total: never throws. Failures are reported via {@link deps.onError} only.
36
- */
37
-
38
- import {
39
- ssoStateKey,
40
- ssoGuardKey,
41
- ssoDestKey,
42
- ssoNavigate,
43
- isCentralIdPOrigin,
44
- } from './ssoBounce';
45
- import { generateSsoState } from '../mixins/OxyServices.sso';
46
-
47
- /**
48
- * The minimal SDK surface this hop needs: mint a server-formed establish URL
49
- * bound to the caller's own session for an approved RP origin. Structural so the
50
- * primitive is unit-testable with a stub and never imports the full client.
51
- */
52
- export interface SsoEstablishClient {
53
- requestSsoEstablishUrl(
54
- origin: string,
55
- state: string,
56
- ): Promise<{ establishUrl: string }>;
57
- }
58
-
59
- /**
60
- * Injectable web seams for {@link establishIdpSessionAfterClaim}. Every seam is
61
- * overridable so the primitive is fully unit-testable with fakes and so native
62
- * callers rely on the defaults (which resolve to `window.*` only when a browser
63
- * is present). Defaults are evaluated lazily inside the function so importing
64
- * this module never touches `window`.
65
- */
66
- export interface EstablishAfterClaimDeps {
67
- /** Per-tab SSO bounce store. Default: `window.sessionStorage`. */
68
- storage?: Pick<Storage, 'getItem' | 'setItem'>;
69
- /** The current location. Default: `window.location`. */
70
- location?: Pick<Location, 'origin' | 'href'>;
71
- /** Top-level navigation seam. Default: {@link ssoNavigate} (`location.assign`). */
72
- navigate?: (url: string) => void;
73
- /**
74
- * Whether the current environment is a web browser with usable
75
- * `sessionStorage`. Default: `typeof window !== 'undefined' && typeof
76
- * window.sessionStorage !== 'undefined'`.
77
- */
78
- isWeb?: () => boolean;
79
- /** CSRF state generator. Default: {@link generateSsoState}. */
80
- generateState?: () => string;
81
- /** Epoch-ms clock for the bounce guard. Default: `Date.now`. */
82
- now?: () => number;
83
- /**
84
- * Optional debug hook invoked with the thrown error when the establish
85
- * request (or state persistence) fails. NEVER rethrown. Default: no-op.
86
- */
87
- onError?: (error: unknown) => void;
88
- }
89
-
90
- /**
91
- * Perform the post-claim establish hop. Returns `true` when a navigation to the
92
- * establish URL was initiated (the document is being torn down and replaced by
93
- * the IdP), `false` on every no-op / failure path.
94
- *
95
- * @param client - The exchange surface (`oxyServices.requestSsoEstablishUrl`).
96
- * @param deps - Injectable web seams; see {@link EstablishAfterClaimDeps}.
97
- */
98
- export async function establishIdpSessionAfterClaim(
99
- client: SsoEstablishClient,
100
- deps: EstablishAfterClaimDeps = {},
101
- ): Promise<boolean> {
102
- const isWeb =
103
- deps.isWeb ??
104
- (() =>
105
- typeof window !== 'undefined' &&
106
- typeof window.sessionStorage !== 'undefined');
107
-
108
- if (!isWeb()) {
109
- return false;
110
- }
111
-
112
- const storage = deps.storage ?? window.sessionStorage;
113
- const location = deps.location ?? window.location;
114
- const navigate = deps.navigate ?? ssoNavigate;
115
- const generateState = deps.generateState ?? generateSsoState;
116
- const now = deps.now ?? (() => Date.now());
117
-
118
- const origin = location.origin;
119
-
120
- // Never establish while sitting on the central IdP itself — that would bounce
121
- // the IdP against itself. (The device-flow claim can only happen on an RP.)
122
- if (isCentralIdPOrigin(origin)) {
123
- return false;
124
- }
125
-
126
- const state = generateState();
127
-
128
- let establishUrl: string;
129
- try {
130
- const result = await client.requestSsoEstablishUrl(origin, state);
131
- if (
132
- !result ||
133
- typeof result.establishUrl !== 'string' ||
134
- result.establishUrl.length === 0
135
- ) {
136
- return false;
137
- }
138
- establishUrl = result.establishUrl;
139
-
140
- // Defense-in-depth before a TOP-LEVEL navigation: the establish URL is
141
- // server-formed, but never follow anything that is not a well-formed https
142
- // `/sso/establish` on an `auth.` host. A malformed or unexpected URL aborts
143
- // silently (no navigation, no state persisted) — same total/no-throw
144
- // contract — rather than navigating the document somewhere unintended.
145
- let parsedEstablishUrl: URL;
146
- try {
147
- parsedEstablishUrl = new URL(establishUrl);
148
- } catch {
149
- return false;
150
- }
151
- if (
152
- parsedEstablishUrl.protocol !== 'https:' ||
153
- parsedEstablishUrl.pathname !== '/sso/establish' ||
154
- !parsedEstablishUrl.hostname.toLowerCase().startsWith('auth.')
155
- ) {
156
- return false;
157
- }
158
-
159
- // Persist the bounce state ONLY now that the request has succeeded and the
160
- // URL is validated — so a failed/rejected request never leaves stale state
161
- // behind. This is the exact contract the terminal `/sso` bounce primes via
162
- // `buildSsoBounceUrl`, so the post-bounce `sso-return` step (`consumeSsoReturn`)
163
- // validates `state`, exchanges the returned code, and restores the dest.
164
- storage.setItem(ssoStateKey(origin), state);
165
- storage.setItem(ssoGuardKey(origin), String(now()));
166
- storage.setItem(ssoDestKey(origin), location.href);
167
- } catch (error) {
168
- deps.onError?.(error);
169
- return false;
170
- }
171
-
172
- navigate(establishUrl);
173
- return true;
174
- }
@@ -1,372 +0,0 @@
1
- /**
2
- * Parse the SSO return fragment delivered by the central IdP.
3
- *
4
- * After a top-level redirect bounce to `auth.oxy.so/sso` (prompt=none), the
5
- * central IdP returns the Relying Party to its `redirect_uri` with the result
6
- * encoded in the URL fragment (the `#…` part). The fragment is used — not a
7
- * query string — so the opaque single-use code never reaches a server access
8
- * log, a `Referer` header, or browser history in a recoverable form.
9
- *
10
- * Three outcomes are possible:
11
- * - `#oxy_sso=ok&code=<opaque>&state=<state>` — the IdP had a session; the RP
12
- * exchanges `code` (via `oxy.exchangeSsoCode`) for the real session. NO
13
- * token/JWT ever appears in the URL — only the opaque code.
14
- * - `#oxy_sso=none&state=<state>` — the IdP had no session (prompt=none, user
15
- * not signed in centrally). The RP shows its own signed-out UI.
16
- * - `#oxy_sso=error&state=<state>` — the bounce failed. The RP recovers.
17
- *
18
- * This parser is pure and defensive: it never throws, and `kind` is strictly
19
- * one of `'ok' | 'none' | 'error'`. It returns `null` when the fragment is not
20
- * an oxy_sso fragment at all (i.e. `oxy_sso` is absent or an unrecognised
21
- * value), so the caller can ignore unrelated fragments without special-casing.
22
- */
23
-
24
- import type { SessionLoginResponse } from '../models/session';
25
- import {
26
- SSO_CALLBACK_PATH,
27
- ssoStateKey,
28
- ssoGuardKey,
29
- ssoDestKey,
30
- ssoNoSessionKey,
31
- ssoAttemptedKey,
32
- ssoCallbackBootstrapKey,
33
- } from './ssoBounce';
34
-
35
- /**
36
- * The recognised outcomes of an SSO bounce.
37
- */
38
- export type SsoReturnKind = 'ok' | 'none' | 'error';
39
-
40
- /**
41
- * The parsed result of an SSO return fragment.
42
- *
43
- * `code` is present only for `kind: 'ok'`. `state` echoes the CSRF state the RP
44
- * generated for the bounce (when the IdP round-tripped it).
45
- */
46
- export interface SsoReturnResult {
47
- kind: SsoReturnKind;
48
- code?: string;
49
- state?: string;
50
- }
51
-
52
- const VALID_KINDS: ReadonlySet<string> = new Set<SsoReturnKind>(['ok', 'none', 'error']);
53
-
54
- /**
55
- * Parse an SSO return fragment.
56
- *
57
- * @param hash - The URL fragment, with or without the leading `#`
58
- * (e.g. `location.hash`). May be `undefined`/empty.
59
- * @returns The parsed result when `hash` is a recognised oxy_sso fragment,
60
- * otherwise `null`. Never throws.
61
- */
62
- export function parseSsoReturnFragment(hash: string | undefined | null): SsoReturnResult | null {
63
- if (typeof hash !== 'string' || hash.length === 0) {
64
- return null;
65
- }
66
-
67
- // Strip a single leading '#'. A bare '#' (empty fragment) yields no params.
68
- const raw = hash.startsWith('#') ? hash.slice(1) : hash;
69
- if (raw.length === 0) {
70
- return null;
71
- }
72
-
73
- let params: URLSearchParams;
74
- try {
75
- params = new URLSearchParams(raw);
76
- } catch {
77
- // URLSearchParams does not throw for malformed input in practice, but guard
78
- // against any environment/polyfill that might so this stays total.
79
- return null;
80
- }
81
-
82
- const kind = params.get('oxy_sso');
83
- if (kind === null || !VALID_KINDS.has(kind)) {
84
- // Not an oxy_sso fragment (absent or unrecognised value) — ignore it.
85
- return null;
86
- }
87
-
88
- const result: SsoReturnResult = { kind: kind as SsoReturnKind };
89
-
90
- const state = params.get('state');
91
- if (state !== null && state.length > 0) {
92
- result.state = state;
93
- }
94
-
95
- // The opaque code is only meaningful on success; ignore any stray `code` on
96
- // none/error so callers never attempt an exchange for a non-ok outcome.
97
- if (result.kind === 'ok') {
98
- const code = params.get('code');
99
- if (code !== null && code.length > 0) {
100
- result.code = code;
101
- }
102
- }
103
-
104
- return result;
105
- }
106
-
107
- /**
108
- * Injectable dependencies for {@link consumeSsoReturn}.
109
- *
110
- * Every web seam (storage, location, history, web-detection) is injectable so
111
- * the function is fully unit-testable with fakes and so SSR / native callers
112
- * can supply their own (or rely on the defaults, which resolve to `window.*`
113
- * only when a browser is present). Defaults are evaluated lazily inside
114
- * `consumeSsoReturn` so importing this module never touches `window`.
115
- */
116
- export interface ConsumeSsoReturnDeps {
117
- /** Per-tab SSO state store. Default: `window.sessionStorage`. */
118
- storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
119
- /** The current location. Default: `window.location`. */
120
- location?: Pick<Location, 'hash' | 'origin' | 'pathname' | 'search'>;
121
- /** History API for fragment stripping / dest restore. Default: `window.history`. */
122
- history?: Pick<History, 'replaceState'>;
123
- /**
124
- * Whether the current environment is a web browser with usable
125
- * `sessionStorage`. Default: `typeof window !== 'undefined' && typeof
126
- * window.sessionStorage !== 'undefined'`.
127
- */
128
- isWeb?: () => boolean;
129
- /**
130
- * Optional debug hook invoked with the thrown error when the code exchange
131
- * fails. NEVER rethrown — `consumeSsoReturn` is total. Default: no-op.
132
- */
133
- onExchangeError?: (error: unknown) => void;
134
- /**
135
- * Notify URL-driven routers (Expo Router / React Navigation web) that the
136
- * location changed via `history.replaceState`, which does NOT itself emit
137
- * `popstate`. Default: dispatch a real `PopStateEvent` on `window` when
138
- * present; no-op off-web. Called ONLY after a successful same-origin
139
- * dest restore on the `ok` path (never when the dest is rejected/absent).
140
- * NEVER throws.
141
- */
142
- dispatchPopState?: () => void;
143
- /**
144
- * Hard, full-document navigation used to leave the internal callback path on
145
- * every NON-`ok` outcome (`none`/`error`, state-mismatch, missing code,
146
- * failed exchange, missing sessionId). A SOFT `history.replaceState` +
147
- * synthetic `popstate` does NOT reliably make Expo Router / TanStack Router
148
- * re-resolve away from the 404 they have already rendered for the
149
- * unregistered callback route — so for these outcomes (where there is no
150
- * in-memory session to preserve) a full navigation is both safe and
151
- * guaranteed to clear the 404. Default: `window.location.replace(url)` when
152
- * present; feature-detected end to end so it never throws off-web.
153
- */
154
- hardRedirect?: (url: string) => void;
155
- }
156
-
157
- /**
158
- * Consume an SSO return: the commit-free, security-critical kernel of the
159
- * cross-domain SSO `sso-return` cold-boot step.
160
- *
161
- * This performs the CSRF/fragment/exchange/dest-restore/loop-breaker sequence
162
- * and RETURNS the exchanged session (or `null`). It deliberately does NOT
163
- * commit any UI/auth state — each provider commits its own way AROUND this
164
- * (e.g. `@oxyhq/services` `OxyContext` calls its `handleWebSSOSession`,
165
- * `@oxyhq/auth` `WebOxyProvider` updates its React state). Hoisting the kernel
166
- * here keeps the two providers byte-for-byte identical on the parts that matter
167
- * for security (state validation, fragment stripping order, loop prevention).
168
- *
169
- * Security/loop invariants (preserved exactly from both former copies):
170
- * - The fragment is stripped via `history.replaceState` FIRST — before the
171
- * exchange — so the opaque code never lingers in the URL, browser history,
172
- * or a `Referer` header even if a later step throws.
173
- * - `state` must match (CSRF). A mismatch or a missing code sets the
174
- * NO_SESSION flag so `sso-bounce` is disabled (no rebounce loop).
175
- * - `none`/`error` outcomes set BOTH the NO_SESSION flag and the
176
- * outcome-independent attempted-flag (the load2 half of the loop proof).
177
- * - A throwing exchange is caught, reported via `onExchangeError`, and
178
- * treated exactly like "no session" (never loops, never rethrows).
179
- * - On EVERY consumed outcome (ok, none, error, state-mismatch, no-code,
180
- * failed-exchange, no-sessionId) — not just ok — if the page landed on
181
- * {@link SSO_CALLBACK_PATH}, the user is taken to a same-origin TARGET so
182
- * they are never stranded on the internal callback path (which is an
183
- * unregistered route in every consumer router → a hard 404). The target is
184
- * the stored DEST when it parses as same-origin (an attacker-planted
185
- * cross-origin / protocol-relative dest is rejected), ELSE the app root
186
- * (`origin + '/'`). The DEST key is removed unconditionally.
187
- * - For the `ok` outcome the target is applied via a SOFT
188
- * `history.replaceState` + synthetic `popstate` so the freshly exchanged
189
- * in-memory session the provider is about to commit is preserved (no
190
- * reload). `popstate` is dispatched only on the `ok` same-origin restore.
191
- * - For every NON-`ok` outcome there is no in-memory session to preserve, and
192
- * the consumer router has ALREADY synchronously rendered its 404 for the
193
- * unregistered callback route — a soft replaceState+popstate does not
194
- * reliably make it re-resolve. So these outcomes perform a HARD
195
- * full-document navigation to the target (`hardRedirect`), which is both
196
- * safe (nothing to lose) and guaranteed to clear the 404 in every router.
197
- *
198
- * Total: this function NEVER throws. Off-web it is a no-op returning `null`.
199
- *
200
- * @param oxy - The exchange surface (`oxyServices.exchangeSsoCode`).
201
- * @param deps - Injectable web seams; see {@link ConsumeSsoReturnDeps}.
202
- * @returns The exchanged session on success, otherwise `null`.
203
- */
204
- export async function consumeSsoReturn(
205
- oxy: { exchangeSsoCode: (code: string, state?: string) => Promise<SessionLoginResponse> },
206
- deps: ConsumeSsoReturnDeps = {},
207
- ): Promise<SessionLoginResponse | null> {
208
- const isWeb =
209
- deps.isWeb ??
210
- (() =>
211
- typeof window !== 'undefined' &&
212
- typeof window.sessionStorage !== 'undefined');
213
-
214
- if (!isWeb()) {
215
- return null;
216
- }
217
-
218
- const storage = deps.storage ?? window.sessionStorage;
219
- const location = deps.location ?? window.location;
220
- const history = deps.history ?? window.history;
221
- const onExchangeError = deps.onExchangeError;
222
-
223
- // Default: emit a synthetic `popstate` so URL-driven routers re-sync after a
224
- // `history.replaceState` (which does NOT emit `popstate` on its own). Feature-
225
- // detected end to end so it never throws in any environment.
226
- const dispatchPopState =
227
- deps.dispatchPopState ??
228
- (() => {
229
- if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') {
230
- return;
231
- }
232
- if (typeof PopStateEvent !== 'undefined') {
233
- window.dispatchEvent(new PopStateEvent('popstate'));
234
- } else if (typeof Event !== 'undefined') {
235
- window.dispatchEvent(new Event('popstate'));
236
- }
237
- });
238
-
239
- // Default: a hard, full-document navigation used to leave the callback path
240
- // on non-`ok` outcomes. Feature-detected end to end so it never throws in any
241
- // environment (SSR / native / a stubbed location without `replace`).
242
- const hardRedirect =
243
- deps.hardRedirect ??
244
- ((url: string) => {
245
- if (
246
- typeof window !== 'undefined' &&
247
- window.location &&
248
- typeof window.location.replace === 'function'
249
- ) {
250
- window.location.replace(url);
251
- }
252
- });
253
-
254
- const ret = parseSsoReturnFragment(location.hash);
255
- if (!ret) {
256
- // Not an oxy_sso fragment — nothing to do (do NOT touch any flags).
257
- return null;
258
- }
259
-
260
- const origin = location.origin;
261
- const callbackBootstrapKey = ssoCallbackBootstrapKey(origin);
262
- const wasCallbackBootstrapped = storage.getItem(callbackBootstrapKey) === '1';
263
- const expectedState = storage.getItem(ssoStateKey(origin));
264
- const stateOk = !!ret.state && !!expectedState && ret.state === expectedState;
265
-
266
- // Strip the fragment FIRST so the opaque code never lingers in the address
267
- // bar, history, or a `Referer` — even if a later step throws.
268
- history.replaceState(null, '', location.pathname + location.search);
269
- storage.removeItem(ssoStateKey(origin));
270
-
271
- // The in-flight bounce is now resolved — drop its guard so a later cold boot
272
- // (e.g. after sign-out) can bounce again.
273
- storage.removeItem(ssoGuardKey(origin));
274
-
275
- const markNoSession = () => {
276
- storage.setItem(ssoNoSessionKey(origin), '1');
277
- // A return was consumed, so the probe definitively happened. Set the
278
- // outcome-independent attempted-flag too so the bounce can never re-fire
279
- // even if some consumer path skipped setting it pre-bounce.
280
- storage.setItem(ssoAttemptedKey(origin), '1');
281
- };
282
-
283
- // Compute the same-origin TARGET to leave the callback path for. Returns the
284
- // stored DEST when present AND it parses as same-origin (never honour a
285
- // cross-origin / protocol-relative dest that could have been planted to
286
- // redirect the user), ELSE the app root (`origin + '/'`) so the user is never
287
- // stranded on the internal callback path even when no dest was stored. The
288
- // DEST key is removed unconditionally. Returns the relative path+search+hash
289
- // (so it can be fed to either `history.replaceState` or a `hardRedirect`),
290
- // or `null` when the page is not on the callback path (nothing to leave).
291
- const consumeCallbackTarget = (): string | null => {
292
- storage.removeItem(callbackBootstrapKey);
293
- if (location.pathname !== SSO_CALLBACK_PATH && !wasCallbackBootstrapped) {
294
- // Not on the callback path — still drop the dest key (consumed) but there
295
- // is nothing to navigate away from.
296
- storage.removeItem(ssoDestKey(origin));
297
- return null;
298
- }
299
- const dest = storage.getItem(ssoDestKey(origin));
300
- storage.removeItem(ssoDestKey(origin));
301
- if (dest) {
302
- try {
303
- const destUrl = new URL(dest, origin);
304
- if (destUrl.origin === origin) {
305
- return destUrl.pathname + destUrl.search + destUrl.hash;
306
- }
307
- } catch {
308
- // Malformed stored destination — fall through to the app-root fallback.
309
- }
310
- }
311
- // No dest, a cross-origin/protocol-relative dest, or an unparseable dest:
312
- // fall back to the app root so the router always leaves the 404.
313
- return '/';
314
- };
315
-
316
- // Non-`ok` outcomes: there is no in-memory session to preserve, and the
317
- // consumer router has already rendered its 404 for the unregistered callback
318
- // route — a soft replaceState+popstate does not reliably make it re-resolve.
319
- // Perform a HARD full-document navigation to the target (safe: nothing to
320
- // lose; guaranteed: every router leaves the 404). Off the callback path this
321
- // is a no-op (target is null).
322
- const leaveCallbackHard = (): void => {
323
- const target = consumeCallbackTarget();
324
- if (target !== null) {
325
- hardRedirect(origin + target);
326
- }
327
- };
328
-
329
- if (ret.kind === 'none' || ret.kind === 'error') {
330
- // The central IdP had no session (or the bounce failed). Record it so we do
331
- // not bounce again this tab — the definitive loop breaker.
332
- markNoSession();
333
- leaveCallbackHard();
334
- return null;
335
- }
336
-
337
- if (!stateOk || !ret.code) {
338
- // Forged / replayed / stale fragment, or a malformed ok with no code. Treat
339
- // exactly like "no session": never exchange, never loop.
340
- markNoSession();
341
- leaveCallbackHard();
342
- return null;
343
- }
344
-
345
- let session: SessionLoginResponse | undefined;
346
- try {
347
- session = await oxy.exchangeSsoCode(ret.code, ret.state);
348
- } catch (error) {
349
- onExchangeError?.(error);
350
- markNoSession();
351
- leaveCallbackHard();
352
- return null;
353
- }
354
-
355
- if (!session?.sessionId) {
356
- markNoSession();
357
- leaveCallbackHard();
358
- return null;
359
- }
360
-
361
- // `ok`: the provider is about to commit the freshly exchanged in-memory
362
- // session — do NOT hard-redirect (a full navigation would discard it). Use a
363
- // SOFT `history.replaceState` to the target + a synthetic `popstate` so
364
- // URL-driven routers re-sync to the restored route without a reload.
365
- const target = consumeCallbackTarget();
366
- if (target !== null) {
367
- history.replaceState(null, '', target);
368
- dispatchPopState();
369
- }
370
-
371
- return session;
372
- }