@oxyhq/core 12.2.0 → 12.3.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 (107) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/crypto/aead.js +79 -0
  3. package/dist/cjs/crypto/ecdh.js +53 -0
  4. package/dist/cjs/crypto/kdf.js +39 -0
  5. package/dist/cjs/crypto/keyManager.js +7 -0
  6. package/dist/cjs/crypto/recoveryPhrase.js +89 -1
  7. package/dist/cjs/i18n/locales/ar-SA.json +2 -0
  8. package/dist/cjs/i18n/locales/ca-ES.json +2 -0
  9. package/dist/cjs/i18n/locales/de-DE.json +2 -0
  10. package/dist/cjs/i18n/locales/en-US.json +7 -0
  11. package/dist/cjs/i18n/locales/es-ES.json +7 -0
  12. package/dist/cjs/i18n/locales/fr-FR.json +2 -0
  13. package/dist/cjs/i18n/locales/it-IT.json +2 -0
  14. package/dist/cjs/i18n/locales/ja-JP.json +2 -0
  15. package/dist/cjs/i18n/locales/ko-KR.json +2 -0
  16. package/dist/cjs/i18n/locales/locales/ar-SA.json +2 -0
  17. package/dist/cjs/i18n/locales/locales/ca-ES.json +2 -0
  18. package/dist/cjs/i18n/locales/locales/de-DE.json +2 -0
  19. package/dist/cjs/i18n/locales/locales/en-US.json +7 -0
  20. package/dist/cjs/i18n/locales/locales/es-ES.json +7 -0
  21. package/dist/cjs/i18n/locales/locales/fr-FR.json +2 -0
  22. package/dist/cjs/i18n/locales/locales/it-IT.json +2 -0
  23. package/dist/cjs/i18n/locales/locales/ja-JP.json +2 -0
  24. package/dist/cjs/i18n/locales/locales/ko-KR.json +2 -0
  25. package/dist/cjs/i18n/locales/locales/pt-PT.json +2 -0
  26. package/dist/cjs/i18n/locales/locales/zh-CN.json +2 -0
  27. package/dist/cjs/i18n/locales/pt-PT.json +2 -0
  28. package/dist/cjs/i18n/locales/zh-CN.json +2 -0
  29. package/dist/cjs/index.js +14 -4
  30. package/dist/cjs/mixins/OxyServices.identity.js +166 -0
  31. package/dist/cjs/mixins/OxyServices.identityBackup.js +161 -0
  32. package/dist/cjs/mixins/OxyServices.user.js +43 -0
  33. package/dist/cjs/mixins/index.js +4 -0
  34. package/dist/esm/.tsbuildinfo +1 -1
  35. package/dist/esm/crypto/aead.js +74 -0
  36. package/dist/esm/crypto/ecdh.js +51 -0
  37. package/dist/esm/crypto/kdf.js +36 -0
  38. package/dist/esm/crypto/keyManager.js +7 -0
  39. package/dist/esm/crypto/recoveryPhrase.js +88 -0
  40. package/dist/esm/i18n/locales/ar-SA.json +2 -0
  41. package/dist/esm/i18n/locales/ca-ES.json +2 -0
  42. package/dist/esm/i18n/locales/de-DE.json +2 -0
  43. package/dist/esm/i18n/locales/en-US.json +7 -0
  44. package/dist/esm/i18n/locales/es-ES.json +7 -0
  45. package/dist/esm/i18n/locales/fr-FR.json +2 -0
  46. package/dist/esm/i18n/locales/it-IT.json +2 -0
  47. package/dist/esm/i18n/locales/ja-JP.json +2 -0
  48. package/dist/esm/i18n/locales/ko-KR.json +2 -0
  49. package/dist/esm/i18n/locales/locales/ar-SA.json +2 -0
  50. package/dist/esm/i18n/locales/locales/ca-ES.json +2 -0
  51. package/dist/esm/i18n/locales/locales/de-DE.json +2 -0
  52. package/dist/esm/i18n/locales/locales/en-US.json +7 -0
  53. package/dist/esm/i18n/locales/locales/es-ES.json +7 -0
  54. package/dist/esm/i18n/locales/locales/fr-FR.json +2 -0
  55. package/dist/esm/i18n/locales/locales/it-IT.json +2 -0
  56. package/dist/esm/i18n/locales/locales/ja-JP.json +2 -0
  57. package/dist/esm/i18n/locales/locales/ko-KR.json +2 -0
  58. package/dist/esm/i18n/locales/locales/pt-PT.json +2 -0
  59. package/dist/esm/i18n/locales/locales/zh-CN.json +2 -0
  60. package/dist/esm/i18n/locales/pt-PT.json +2 -0
  61. package/dist/esm/i18n/locales/zh-CN.json +2 -0
  62. package/dist/esm/index.js +4 -0
  63. package/dist/esm/mixins/OxyServices.identity.js +166 -0
  64. package/dist/esm/mixins/OxyServices.identityBackup.js +158 -0
  65. package/dist/esm/mixins/OxyServices.user.js +43 -0
  66. package/dist/esm/mixins/index.js +4 -0
  67. package/dist/types/.tsbuildinfo +1 -1
  68. package/dist/types/crypto/aead.d.ts +56 -0
  69. package/dist/types/crypto/ecdh.d.ts +29 -0
  70. package/dist/types/crypto/kdf.d.ts +25 -0
  71. package/dist/types/crypto/keyManager.d.ts +5 -0
  72. package/dist/types/crypto/recoveryPhrase.d.ts +85 -0
  73. package/dist/types/index.d.ts +7 -3
  74. package/dist/types/mixins/OxyServices.identity.d.ts +95 -0
  75. package/dist/types/mixins/OxyServices.identityBackup.d.ts +129 -0
  76. package/dist/types/mixins/OxyServices.user.d.ts +38 -8
  77. package/dist/types/mixins/index.d.ts +2 -1
  78. package/package.json +4 -2
  79. package/src/crypto/__tests__/backupMaterial.test.ts +86 -0
  80. package/src/crypto/__tests__/cryptoPrimitives.test.ts +225 -0
  81. package/src/crypto/__tests__/keyManager.atomicity.test.ts +33 -0
  82. package/src/crypto/__tests__/recoveryPhrase.test.ts +61 -0
  83. package/src/crypto/aead.ts +97 -0
  84. package/src/crypto/ecdh.ts +60 -0
  85. package/src/crypto/kdf.ts +43 -0
  86. package/src/crypto/keyManager.ts +8 -0
  87. package/src/crypto/recoveryPhrase.ts +133 -0
  88. package/src/i18n/locales/ar-SA.json +2 -0
  89. package/src/i18n/locales/ca-ES.json +2 -0
  90. package/src/i18n/locales/de-DE.json +2 -0
  91. package/src/i18n/locales/en-US.json +7 -0
  92. package/src/i18n/locales/es-ES.json +7 -0
  93. package/src/i18n/locales/fr-FR.json +2 -0
  94. package/src/i18n/locales/it-IT.json +2 -0
  95. package/src/i18n/locales/ja-JP.json +2 -0
  96. package/src/i18n/locales/ko-KR.json +2 -0
  97. package/src/i18n/locales/pt-PT.json +2 -0
  98. package/src/i18n/locales/zh-CN.json +2 -0
  99. package/src/index.ts +16 -1
  100. package/src/mixins/OxyServices.identity.ts +250 -0
  101. package/src/mixins/OxyServices.identityBackup.ts +237 -0
  102. package/src/mixins/OxyServices.user.ts +82 -4
  103. package/src/mixins/__tests__/OxyServices.rotateKey.test.ts +277 -0
  104. package/src/mixins/__tests__/getFollowStatuses.test.ts +95 -0
  105. package/src/mixins/__tests__/identityBackup.test.ts +258 -0
  106. package/src/mixins/index.ts +5 -0
  107. package/src/types/elliptic.d.ts +10 -2
