@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
@@ -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,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
+ });