@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,3 +1,4 @@
1
+ import { loginResultSchema, safeParseContract } from '@oxyhq/contracts';
1
2
  import { OxyAuthenticationError } from '../OxyServices.errors.js';
2
3
  import { KeyManager } from '../crypto/keyManager.js';
3
4
  import { SignatureService } from '../crypto/signatureService.js';
@@ -613,207 +614,6 @@ export function OxyServicesAuthMixin(Base) {
613
614
  throw this.handleError(error);
614
615
  }
615
616
  }
616
- /**
617
- * Refresh every device-local refresh-cookie slot in a single round trip
618
- * (Google-style multi-account rebuild).
619
- *
620
- * Calls `POST {sessionBaseUrl}/auth/refresh-all` with `credentials: 'include'`
621
- * and NO bearer. The browser attaches every indexed `oxy_rt_${authuser}`
622
- * cookie it has; the server rotates each in parallel and returns one entry
623
- * per VALID account.
624
- *
625
- * Failure handling:
626
- * - 401 → no signed-in accounts on this device → returns `{ accounts: [] }`
627
- * (NOT an error; this is the cold-boot "not signed in" path).
628
- * - 404 → endpoint not deployed → returns `{ accounts: [] }`.
629
- * - Any other non-2xx → throws via `handleError`.
630
- *
631
- * The refresh cookie itself never enters JS — only the rotated access
632
- * tokens do. Each access token still needs to be planted via
633
- * `setTokens(...)` (or per-account in-memory storage) at the consumer.
634
- */
635
- async refreshAllSessions(options = {}) {
636
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/refresh-all`;
637
- // Optional bounded abort (see `RefreshAllOptions.timeout`). A positive
638
- // timeout arms an `AbortController` that aborts the in-flight request; an
639
- // abort is treated as "no signed-in accounts on this device" — the same
640
- // outcome as a 401 — so a cross-domain stall falls through cleanly instead
641
- // of hanging the cold boot.
642
- const timeout = typeof options.timeout === 'number' && options.timeout > 0 ? options.timeout : undefined;
643
- const controller = timeout !== undefined ? new AbortController() : undefined;
644
- const timeoutId = timeout !== undefined && controller
645
- ? setTimeout(() => controller.abort(), timeout)
646
- : undefined;
647
- let response;
648
- try {
649
- response = await fetch(url, {
650
- method: 'POST',
651
- credentials: 'include',
652
- headers: { Accept: 'application/json' },
653
- signal: controller?.signal,
654
- });
655
- }
656
- catch (error) {
657
- // A bounded-timeout abort is the "not signed in / cross-domain stall"
658
- // path, NOT an error. The browser raises a DOMException named
659
- // 'AbortError' (some runtimes use a generic Error); match on the name so
660
- // we never throw the timeout into the cold-boot error handler.
661
- if (error instanceof Error && error.name === 'AbortError') {
662
- return { accounts: [] };
663
- }
664
- throw this.handleError(error);
665
- }
666
- finally {
667
- if (timeoutId !== undefined) {
668
- clearTimeout(timeoutId);
669
- }
670
- }
671
- if (response.status === 401) {
672
- return { accounts: [] };
673
- }
674
- if (response.status === 404) {
675
- return { accounts: [] };
676
- }
677
- if (!response.ok) {
678
- throw this.handleError(new Error(`Refresh-all failed with HTTP ${response.status}`));
679
- }
680
- const payload = (await response.json());
681
- const raw = Array.isArray(payload.accounts) ? payload.accounts : [];
682
- const accounts = [];
683
- for (const entry of raw) {
684
- if (entry === null || typeof entry !== 'object') {
685
- continue;
686
- }
687
- const e = entry;
688
- if (!e.accessToken || !e.expiresAt || !e.sessionId || !e.user) {
689
- continue;
690
- }
691
- const userId = e.user.id ?? e.user._id;
692
- // `name.displayName` is optional on the contract — do NOT drop no-name
693
- // accounts. Only an absent userId or username makes the entry unusable.
694
- if (!userId || !e.user.username) {
695
- continue;
696
- }
697
- if (typeof e.authuser !== 'number') {
698
- continue;
699
- }
700
- accounts.push({
701
- authuser: e.authuser,
702
- accessToken: e.accessToken,
703
- expiresAt: e.expiresAt,
704
- sessionId: e.sessionId,
705
- user: {
706
- id: userId,
707
- username: e.user.username,
708
- // `name.displayName` is optional; carry whatever structured name the
709
- // server sent (possibly an empty object) and let consumers fall back.
710
- name: e.user.name ?? {},
711
- avatar: e.user.avatar ?? null,
712
- email: e.user.email,
713
- color: e.user.color ?? null,
714
- },
715
- });
716
- }
717
- return { accounts };
718
- }
719
- /**
720
- * Rotate a single refresh-cookie slot and return the fresh access token.
721
- *
722
- * When `authuser` is provided, the server rotates ONLY that slot
723
- * (`oxy_rt_${authuser}`) — sibling accounts on the same device stay
724
- * untouched. When omitted, the server picks the lowest indexed slot present.
725
- * The refresh cookie itself never enters JS.
726
- *
727
- * Returns `null` on 401 (no cookie / expired / reused) so the caller can
728
- * fall through cleanly to the unauthenticated path.
729
- */
730
- async refreshTokenViaCookie(opts = {}) {
731
- const result = await this._refreshCookieRaw(opts.authuser);
732
- return result;
733
- }
734
- /**
735
- * Sign out a single device-local account by its authuser slot index.
736
- *
737
- * Revokes that slot's refresh-token family and deactivates its session;
738
- * sibling indexed slots stay signed in. The browser-side `oxy_rt_${n}`
739
- * cookie is cleared by the server's `Set-Cookie` response header.
740
- */
741
- async logoutSessionByAuthuser(authuser) {
742
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout?authuser=${encodeURIComponent(String(authuser))}`;
743
- try {
744
- const response = await fetch(url, {
745
- method: 'POST',
746
- credentials: 'include',
747
- headers: { Accept: 'application/json' },
748
- });
749
- if (!response.ok && response.status !== 401) {
750
- throw new Error(`Logout (authuser=${authuser}) failed with HTTP ${response.status}`);
751
- }
752
- }
753
- catch (error) {
754
- throw this.handleError(error);
755
- }
756
- }
757
- /**
758
- * Sign out EVERY device-local account on this device by clearing every
759
- * presented refresh-cookie slot at once. Revokes every family + clears
760
- * every slot. Always succeeds (idempotent on unknown/garbage tokens).
761
- */
762
- async logoutAllSessionsViaCookie() {
763
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout`;
764
- try {
765
- const response = await fetch(url, {
766
- method: 'POST',
767
- credentials: 'include',
768
- headers: { Accept: 'application/json' },
769
- });
770
- if (!response.ok && response.status !== 401) {
771
- throw new Error(`Logout-all failed with HTTP ${response.status}`);
772
- }
773
- }
774
- catch (error) {
775
- throw this.handleError(error);
776
- }
777
- }
778
- /**
779
- * Internal: raw `POST /auth/refresh[?authuser=N]` call returning the
780
- * minted access token. Returns `null` on 401 / non-2xx.
781
- *
782
- * @internal
783
- */
784
- async _refreshCookieRaw(authuser) {
785
- const base = this.getSessionBaseUrl().replace(/\/$/, '');
786
- const url = typeof authuser === 'number'
787
- ? `${base}/auth/refresh?authuser=${encodeURIComponent(String(authuser))}`
788
- : `${base}/auth/refresh`;
789
- let response;
790
- try {
791
- response = await fetch(url, {
792
- method: 'POST',
793
- credentials: 'include',
794
- headers: { Accept: 'application/json' },
795
- });
796
- }
797
- catch (error) {
798
- throw this.handleError(error);
799
- }
800
- if (!response.ok) {
801
- return null;
802
- }
803
- const payload = (await response.json());
804
- if (typeof payload.accessToken !== 'string' || !payload.accessToken) {
805
- return null;
806
- }
807
- const expiresAt = typeof payload.expiresAt === 'string' ? payload.expiresAt : '';
808
- if (typeof payload.authuser !== 'number') {
809
- return null;
810
- }
811
- return {
812
- accessToken: payload.accessToken,
813
- expiresAt,
814
- authuser: payload.authuser,
815
- };
816
- }
817
617
  /**
818
618
  * Internal: decode (without verifying) the `sessionId` claim from a
819
619
  * server-signed access token. The server already verified the signature;
@@ -983,5 +783,70 @@ export function OxyServicesAuthMixin(Base) {
983
783
  async signInWithEmail(email, password, deviceName, deviceFingerprint) {
984
784
  return this.signIn(email, password, deviceName, deviceFingerprint);
985
785
  }
786
+ /**
787
+ * Device-first password sign-in. Unlike the legacy {@link signIn} (which
788
+ * assumes a one-step session and is kept intact for existing callers until
789
+ * the F4 cutover), this returns the FULL `POST /auth/login` contract — the
790
+ * discriminated {@link LoginResult}: either a 2FA challenge
791
+ * (`{ twoFactorRequired, loginToken }`) to complete via
792
+ * {@link completeTwoFactorSignIn}, or a session arm.
793
+ *
794
+ * `options.deviceToken` attributes the new session to the caller's existing
795
+ * device set (so an in-app login from a cross-apex, cookie-less web app
796
+ * still joins the same DeviceSession). On the session arm, a returned access
797
+ * token is planted immediately (mirroring {@link verifyChallenge}), so the
798
+ * caller has an authenticated client without a second round-trip.
799
+ */
800
+ async passwordSignIn(identifier, password, options = {}) {
801
+ try {
802
+ const res = await this.makeRequest('POST', '/auth/login', {
803
+ identifier,
804
+ password,
805
+ deviceName: options.deviceName,
806
+ deviceFingerprint: options.deviceFingerprint,
807
+ deviceToken: options.deviceToken,
808
+ }, { cache: false });
809
+ const parsed = safeParseContract(loginResultSchema, res);
810
+ if (!parsed) {
811
+ throw new Error('auth/login returned an unexpected response shape');
812
+ }
813
+ if (!('twoFactorRequired' in parsed) && parsed.accessToken) {
814
+ this.setTokens(parsed.accessToken);
815
+ }
816
+ return parsed;
817
+ }
818
+ catch (error) {
819
+ throw this.handleError(error);
820
+ }
821
+ }
822
+ /**
823
+ * Complete a 2FA-gated sign-in started by {@link passwordSignIn}. Presents
824
+ * the short-lived `loginToken` with either a TOTP `token` or a `backupCode`
825
+ * to `POST /security/2fa/verify-login`, which must resolve to the session
826
+ * arm of {@link LoginResult} (a second 2FA challenge here is a protocol
827
+ * error). A returned access token is planted immediately.
828
+ */
829
+ async completeTwoFactorSignIn(params) {
830
+ try {
831
+ const res = await this.makeRequest('POST', '/security/2fa/verify-login', {
832
+ loginToken: params.loginToken,
833
+ token: params.token,
834
+ backupCode: params.backupCode,
835
+ deviceToken: params.deviceToken,
836
+ deviceName: params.deviceName,
837
+ }, { cache: false });
838
+ const parsed = safeParseContract(loginResultSchema, res);
839
+ if (!parsed || 'twoFactorRequired' in parsed) {
840
+ throw new Error('security/2fa/verify-login returned an unexpected response shape');
841
+ }
842
+ if (parsed.accessToken) {
843
+ this.setTokens(parsed.accessToken);
844
+ }
845
+ return parsed;
846
+ }
847
+ catch (error) {
848
+ throw this.handleError(error);
849
+ }
850
+ }
986
851
  };
987
852
  }
@@ -0,0 +1,35 @@
1
+ export function OxyServicesAuthorizedAppsMixin(Base) {
2
+ return class extends Base {
3
+ /**
4
+ * List the authenticated user's authorized RP apps — the intersection of the
5
+ * user's FedCM grants and the currently-approved RP catalog. Powers the
6
+ * "Connected apps" management UI. Requires a real user session.
7
+ */
8
+ async listAuthorizedApps() {
9
+ try {
10
+ const response = await this.makeRequest('GET', '/fedcm/me/authorized-apps', undefined, {
11
+ cache: true,
12
+ cacheTTL: 30 * 1000, // 30 second cache — short, this drives a manageable UI
13
+ });
14
+ return response?.apps ?? [];
15
+ }
16
+ catch (error) {
17
+ throw this.handleError(error);
18
+ }
19
+ }
20
+ /**
21
+ * Revoke the authenticated user's authorization for a specific RP origin.
22
+ * The corresponding cache entry is invalidated so a subsequent
23
+ * `listAuthorizedApps()` sees fresh data.
24
+ */
25
+ async revokeAuthorizedApp(origin) {
26
+ try {
27
+ await this.makeRequest('DELETE', `/fedcm/me/authorized-apps/${encodeURIComponent(origin)}`, undefined, { cache: false });
28
+ this.clearCacheEntry('GET:/fedcm/me/authorized-apps');
29
+ }
30
+ catch (error) {
31
+ throw this.handleError(error);
32
+ }
33
+ }
34
+ };
35
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Device-first bootstrap mixin (auth centralization, wave 1).
3
+ *
4
+ * The client half of the new device-first session bootstrap: the four network
5
+ * calls the cold boot (`coldBootV2`) and the unified refresh handler
6
+ * (`refresh.ts`) make, plus the URL builder for the cross-apex bootstrap hop.
7
+ * Every response is validated against the `@oxyhq/contracts` `deviceBoot`
8
+ * schemas via `safeParseContract`, so producer (oxy-api) and consumer cannot
9
+ * drift — an unexpected shape throws here rather than silently corrupting the
10
+ * persisted store.
11
+ *
12
+ * These methods are ADDITIVE and carry NO persistence or token-planting side
13
+ * effects of their own (except the bearer-authenticated calls that naturally
14
+ * flow through `HttpService`). The cold boot / refresh handler own persistence
15
+ * and `setTokens`, so the same network primitive can be reused from either
16
+ * without double-planting.
17
+ */
18
+ import { authTokenBundleSchema, tokenRefreshResponseSchema, deviceTokenIssueResponseSchema, webSessionResultSchema, safeParseContract, } from '@oxyhq/contracts';
19
+ export function OxyServicesDeviceBootMixin(Base) {
20
+ return class extends Base {
21
+ /**
22
+ * Exchange a single-use boot `code` (from the `#oxy_boot` return fragment)
23
+ * for a token bundle. Origin-bound + GETDEL-burned server-side.
24
+ *
25
+ * @throws if the response does not match {@link authTokenBundleSchema}.
26
+ */
27
+ async exchangeBootCode(code) {
28
+ try {
29
+ const res = await this.makeRequest('POST', '/auth/device/exchange', { code }, { cache: false });
30
+ const parsed = safeParseContract(authTokenBundleSchema, res);
31
+ if (!parsed) {
32
+ throw new Error('device/exchange returned an unexpected response shape');
33
+ }
34
+ return parsed;
35
+ }
36
+ catch (error) {
37
+ throw this.handleError(error);
38
+ }
39
+ }
40
+ /**
41
+ * Same-site fast path (`*.oxy.so` apps). Reads the first-party `oxy_device`
42
+ * cookie via a credentialed same-origin fetch and either resolves a full
43
+ * session bundle or reports the device is known-but-signed-out. Never
44
+ * redirects.
45
+ *
46
+ * @throws if the response matches neither arm of {@link webSessionResultSchema}.
47
+ */
48
+ async requestWebSession() {
49
+ try {
50
+ const res = await this.makeRequest('POST', '/auth/device/web-session', undefined, { cache: false });
51
+ const parsed = safeParseContract(webSessionResultSchema, res);
52
+ if (!parsed) {
53
+ throw new Error('device/web-session returned an unexpected response shape');
54
+ }
55
+ return parsed;
56
+ }
57
+ catch (error) {
58
+ throw this.handleError(error);
59
+ }
60
+ }
61
+ /**
62
+ * Rotate the persisted refresh-token family (web + native, one call). The
63
+ * caller (refresh handler / cold boot) plants + persists the rotated pair.
64
+ *
65
+ * @throws if the response does not match {@link tokenRefreshResponseSchema}.
66
+ */
67
+ async refreshWithToken(refreshToken) {
68
+ try {
69
+ const res = await this.makeRequest('POST', '/auth/refresh-token', { refreshToken },
70
+ // `skipAuth`: refresh-token is body-authenticated and is called from
71
+ // inside the refresh handler — sending the near-expired bearer through
72
+ // the preflight would deadlock. See RequestOptions.skipAuth.
73
+ { cache: false, skipAuth: true });
74
+ const parsed = safeParseContract(tokenRefreshResponseSchema, res);
75
+ if (!parsed) {
76
+ throw new Error('auth/refresh-token returned an unexpected response shape');
77
+ }
78
+ return parsed;
79
+ }
80
+ catch (error) {
81
+ throw this.handleError(error);
82
+ }
83
+ }
84
+ /**
85
+ * Issue (or rotate) the native channel's opaque device token. Bearer-gated —
86
+ * the server derives the deviceId from the JWT. Native apps mirror the
87
+ * returned token into the shared keychain via
88
+ * `KeyManager.setSharedDeviceToken`.
89
+ *
90
+ * @throws if the response does not match {@link deviceTokenIssueResponseSchema}.
91
+ */
92
+ async issueNativeDeviceToken() {
93
+ try {
94
+ const res = await this.makeRequest('POST', '/auth/device/token', undefined, { cache: false });
95
+ const parsed = safeParseContract(deviceTokenIssueResponseSchema, res);
96
+ if (!parsed) {
97
+ throw new Error('auth/device/token returned an unexpected response shape');
98
+ }
99
+ return parsed.deviceToken;
100
+ }
101
+ catch (error) {
102
+ throw this.handleError(error);
103
+ }
104
+ }
105
+ /**
106
+ * Build the top-level `GET /auth/device/bootstrap` URL for the cross-apex
107
+ * hop. The server validates `return_to` against the trusted-origin lane and
108
+ * echoes `state` back in the return fragment for CSRF verification.
109
+ */
110
+ buildBootstrapUrl(returnTo, state) {
111
+ const base = this.getBaseURL().replace(/\/+$/, '');
112
+ const params = new URLSearchParams({ return_to: returnTo, state });
113
+ return `${base}/auth/device/bootstrap?${params.toString()}`;
114
+ }
115
+ };
116
+ }
@@ -6,10 +6,7 @@
6
6
  */