package/dist/cjs/index.js CHANGED
@@ -18,10 +18,10 @@
18
18
  * If a symbol does not appear here, it is NOT part of the public API.
19
19
  */
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.isWeb = exports.setPlatformOS = exports.getPlatformOS = exports.getPrimaryLanguage = exports.getUserLanguages = exports.isRTLLocale = exports.getNativeLanguageName = exports.getLanguageName = exports.getLanguageMetadata = exports.isSupportedLocale = exports.normalizeLocale = exports.getBaseLanguage = exports.FALLBACK_LOCALE = exports.SUPPORTED_LANGUAGES = exports.TopicSource = exports.TopicType = exports.SECURITY_EVENT_SEVERITY_MAP = exports.DeviceManager = exports.RecoveryPhraseService = exports.SignatureService = exports.IdentityPersistError = exports.IdentityAlreadyExistsError = exports.KeyManager = exports.sessionsArraysEqual = exports.normalizeAndSortSessions = exports.mergeSessions = exports.authenticatedApiCall = exports.withAuthErrorHandling = exports.isAuthenticationError = exports.ensureValidToken = exports.AuthenticationFailedError = exports.SessionSyncRequiredError = exports.verifyPublicCardAttestation = exports.parseAttestPayload = exports.parseIdPayload = exports.buildUserDid = exports.ORGANIZATION_CATEGORIES = exports.normalizeProfileLinks = exports.getNormalizedUserHandle = exports.getCanonicalUserHandle = exports.normalizeUserIdentityOrNull = exports.normalizeUserIdentity = exports.getNormalizedUserId = exports.OxyAppDataIdentifierError = exports.ServiceCredentialMismatchError = exports.oxyClient = exports.OXY_CLOUD_URL = exports.OxyAuthenticationTimeoutError = exports.OxyAuthenticationError = exports.OxyServices = void 0;
22
- exports.isValidUsername = exports.isValidEmail = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = exports.retryAsync = exports.validateRequiredFields = exports.handleHttpError = exports.createApiError = exports.ErrorCodes = exports.safeJsonParse = exports.buildPaginationParams = exports.buildUrl = exports.buildSearchParams = exports.translate = exports.withRetry = exports.delay = exports.shouldAllowRequest = exports.recordSuccess = exports.recordFailure = exports.calculateBackoffInterval = exports.createCircuitBreakerState = exports.DEFAULT_CIRCUIT_BREAKER_CONFIG = exports.isRetryableError = exports.isNetworkError = exports.isServerError = exports.isRateLimitError = exports.isNotFoundError = exports.isForbiddenError = exports.isUnauthorizedError = exports.isAlreadyRegisteredError = exports.getErrorMessage = exports.getErrorStatus = exports.HttpStatus = exports.getSystemColorScheme = exports.systemPrefersDarkMode = exports.getOppositeTheme = exports.normalizeColorScheme = exports.normalizeTheme = exports.getContrastTextColor = exports.isLightColor = exports.withOpacity = exports.rgbToHex = exports.hexToRgb = exports.lightenColor = exports.darkenColor = exports.isWebBrowser = exports.isAndroid = exports.isIOS = exports.isNative = void 0;
23
- exports.clearOAuthHandshake = exports.readOAuthHandshake = exports.persistOAuthHandshake = exports.normalizeOAuthRedirectUri = exports.OXY_CROSS_ORIGIN_RESTORE_ATTEMPTED_KEY = exports.OXY_SILENT_OAUTH_ATTEMPTED_KEY = exports.OXY_OAUTH_CODE_VERIFIER_STORAGE_KEY = exports.OXY_OAUTH_STATE_STORAGE_KEY = exports.OXY_AUTHORIZE_URL = exports.DEFAULT_OAUTH_SCOPE = exports.generatePkcePair = exports.generateOAuthState = exports.computeCodeChallenge = exports.buildOAuthAuthorizeUrl = exports.runColdBoot = exports.isOxyRpOrigin = exports.CENTRAL_IDP_APEX = exports.registrableApex = exports.getAccountColor = exports.formatPublicKeyHandle = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.createQuickAccount = exports.buildAccountsArray = exports.updateAvatarVisibility = exports.isDev = exports.consoleSink = exports.resetLoggerConfig = exports.getLoggerConfig = exports.configureLogger = exports.createLogger = exports.logger = exports.normalizeMultilineText = exports.normalizeInlineText = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.isValidDisplayName = exports.isValidPassword = void 0;
24
- exports.packageInfo = exports.runSessionColdBoot = exports.TOKEN_REFRESH_LEAD_MS = exports.startTokenRefreshScheduler = exports.installAuthRefreshHandler = exports.createAuthRefreshHandler = exports.refreshDeviceSecretArm = exports.refreshPersistedSession = exports.AUTH_STATE_STORAGE_KEY = exports.createMemoryAuthStateStore = exports.createNativeAuthStateStore = exports.createWebAuthStateStore = exports.createAccountDialogController = exports.AccountDialogController = exports.switchableAccountIds = exports.projectSwitchableAccounts = exports.accountIdsOf = exports.activeUserOf = exports.activeSessionIdOf = exports.deviceStateToClientSessions = exports.createSessionClient = exports.createSessionClientHost = exports.SessionClient = exports.redeemHubTicketOnHub = exports.syncHubAfterSignIn = exports.parseHubSyncReturnUrl = exports.normalizeOfficialReturnOrigin = exports.isAllowedDeviceJoinOrigin = exports.isOfficialWebOrigin = exports.isLoopbackOrigin = exports.isIdpHubOrigin = exports.buildHubSyncUrl = exports.buildIdpHubOrigin = void 0;
21
+ exports.getNativeLanguageName = exports.getLanguageName = exports.getLanguageMetadata = exports.isSupportedLocale = exports.normalizeLocale = exports.getBaseLanguage = exports.FALLBACK_LOCALE = exports.SUPPORTED_LANGUAGES = exports.TopicSource = exports.TopicType = exports.SECURITY_EVENT_SEVERITY_MAP = exports.DeviceManager = exports.deriveSharedSecret = exports.AEAD_NONCE_LENGTH = exports.AEAD_KEY_LENGTH = exports.decryptAead = exports.encryptAead = exports.hkdfSha256 = exports.RecoveryPhraseService = exports.SignatureService = exports.IdentityPersistError = exports.IdentityAlreadyExistsError = exports.KeyManager = exports.sessionsArraysEqual = exports.normalizeAndSortSessions = exports.mergeSessions = exports.authenticatedApiCall = exports.withAuthErrorHandling = exports.isAuthenticationError = exports.ensureValidToken = exports.AuthenticationFailedError = exports.SessionSyncRequiredError = exports.verifyPublicCardAttestation = exports.parseAttestPayload = exports.parseIdPayload = exports.buildUserDid = exports.ORGANIZATION_CATEGORIES = exports.normalizeProfileLinks = exports.getNormalizedUserHandle = exports.getCanonicalUserHandle = exports.normalizeUserIdentityOrNull = exports.normalizeUserIdentity = exports.getNormalizedUserId = exports.OxyAppDataIdentifierError = exports.ServiceCredentialMismatchError = exports.oxyClient = exports.OXY_CLOUD_URL = exports.OxyAuthenticationTimeoutError = exports.OxyAuthenticationError = exports.OxyServices = void 0;
22
+ exports.validateRequiredFields = exports.handleHttpError = exports.createApiError = exports.ErrorCodes = exports.safeJsonParse = exports.buildPaginationParams = exports.buildUrl = exports.buildSearchParams = exports.translate = exports.withRetry = exports.delay = exports.shouldAllowRequest = exports.recordSuccess = exports.recordFailure = exports.calculateBackoffInterval = exports.createCircuitBreakerState = exports.DEFAULT_CIRCUIT_BREAKER_CONFIG = exports.isRetryableError = exports.isNetworkError = exports.isServerError = exports.isRateLimitError = exports.isNotFoundError = exports.isForbiddenError = exports.isUnauthorizedError = exports.isAlreadyRegisteredError = exports.getErrorMessage = exports.getErrorStatus = exports.HttpStatus = exports.getSystemColorScheme = exports.systemPrefersDarkMode = exports.getOppositeTheme = exports.normalizeColorScheme = exports.normalizeTheme = exports.getContrastTextColor = exports.isLightColor = exports.withOpacity = exports.rgbToHex = exports.hexToRgb = exports.lightenColor = exports.darkenColor = exports.isWebBrowser = exports.isAndroid = exports.isIOS = exports.isNative = exports.isWeb = exports.setPlatformOS = exports.getPlatformOS = exports.getPrimaryLanguage = exports.getUserLanguages = exports.isRTLLocale = void 0;
23
+ exports.OXY_OAUTH_CODE_VERIFIER_STORAGE_KEY = exports.OXY_OAUTH_STATE_STORAGE_KEY = exports.OXY_AUTHORIZE_URL = exports.DEFAULT_OAUTH_SCOPE = exports.generatePkcePair = exports.generateOAuthState = exports.computeCodeChallenge = exports.buildOAuthAuthorizeUrl = exports.runColdBoot = exports.isOxyRpOrigin = exports.CENTRAL_IDP_APEX = exports.registrableApex = exports.getAccountColor = exports.formatPublicKeyHandle = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.createQuickAccount = exports.buildAccountsArray = exports.updateAvatarVisibility = exports.isDev = exports.consoleSink = exports.resetLoggerConfig = exports.getLoggerConfig = exports.configureLogger = exports.createLogger = exports.logger = exports.normalizeMultilineText = exports.normalizeInlineText = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.isValidDisplayName = exports.isValidPassword = exports.isValidUsername = exports.isValidEmail = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = exports.retryAsync = void 0;
24
+ exports.packageInfo = exports.runSessionColdBoot = exports.TOKEN_REFRESH_LEAD_MS = exports.startTokenRefreshScheduler = exports.installAuthRefreshHandler = exports.createAuthRefreshHandler = exports.refreshDeviceSecretArm = exports.refreshPersistedSession = exports.AUTH_STATE_STORAGE_KEY = exports.createMemoryAuthStateStore = exports.createNativeAuthStateStore = exports.createWebAuthStateStore = exports.createAccountDialogController = exports.AccountDialogController = exports.switchableAccountIds = exports.projectSwitchableAccounts = exports.accountIdsOf = exports.activeUserOf = exports.activeSessionIdOf = exports.deviceStateToClientSessions = exports.createSessionClient = exports.createSessionClientHost = exports.SessionClient = exports.redeemHubTicketOnHub = exports.syncHubAfterSignIn = exports.parseHubSyncReturnUrl = exports.normalizeOfficialReturnOrigin = exports.isAllowedDeviceJoinOrigin = exports.isOfficialWebOrigin = exports.isLoopbackOrigin = exports.isIdpHubOrigin = exports.buildHubSyncUrl = exports.buildIdpHubOrigin = exports.clearOAuthHandshake = exports.readOAuthHandshake = exports.persistOAuthHandshake = exports.normalizeOAuthRedirectUri = exports.OXY_CROSS_ORIGIN_RESTORE_ATTEMPTED_KEY = exports.OXY_SILENT_OAUTH_ATTEMPTED_KEY = void 0;
25
25
  // Ensure crypto polyfills are loaded before anything else
