@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,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OxyServicesRedirectAuthMixin = OxyServicesRedirectAuthMixin;
4
- exports.RedirectAuthMixin = OxyServicesRedirectAuthMixin;
5
- const OxyServices_errors_1 = require("../OxyServices.errors");
6
- const ssoBounce_1 = require("../utils/ssoBounce");
7
- /**
8
- * Redirect-based authentication without bearer tokens in URLs.
9
- *
10
- * The redirect fallback now uses the same central SSO code-return contract as
11
- * cold boot: the RP stores CSRF/destination state in sessionStorage, navigates
12
- * to the central IdP, receives only an opaque one-time code in the URL fragment,
13
- * and the provider's `sso-return` step exchanges that code for the real session.
14
- */
15
- function OxyServicesRedirectAuthMixin(Base) {
16
- return class extends Base {
17
- constructor(...args) {
18
- super(...args);
19
- }
20
- /**
21
- * Start a full-page redirect through the central SSO flow.
22
- *
23
- * No access token, refresh token, or session id is ever put in the URL or
24
- * localStorage. The caller's provider must run `consumeSsoReturn` on startup
25
- * to complete the code exchange and commit the session.
26
- */
27
- signInWithRedirect(options = {}) {
28
- if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') {
29
- throw new OxyServices_errors_1.OxyAuthenticationError('Redirect authentication requires browser sessionStorage');
30
- }
31
- const origin = window.location.origin;
32
- const state = this.generateState();
33
- const destination = options.preserveUrl === false
34
- ? (options.redirectUri || origin)
35
- : (options.redirectUri || window.location.href);
36
- window.sessionStorage.setItem((0, ssoBounce_1.ssoStateKey)(origin), state);
37
- window.sessionStorage.setItem((0, ssoBounce_1.ssoGuardKey)(origin), String(Date.now()));
38
- window.sessionStorage.setItem((0, ssoBounce_1.ssoDestKey)(origin), destination);
39
- window.sessionStorage.setItem((0, ssoBounce_1.ssoAttemptedKey)(origin), '1');
40
- window.location.assign((0, ssoBounce_1.buildSsoBounceUrl)(origin, state, this.config.authWebUrl));
41
- }
42
- signUpWithRedirect(options = {}) {
43
- this.signInWithRedirect({ ...options, mode: 'signup' });
44
- }
45
- /**
46
- * Legacy token-query callbacks are intentionally rejected. Modern providers
47
- * complete redirect auth through `consumeSsoReturn`, which accepts only
48
- * `#oxy_sso=ok&code=...`.
49
- */
50
- handleAuthCallback() {
51
- if (typeof window === 'undefined') {
52
- return null;
53
- }
54
- const url = new URL(window.location.href);
55
- if (url.searchParams.has('access_token') || url.searchParams.has('session_id')) {
56
- this.cleanAuthCallbackUrl(url);
57
- throw new OxyServices_errors_1.OxyAuthenticationError('Legacy access-token redirect callbacks are no longer accepted.');
58
- }
59
- return null;
60
- }
61
- restoreSession() {
62
- return false;
63
- }
64
- clearStoredSession() {
65
- this.httpService.clearTokens();
66
- }
67
- getStoredSessionId() {
68
- return null;
69
- }
70
- generateState() {
71
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
72
- return crypto.randomUUID();
73
- }
74
- if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
75
- const bytes = new Uint8Array(16);
76
- crypto.getRandomValues(bytes);
77
- return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
78
- }
79
- throw new Error('No secure random source available for state generation');
80
- }
81
- generateNonce() {
82
- return this.generateState();
83
- }
84
- cleanAuthCallbackUrl(url) {
85
- url.searchParams.delete('access_token');
86
- url.searchParams.delete('session_id');
87
- url.searchParams.delete('expires_at');
88
- url.searchParams.delete('state');
89
- url.searchParams.delete('nonce');
90
- url.searchParams.delete('error');
91
- url.searchParams.delete('error_description');
92
- window.history.replaceState({}, '', url.toString());
93
- }
94
- };
95
- }
@@ -1,204 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OxyServicesSilentAuthMixin = OxyServicesSilentAuthMixin;
4
- exports.SilentAuthMixin = OxyServicesSilentAuthMixin;
5
- const debugUtils_1 = require("../shared/utils/debugUtils");
6
- const debug = (0, debugUtils_1.createDebugLogger)("SilentAuth");
7
- /**
8
- * Cross-domain silent browser auth helpers.
9
- *
10
- * The clean session model supports FedCM, tokenless redirect SSO, and silent
11
- * iframe SSO. Bearer-token callback URLs are not part of this surface.
12
- */
13
- function OxyServicesSilentAuthMixin(Base) {
14
- var _a;
15
- return _a = class extends Base {
16
- constructor(...args) {
17
- super(...args);
18
- }
19
- /** Resolve auth URL from config or static default (method, not getter — getters break in TS mixins) */
20
- resolveAuthUrl() {
21
- return (this.config.authWebUrl || this.constructor.DEFAULT_AUTH_URL);
22
- }
23
- /**
24
- * Silent sign-in using hidden iframe
25
- *
26
- * Attempts to automatically re-authenticate the user without any UI.
27
- * This is what enables seamless SSO across all Oxy domains.
28
- *
29
- * How it works:
30
- * 1. Creates hidden iframe pointing to auth.oxy.so/silent-auth
31
- * 2. If user has valid session at auth.oxy.so, it exchanges an opaque SSO code
32
- * 3. If not, iframe responds with null (no error thrown)
33
- *
34
- * This should be called on app startup to check for existing sessions.
35
- *
36
- * @param options - Silent auth options
37
- * @returns Session if user is signed in, null otherwise
38
- *
39
- * @example
40
- * ```typescript
41
- * useEffect(() => {
42
- * const checkAuth = async () => {
43
- * const session = await oxyServices.silentSignIn();
44
- * if (session) {
45
- * setUser(session.user);
46
- * }
47
- * };
48
- * checkAuth();
49
- * }, []);
50
- * ```
51
- */
52
- async silentSignIn(options = {}) {
53
- if (typeof window === "undefined") {
54
- return null;
55
- }
56
- const timeout = options.timeout || this.constructor.SILENT_TIMEOUT;
57
- const nonce = this.generateNonce();
58
- const clientId = window.location.origin;
59
- // Resolve the IdP origin for the iframe. An explicit per-apex override (the
60
- // durable cross-domain reload path — see `SilentAuthOptions.authWebUrlOverride`)
61
- // wins over the instance's configured central auth URL. The SAME origin is
62
- // handed to `waitForIframeAuth` so the postMessage origin check matches the
63
- // exact host the iframe was loaded from.
64
- const authOrigin = options.authWebUrlOverride && options.authWebUrlOverride.length > 0
65
- ? options.authWebUrlOverride
66
- : this.resolveAuthUrl();
67
- const iframe = document.createElement("iframe");
68
- iframe.style.display = "none";
69
- iframe.style.position = "absolute";
70
- iframe.style.width = "0";
71
- iframe.style.height = "0";
72
- iframe.style.border = "none";
73
- const silentUrl = `${authOrigin}/auth/silent?` +
74
- `client_id=${encodeURIComponent(clientId)}&` +
75
- `nonce=${nonce}`;
76
- iframe.src = silentUrl;
77
- document.body.appendChild(iframe);
78
- try {
79
- const session = await this.waitForIframeAuth(iframe, timeout, authOrigin);
80
- // Bail early on incomplete responses. The iframe contract requires
81
- // both an access token and a session id; anything less is unusable.
82
- // Returning `null` here (without installing the token) prevents a
83
- // stale credential from being committed to HttpService when the
84
- // user is actually signed out — that pattern caused a `getCurrentUser`
85
- // -> 401 -> token-clear loop in consumer apps because callers gated
86
- // on `session?.user` and never installed the user via
87
- // `handleAuthSuccess`, while HttpService quietly held the token.
88
- const accessToken = session
89
- ? session.accessToken
90
- : undefined;
91
- if (!session || !accessToken || !session.sessionId) {
92
- return null;
93
- }
94
- // Snapshot the previous token so we can roll back if the user
95
- // lookup below fails — this avoids leaving a half-committed session
96
- // (token installed, user missing) which would let the next
97
- // authenticated request 401 with no way to recover.
98
- const previousAccessToken = this.httpService.getAccessToken();
99
- this.httpService.setTokens(accessToken);
100
- // The iframe typically returns `{ sessionId, accessToken }` without
101
- // user data. Fetch the user explicitly so callers receive a
102
- // fully-formed session and never need a second `/users/me` round
103
- // trip. If this fails the session is unusable — revert the token
104
- // and return null so the caller treats this exactly like a
105
- // missing-session response.
106
- if (!session.user) {
107
- try {
108
- const userData = await this.makeRequest("GET", `/session/user/${session.sessionId}`, undefined, { cache: false, retry: false });
109
- if (!userData) {
110
- throw new Error("Empty user response");
111
- }
112
- session.user = userData;
113
- }
114
- catch (userError) {
115
- debug.warn("silentSignIn: failed to fetch user data, rolling back token", userError);
116
- if (previousAccessToken) {
117
- this.httpService.setTokens(previousAccessToken);
118
- }
119
- else {
120
- this.httpService.clearTokens();
121
- }
122
- return null;
123
- }
124
- }
125
- return session;
126
- }
127
- catch (error) {
128
- return null;
129
- }
130
- finally {
131
- document.body.removeChild(iframe);
132
- }
133
- }
134
- /**
135
- * Wait for authentication response from iframe
136
- *
137
- * @private
138
- */
139
- async waitForIframeAuth(iframe, timeout, expectedOrigin) {
140
- return new Promise((resolve) => {
141
- const timeoutId = setTimeout(() => {
142
- cleanup();
143
- resolve(null); // Silent failure - don't throw
144
- }, timeout);
145
- const messageHandler = (event) => {
146
- // Verify origin against the EXACT host the iframe was loaded from
147
- // (`expectedOrigin`). For the per-apex durable-restore path this is
148
- // `auth.<rp-apex>`, not the instance's central `resolveAuthUrl()` — so
149
- // we must honour the caller-supplied origin, never re-derive it here.
150
- if (event.origin !== expectedOrigin) {
151
- return;
152
- }
153
- const { type, session } = event.data;
154
- if (type !== "oxy_silent_auth") {
155
- return;
156
- }
157
- cleanup();
158
- resolve(session || null);
159
- };
160
- // Fail-fast on a load failure. When the per-apex `/auth/silent` host is
161
- // unreachable, blocked by CSP `frame-ancestors`/`X-Frame-Options`, or the
162
- // network drops, the iframe never posts a message — without this handler
163
- // the silent restore would block for the FULL `timeout` (dead latency in
164
- // the cold-boot critical path). `onerror`/`onabort` fire on a failed load,
165
- // so resolve `null` immediately and let the next cold-boot step run. The
166
- // success path posts a message and is handled above; these only catch the
167
- // no-message failure modes.
168
- const failFast = () => {
169
- cleanup();
170
- resolve(null);
171
- };
172
- iframe.onerror = failFast;
173
- iframe.onabort = failFast;
174
- const cleanup = () => {
175
- clearTimeout(timeoutId);
176
- iframe.onerror = null;
177
- iframe.onabort = null;
178
- window.removeEventListener("message", messageHandler);
179
- };
180
- window.addEventListener("message", messageHandler);
181
- });
182
- }
183
- /**
184
- * Generate nonce for replay attack prevention
185
- *
186
- * @private
187
- */
188
- generateNonce() {
189
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
190
- return crypto.randomUUID();
191
- }
192
- if (typeof crypto !== "undefined" && crypto.getRandomValues) {
193
- const bytes = new Uint8Array(16);
194
- crypto.getRandomValues(bytes);
195
- return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
196
- }
197
- throw new Error("No secure random source available for nonce generation");
198
- }
199
- },
200
- _a.DEFAULT_AUTH_URL = "https://auth.oxy.so",
201
- _a.SILENT_TIMEOUT = 5000 // 5 seconds
202
- ,
203
- _a;
204
- }
@@ -1,208 +0,0 @@
1
- "use strict";
2
- /**
3
- * Central Cross-Domain SSO (opaque-code) Mixin
4
- *
5
- * Implements the Relying-Party half of TRUE central cross-domain SSO
6
- * (Google/Meta/Clerk style). The central IdP at `auth.oxy.so` owns the session;
7
- * an RP bounces a top-level redirect (prompt=none) to `auth.oxy.so/sso`, which
8
- * returns an OPAQUE single-use code in the redirect fragment. The RP then
9
- * exchanges that code here for the real session.
10
- *
11
- * Security properties:
12
- * - NO token/JWT ever travels in a URL — only the opaque code does. The real
13
- * `accessToken` is delivered exclusively in this exchange response body.
14
- * - The exchange is a CORS POST with NO credentials/cookies — the opaque code
15
- * is the only bearer of authority, and the central store burns it atomically
16
- * (single-use). Sending no cookies keeps the request a clean, ambient-
17
- * authority-free bearer exchange that the central `POST /sso/exchange`
18
- * endpoint validates by `Origin` against the code's bound `clientOrigin`.
19
- * - The code is minted server-side bound to the RP origin and expires in
20
- * seconds, so a leaked code is useless cross-origin and short-lived.
21
- *
22
- * On success the mixin plants the returned access token via
23
- * `httpService.setTokens(...)` — mirroring `exchangeIdTokenForSession` /
24
- * `verifyChallenge` — so callers do NOT need to plant tokens manually.
25
- */
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.generateSsoState = generateSsoState;
28
- exports.OxyServicesSsoMixin = OxyServicesSsoMixin;
29
- const debugUtils_1 = require("../shared/utils/debugUtils");
30
- const ssoBounce_1 = require("../utils/ssoBounce");
31
- const debug = (0, debugUtils_1.createDebugLogger)('SSO');
32
- /**
33
- * Generate a cryptographically secure state value for the SSO bounce.
34
- *
35
- * Exposed as a module-level helper (in addition to the instance method below)
36
- * so consumers that do not yet hold an `OxyServices` instance can still mint a
37
- * bounce state. Uses `crypto.randomUUID` with a `getRandomValues` fallback.
38
- */
39
- function generateSsoState() {
40
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
41
- return crypto.randomUUID();
42
- }
43
- if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
44
- const bytes = new Uint8Array(16);
45
- crypto.getRandomValues(bytes);
46
- return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
47
- }
48
- throw new Error('No secure random source available for SSO state generation');
49
- }
50
- /**
51
- * Read the SSO bounce state stored for the current browser origin, if any.
52
- *
53
- * Returns `null` outside a browser (no `window`/`sessionStorage`) or when no
54
- * state is stored — in which case the caller cannot (and must not) enforce a
55
- * state match, e.g. native flows or pre-hydration callbacks that already
56
- * validated the state before this exchange.
57
- */
58
- function getStoredSsoStateForCurrentOrigin() {
59
- if (typeof window === 'undefined' || !window.location || !window.sessionStorage) {
60
- return null;
61
- }
62
- try {
63
- return window.sessionStorage.getItem((0, ssoBounce_1.ssoStateKey)(window.location.origin));
64
- }
65
- catch {
66
- return null;
67
- }
68
- }
69
- function OxyServicesSsoMixin(Base) {
70
- return class extends Base {
71
- constructor(...args) {
72
- super(...args);
73
- }
74
- /**
75
- * Generate cryptographically secure state for the SSO bounce (CSRF
76
- * protection). Delegates to the module-level {@link generateSsoState}
77
- * helper, which uses `crypto.randomUUID` when available and falls back to
78
- * `crypto.getRandomValues`.
79
- */
80
- generateSsoState() {
81
- return generateSsoState();
82
- }
83
- /**
84
- * Exchange an opaque single-use SSO code for the real Oxy session.
85
- *
86
- * POSTs `{ code }` to `${getSessionBaseUrl()}/sso/exchange` as a CORS
87
- * request with NO credentials/cookies. On success the returned access token
88
- * is planted via `httpService.setTokens(...)` (matching
89
- * `exchangeIdTokenForSession` / `verifyChallenge`), so callers do not need
90
- * to plant tokens manually.
91
- *
92
- * @param code - The opaque single-use code delivered in the SSO return
93
- * fragment (see {@link parseSsoReturnFragment}). The central store burns
94
- * it atomically on exchange.
95
- * @param state - The state value returned alongside the code. In browsers,
96
- * when an SSO bounce state is still stored for the current origin, this
97
- * must match before any token-committing exchange is attempted.
98
- * @returns The resolved {@link SessionLoginResponse}.
99
- */
100
- async exchangeSsoCode(code, state) {
101
- if (typeof code !== 'string' || code.length === 0) {
102
- throw this.handleError(new Error('exchangeSsoCode requires a non-empty code'));
103
- }
104
- const expectedState = getStoredSsoStateForCurrentOrigin();
105
- if (expectedState !== null && (typeof state !== 'string' || state.length === 0 || state !== expectedState)) {
106
- throw this.handleError(new Error('SSO exchange state mismatch'));
107
- }
108
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/sso/exchange`;
109
- debug.log('Exchanging SSO code for session...');
110
- let response;
111
- try {
112
- response = await fetch(url, {
113
- method: 'POST',
114
- // No cookies: the opaque code is the sole bearer of authority and the
115
- // server validates by Origin against the code's bound clientOrigin.
116
- credentials: 'omit',
117
- headers: {
118
- 'Content-Type': 'application/json',
119
- Accept: 'application/json',
120
- },
121
- body: JSON.stringify({ code }),
122
- });
123
- }
124
- catch (error) {
125
- debug.error('SSO exchange request failed:', error instanceof Error ? error.message : String(error));
126
- throw this.handleError(error);
127
- }
128
- if (!response.ok) {
129
- throw this.handleError(new Error(`SSO exchange failed with HTTP ${response.status}`));
130
- }
131
- let payload;
132
- try {
133
- payload = (await response.json());
134
- }
135
- catch (error) {
136
- throw this.handleError(error);
137
- }
138
- if (!payload || typeof payload.accessToken !== 'string' || payload.accessToken.length === 0) {
139
- throw this.handleError(new Error('SSO exchange returned no access token'));
140
- }
141
- if (typeof payload.sessionId !== 'string' || payload.sessionId.length === 0) {
142
- throw this.handleError(new Error('SSO exchange returned no sessionId'));
143
- }
144
- const userId = payload.user?.id ?? payload.user?._id;
145
- if (!userId || typeof payload.user?.username !== 'string') {
146
- throw this.handleError(new Error('SSO exchange returned an invalid user'));
147
- }
148
- const user = {
149
- id: userId,
150
- username: payload.user.username,
151
- // `name.displayName` is optional on the contract. A no-name user is
152
- // valid; carry whatever structured name the server sent (possibly an
153
- // empty object) and let consumers fall back to a handle.
154
- name: payload.user.name ?? {},
155
- avatar: payload.user.avatar,
156
- };
157
- // Plant the access token exactly like exchangeIdTokenForSession does.
158
- // The SSO exchange does not return a refresh token (the central store
159
- // holds the refresh credential), so default it to an empty string.
160
- this.httpService.setTokens(payload.accessToken);
161
- debug.log('SSO exchange complete:', { hasSession: !!payload.sessionId });
162
- const session = {
163
- sessionId: payload.sessionId,
164
- deviceId: '',
165
- expiresAt: payload.expiresAt ?? '',
166
- user,
167
- accessToken: payload.accessToken,
168
- };
169
- return session;
170
- }
171
- /**
172
- * Mint a server-formed `/sso/establish` URL for the caller's OWN session,
173
- * bound to an approved RP `origin`.
174
- *
175
- * Bearer-authenticated (the session id is taken from the caller's own
176
- * bearer, server-side — never from any argument). The server validates that
177
- * `origin` is an approved client origin (and matches the request `Origin`),
178
- * derives the per-apex IdP host (`auth.<apex>`), mints a short-lived HS256
179
- * establish-token, and returns a fully-formed
180
- * `https://<auth-host>/sso/establish?et=…&return_to=<origin>/__oxy/sso-callback&state=<state>`.
181
- *
182
- * Used AFTER a web device-flow claim to plant the durable first-party
183
- * `fedcm_session` cookie so a reload can re-mint a token (see
184
- * {@link establishIdpSessionAfterClaim}). Cache-free (a POST is never
185
- * cached, but `cache: false` is explicit).
186
- *
187
- * @param origin - The RP origin (`window.location.origin`) to establish for.
188
- * @param state - The CSRF state echoed back in the callback fragment; the
189
- * caller persists the SAME value under `ssoStateKey(origin)` so the
190
- * post-bounce `sso-return` step validates it.
191
- */
192
- async requestSsoEstablishUrl(origin, state) {
193
- if (typeof origin !== 'string' || origin.length === 0) {
194
- throw this.handleError(new Error('requestSsoEstablishUrl requires a non-empty origin'));
195
- }
196
- if (typeof state !== 'string' || state.length === 0) {
197
- throw this.handleError(new Error('requestSsoEstablishUrl requires a non-empty state'));
198
- }
199
- const response = await this.makeRequest('POST', '/sso/establish-token', { origin, state }, { cache: false });
200
- if (!response ||
201
- typeof response.establishUrl !== 'string' ||
202
- response.establishUrl.length === 0) {
203
- throw this.handleError(new Error('SSO establish-token returned no establishUrl'));
204
- }
205
- return { establishUrl: response.establishUrl };
206
- }
207
- };
208
- }
@@ -1,99 +0,0 @@
1
- "use strict";
2
- /**
3
- * Auto-detect the FAPI (IdP) URL from the current browser hostname.
4
- *
5
- * This is the canonical cross-domain IdP-resolution primitive for the Oxy
6
- * ecosystem. Both candidate cross-domain SSO designs derive `auth.<rp-apex>`
7
- * through this helper; do not fork it.
8
- *
9
- * Clerk-style multi-domain SSO depends on the IdP being reachable on a
10
- * subdomain of the RP's own apex (e.g. `auth.mention.earth` CNAMEd to the
11
- * central Oxy IdP). That way every FedCM endpoint, the session cookie,
12
- * and any redirect target are same-site with the RP — the only way
13
- * to get first-party cookies in Safari ITP and Firefox Total Cookie
14
- * Protection.
15
- *
16
- * This helper computes `https://auth.<rp-apex>` from
17
- * `window.location.hostname` so a consuming app doesn't have to pass
18
- * `authWebUrl` explicitly. Returns `undefined` for environments where
19
- * auto-detection would be wrong:
20
- *
21
- * - SSR / non-browser (no `window`).
22
- * - `localhost`, `127.0.0.1`, IPv4/IPv6 literals.
23
- * - Hostnames with fewer than two labels.
24
- * - Hostnames where a registrable domain cannot be determined from the
25
- * Public Suffix List, including private hosted suffixes such as
26
- * `github.io`, `pages.dev`, and `netlify.app`.
27
- *
28
- * When the page is already loaded ON the IdP itself (`auth.<anything>`),
29
- * the helper returns the current origin so the SDK keeps everything
30
- * same-origin instead of hopping to a different IdP host.
31
- *
32
- * The IdP backend independently derives `iss`, `provider_urls`, and the
33
- * `fedcm.json` icon URLs from the request host
34
- * (`packages/auth/server/index.ts`), so an honest CNAME pair is all that
35
- * is required for end-to-end FedCM correctness — no per-RP config.
36
- */
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.registrableApex = registrableApex;
39
- exports.autoDetectAuthWebUrl = autoDetectAuthWebUrl;
40
- const tldts_1 = require("tldts");
41
- /**
42
- * Compute the bare registrable apex (eTLD+1) of a hostname using the Public
43
- * Suffix List, including private hosted suffixes.
44
- *
45
- * This is the pure host-handling kernel shared by {@link autoDetectAuthWebUrl}
46
- * and the IdP worker — it performs NO protocol handling, NO `auth.` prefixing,
47
- * and builds NO URL. It only answers "what is the registrable domain of this
48
- * host, or is that undefinable?".
49
- *
50
- * Returns `null` (apex undefinable) for:
51
- * - empty input;
52
- * - IPv4 literals (`192.168.1.10`);
53
- * - IPv6 literals or any host carrying a port (`[::1]`, anything with `:`);
54
- * - single-label hosts (`intranet`, `localhost`);
55
- * - public suffixes without a registrable label (e.g. `co.uk`, `github.io`).
56
- *
57
- * @param hostname - A bare hostname (no scheme), e.g. `www.mention.earth`.
58
- * @returns The eTLD+1 (`mention.earth`), or `null` when undefinable.
59
- */
60
- function registrableApex(hostname) {
61
- if (!hostname)
62
- return null;
63
- const host = hostname.toLowerCase();
64
- if (/^\d+\.\d+\.\d+\.\d+$/.test(host))
65
- return null;
66
- // IPv6 literals are bracketed; any remaining ':' implies a port — neither
67
- // yields a registrable apex.
68
- if (host.startsWith('[') || host.includes(':'))
69
- return null;
70
- // The Public Suffix List (private suffixes included) is the source of truth
71
- // for what an attacker can register. A multi-part public suffix like `co.uk`
72
- // or a hosted suffix like `github.io` returns no registrable domain, so
73
- // deriving `auth.<apex>` against it is impossible — `getDomain` returns null.
74
- return (0, tldts_1.getDomain)(host, { allowPrivateDomains: true });
75
- }
76
- function autoDetectAuthWebUrl(location = typeof window !== 'undefined' ? window.location : undefined) {
77
- if (!location)
78
- return undefined;
79
- const { hostname, protocol } = location;
80
- if (!hostname)
81
- return undefined;
82
- if (protocol !== 'https:' && protocol !== 'http:')
83
- return undefined;
84
- if (hostname === 'localhost' || hostname === '127.0.0.1')
85
- return undefined;
86
- if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname))
87
- return undefined;
88
- if (hostname.startsWith('['))
89
- return undefined;
90
- // Already ON the IdP — keep everything same-origin instead of hopping to a
91
- // sibling host.
92
- if (hostname.startsWith('auth.')) {
93
- return `${protocol}//${hostname}`;
94
- }
95
- const apex = registrableApex(hostname);
96
- if (apex === null)
97
- return undefined;
98
- return `${protocol}//auth.${apex}`;
99
- }