7
7
  import { OxyServicesBase } from '../OxyServices.base.js';
8
8
  import { OxyServicesAuthMixin } from './OxyServices.auth.js';
9
- import { OxyServicesFedCMMixin } from './OxyServices.fedcm.js';
10
- import { OxyServicesSilentAuthMixin } from './OxyServices.silent.js';
11
- import { OxyServicesRedirectAuthMixin } from './OxyServices.redirect.js';
12
- import { OxyServicesSsoMixin } from './OxyServices.sso.js';
9
+ import { OxyServicesAuthorizedAppsMixin } from './OxyServices.authorizedApps.js';
13
10
  import { OxyServicesUserMixin } from './OxyServices.user.js';
14
11
  import { OxyServicesIdentityMixin } from './OxyServices.identity.js';
15
12
  import { OxyServicesPrivacyMixin } from './OxyServices.privacy.js';
@@ -31,30 +28,25 @@ import { OxyServicesAppDataMixin } from './OxyServices.appData.js';
31
28
  import { OxyServicesCivicMixin } from './OxyServices.civic.js';
32
29
  import { OxyServicesNodesMixin } from './OxyServices.nodes.js';
33
30
  import { OxyServicesLinksMixin } from './OxyServices.links.js';
31
+ import { OxyServicesDeviceBootMixin } from './OxyServices.deviceBoot.js';
34
32
  /**
35
33
  * Mixin pipeline - applied in order from first to last.
36
34
  *
37
35
  * Order matters for dependencies:
38
36
  * 1. Base auth mixin first (required by all others)
39
- * 2. Cross-domain auth mixins (FedCM, silent iframe, Redirect)
40
- * 3. User mixin (requires auth)
41
- * 4. Feature mixins (can depend on user)
42
- * 5. Utility mixin last (augments all)
37
+ * 2. User mixin (requires auth)
38
+ * 3. Feature mixins (can depend on user)
39
+ * 4. Utility mixin last (augments all)
43
40
  *
44
41
  * To add a new mixin: insert it at the appropriate position in this array.
45
42
  */