26
26
  require("./crypto/polyfill");
27
27
  // ---------------------------------------------------------------------------
@@ -103,6 +103,16 @@ var signatureService_1 = require("./crypto/signatureService");
103
103
  Object.defineProperty(exports, "SignatureService", { enumerable: true, get: function () { return signatureService_1.SignatureService; } });
104
104
  var recoveryPhrase_1 = require("./crypto/recoveryPhrase");
105
105
  Object.defineProperty(exports, "RecoveryPhraseService", { enumerable: true, get: function () { return recoveryPhrase_1.RecoveryPhraseService; } });
106
+ // Low-level crypto primitives (b3 Phase 0 — encrypted backup + device transfer)
107
+ var kdf_1 = require("./crypto/kdf");
108
+ Object.defineProperty(exports, "hkdfSha256", { enumerable: true, get: function () { return kdf_1.hkdfSha256; } });
109
+ var aead_1 = require("./crypto/aead");
110
+ Object.defineProperty(exports, "encryptAead", { enumerable: true, get: function () { return aead_1.encryptAead; } });
111
+ Object.defineProperty(exports, "decryptAead", { enumerable: true, get: function () { return aead_1.decryptAead; } });
112
+ Object.defineProperty(exports, "AEAD_KEY_LENGTH", { enumerable: true, get: function () { return aead_1.AEAD_KEY_LENGTH; } });
113
+ Object.defineProperty(exports, "AEAD_NONCE_LENGTH", { enumerable: true, get: function () { return aead_1.AEAD_NONCE_LENGTH; } });
114
+ var ecdh_1 = require("./crypto/ecdh");
115
+ Object.defineProperty(exports, "deriveSharedSecret", { enumerable: true, get: function () { return ecdh_1.deriveSharedSecret; } });
106
116
  // ---------------------------------------------------------------------------
