@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
@@ -3,13 +3,9 @@
3
3
  *
4
4
  * Supports password-based login (email/username) and public key challenge-response.
5
5
  */
6
- import type {
7
- User,
8
- RefreshAllResponse,
9
- RefreshAllAccount,
10
- RefreshCookieResponse,
11
- } from '../models/interfaces';
12
- import type { UserNameResponse } from '@oxyhq/contracts';
6
+ import type { User } from '../models/interfaces';
7
+ import type { UserNameResponse, LoginResult, LoginSessionResult } from '@oxyhq/contracts';
8
+ import { loginResultSchema, safeParseContract } from '@oxyhq/contracts';
13
9
  import type { SessionLoginResponse } from '../models/session';
14
10
  import type { OxyServicesBase } from '../OxyServices.base';
15
11
  import type { PublicApplication } from './OxyServices.connectedApps';
@@ -32,26 +28,6 @@ export interface ChallengeResponse {
32
28
  expiresAt: string;
33
29
  }
34
30
 
35
- /**
36
- * Options for {@link refreshAllSessions}.
37
- */
38
- export interface RefreshAllOptions {
39
- /**
40
- * Abort the `POST /auth/refresh-all` request after this many milliseconds and
41
- * resolve as "no signed-in accounts" (`{ accounts: [] }`) rather than hanging.
42
- *
43
- * Why: on a cross-domain RP (e.g. `mention.earth`) the `Domain=oxy.so` refresh
44
- * cookie never reaches `api.<apex>`, so this request can stall behind a slow
45
- * or unreachable endpoint with no useful answer coming back. As one step of
46
- * the ordered cold-boot sequence, a stalled refresh is dead latency in front
47
- * of the steps that actually hold the answer. A bounded abort lets cold boot
48
- * fall through quickly. Omit (or pass `0`/negative) to wait indefinitely.
49
- * The abort is treated identically to a 401 — the
50
- * "not signed in on this device" path — never an error.
51
- */
52
- timeout?: number;
53
- }
54
-
55
31
  export interface RegistrationRequest {
56
32
  publicKey: string;
57
33
  username: string;
@@ -937,232 +913,6 @@ export function OxyServicesAuthMixin<T extends typeof OxyServicesBase>(Base: T)
937
913
  }
938
914
  }
939
915
 
