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