46
43
  const MIXIN_PIPELINE = [
47
44
  // Base authentication
48
45
  OxyServicesAuthMixin,
49
- // Cross-domain authentication (web-only)
50
- // - FedCM: Modern browser-native identity federation (Google-style)
51
- // - Silent: iframe-based restore for first-party IdP hosts
52
- // - Redirect: Traditional redirect-based authentication
53
- OxyServicesFedCMMixin,
54
- OxyServicesSilentAuthMixin,
55
- OxyServicesRedirectAuthMixin,
56
- // Central cross-domain SSO (opaque-code exchange).
57
- OxyServicesSsoMixin,
46
+ // Legacy FedCM "Connected apps" management (list/revoke authorized RP grants).
47
+ // The FedCM sign-in surface was removed in the device-first cutover; only
48
+ // this management pair survives until the AppGrant migration.
49
+ OxyServicesAuthorizedAppsMixin,
58
50
  // User management (requires auth)
59
51
  OxyServicesUserMixin,
60
52
  // Self-sovereign identity (DID, signed records, auth-method ↔ VM mapping)
@@ -88,6 +80,10 @@ const MIXIN_PIPELINE = [
88
80
  // Link previews / unfurls: SDK-owned link-metadata resolution via oxy-api,
89
81
  // so apps stop scraping link metadata locally.
90
82
  OxyServicesLinksMixin,
83
+ // Device-first session bootstrap: the client half of the new
84
+ // /auth/device/* + /auth/refresh-token surface (exchange, web-session,
85
+ // refresh, native device-token, bootstrap-url builder).
86
+ OxyServicesDeviceBootMixin,
91
87
  // Utility (last, can use all above)
92
88
  OxyServicesUtilityMixin,
93
89
  ];
@@ -37,7 +37,15 @@ export class SessionClient {
37
37
  logger.warn('[SessionClient] discarded invalid session state');
38
38
  return false;
39
39
  }
40
- if (this.state && next.revision <= this.state.revision) {
40
+ // The revision is monotone ONLY within a single deviceId. When the incoming
41
+ // state belongs to a DIFFERENT device than the currently-applied one, reset
42
+ // the baseline and accept it regardless of revision: a freshly-converged
43
+ // device (low revision) must not lose last-writer-wins to a stale, higher-
44
+ // revision state from a retired device. Only when the deviceIds MATCH is the
45
+ // `revision <= current` guard a valid staleness check.
46
+ if (this.state &&
47
+ next.deviceId === this.state.deviceId &&
48
+ next.revision <= this.state.revision) {
41
49
  return false;
42
50
  }
43
51
  this.state = next;
@@ -47,6 +55,16 @@ export class SessionClient {
47
55
  logger.warn('[SessionClient] ensureActiveToken failed', { component: 'SessionClient' }, error);
48
56
  });
49
57
  }