940
- /**
941
- * Refresh every device-local refresh-cookie slot in a single round trip
942
- * (Google-style multi-account rebuild).
943
- *
944
- * Calls `POST {sessionBaseUrl}/auth/refresh-all` with `credentials: 'include'`
945
- * and NO bearer. The browser attaches every indexed `oxy_rt_${authuser}`
946
- * cookie it has; the server rotates each in parallel and returns one entry
947
- * per VALID account.
948
- *
949
- * Failure handling:
950
- * - 401 → no signed-in accounts on this device → returns `{ accounts: [] }`
951
- * (NOT an error; this is the cold-boot "not signed in" path).
952
- * - 404 → endpoint not deployed → returns `{ accounts: [] }`.
953
- * - Any other non-2xx → throws via `handleError`.
954
- *
955
- * The refresh cookie itself never enters JS — only the rotated access
956
- * tokens do. Each access token still needs to be planted via
957
- * `setTokens(...)` (or per-account in-memory storage) at the consumer.
958
- */
959
- async refreshAllSessions(options: RefreshAllOptions = {}): Promise<RefreshAllResponse> {
960
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/refresh-all`;
961
-
962
- // Optional bounded abort (see `RefreshAllOptions.timeout`). A positive
963
- // timeout arms an `AbortController` that aborts the in-flight request; an
964
- // abort is treated as "no signed-in accounts on this device" — the same
965
- // outcome as a 401 — so a cross-domain stall falls through cleanly instead
966
- // of hanging the cold boot.
967
- const timeout = typeof options.timeout === 'number' && options.timeout > 0 ? options.timeout : undefined;
968
- const controller = timeout !== undefined ? new AbortController() : undefined;
969
- const timeoutId = timeout !== undefined && controller
970
- ? setTimeout(() => controller.abort(), timeout)
971
- : undefined;
972
-
973
- let response: Response;
974
- try {
975
- response = await fetch(url, {
976
- method: 'POST',
977
- credentials: 'include',
978
- headers: { Accept: 'application/json' },
979
- signal: controller?.signal,
980
- });
981
- } catch (error) {
982
- // A bounded-timeout abort is the "not signed in / cross-domain stall"
983
- // path, NOT an error. The browser raises a DOMException named
984
- // 'AbortError' (some runtimes use a generic Error); match on the name so
985
- // we never throw the timeout into the cold-boot error handler.
986
- if (error instanceof Error && error.name === 'AbortError') {
987
- return { accounts: [] };
988
- }
989
- throw this.handleError(error);
990
- } finally {
991
- if (timeoutId !== undefined) {
992
- clearTimeout(timeoutId);
993
- }
994
- }
995
-
996
- if (response.status === 401) {
997
- return { accounts: [] };
998
- }
999
-
1000
- if (response.status === 404) {
1001
- return { accounts: [] };
1002
- }
1003
-
1004
- if (!response.ok) {
1005
- throw this.handleError(
1006
- new Error(`Refresh-all failed with HTTP ${response.status}`)
1007
- );
1008
- }
1009
-
1010
- const payload = (await response.json()) as { accounts?: unknown };
1011
- const raw = Array.isArray(payload.accounts) ? payload.accounts : [];
1012
- const accounts: RefreshAllAccount[] = [];
1013
-
1014
- for (const entry of raw) {
1015
- if (entry === null || typeof entry !== 'object') {
1016
- continue;
1017
- }
1018
- const e = entry as {
1019
- authuser?: number;
1020
- accessToken?: string;
1021
- expiresAt?: string;
1022
- sessionId?: string;
1023
- user?: { id?: string; _id?: string; username?: string; name?: UserNameResponse; avatar?: string | null; email?: string; color?: string | null };
1024
- };
1025
- if (!e.accessToken || !e.expiresAt || !e.sessionId || !e.user) {
1026
- continue;
1027
- }
1028
- const userId = e.user.id ?? e.user._id;
1029
- // `name.displayName` is optional on the contract — do NOT drop no-name
1030
- // accounts. Only an absent userId or username makes the entry unusable.
1031
- if (!userId || !e.user.username) {
1032
- continue;
1033
- }
1034
- if (typeof e.authuser !== 'number') {
1035
- continue;
1036
- }
1037
- accounts.push({
1038
- authuser: e.authuser,
1039
- accessToken: e.accessToken,
1040
- expiresAt: e.expiresAt,
1041
- sessionId: e.sessionId,
1042
- user: {
1043
- id: userId,
1044
- username: e.user.username,
1045
- // `name.displayName` is optional; carry whatever structured name the
1046
- // server sent (possibly an empty object) and let consumers fall back.
1047
- name: e.user.name ?? {},
1048
- avatar: e.user.avatar ?? null,
1049
- email: e.user.email,
1050
- color: e.user.color ?? null,
1051
- },
1052
- });
1053
- }
1054
-
1055
- return { accounts };
1056
- }
1057
-
1058
- /**
1059
- * Rotate a single refresh-cookie slot and return the fresh access token.
1060
- *
1061
- * When `authuser` is provided, the server rotates ONLY that slot
1062
- * (`oxy_rt_${authuser}`) — sibling accounts on the same device stay
1063
- * untouched. When omitted, the server picks the lowest indexed slot present.
1064
- * The refresh cookie itself never enters JS.
1065
- *
1066
- * Returns `null` on 401 (no cookie / expired / reused) so the caller can
1067
- * fall through cleanly to the unauthenticated path.
1068
- */
1069
- async refreshTokenViaCookie(
1070
- opts: { authuser?: number } = {}
1071
- ): Promise<RefreshCookieResponse | null> {
1072
- const result = await this._refreshCookieRaw(opts.authuser);
1073
- return result;
1074
- }
1075
-
1076
- /**
1077
- * Sign out a single device-local account by its authuser slot index.
1078
- *
1079
- * Revokes that slot's refresh-token family and deactivates its session;
1080
- * sibling indexed slots stay signed in. The browser-side `oxy_rt_${n}`
1081
- * cookie is cleared by the server's `Set-Cookie` response header.
1082
- */
1083
- async logoutSessionByAuthuser(authuser: number): Promise<void> {
1084
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout?authuser=${encodeURIComponent(String(authuser))}`;
1085
- try {
1086
- const response = await fetch(url, {
1087
- method: 'POST',
1088
- credentials: 'include',
1089
- headers: { Accept: 'application/json' },
1090
- });
1091
- if (!response.ok && response.status !== 401) {
1092
- throw new Error(`Logout (authuser=${authuser}) failed with HTTP ${response.status}`);
1093
- }
1094
- } catch (error) {
1095
- throw this.handleError(error);
1096
- }
1097
- }
1098
-
1099
- /**
1100
- * Sign out EVERY device-local account on this device by clearing every
1101
- * presented refresh-cookie slot at once. Revokes every family + clears
1102
- * every slot. Always succeeds (idempotent on unknown/garbage tokens).
1103
- */
1104
- async logoutAllSessionsViaCookie(): Promise<void> {
1105
- const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout`;
1106
- try {
1107
- const response = await fetch(url, {
1108
- method: 'POST',
1109
- credentials: 'include',
1110
- headers: { Accept: 'application/json' },
1111
- });
1112
- if (!response.ok && response.status !== 401) {
1113
- throw new Error(`Logout-all failed with HTTP ${response.status}`);
1114
- }
1115
- } catch (error) {
1116
- throw this.handleError(error);
1117
- }
1118
- }
1119
-
1120
- /**
1121
- * Internal: raw `POST /auth/refresh[?authuser=N]` call returning the
1122
- * minted access token. Returns `null` on 401 / non-2xx.
1123
- *
1124
- * @internal
1125
- */
1126
- async _refreshCookieRaw(authuser?: number): Promise<RefreshCookieResponse | null> {
1127
- const base = this.getSessionBaseUrl().replace(/\/$/, '');
1128
- const url = typeof authuser === 'number'
1129
- ? `${base}/auth/refresh?authuser=${encodeURIComponent(String(authuser))}`
1130
- : `${base}/auth/refresh`;
1131
-
1132
- let response: Response;
1133
- try {
1134
- response = await fetch(url, {
1135
- method: 'POST',
1136
- credentials: 'include',
1137
- headers: { Accept: 'application/json' },
1138
- });
1139
- } catch (error) {
1140
- throw this.handleError(error);
1141
- }
1142
-
1143
- if (!response.ok) {
1144
- return null;
1145
- }
1146
-
1147
- const payload = (await response.json()) as {
1148
- accessToken?: unknown;
1149
- expiresAt?: unknown;
1150
- authuser?: unknown;
1151
- };
1152
- if (typeof payload.accessToken !== 'string' || !payload.accessToken) {
1153
- return null;
1154
- }
1155
- const expiresAt = typeof payload.expiresAt === 'string' ? payload.expiresAt : '';
1156
- if (typeof payload.authuser !== 'number') {
1157
- return null;
1158
- }
1159
- return {
1160
- accessToken: payload.accessToken,
1161
- expiresAt,
1162
- authuser: payload.authuser,
1163
- };
1164
- }
1165
-
1166
916
  /**
1167
917
  * Internal: decode (without verifying) the `sessionId` claim from a
1168
918
  * server-signed access token. The server already verified the signature;
@@ -1369,5 +1119,80 @@ export function OxyServicesAuthMixin<T extends typeof OxyServicesBase>(Base: T)
1369
1119
  ): Promise<SessionLoginResponse> {
1370
1120
  return this.signIn(email, password, deviceName, deviceFingerprint);
1371
1121
  }
1122
+
1123
+ /**
1124
+ * Device-first password sign-in. Unlike the legacy {@link signIn} (which
1125
+ * assumes a one-step session and is kept intact for existing callers until
1126
+ * the F4 cutover), this returns the FULL `POST /auth/login` contract — the
1127
+ * discriminated {@link LoginResult}: either a 2FA challenge
1128
+ * (`{ twoFactorRequired, loginToken }`) to complete via
1129
+ * {@link completeTwoFactorSignIn}, or a session arm.
1130
+ *
1131
+ * `options.deviceToken` attributes the new session to the caller's existing
1132
+ * device set (so an in-app login from a cross-apex, cookie-less web app
1133
+ * still joins the same DeviceSession). On the session arm, a returned access
1134
+ * token is planted immediately (mirroring {@link verifyChallenge}), so the
1135
+ * caller has an authenticated client without a second round-trip.
1136
+ */
1137
+ async passwordSignIn(
1138
+ identifier: string,
1139
+ password: string,
1140
+ options: { deviceToken?: string; deviceName?: string; deviceFingerprint?: string } = {},
1141
+ ): Promise<LoginResult> {
1142
+ try {
1143
+ const res = await this.makeRequest<unknown>('POST', '/auth/login', {
1144
+ identifier,
1145
+ password,
1146
+ deviceName: options.deviceName,
1147
+ deviceFingerprint: options.deviceFingerprint,
1148
+ deviceToken: options.deviceToken,
1149
+ }, { cache: false });
1150
+ const parsed = safeParseContract(loginResultSchema, res);
1151
+ if (!parsed) {
1152
+ throw new Error('auth/login returned an unexpected response shape');
1153
+ }
1154
+ if (!('twoFactorRequired' in parsed) && parsed.accessToken) {
1155
+ this.setTokens(parsed.accessToken);
1156
+ }
1157
+ return parsed;
1158
+ } catch (error) {
1159
+ throw this.handleError(error);
1160
+ }
1161
+ }
1162
+
1163
+ /**
1164
+ * Complete a 2FA-gated sign-in started by {@link passwordSignIn}. Presents
1165
+ * the short-lived `loginToken` with either a TOTP `token` or a `backupCode`
1166
+ * to `POST /security/2fa/verify-login`, which must resolve to the session
1167
+ * arm of {@link LoginResult} (a second 2FA challenge here is a protocol
1168
+ * error). A returned access token is planted immediately.
1169
+ */
1170
+ async completeTwoFactorSignIn(params: {
1171
+ loginToken: string;
1172
+ token?: string;
1173
+ backupCode?: string;
1174
+ deviceToken?: string;
1175
+ deviceName?: string;
1176
+ }): Promise<LoginSessionResult> {
1177
+ try {
1178
+ const res = await this.makeRequest<unknown>('POST', '/security/2fa/verify-login', {
1179
+ loginToken: params.loginToken,
1180
+ token: params.token,
1181
+ backupCode: params.backupCode,
1182
+ deviceToken: params.deviceToken,
1183
+ deviceName: params.deviceName,
1184
+ }, { cache: false });
1185
+ const parsed = safeParseContract(loginResultSchema, res);
1186
+ if (!parsed || 'twoFactorRequired' in parsed) {
1187
+ throw new Error('security/2fa/verify-login returned an unexpected response shape');
1188
+ }
1189
+ if (parsed.accessToken) {
1190
+ this.setTokens(parsed.accessToken);
1191
+ }
1192
+ return parsed;
1193
+ } catch (error) {
1194
+ throw this.handleError(error);
1195
+ }
1196
+ }
1372
1197
  };
1373
1198
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Authorized-apps mixin — the "Connected apps" management surface that survived
3
+ * the FedCM removal.
4
+ *
5
+ * These two methods read/revoke the user's LEGACY FedCM authorization grants
6
+ * (`GET`/`DELETE /fedcm/me/authorized-apps`). They are the last live consumers
7
+ * of that endpoint (services' `ConnectedAppsScreen` via `useAccountQueries` /
8
+ * `useAccountMutations`) and stay until the AppGrant migration retires the
9
+ * FedCM grant store. All FedCM SIGN-IN machinery was deleted with
10
+ * `OxyServices.fedcm.ts`; this is management-only, so it has no dependency on
11
+ * the credential/nonce pipeline.
12
+ */
13
+ import type { OxyServicesBase } from '../OxyServices.base';
14
+
15
+ /**
16
+ * Public summary of an RP application the user has authorized — mirrors the
17
+ * `AuthorizedAppSummary` shape returned by `GET /fedcm/me/authorized-apps`.
18
+ */
19
+ export interface AuthorizedApp {
20
+ /** Normalised RP origin. */
21
+ origin: string;
22
+ /** Friendly display name. */
23
+ name: string;
24
+ /** Optional human-readable description. */
25
+ description?: string;
26
+ /** ISO-8601 timestamp of when the user first authorized this RP. */
27
+ firstGrantedAt: string;
28
+ /** ISO-8601 timestamp of the most recent FedCM exchange for this user+RP. */
29
+ lastUsedAt: string;
30
+ }
31
+
32
+ export function OxyServicesAuthorizedAppsMixin<T extends typeof OxyServicesBase>(Base: T) {
33
+ return class extends Base {
34
+ /**
35
+ * List the authenticated user's authorized RP apps — the intersection of the
36
+ * user's FedCM grants and the currently-approved RP catalog. Powers the
37
+ * "Connected apps" management UI. Requires a real user session.
38
+ */
39
+ async listAuthorizedApps(): Promise<AuthorizedApp[]> {
40
+ try {
41
+ const response = await this.makeRequest<{ apps: AuthorizedApp[] }>(
42
+ 'GET',
43
+ '/fedcm/me/authorized-apps',
44
+ undefined,
45
+ {
46
+ cache: true,
47
+ cacheTTL: 30 * 1000, // 30 second cache — short, this drives a manageable UI
48
+ },
49
+ );
50
+ return response?.apps ?? [];
51
+ } catch (error) {
52
+ throw this.handleError(error);
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Revoke the authenticated user's authorization for a specific RP origin.
58
+ * The corresponding cache entry is invalidated so a subsequent
59
+ * `listAuthorizedApps()` sees fresh data.
60
+ */
61
+ async revokeAuthorizedApp(origin: string): Promise<void> {
62
+ try {
63
+ await this.makeRequest(
64
+ 'DELETE',
65
+ `/fedcm/me/authorized-apps/${encodeURIComponent(origin)}`,
66
+ undefined,
67
+ { cache: false },
68
+ );
69
+ this.clearCacheEntry('GET:/fedcm/me/authorized-apps');
70
+ } catch (error) {
71
+ throw this.handleError(error);
72
+ }
73
+ }
74
+ };
75
+ }
@@ -0,0 +1,146 @@
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 {
19
+ authTokenBundleSchema,
20
+ tokenRefreshResponseSchema,
21
+ deviceTokenIssueResponseSchema,
22
+ webSessionResultSchema,
23
+ safeParseContract,
24
+ type AuthTokenBundle,
25
+ type TokenRefreshResponse,
26
+ type WebSessionResult,
27
+ } from '@oxyhq/contracts';
28
+ import type { OxyServicesBase } from '../OxyServices.base';
29
+
30
+ export function OxyServicesDeviceBootMixin<T extends typeof OxyServicesBase>(Base: T) {
31
+ return class extends Base {
32
+ /**
33
+ * Exchange a single-use boot `code` (from the `#oxy_boot` return fragment)
34
+ * for a token bundle. Origin-bound + GETDEL-burned server-side.
35
+ *
36
+ * @throws if the response does not match {@link authTokenBundleSchema}.
37
+ */
38
+ async exchangeBootCode(code: string): Promise<AuthTokenBundle> {
39
+ try {
40
+ const res = await this.makeRequest<unknown>(
41
+ 'POST',
42
+ '/auth/device/exchange',
43
+ { code },
44
+ { cache: false },
45
+ );
46
+ const parsed = safeParseContract(authTokenBundleSchema, res);
47
+ if (!parsed) {
48
+ throw new Error('device/exchange returned an unexpected response shape');
49
+ }
50
+ return parsed;
51
+ } catch (error) {
52
+ throw this.handleError(error);
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Same-site fast path (`*.oxy.so` apps). Reads the first-party `oxy_device`
58
+ * cookie via a credentialed same-origin fetch and either resolves a full
59
+ * session bundle or reports the device is known-but-signed-out. Never
60
+ * redirects.
61
+ *
62
+ * @throws if the response matches neither arm of {@link webSessionResultSchema}.
63
+ */
64
+ async requestWebSession(): Promise<WebSessionResult> {
65
+ try {
66
+ const res = await this.makeRequest<unknown>(
67
+ 'POST',
68
+ '/auth/device/web-session',
69
+ undefined,
70
+ { cache: false },
71
+ );
72
+ const parsed = safeParseContract(webSessionResultSchema, res);
73
+ if (!parsed) {
74
+ throw new Error('device/web-session returned an unexpected response shape');
75
+ }
76
+ return parsed;
77
+ } catch (error) {
78
+ throw this.handleError(error);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Rotate the persisted refresh-token family (web + native, one call). The
84
+ * caller (refresh handler / cold boot) plants + persists the rotated pair.
85
+ *
86
+ * @throws if the response does not match {@link tokenRefreshResponseSchema}.
87
+ */
88
+ async refreshWithToken(refreshToken: string): Promise<TokenRefreshResponse> {
89
+ try {
90
+ const res = await this.makeRequest<unknown>(
91
+ 'POST',
92
+ '/auth/refresh-token',
93
+ { refreshToken },
94
+ // `skipAuth`: refresh-token is body-authenticated and is called from
95
+ // inside the refresh handler — sending the near-expired bearer through
96
+ // the preflight would deadlock. See RequestOptions.skipAuth.
97
+ { cache: false, skipAuth: true },
98
+ );
99
+ const parsed = safeParseContract(tokenRefreshResponseSchema, res);
100
+ if (!parsed) {
101
+ throw new Error('auth/refresh-token returned an unexpected response shape');
102
+ }
103
+ return parsed;
104
+ } catch (error) {
105
+ throw this.handleError(error);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Issue (or rotate) the native channel's opaque device token. Bearer-gated —
111
+ * the server derives the deviceId from the JWT. Native apps mirror the
112
+ * returned token into the shared keychain via
113
+ * `KeyManager.setSharedDeviceToken`.
114
+ *
115
+ * @throws if the response does not match {@link deviceTokenIssueResponseSchema}.
116
+ */
117
+ async issueNativeDeviceToken(): Promise<string> {
118
+ try {
119
+ const res = await this.makeRequest<unknown>(
120
+ 'POST',
121
+ '/auth/device/token',
122
+ undefined,
123
+ { cache: false },
124
+ );
125
+ const parsed = safeParseContract(deviceTokenIssueResponseSchema, res);
126
+ if (!parsed) {
127
+ throw new Error('auth/device/token returned an unexpected response shape');
128
+ }
129
+ return parsed.deviceToken;
130
+ } catch (error) {
131
+ throw this.handleError(error);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Build the top-level `GET /auth/device/bootstrap` URL for the cross-apex
137
+ * hop. The server validates `return_to` against the trusted-origin lane and
138
+ * echoes `state` back in the return fragment for CSRF verification.
139
+ */
140
+ buildBootstrapUrl(returnTo: string, state: string): string {
141
+ const base = this.getBaseURL().replace(/\/+$/, '');
142
+ const params = new URLSearchParams({ return_to: returnTo, state });
143
+ return `${base}/auth/device/bootstrap?${params.toString()}`;
144
+ }
145
+ };
146
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Device-boot mixin tests. Stubs `makeRequest` so the tests run with no network
3
+ * and asserts each method's route/shape, contract validation, and the
4
+ * `skipAuth` flag on the refresh call.
5
+ */
6
+ import type { AuthTokenBundle, TokenRefreshResponse, WebSessionResult } from '@oxyhq/contracts';
7
+ import { OxyServices } from '../../OxyServices';
8
+
9
+ const BUNDLE: AuthTokenBundle = {
10
+ sessionId: 'sess-1',
11
+ accessToken: 'access-1',
12
+ refreshToken: 'refresh-abcdefghijkl',
13
+ expiresAt: '2030-01-01T00:00:00.000Z',
14
+ user: { id: 'user-1', name: {} } as AuthTokenBundle['user'],
15
+ };
16
+
17
+ const ROTATED: TokenRefreshResponse = {
18
+ accessToken: 'access-2',
19
+ refreshToken: 'refresh-mnopqrstuvwx',
20
+ expiresAt: '2030-01-01T00:00:00.000Z',
21
+ sessionId: 'sess-1',
22
+ };
23
+
24
+ describe('OxyServices.deviceBoot', () => {
25
+ let oxy: OxyServices;
26
+ let makeRequest: jest.SpyInstance;
27
+
28
+ beforeEach(() => {
29
+ oxy = new OxyServices({ baseURL: 'http://test.invalid' });
30
+ makeRequest = jest.spyOn(oxy, 'makeRequest');
31
+ });
32
+
33
+ afterEach(() => jest.restoreAllMocks());
34
+
35
+ describe('exchangeBootCode', () => {
36
+ it('POSTs the code and returns the validated bundle', async () => {
37
+ makeRequest.mockResolvedValueOnce(BUNDLE);
38
+ const result = await oxy.exchangeBootCode('code-123');
39
+ expect(result).toEqual(BUNDLE);
40
+ expect(makeRequest).toHaveBeenCalledWith('POST', '/auth/device/exchange', { code: 'code-123' }, { cache: false });
41
+ });
42
+
43
+ it('throws on an unexpected response shape', async () => {
44
+ makeRequest.mockResolvedValueOnce({ nope: true });
45
+ await expect(oxy.exchangeBootCode('code-123')).rejects.toThrow();
46
+ });
47
+ });
48
+
49
+ describe('requestWebSession', () => {
50
+ it('returns the session arm (bundle nested under `session` + deviceToken)', async () => {
51
+ const sessionArm: WebSessionResult = { reason: 'session', session: BUNDLE, deviceToken: 'device-abcdefghij' };
52
+ makeRequest.mockResolvedValueOnce(sessionArm);
53
+ const result = await oxy.requestWebSession();
54
+ expect(result).toEqual(sessionArm);
55
+ expect(makeRequest).toHaveBeenCalledWith('POST', '/auth/device/web-session', undefined, { cache: false });
56
+ });
57
+
58
+ it('returns the no-session arm', async () => {
59
+ const noSession: WebSessionResult = { reason: 'no_session', deviceToken: 'device-abcdefghij' };
60
+ makeRequest.mockResolvedValueOnce(noSession);
61
+ const result = await oxy.requestWebSession();
62
+ expect(result.reason).toBe('no_session');
63
+ expect(result).toEqual(noSession);
64
+ });
65
+
66
+ it('throws on the OLD bare-bundle shape (regression: server now wraps in a reason envelope)', async () => {
67
+ makeRequest.mockResolvedValueOnce(BUNDLE);
68
+ await expect(oxy.requestWebSession()).rejects.toThrow();
69
+ });
70
+
71
+ it('throws when the response matches neither arm', async () => {
72
+ makeRequest.mockResolvedValueOnce({ reason: 'weird' });
73
+ await expect(oxy.requestWebSession()).rejects.toThrow();
74
+ });
75
+ });
76
+
77
+ describe('refreshWithToken', () => {
78
+ it('POSTs with skipAuth and returns the rotated pair', async () => {
79
+ makeRequest.mockResolvedValueOnce(ROTATED);
80
+ const result = await oxy.refreshWithToken('refresh-abcdefghijkl');
81
+ expect(result).toEqual(ROTATED);
82
+ expect(makeRequest).toHaveBeenCalledWith(
83
+ 'POST',
84
+ '/auth/refresh-token',
85
+ { refreshToken: 'refresh-abcdefghijkl' },
86
+ { cache: false, skipAuth: true },
87
+ );
88
+ });
89
+ });
90
+
91
+ describe('issueNativeDeviceToken', () => {
92
+ it('POSTs and returns just the token string', async () => {
93
+ makeRequest.mockResolvedValueOnce({ deviceToken: 'native-dt' });
94
+ expect(await oxy.issueNativeDeviceToken()).toBe('native-dt');
95
+ expect(makeRequest).toHaveBeenCalledWith('POST', '/auth/device/token', undefined, { cache: false });
96
+ });
97
+ });
98
+
99
+ describe('buildBootstrapUrl', () => {
100
+ it('builds the bootstrap URL with encoded params', () => {
101
+ const url = oxy.buildBootstrapUrl('https://accounts.oxy.so/home', 'st-1');
102
+ expect(url).toContain('http://test.invalid/auth/device/bootstrap?');
103
+ expect(url).toContain('return_to=https%3A%2F%2Faccounts.oxy.so%2Fhome');
104
+ expect(url).toContain('state=st-1');
105
+ });
106
+ });
107
+ });