107
117
  // Devices
108
118
  // ---------------------------------------------------------------------------
@@ -2,8 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildUserDid = buildUserDid;
4
4
  exports.OxyServicesIdentityMixin = OxyServicesIdentityMixin;
5
+ const protocol_1 = require("@oxyhq/protocol");
5
6
  const keyManager_1 = require("../crypto/keyManager");
6
7
  const signatureService_1 = require("../crypto/signatureService");
8
+ const recoveryPhrase_1 = require("../crypto/recoveryPhrase");
9
+ const platform_1 = require("../utils/platform");
10
+ const logger_1 = require("../logger");
7
11
  const mixinHelpers_1 = require("./mixinHelpers");
8
12
  /**
9
13
  * Registrable apex the Oxy DID method is anchored on. A user's DID is
@@ -141,6 +145,168 @@ function OxyServicesIdentityMixin(Base) {
141
145
  throw this.handleError(error);
142
146
  }
143
147
  }
148
+ /**
149
+ * Rotate the account's identity key: derive a brand-new keypair, prove
150
+ * control of the CURRENT key, and have the server ATOMICALLY replace the old
151
+ * key with the new one.
152
+ *
153
+ * The rotation is an atomic REPLACE on the server (never remove-then-add), so
154
+ * it never passes through a zero-auth-method state and is independent of the
155
+ * unlink guards. Because control of the current key is PROVEN (from
156
+ * SecureStore in `'device'` mode, or a recovery-phrase re-derivation in
157
+ * `'phrase'` mode), even the LAST remaining credential can be replaced.
158
+ *
159
+ * Ordering (safety-critical): the new key is persisted on-device ONLY AFTER
160
+ * the server confirms the swap. Persisting earlier would clobber the local
161
+ * key while the server still trusts the old one, locking the device out.
162
+ *
163
+ * Ambiguous-network-failure guard: if the `complete` response is lost
164
+ * (request sent, no reply), the swap may already have applied server-side.
165
+ * Before surfacing the error we reconcile against the derived DID document —
166
+ * if it already advertises the new key, the rotation is treated as done.
167
+ *
168
+ * NOTE: the UI is responsible for showing `newPhrase` to the user. For a
169
+ * "show-phrase-first" flow, derive the identity up front via
170
+ * {@link RecoveryPhraseService.derivePendingIdentity}, display it, then pass
171
+ * it back as `options.pendingIdentity` so the SAME identity is committed.
172
+ *
173
+ * @throws when no user is authenticated, when `proof: 'phrase'` is given
174
+ * without a `phrase`, when `proof: 'device'` runs with no on-device key,
175
+ * or when the rotation does not complete.
176
+ */
177
+ async rotateKey(options) {
178
+ try {
179
+ const userId = this.getCurrentUserId();
180
+ if (!userId) {
181
+ throw new Error('No authenticated user — sign in before rotating your key.');
182
+ }
183
+ // 1. The NEW identity (in memory only). The UI may pre-derive + pre-show
184
+ // it and pass it back here so the phrase shown === the phrase committed.
185
+ const pending = options.pendingIdentity ?? (await recoveryPhrase_1.RecoveryPhraseService.derivePendingIdentity());
186
+ const newPublicKey = pending.publicKey;
187
+ // 2. Resolve the OLD signing capability from the chosen proof mode.
188
+ let oldPublicKey;
189
+ let signWithOldKey;
190
+ if (options.proof === 'phrase') {
191
+ const phrase = options.phrase?.trim();
192
+ if (!phrase) {
193
+ throw new Error('A recovery phrase is required for phrase-proof rotation.');
194
+ }
195
+ const oldPrivateKey = await recoveryPhrase_1.RecoveryPhraseService.derivePrivateKeyFromPhrase(phrase);
196
+ oldPublicKey = keyManager_1.KeyManager.derivePublicKey(oldPrivateKey);
197
+ signWithOldKey = (message) => (0, protocol_1.signMessage)(message, oldPrivateKey);
198
+ }
199
+ else {
200
+ const currentPublicKey = await keyManager_1.KeyManager.getPublicKey();
201
+ if (!currentPublicKey) {
202
+ throw new Error('No on-device identity found. Use the recovery-phrase option to rotate your key.');
203
+ }
204
+ oldPublicKey = currentPublicKey;
205
+ signWithOldKey = (message) => signatureService_1.SignatureService.sign(message);
206
+ }
207
+ // 3. Request a single-use rotate_key challenge (bearer).
208
+ const { challenge } = await this.makeRequest('POST', '/auth/rotate/challenge', undefined, { cache: false });
209
+ // 4. Sign the rotation proofs. The OLD key proves control of the key being
210
+ // replaced; the NEW key proves possession of the key being rotated in
211
+ // (so the server never accepts a re-encoding of a key the caller does
212
+ // not control). Both signed byte strings MUST match the server's
213
+ // reconstruction exactly (this key order). The old key is canonicalized
214
+ // so legacy compressed encodings in Mongo still verify.
215
+ const timestamp = Date.now();
216
+ const canonicalOldPublicKey = keyManager_1.KeyManager.canonicalPublicKey(oldPublicKey);
217
+ const message = JSON.stringify({
218
+ action: 'rotate_key',
219
+ userId,
220
+ oldPublicKey: canonicalOldPublicKey,
221
+ newPublicKey,
222
+ challenge,
223
+ timestamp,
224
+ });
225
+ const signature = await signWithOldKey(message);
226
+ const newKeyMessage = JSON.stringify({
227
+ action: 'rotate_key_new',
228
+ userId,
229
+ newPublicKey,
230
+ challenge,
231
+ timestamp,
232
+ });
233
+ const newKeyProof = await (0, protocol_1.signMessage)(newKeyMessage, pending.privateKey);
234
+ // 5. Complete the rotation. On an AMBIGUOUS failure, reconcile against the
235
+ // DID before deciding the rotation failed.
236
+ let applied = false;
237
+ try {
238
+ const result = await this.makeRequest('POST', '/auth/rotate/complete', {
239
+ newPublicKey,
240
+ challenge,
241
+ signature,
242
+ newKeyProof,
243
+ timestamp,
244
+ ...(options.signOutEverywhere ? { signOutEverywhere: true } : {}),
245
+ }, { cache: false });
246
+ applied = result.success && result.publicKey.toLowerCase() === newPublicKey.toLowerCase();
247
+ }
248
+ catch (error) {
249
+ const reconciled = await this._rotationAlreadyApplied(userId, newPublicKey);
250
+ if (!reconciled) {
251
+ throw error;
252
+ }
253
+ applied = true;
254
+ }
255
+ if (!applied) {
256
+ throw new Error('Key rotation did not complete — your previous key is unchanged.');
257
+ }
258
+ // 6. ONLY after the server confirms the swap, persist the new key locally,
259
+ // overwriting the old one. `importKeyPair({ overwrite: true })` uses the
260
+ // atomic persist path (backs the previous key up first). Native-only —
261
+ // on web the key never lived in SecureStore, so there is nothing to
262
+ // persist locally.
263
+ //
264
+ // If this local write fails the server key is ALREADY the new one, so
265
+ // we must NOT throw and swallow the phrase — the caller needs it to
266
+ // re-import the now-live key. Surface the result with
267
+ // `localPersistFailed: true` (mirrors the pendingIdentity
268
+ // show-phrase-first path, where the caller already holds the phrase).
269
+ let localPersistFailed = false;
270
+ if (!(0, platform_1.isWeb)()) {
271
+ try {
272
+ await keyManager_1.KeyManager.importKeyPair(pending.privateKey, { overwrite: true });
273
+ }
274
+ catch (persistError) {
275
+ localPersistFailed = true;
276
+ logger_1.logger.warn('Key rotated on the server but persisting the new key on-device failed; returning the new phrase so it can be re-imported.', { component: 'OxyServices.identity', method: 'rotateKey' }, persistError);
277
+ }
278
+ }
279
+ this._invalidateIdentityCaches(userId);
280
+ return localPersistFailed
281
+ ? { newPublicKey, newPhrase: pending.phrase, words: pending.words, localPersistFailed: true }
282
+ : { newPublicKey, newPhrase: pending.phrase, words: pending.words };
283
+ }
284
+ catch (error) {
285
+ throw this.handleError(error);
286
+ }
287
+ }
288
+ /**
289
+ * Reconciliation probe for the rotation ambiguous-failure guard: fetch the
290
+ * account's derived DID document (uncached) and report whether it already
291
+ * advertises `newPublicKey` as a verification method — i.e. whether the swap
292
+ * already landed server-side. A failed probe returns `false` (unconfirmed),
293
+ * so the caller surfaces the original network error.
294
+ *
295
+ * Uses the DID document rather than `GET /auth/methods` because the latter
296
+ * intentionally does NOT expose raw public keys, whereas the DID's
297
+ * `verificationMethod[].publicKeyHex` is derived live from the account's
298
+ * current key — so it reflects a completed rotation immediately.
299
+ *
300
+ * Internal helper (leading underscore); public rather than `private` for the
301
+ * same TS4094 reason as {@link _invalidateIdentityCaches}.
302
+ */
303
+ async _rotationAlreadyApplied(userId, newPublicKey) {
304
+ return this.makeRequest('GET', `/u/${encodeURIComponent(userId)}/did.json`, undefined, { cache: false })
305
+ .then((doc) => doc.verificationMethod.some((vm) => 'publicKeyHex' in vm &&
306
+ typeof vm.publicKeyHex === 'string' &&
307
+ vm.publicKeyHex.toLowerCase() === newPublicKey.toLowerCase()))
308
+ .catch(() => false);
309
+ }
144
310
  /**
145
311
  * Sign a record with the on-device identity key, WITHOUT publishing it.
146
312
  * The subject is the current user's DID. NATIVE-ONLY (requires a stored
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OxyServicesIdentityBackupMixin = OxyServicesIdentityBackupMixin;
4
+ const keyManager_1 = require("../crypto/keyManager");
5
+ const recoveryPhrase_1 = require("../crypto/recoveryPhrase");
6
+ const aead_1 = require("../crypto/aead");
7
+ /** Envelope/KDF version — bump only on a breaking scheme change. */
8
+ const BACKUP_ENVELOPE_VERSION = 1;
9
+ /** The AEAD the backup is sealed with. Pinned so a mismatched decryptor fails loudly. */
10
+ const BACKUP_ALGORITHM = 'xchacha20poly1305';
11
+ /**
12
+ * Length (hex chars) of the public-key HINT stored/echoed with a backup — enough
13
+ * to let the owner recognise WHICH identity a backup belongs to, but only a
14
+ * prefix (the full key is public anyway; a prefix keeps the record minimal).
15
+ */
16
+ const PUBLIC_KEY_HINT_LENGTH = 16;
17
+ /** Encode bytes as lowercase hex (cross-platform, no Buffer dependency). */
18
+ function toHex(bytes) {
19
+ let out = '';
20
+ for (let i = 0; i < bytes.length; i += 1) {
21
+ out += bytes[i].toString(16).padStart(2, '0');
22
+ }
23
+ return out;
24
+ }
25
+ /** Decode a lowercase/uppercase hex string to bytes. Throws on malformed input. */
26
+ function fromHex(hex) {
27
+ if (hex.length % 2 !== 0 || /[^0-9a-fA-F]/.test(hex)) {
28
+ throw new Error('Malformed hex in encrypted backup envelope.');
29
+ }
30
+ const out = new Uint8Array(hex.length / 2);
31
+ for (let i = 0; i < out.length; i += 1) {
32
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
33
+ }
34
+ return out;
35
+ }
36
+ /**
37
+ * The AEAD associated data binds the ciphertext to its `{version, publicKeyHint}`
38
+ * context: the exact bytes must be reproduced at decrypt time, so a mismatched
39
+ * version or hint (e.g. an envelope re-stamped by a tamperer) fails the
40
+ * Poly1305 check. Deterministic: both sides build the SAME object literal, so
41
+ * `JSON.stringify` yields identical bytes.
42
+ */
43
+ function buildBackupAad(version, publicKeyHint) {
44
+ return new TextEncoder().encode(JSON.stringify({ version, publicKeyHint }));
45
+ }
46
+ function OxyServicesIdentityBackupMixin(Base) {
47
+ return class extends Base {
48
+ constructor(...args) {
49
+ super(...args);
50
+ }
51
+ /**
52
+ * Derive the backup key material from the recovery phrase, encrypt the
53
+ * identity's `{privateKey, publicKey, createdAt}` with it, and upload the
54
+ * ciphertext + raw `lookupId` (`POST /identity/backup`, bearer). The server
55
+ * stores only `sha256(lookupId)` + the ciphertext. Idempotent per user: a
56
+ * re-upload REPLACES the prior backup (upsert by user id).
57
+ *
58
+ * The identity is derived from the PHRASE (not read from SecureStore), so
59
+ * this works cross-platform and does not require an on-device key.
60
+ *
61
+ * @param phrase - The identity's BIP-39 recovery phrase.
62
+ * @returns The post-write backup status (`{ exists: true, publicKeyHint, createdAt }`).
63
+ */
64
+ async createEncryptedBackup(phrase) {
65
+ try {
66
+ const { backupKey, lookupId } = await recoveryPhrase_1.RecoveryPhraseService.deriveBackupMaterial(phrase);
67
+ const privateKey = await recoveryPhrase_1.RecoveryPhraseService.derivePrivateKeyFromPhrase(phrase);
68
+ const publicKey = keyManager_1.KeyManager.derivePublicKey(privateKey);
69
+ const createdAt = new Date().toISOString();
70
+ const publicKeyHint = publicKey.slice(0, PUBLIC_KEY_HINT_LENGTH);
71
+ const payload = { privateKey, publicKey, createdAt };
72
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
73
+ const aad = buildBackupAad(BACKUP_ENVELOPE_VERSION, publicKeyHint);
74
+ const { nonce, ciphertext } = (0, aead_1.encryptAead)(backupKey, plaintext, aad);
75
+ const body = {
76
+ version: BACKUP_ENVELOPE_VERSION,
77
+ algorithm: BACKUP_ALGORITHM,
78
+ kdfInfo: recoveryPhrase_1.BACKUP_KDF_ENCRYPTION_INFO,
79
+ nonce: toHex(nonce),
80
+ ciphertext: toHex(ciphertext),
81
+ publicKeyHint,
82
+ createdAt,
83
+ lookupId,
84
+ };
85
+ return await this.makeRequest('POST', '/identity/backup', body, { cache: false });
86
+ }
87
+ catch (error) {
88
+ throw this.handleError(error);
89
+ }
90
+ }
91
+ /**
92
+ * Whether the authenticated user has a stored encrypted backup, plus the
93
+ * non-sensitive hint + timestamp when one exists (`GET /identity/backup/status`,
94
+ * bearer). Returns no ciphertext and no locator.
95
+ */
96
+ async getBackupStatus() {
97
+ try {
98
+ return await this.makeRequest('GET', '/identity/backup/status', undefined, { cache: false });
99
+ }
100
+ catch (error) {
101
+ throw this.handleError(error);
102
+ }
103
+ }
104
+ /**
105
+ * Delete the authenticated user's stored backup (`DELETE /identity/backup`,
106
+ * bearer). Idempotent — deleting a non-existent backup still succeeds.
107
+ */
108
+ async deleteBackup() {
109
+ try {
110
+ return await this.makeRequest('DELETE', '/identity/backup', undefined, { cache: false });
111
+ }
112
+ catch (error) {
113
+ throw this.handleError(error);
114
+ }
115
+ }
116
+ /**
117
+ * Restore an identity from its encrypted off-device backup using ONLY the
118
+ * recovery phrase: re-derive `{backupKey, lookupId}`, fetch the envelope by
119
+ * `lookupId` (`GET /identity/backup/:lookupId`, PUBLIC — the 256-bit locator
120
+ * is the protection), decrypt + authenticate locally, then persist the key.
121
+ *
122
+ * NATIVE-ONLY persistence: `KeyManager.importKeyPair` throws on web. It also
123
+ * refuses to clobber a DIFFERENT existing on-device identity unless
124
+ * `overwrite: true` — the {@link import('../crypto/keyManager').IdentityAlreadyExistsError}
125
+ * propagates to the caller (never swallowed) so the UI can confirm before
126
+ * overwriting.
127
+ *
128
+ * @param phrase - The identity's BIP-39 recovery phrase.
129
+ * @param options.overwrite - Replace a different existing on-device identity.
130
+ * @returns The restored identity's public key.
131
+ * @throws if the phrase is invalid, no backup exists (404), the ciphertext
132
+ * fails authentication (tamper), or an existing identity blocks the import.
133
+ */
134
+ async restoreFromEncryptedBackup(phrase, options) {
135
+ try {
136
+ const { backupKey, lookupId } = await recoveryPhrase_1.RecoveryPhraseService.deriveBackupMaterial(phrase);
137
+ const envelope = await this.makeRequest('GET', `/identity/backup/${encodeURIComponent(lookupId)}`, undefined, { cache: false });
138
+ if (envelope.algorithm !== BACKUP_ALGORITHM) {
139
+ throw new Error(`Unsupported backup algorithm: ${envelope.algorithm}`);
140
+ }
141
+ const aad = buildBackupAad(envelope.version, envelope.publicKeyHint);
142
+ const plaintext = (0, aead_1.decryptAead)(backupKey, fromHex(envelope.nonce), fromHex(envelope.ciphertext), aad);
143
+ const payload = JSON.parse(new TextDecoder().decode(plaintext));
144
+ // Persist the recovered key. Native-only; refuses to clobber a different
145
+ // identity unless overwrite — the IdentityAlreadyExistsError propagates.
146
+ return await keyManager_1.KeyManager.importKeyPair(payload.privateKey, {
147
+ overwrite: options?.overwrite === true,
148
+ });
149
+ }
150
+ catch (error) {
151
+ // Preserve the typed "an identity already exists" signal so the caller
152
+ // can prompt for overwrite. `handleError` would flatten it to a generic
153
+ // Error and lose that discrimination.
154
+ if (error instanceof keyManager_1.IdentityAlreadyExistsError) {
155
+ throw error;
156
+ }
157
+ throw this.handleError(error);
158
+ }
159
+ }
160
+ };
161
+ }
@@ -13,6 +13,12 @@ const errorUtils_1 = require("../utils/errorUtils");
13
13
  * server-side batch cap; larger inputs are split into multiple chunked calls.