58
+ // A device signout-all leaves zero accounts — tell the provider to clear
59
+ // the persisted store so a reload does not try to restore a dead session.
60
+ if (next.accounts.length === 0 && this.options.onUnauthenticated) {
61
+ try {
62
+ this.options.onUnauthenticated();
63
+ }
64
+ catch (error) {
65
+ logger.error('[SessionClient] onUnauthenticated threw', error);
66
+ }
67
+ }
50
68
  return true;
51
69
  }
52
70
  /**
@@ -93,6 +111,27 @@ export class SessionClient {
93
111
  const res = await this.host.makeRequest('POST', '/session/device/add', undefined, { cache: false });
94
112
  this.applySync(res);
95
113
  }
114
+ /**
115
+ * Register the just-signed-in account into the device set AND make it the
116
+ * ACTIVE account — the explicit user-intent activation a sign-in UI performs.
117
+ *
118
+ * `addCurrentAccount` alone honors the server's `activate:'if-empty'` policy
119
+ * (a new account does NOT steal focus from an already-active one), which is
120
+ * correct for a background/silent add but wrong right after a deliberate
121
+ * sign-in. This adds, then switches to the target so the UI lands on the
122
+ * account the user just authenticated.
123
+ *
124
+ * @param accountId - The signed-in account id (e.g. `session.user.id`). When
125
+ * omitted, falls back to the host's current-account ref. If neither
126
+ * resolves, the add still applies and no switch is performed.
127
+ */
128
+ async registerAndActivate(accountId) {
129
+ await this.addCurrentAccount();
130
+ const target = accountId ?? this.host.getCurrentAccountId();
131
+ if (target && this.state?.activeAccountId !== target) {
132
+ await this.switchAccount(target);
133
+ }
134
+ }
96
135
  async start() {
97
136
  if (this.started)
98
137
  return;
@@ -117,7 +156,10 @@ export class SessionClient {
117
156
  }
118
157
  }
119
158
  async connectSocket() {
120
- const io = await getSocketIO();
159
+ // Prefer a statically-injected factory (services/auth-sdk bundle
160
+ // socket.io-client as a real dep); fall back to the lazy loader — and warn
161
+ // if THAT yields nothing — only when no factory was injected.
162
+ const io = this.options.socketFactory ?? (await getSocketIO());
121
163
  if (!io) {
122
164
  logger.warn('[SessionClient] no socket.io-client; running REST-only (no realtime sync)', { component: 'SessionClient' });
123
165
  return;