14
14
  */
15
15
  const USERS_BY_IDS_CHUNK_SIZE = 100;
16
+ /**
17
+ * Maximum number of ids sent per `POST /users/follow-status/bulk` request.
18
+ * Matches the server-side `MAX_BULK_FOLLOW` cap; larger inputs are split into
19
+ * multiple chunked calls whose result maps are merged.
20
+ */
21
+ const FOLLOW_STATUS_CHUNK_SIZE = 200;
16
22
  function OxyServicesUserMixin(Base) {
17
23
  return class extends Base {
18
24
  constructor(...args) {
@@ -604,6 +610,43 @@ function OxyServicesUserMixin(Base) {
604
610
  throw this.handleError(error);
605
611
  }
606
612
  }
613
+ /**
614
+ * Resolve the viewer's follow status for MANY users in one round-trip per
615
+ * chunk. Built for list UIs (a page of `FollowButton`s) that would otherwise
616
+ * fire one `getFollowStatus` per button (the classic N+1).
617
+ *
618
+ * Ids are deduplicated and validated (empty/blank ids dropped), split into
619
+ * chunks of {@link FOLLOW_STATUS_CHUNK_SIZE} (the server's bulk cap), and
620
+ * POSTed to `/users/follow-status/bulk` as `{ userIds }`. The per-chunk
621
+ * `{ statuses }` maps are merged into one `Record<string, boolean>` covering
622
+ * every requested id — ids the viewer does not follow come back `false`.
623
+ *
624
+ * Uncached (`{ cache: false }`): the UI store owns follow-status freshness
625
+ * and writes optimistically on every mutation, so an SDK cache here would
626
+ * serve a stale status right after a follow/unfollow. An empty/whitespace-
627
+ * only input resolves immediately with `{}` and performs no network call.
628
+ */
629
+ async getFollowStatuses(userIds) {
630
+ const uniqueIds = Array.from(new Set(userIds.filter((id) => typeof id === 'string' && id.trim().length > 0)));
631
+ if (uniqueIds.length === 0) {
632
+ return {};
633
+ }
634
+ const chunks = [];
635
+ for (let i = 0; i < uniqueIds.length; i += FOLLOW_STATUS_CHUNK_SIZE) {
636
+ chunks.push(uniqueIds.slice(i, i + FOLLOW_STATUS_CHUNK_SIZE));
637
+ }
638
+ try {
639
+ const responses = await Promise.all(chunks.map((chunk) => this.makeRequest('POST', '/users/follow-status/bulk', { userIds: chunk }, { cache: false })));
640
+ const merged = {};
641
+ for (const response of responses) {
642
+ Object.assign(merged, response?.statuses ?? {});
643
+ }
644
+ return merged;
645
+ }
646
+ catch (error) {
647
+ throw this.handleError(error);
648
+ }
649
+ }
607
650
  /**
608
651
  * Get user followers
609
652
  */
@@ -12,6 +12,7 @@ const OxyServices_base_1 = require("../OxyServices.base");
12
12
  const OxyServices_auth_1 = require("./OxyServices.auth");
13
13
  const OxyServices_user_1 = require("./OxyServices.user");
14
14
  const OxyServices_identity_1 = require("./OxyServices.identity");
15
+ const OxyServices_identityBackup_1 = require("./OxyServices.identityBackup");
15
16
  const OxyServices_privacy_1 = require("./OxyServices.privacy");
16
17
  const OxyServices_language_1 = require("./OxyServices.language");
17
18
  const OxyServices_payment_1 = require("./OxyServices.payment");
@@ -50,6 +51,9 @@ const MIXIN_PIPELINE = [
50
51
  OxyServices_user_1.OxyServicesUserMixin,
51
52
  // Self-sovereign identity (DID, signed records, auth-method ↔ VM mapping)
52
53
  OxyServices_identity_1.OxyServicesIdentityMixin,
54
+ // Encrypted off-device identity backup (b3 Feature 1): store/restore an
55
+ // encrypted copy of the self-custody key, keyed off the recovery phrase.
56
+ OxyServices_identityBackup_1.OxyServicesIdentityBackupMixin,
53
57
  OxyServices_privacy_1.OxyServicesPrivacyMixin,
54
58
  // Feature mixins
55
59
  OxyServices_language_1.OxyServicesLanguageMixin,